blob: 2c4d45f82f166caec67f0853be34bc64ec78c450 [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
1112 Note that \ctype{Py_UNICODE} data is being interpreted as UTF-16
1113 reduced to UCS-2. This trick makes it possible to add full UTF-16
1114 capabilities at a later point without comprimising the APIs.
1115
1116 Returns \NULL{} if an exception was raised by the codec.
1117\end{cfuncdesc}
1118
1119\begin{cfuncdesc}{PyObject*}{PyUnicode_AsUTF16String}{PyObject *unicode}
1120 Returns a Python string using the UTF-16 encoding in native byte
1121 order. The string always starts with a BOM mark. Error handling is
1122 ``strict''. Returns \NULL{} if an exception was raised by the
1123 codec.
1124\end{cfuncdesc}
1125
1126% --- Unicode-Escape Codecs ----------------------------------------------
1127
Martin v. Löwis95cf84a2003-10-19 07:32:24 +00001128These are the ``Unicode Escape'' codec APIs:
Fred Drake3adf79e2001-10-12 19:01:43 +00001129
1130\begin{cfuncdesc}{PyObject*}{PyUnicode_DecodeUnicodeEscape}{const char *s,
1131 int size,
1132 const char *errors}
1133 Creates a Unicode object by decoding \var{size} bytes of the
1134 Unicode-Escape encoded string \var{s}. Returns \NULL{} if an
1135 exception was raised by the codec.
1136\end{cfuncdesc}
1137
1138\begin{cfuncdesc}{PyObject*}{PyUnicode_EncodeUnicodeEscape}{const Py_UNICODE *s,
1139 int size,
1140 const char *errors}
1141 Encodes the \ctype{Py_UNICODE} buffer of the given size using
1142 Unicode-Escape and returns a Python string object. Returns \NULL{}
1143 if an exception was raised by the codec.
1144\end{cfuncdesc}
1145
1146\begin{cfuncdesc}{PyObject*}{PyUnicode_AsUnicodeEscapeString}{PyObject *unicode}
1147 Encodes a Unicode objects using Unicode-Escape and returns the
1148 result as Python string object. Error handling is ``strict''.
1149 Returns \NULL{} if an exception was raised by the codec.
1150\end{cfuncdesc}
1151
1152% --- Raw-Unicode-Escape Codecs ------------------------------------------
1153
Martin v. Löwis95cf84a2003-10-19 07:32:24 +00001154These are the ``Raw Unicode Escape'' codec APIs:
Fred Drake3adf79e2001-10-12 19:01:43 +00001155
1156\begin{cfuncdesc}{PyObject*}{PyUnicode_DecodeRawUnicodeEscape}{const char *s,
1157 int size,
1158 const char *errors}
1159 Creates a Unicode object by decoding \var{size} bytes of the
Martin v. Löwis95cf84a2003-10-19 07:32:24 +00001160 Raw-Unicode-Escape encoded string \var{s}. Returns \NULL{} if an
Fred Drake3adf79e2001-10-12 19:01:43 +00001161 exception was raised by the codec.
1162\end{cfuncdesc}
1163
1164\begin{cfuncdesc}{PyObject*}{PyUnicode_EncodeRawUnicodeEscape}{const Py_UNICODE *s,
1165 int size,
1166 const char *errors}
1167 Encodes the \ctype{Py_UNICODE} buffer of the given size using
1168 Raw-Unicode-Escape and returns a Python string object. Returns
1169 \NULL{} if an exception was raised by the codec.
1170\end{cfuncdesc}
1171
1172\begin{cfuncdesc}{PyObject*}{PyUnicode_AsRawUnicodeEscapeString}{PyObject *unicode}
1173 Encodes a Unicode objects using Raw-Unicode-Escape and returns the
1174 result as Python string object. Error handling is ``strict''.
1175 Returns \NULL{} if an exception was raised by the codec.
1176\end{cfuncdesc}
1177
Tim Petersf582b822001-12-11 18:51:08 +00001178% --- Latin-1 Codecs -----------------------------------------------------
Fred Drake3adf79e2001-10-12 19:01:43 +00001179
1180These are the Latin-1 codec APIs:
1181Latin-1 corresponds to the first 256 Unicode ordinals and only these
1182are accepted by the codecs during encoding.
1183
1184\begin{cfuncdesc}{PyObject*}{PyUnicode_DecodeLatin1}{const char *s,
1185 int size,
1186 const char *errors}
1187 Creates a Unicode object by decoding \var{size} bytes of the Latin-1
1188 encoded string \var{s}. Returns \NULL{} if an exception was raised
1189 by the codec.
1190\end{cfuncdesc}
1191
1192\begin{cfuncdesc}{PyObject*}{PyUnicode_EncodeLatin1}{const Py_UNICODE *s,
1193 int size,
1194 const char *errors}
1195 Encodes the \ctype{Py_UNICODE} buffer of the given size using
1196 Latin-1 and returns a Python string object. Returns \NULL{} if an
1197 exception was raised by the codec.
1198\end{cfuncdesc}
1199
1200\begin{cfuncdesc}{PyObject*}{PyUnicode_AsLatin1String}{PyObject *unicode}
1201 Encodes a Unicode objects using Latin-1 and returns the result as
1202 Python string object. Error handling is ``strict''. Returns
1203 \NULL{} if an exception was raised by the codec.
1204\end{cfuncdesc}
1205
Tim Petersf582b822001-12-11 18:51:08 +00001206% --- ASCII Codecs -------------------------------------------------------
Fred Drake3adf79e2001-10-12 19:01:43 +00001207
1208These are the \ASCII{} codec APIs. Only 7-bit \ASCII{} data is
1209accepted. All other codes generate errors.
1210
1211\begin{cfuncdesc}{PyObject*}{PyUnicode_DecodeASCII}{const char *s,
1212 int size,
1213 const char *errors}
1214 Creates a Unicode object by decoding \var{size} bytes of the
1215 \ASCII{} encoded string \var{s}. Returns \NULL{} if an exception
1216 was raised by the codec.
1217\end{cfuncdesc}
1218
1219\begin{cfuncdesc}{PyObject*}{PyUnicode_EncodeASCII}{const Py_UNICODE *s,
1220 int size,
1221 const char *errors}
1222 Encodes the \ctype{Py_UNICODE} buffer of the given size using
1223 \ASCII{} and returns a Python string object. Returns \NULL{} if an
1224 exception was raised by the codec.
1225\end{cfuncdesc}
1226
1227\begin{cfuncdesc}{PyObject*}{PyUnicode_AsASCIIString}{PyObject *unicode}
1228 Encodes a Unicode objects using \ASCII{} and returns the result as
1229 Python string object. Error handling is ``strict''. Returns
1230 \NULL{} if an exception was raised by the codec.
1231\end{cfuncdesc}
1232
Tim Petersf582b822001-12-11 18:51:08 +00001233% --- Character Map Codecs -----------------------------------------------
Fred Drake3adf79e2001-10-12 19:01:43 +00001234
1235These are the mapping codec APIs:
1236
1237This codec is special in that it can be used to implement many
1238different codecs (and this is in fact what was done to obtain most of
1239the standard codecs included in the \module{encodings} package). The
1240codec uses mapping to encode and decode characters.
1241
1242Decoding mappings must map single string characters to single Unicode
1243characters, integers (which are then interpreted as Unicode ordinals)
Tim Petersf582b822001-12-11 18:51:08 +00001244or None (meaning "undefined mapping" and causing an error).
Fred Drake3adf79e2001-10-12 19:01:43 +00001245
1246Encoding mappings must map single Unicode characters to single string
1247characters, integers (which are then interpreted as Latin-1 ordinals)
1248or None (meaning "undefined mapping" and causing an error).
1249
1250The mapping objects provided must only support the __getitem__ mapping
1251interface.
1252
1253If a character lookup fails with a LookupError, the character is
1254copied as-is meaning that its ordinal value will be interpreted as
1255Unicode or Latin-1 ordinal resp. Because of this, mappings only need
1256to contain those mappings which map characters to different code
1257points.
1258
1259\begin{cfuncdesc}{PyObject*}{PyUnicode_DecodeCharmap}{const char *s,
1260 int size,
1261 PyObject *mapping,
1262 const char *errors}
1263 Creates a Unicode object by decoding \var{size} bytes of the encoded
1264 string \var{s} using the given \var{mapping} object. Returns
1265 \NULL{} if an exception was raised by the codec.
1266\end{cfuncdesc}
1267
1268\begin{cfuncdesc}{PyObject*}{PyUnicode_EncodeCharmap}{const Py_UNICODE *s,
1269 int size,
1270 PyObject *mapping,
1271 const char *errors}
1272 Encodes the \ctype{Py_UNICODE} buffer of the given size using the
1273 given \var{mapping} object and returns a Python string object.
1274 Returns \NULL{} if an exception was raised by the codec.
1275\end{cfuncdesc}
1276
1277\begin{cfuncdesc}{PyObject*}{PyUnicode_AsCharmapString}{PyObject *unicode,
1278 PyObject *mapping}
1279 Encodes a Unicode objects using the given \var{mapping} object and
1280 returns the result as Python string object. Error handling is
1281 ``strict''. Returns \NULL{} if an exception was raised by the
1282 codec.
1283\end{cfuncdesc}
1284
1285The following codec API is special in that maps Unicode to Unicode.
1286
1287\begin{cfuncdesc}{PyObject*}{PyUnicode_TranslateCharmap}{const Py_UNICODE *s,
1288 int size,
1289 PyObject *table,
1290 const char *errors}
1291 Translates a \ctype{Py_UNICODE} buffer of the given length by
1292 applying a character mapping \var{table} to it and returns the
1293 resulting Unicode object. Returns \NULL{} when an exception was
1294 raised by the codec.
1295
1296 The \var{mapping} table must map Unicode ordinal integers to Unicode
1297 ordinal integers or None (causing deletion of the character).
1298
1299 Mapping tables need only provide the method{__getitem__()}
1300 interface; dictionaries and sequences work well. Unmapped character
1301 ordinals (ones which cause a \exception{LookupError}) are left
1302 untouched and are copied as-is.
1303\end{cfuncdesc}
1304
1305% --- MBCS codecs for Windows --------------------------------------------
1306
1307These are the MBCS codec APIs. They are currently only available on
1308Windows and use the Win32 MBCS converters to implement the
1309conversions. Note that MBCS (or DBCS) is a class of encodings, not
1310just one. The target encoding is defined by the user settings on the
1311machine running the codec.
1312
1313\begin{cfuncdesc}{PyObject*}{PyUnicode_DecodeMBCS}{const char *s,
1314 int size,
1315 const char *errors}
1316 Creates a Unicode object by decoding \var{size} bytes of the MBCS
1317 encoded string \var{s}. Returns \NULL{} if an exception was
1318 raised by the codec.
1319\end{cfuncdesc}
1320
1321\begin{cfuncdesc}{PyObject*}{PyUnicode_EncodeMBCS}{const Py_UNICODE *s,
1322 int size,
1323 const char *errors}
1324 Encodes the \ctype{Py_UNICODE} buffer of the given size using MBCS
1325 and returns a Python string object. Returns \NULL{} if an exception
1326 was raised by the codec.
1327\end{cfuncdesc}
1328
1329\begin{cfuncdesc}{PyObject*}{PyUnicode_AsMBCSString}{PyObject *unicode}
1330 Encodes a Unicode objects using MBCS and returns the result as
1331 Python string object. Error handling is ``strict''. Returns
1332 \NULL{} if an exception was raised by the codec.
1333\end{cfuncdesc}
1334
1335% --- Methods & Slots ----------------------------------------------------
1336
1337\subsubsection{Methods and Slot Functions \label{unicodeMethodsAndSlots}}
1338
1339The following APIs are capable of handling Unicode objects and strings
1340on input (we refer to them as strings in the descriptions) and return
Martin v. Löwis95cf84a2003-10-19 07:32:24 +00001341Unicode objects or integers as appropriate.
Fred Drake3adf79e2001-10-12 19:01:43 +00001342
1343They all return \NULL{} or \code{-1} if an exception occurs.
1344
1345\begin{cfuncdesc}{PyObject*}{PyUnicode_Concat}{PyObject *left,
1346 PyObject *right}
1347 Concat two strings giving a new Unicode string.
1348\end{cfuncdesc}
1349
1350\begin{cfuncdesc}{PyObject*}{PyUnicode_Split}{PyObject *s,
1351 PyObject *sep,
1352 int maxsplit}
1353 Split a string giving a list of Unicode strings. If sep is \NULL,
1354 splitting will be done at all whitespace substrings. Otherwise,
1355 splits occur at the given separator. At most \var{maxsplit} splits
1356 will be done. If negative, no limit is set. Separators are not
1357 included in the resulting list.
1358\end{cfuncdesc}
1359
1360\begin{cfuncdesc}{PyObject*}{PyUnicode_Splitlines}{PyObject *s,
Martin v. Löwis24b88812003-03-30 16:40:42 +00001361 int keepend}
Fred Drake3adf79e2001-10-12 19:01:43 +00001362 Split a Unicode string at line breaks, returning a list of Unicode
Martin v. Löwis24b88812003-03-30 16:40:42 +00001363 strings. CRLF is considered to be one line break. If \var{keepend}
1364 is 0, the Line break characters are not included in the resulting
1365 strings.
Fred Drake3adf79e2001-10-12 19:01:43 +00001366\end{cfuncdesc}
1367
1368\begin{cfuncdesc}{PyObject*}{PyUnicode_Translate}{PyObject *str,
1369 PyObject *table,
1370 const char *errors}
1371 Translate a string by applying a character mapping table to it and
1372 return the resulting Unicode object.
1373
1374 The mapping table must map Unicode ordinal integers to Unicode
1375 ordinal integers or None (causing deletion of the character).
1376
1377 Mapping tables need only provide the \method{__getitem__()}
1378 interface; dictionaries and sequences work well. Unmapped character
1379 ordinals (ones which cause a \exception{LookupError}) are left
1380 untouched and are copied as-is.
1381
1382 \var{errors} has the usual meaning for codecs. It may be \NULL{}
1383 which indicates to use the default error handling.
1384\end{cfuncdesc}
1385
1386\begin{cfuncdesc}{PyObject*}{PyUnicode_Join}{PyObject *separator,
1387 PyObject *seq}
1388 Join a sequence of strings using the given separator and return the
1389 resulting Unicode string.
1390\end{cfuncdesc}
1391
1392\begin{cfuncdesc}{PyObject*}{PyUnicode_Tailmatch}{PyObject *str,
1393 PyObject *substr,
1394 int start,
1395 int end,
1396 int direction}
1397 Return 1 if \var{substr} matches \var{str}[\var{start}:\var{end}] at
1398 the given tail end (\var{direction} == -1 means to do a prefix
1399 match, \var{direction} == 1 a suffix match), 0 otherwise.
1400\end{cfuncdesc}
1401
Fred Drake1d1e1db2002-06-20 22:07:04 +00001402\begin{cfuncdesc}{int}{PyUnicode_Find}{PyObject *str,
1403 PyObject *substr,
1404 int start,
1405 int end,
1406 int direction}
Fred Drake3adf79e2001-10-12 19:01:43 +00001407 Return the first position of \var{substr} in
1408 \var{str}[\var{start}:\var{end}] using the given \var{direction}
1409 (\var{direction} == 1 means to do a forward search,
Fred Drake1d1e1db2002-06-20 22:07:04 +00001410 \var{direction} == -1 a backward search). The return value is the
1411 index of the first match; a value of \code{-1} indicates that no
1412 match was found, and \code{-2} indicates that an error occurred and
1413 an exception has been set.
Fred Drake3adf79e2001-10-12 19:01:43 +00001414\end{cfuncdesc}
1415
Fred Drake1d1e1db2002-06-20 22:07:04 +00001416\begin{cfuncdesc}{int}{PyUnicode_Count}{PyObject *str,
1417 PyObject *substr,
1418 int start,
1419 int end}
1420 Return the number of non-overlapping occurrences of \var{substr} in
1421 \code{\var{str}[\var{start}:\var{end}]}. Returns \code{-1} if an
1422 error occurred.
Fred Drake3adf79e2001-10-12 19:01:43 +00001423\end{cfuncdesc}
1424
1425\begin{cfuncdesc}{PyObject*}{PyUnicode_Replace}{PyObject *str,
1426 PyObject *substr,
1427 PyObject *replstr,
1428 int maxcount}
1429 Replace at most \var{maxcount} occurrences of \var{substr} in
1430 \var{str} with \var{replstr} and return the resulting Unicode object.
1431 \var{maxcount} == -1 means replace all occurrences.
1432\end{cfuncdesc}
1433
1434\begin{cfuncdesc}{int}{PyUnicode_Compare}{PyObject *left, PyObject *right}
1435 Compare two strings and return -1, 0, 1 for less than, equal, and
1436 greater than, respectively.
1437\end{cfuncdesc}
1438
1439\begin{cfuncdesc}{PyObject*}{PyUnicode_Format}{PyObject *format,
1440 PyObject *args}
1441 Returns a new string object from \var{format} and \var{args}; this
1442 is analogous to \code{\var{format} \%\ \var{args}}. The
1443 \var{args} argument must be a tuple.
1444\end{cfuncdesc}
1445
1446\begin{cfuncdesc}{int}{PyUnicode_Contains}{PyObject *container,
1447 PyObject *element}
1448 Checks whether \var{element} is contained in \var{container} and
1449 returns true or false accordingly.
1450
1451 \var{element} has to coerce to a one element Unicode
1452 string. \code{-1} is returned if there was an error.
1453\end{cfuncdesc}
1454
1455
1456\subsection{Buffer Objects \label{bufferObjects}}
1457\sectionauthor{Greg Stein}{gstein@lyra.org}
1458
1459\obindex{buffer}
1460Python objects implemented in C can export a group of functions called
1461the ``buffer\index{buffer interface} interface.'' These functions can
1462be used by an object to expose its data in a raw, byte-oriented
1463format. Clients of the object can use the buffer interface to access
1464the object data directly, without needing to copy it first.
1465
Tim Petersf582b822001-12-11 18:51:08 +00001466Two examples of objects that support
1467the buffer interface are strings and arrays. The string object exposes
Fred Drake3adf79e2001-10-12 19:01:43 +00001468the character contents in the buffer interface's byte-oriented
1469form. An array can also expose its contents, but it should be noted
1470that array elements may be multi-byte values.
1471
1472An example user of the buffer interface is the file object's
1473\method{write()} method. Any object that can export a series of bytes
1474through the buffer interface can be written to a file. There are a
Tim Petersf582b822001-12-11 18:51:08 +00001475number of format codes to \cfunction{PyArg_ParseTuple()} that operate
Fred Drake3adf79e2001-10-12 19:01:43 +00001476against an object's buffer interface, returning data from the target
1477object.
1478
1479More information on the buffer interface is provided in the section
Fred Drake54e62942001-12-11 19:40:16 +00001480``Buffer Object Structures'' (section~\ref{buffer-structs}), under
Fred Drake3adf79e2001-10-12 19:01:43 +00001481the description for \ctype{PyBufferProcs}\ttindex{PyBufferProcs}.
1482
1483A ``buffer object'' is defined in the \file{bufferobject.h} header
1484(included by \file{Python.h}). These objects look very similar to
1485string objects at the Python programming level: they support slicing,
1486indexing, concatenation, and some other standard string
1487operations. However, their data can come from one of two sources: from
1488a block of memory, or from another object which exports the buffer
1489interface.
1490
1491Buffer objects are useful as a way to expose the data from another
1492object's buffer interface to the Python programmer. They can also be
1493used as a zero-copy slicing mechanism. Using their ability to
1494reference a block of memory, it is possible to expose any data to the
1495Python programmer quite easily. The memory could be a large, constant
1496array in a C extension, it could be a raw block of memory for
1497manipulation before passing to an operating system library, or it
1498could be used to pass around structured data in its native, in-memory
1499format.
1500
1501\begin{ctypedesc}{PyBufferObject}
1502 This subtype of \ctype{PyObject} represents a buffer object.
1503\end{ctypedesc}
1504
1505\begin{cvardesc}{PyTypeObject}{PyBuffer_Type}
1506 The instance of \ctype{PyTypeObject} which represents the Python
1507 buffer type; it is the same object as \code{types.BufferType} in the
1508 Python layer.\withsubitem{(in module types)}{\ttindex{BufferType}}.
1509\end{cvardesc}
1510
1511\begin{cvardesc}{int}{Py_END_OF_BUFFER}
1512 This constant may be passed as the \var{size} parameter to
1513 \cfunction{PyBuffer_FromObject()} or
1514 \cfunction{PyBuffer_FromReadWriteObject()}. It indicates that the
1515 new \ctype{PyBufferObject} should refer to \var{base} object from
1516 the specified \var{offset} to the end of its exported buffer. Using
1517 this enables the caller to avoid querying the \var{base} object for
1518 its length.
1519\end{cvardesc}
1520
1521\begin{cfuncdesc}{int}{PyBuffer_Check}{PyObject *p}
1522 Return true if the argument has type \cdata{PyBuffer_Type}.
1523\end{cfuncdesc}
1524
1525\begin{cfuncdesc}{PyObject*}{PyBuffer_FromObject}{PyObject *base,
1526 int offset, int size}
1527 Return a new read-only buffer object. This raises
1528 \exception{TypeError} if \var{base} doesn't support the read-only
1529 buffer protocol or doesn't provide exactly one buffer segment, or it
1530 raises \exception{ValueError} if \var{offset} is less than zero. The
1531 buffer will hold a reference to the \var{base} object, and the
1532 buffer's contents will refer to the \var{base} object's buffer
1533 interface, starting as position \var{offset} and extending for
1534 \var{size} bytes. If \var{size} is \constant{Py_END_OF_BUFFER}, then
1535 the new buffer's contents extend to the length of the \var{base}
1536 object's exported buffer data.
1537\end{cfuncdesc}
1538
1539\begin{cfuncdesc}{PyObject*}{PyBuffer_FromReadWriteObject}{PyObject *base,
1540 int offset,
1541 int size}
1542 Return a new writable buffer object. Parameters and exceptions are
1543 similar to those for \cfunction{PyBuffer_FromObject()}. If the
1544 \var{base} object does not export the writeable buffer protocol,
1545 then \exception{TypeError} is raised.
1546\end{cfuncdesc}
1547
1548\begin{cfuncdesc}{PyObject*}{PyBuffer_FromMemory}{void *ptr, int size}
1549 Return a new read-only buffer object that reads from a specified
1550 location in memory, with a specified size. The caller is
1551 responsible for ensuring that the memory buffer, passed in as
1552 \var{ptr}, is not deallocated while the returned buffer object
1553 exists. Raises \exception{ValueError} if \var{size} is less than
1554 zero. Note that \constant{Py_END_OF_BUFFER} may \emph{not} be
1555 passed for the \var{size} parameter; \exception{ValueError} will be
1556 raised in that case.
1557\end{cfuncdesc}
1558
1559\begin{cfuncdesc}{PyObject*}{PyBuffer_FromReadWriteMemory}{void *ptr, int size}
1560 Similar to \cfunction{PyBuffer_FromMemory()}, but the returned
1561 buffer is writable.
1562\end{cfuncdesc}
1563
1564\begin{cfuncdesc}{PyObject*}{PyBuffer_New}{int size}
1565 Returns a new writable buffer object that maintains its own memory
1566 buffer of \var{size} bytes. \exception{ValueError} is returned if
1567 \var{size} is not zero or positive.
1568\end{cfuncdesc}
1569
1570
1571\subsection{Tuple Objects \label{tupleObjects}}
1572
1573\obindex{tuple}
1574\begin{ctypedesc}{PyTupleObject}
1575 This subtype of \ctype{PyObject} represents a Python tuple object.
1576\end{ctypedesc}
1577
1578\begin{cvardesc}{PyTypeObject}{PyTuple_Type}
1579 This instance of \ctype{PyTypeObject} represents the Python tuple
1580 type; it is the same object as \code{types.TupleType} in the Python
1581 layer.\withsubitem{(in module types)}{\ttindex{TupleType}}.
1582\end{cvardesc}
1583
1584\begin{cfuncdesc}{int}{PyTuple_Check}{PyObject *p}
1585 Return true if \var{p} is a tuple object or an instance of a subtype
1586 of the tuple type.
1587 \versionchanged[Allowed subtypes to be accepted]{2.2}
1588\end{cfuncdesc}
1589
1590\begin{cfuncdesc}{int}{PyTuple_CheckExact}{PyObject *p}
1591 Return true if \var{p} is a tuple object, but not an instance of a
1592 subtype of the tuple type.
1593 \versionadded{2.2}
1594\end{cfuncdesc}
1595
1596\begin{cfuncdesc}{PyObject*}{PyTuple_New}{int len}
1597 Return a new tuple object of size \var{len}, or \NULL{} on failure.
1598\end{cfuncdesc}
1599
Raymond Hettingercb2da432003-10-12 18:24:34 +00001600\begin{cfuncdesc}{PyObject*}{PyTuple_Pack}{int n, \moreargs}
1601 Return a new tuple object of size \var{n}, or \NULL{} on failure.
1602 The tuple values are initialized to the subsequent \var{n} C arguments
1603 pointing to Python objects. \samp{PyTuple_Pack(2, \var{a}, \var{b})}
1604 is equivalent to \samp{Py_BuildValue("(OO)", \var{a}, \var{b})}.
1605 \versionadded{2.4}
1606\end{cfuncdesc}
1607
Fred Drake3adf79e2001-10-12 19:01:43 +00001608\begin{cfuncdesc}{int}{PyTuple_Size}{PyObject *p}
1609 Takes a pointer to a tuple object, and returns the size of that
1610 tuple.
1611\end{cfuncdesc}
1612
1613\begin{cfuncdesc}{int}{PyTuple_GET_SIZE}{PyObject *p}
1614 Return the size of the tuple \var{p}, which must be non-\NULL{} and
1615 point to a tuple; no error checking is performed.
1616\end{cfuncdesc}
1617
1618\begin{cfuncdesc}{PyObject*}{PyTuple_GetItem}{PyObject *p, int pos}
1619 Returns the object at position \var{pos} in the tuple pointed to by
1620 \var{p}. If \var{pos} is out of bounds, returns \NULL{} and sets an
1621 \exception{IndexError} exception.
1622\end{cfuncdesc}
1623
1624\begin{cfuncdesc}{PyObject*}{PyTuple_GET_ITEM}{PyObject *p, int pos}
1625 Like \cfunction{PyTuple_GetItem()}, but does no checking of its
1626 arguments.
1627\end{cfuncdesc}
1628
1629\begin{cfuncdesc}{PyObject*}{PyTuple_GetSlice}{PyObject *p,
1630 int low, int high}
1631 Takes a slice of the tuple pointed to by \var{p} from \var{low} to
1632 \var{high} and returns it as a new tuple.
1633\end{cfuncdesc}
1634
1635\begin{cfuncdesc}{int}{PyTuple_SetItem}{PyObject *p,
1636 int pos, PyObject *o}
1637 Inserts a reference to object \var{o} at position \var{pos} of the
1638 tuple pointed to by \var{p}. It returns \code{0} on success.
1639 \note{This function ``steals'' a reference to \var{o}.}
1640\end{cfuncdesc}
1641
1642\begin{cfuncdesc}{void}{PyTuple_SET_ITEM}{PyObject *p,
1643 int pos, PyObject *o}
1644 Like \cfunction{PyTuple_SetItem()}, but does no error checking, and
1645 should \emph{only} be used to fill in brand new tuples. \note{This
1646 function ``steals'' a reference to \var{o}.}
1647\end{cfuncdesc}
1648
1649\begin{cfuncdesc}{int}{_PyTuple_Resize}{PyObject **p, int newsize}
1650 Can be used to resize a tuple. \var{newsize} will be the new length
1651 of the tuple. Because tuples are \emph{supposed} to be immutable,
1652 this should only be used if there is only one reference to the
1653 object. Do \emph{not} use this if the tuple may already be known to
1654 some other part of the code. The tuple will always grow or shrink
1655 at the end. Think of this as destroying the old tuple and creating
1656 a new one, only more efficiently. Returns \code{0} on success.
1657 Client code should never assume that the resulting value of
1658 \code{*\var{p}} will be the same as before calling this function.
1659 If the object referenced by \code{*\var{p}} is replaced, the
1660 original \code{*\var{p}} is destroyed. On failure, returns
1661 \code{-1} and sets \code{*\var{p}} to \NULL, and raises
1662 \exception{MemoryError} or
1663 \exception{SystemError}.
Tim Petersf582b822001-12-11 18:51:08 +00001664 \versionchanged[Removed unused third parameter, \var{last_is_sticky}]{2.2}
Fred Drake3adf79e2001-10-12 19:01:43 +00001665\end{cfuncdesc}
1666
1667
1668\subsection{List Objects \label{listObjects}}
1669
1670\obindex{list}
1671\begin{ctypedesc}{PyListObject}
1672 This subtype of \ctype{PyObject} represents a Python list object.
1673\end{ctypedesc}
1674
1675\begin{cvardesc}{PyTypeObject}{PyList_Type}
1676 This instance of \ctype{PyTypeObject} represents the Python list
1677 type. This is the same object as \code{types.ListType}.
1678 \withsubitem{(in module types)}{\ttindex{ListType}}
1679\end{cvardesc}
1680
1681\begin{cfuncdesc}{int}{PyList_Check}{PyObject *p}
Andrew MacIntyre13cd8892003-12-25 23:57:52 +00001682 Returns true if \var{p} is a list object or an instance of a
1683 subtype of the list type.
1684 \versionchanged[Allowed subtypes to be accepted]{2.2}
1685\end{cfuncdesc}
1686
1687\begin{cfuncdesc}{int}{PyList_CheckExact}{PyObject *p}
1688 Return true if \var{p} is a list object, but not an instance of a
1689 subtype of the list type.
1690 \versionadded{2.2}
Fred Drake3adf79e2001-10-12 19:01:43 +00001691\end{cfuncdesc}
1692
1693\begin{cfuncdesc}{PyObject*}{PyList_New}{int len}
1694 Returns a new list of length \var{len} on success, or \NULL{} on
1695 failure.
1696\end{cfuncdesc}
1697
1698\begin{cfuncdesc}{int}{PyList_Size}{PyObject *list}
1699 Returns the length of the list object in \var{list}; this is
1700 equivalent to \samp{len(\var{list})} on a list object.
1701 \bifuncindex{len}
1702\end{cfuncdesc}
1703
1704\begin{cfuncdesc}{int}{PyList_GET_SIZE}{PyObject *list}
1705 Macro form of \cfunction{PyList_Size()} without error checking.
1706\end{cfuncdesc}
1707
1708\begin{cfuncdesc}{PyObject*}{PyList_GetItem}{PyObject *list, int index}
1709 Returns the object at position \var{pos} in the list pointed to by
1710 \var{p}. If \var{pos} is out of bounds, returns \NULL{} and sets an
1711 \exception{IndexError} exception.
1712\end{cfuncdesc}
1713
1714\begin{cfuncdesc}{PyObject*}{PyList_GET_ITEM}{PyObject *list, int i}
1715 Macro form of \cfunction{PyList_GetItem()} without error checking.
1716\end{cfuncdesc}
1717
1718\begin{cfuncdesc}{int}{PyList_SetItem}{PyObject *list, int index,
1719 PyObject *item}
1720 Sets the item at index \var{index} in list to \var{item}. Returns
1721 \code{0} on success or \code{-1} on failure. \note{This function
1722 ``steals'' a reference to \var{item} and discards a reference to an
1723 item already in the list at the affected position.}
1724\end{cfuncdesc}
1725
1726\begin{cfuncdesc}{void}{PyList_SET_ITEM}{PyObject *list, int i,
1727 PyObject *o}
1728 Macro form of \cfunction{PyList_SetItem()} without error checking.
1729 This is normally only used to fill in new lists where there is no
1730 previous content.
1731 \note{This function ``steals'' a reference to \var{item}, and,
1732 unlike \cfunction{PyList_SetItem()}, does \emph{not} discard a
1733 reference to any item that it being replaced; any reference in
1734 \var{list} at position \var{i} will be leaked.}
1735\end{cfuncdesc}
1736
1737\begin{cfuncdesc}{int}{PyList_Insert}{PyObject *list, int index,
1738 PyObject *item}
1739 Inserts the item \var{item} into list \var{list} in front of index
1740 \var{index}. Returns \code{0} if successful; returns \code{-1} and
1741 raises an exception if unsuccessful. Analogous to
1742 \code{\var{list}.insert(\var{index}, \var{item})}.
1743\end{cfuncdesc}
1744
1745\begin{cfuncdesc}{int}{PyList_Append}{PyObject *list, PyObject *item}
1746 Appends the object \var{item} at the end of list \var{list}.
1747 Returns \code{0} if successful; returns \code{-1} and sets an
1748 exception if unsuccessful. Analogous to
1749 \code{\var{list}.append(\var{item})}.
1750\end{cfuncdesc}
1751
1752\begin{cfuncdesc}{PyObject*}{PyList_GetSlice}{PyObject *list,
1753 int low, int high}
1754 Returns a list of the objects in \var{list} containing the objects
1755 \emph{between} \var{low} and \var{high}. Returns \NULL{} and sets
1756 an exception if unsuccessful.
1757 Analogous to \code{\var{list}[\var{low}:\var{high}]}.
1758\end{cfuncdesc}
1759
1760\begin{cfuncdesc}{int}{PyList_SetSlice}{PyObject *list,
1761 int low, int high,
1762 PyObject *itemlist}
1763 Sets the slice of \var{list} between \var{low} and \var{high} to the
1764 contents of \var{itemlist}. Analogous to
Raymond Hettinger9c7ed4c2003-10-26 17:20:07 +00001765 \code{\var{list}[\var{low}:\var{high}] = \var{itemlist}}.
1766 The \var{itemlist} may be \NULL{}, indicating the assignment
1767 of an empty list (slice deletion).
1768 Returns \code{0} on success, \code{-1} on failure.
Fred Drake3adf79e2001-10-12 19:01:43 +00001769\end{cfuncdesc}
1770
1771\begin{cfuncdesc}{int}{PyList_Sort}{PyObject *list}
1772 Sorts the items of \var{list} in place. Returns \code{0} on
1773 success, \code{-1} on failure. This is equivalent to
1774 \samp{\var{list}.sort()}.
1775\end{cfuncdesc}
1776
1777\begin{cfuncdesc}{int}{PyList_Reverse}{PyObject *list}
1778 Reverses the items of \var{list} in place. Returns \code{0} on
1779 success, \code{-1} on failure. This is the equivalent of
1780 \samp{\var{list}.reverse()}.
1781\end{cfuncdesc}
1782
1783\begin{cfuncdesc}{PyObject*}{PyList_AsTuple}{PyObject *list}
1784 Returns a new tuple object containing the contents of \var{list};
1785 equivalent to \samp{tuple(\var{list})}.\bifuncindex{tuple}
1786\end{cfuncdesc}
1787
1788
1789\section{Mapping Objects \label{mapObjects}}
1790
1791\obindex{mapping}
1792
1793
1794\subsection{Dictionary Objects \label{dictObjects}}
1795
1796\obindex{dictionary}
1797\begin{ctypedesc}{PyDictObject}
1798 This subtype of \ctype{PyObject} represents a Python dictionary
1799 object.
1800\end{ctypedesc}
1801
1802\begin{cvardesc}{PyTypeObject}{PyDict_Type}
1803 This instance of \ctype{PyTypeObject} represents the Python
1804 dictionary type. This is exposed to Python programs as
1805 \code{types.DictType} and \code{types.DictionaryType}.
1806 \withsubitem{(in module types)}{\ttindex{DictType}\ttindex{DictionaryType}}
1807\end{cvardesc}
1808
1809\begin{cfuncdesc}{int}{PyDict_Check}{PyObject *p}
Andrew MacIntyre13cd8892003-12-25 23:57:52 +00001810 Returns true if \var{p} is a dict object or an instance of a
1811 subtype of the dict type.
1812 \versionchanged[Allowed subtypes to be accepted]{2.2}
Fred Drake3adf79e2001-10-12 19:01:43 +00001813\end{cfuncdesc}
1814
Andrew MacIntyref72af652003-12-26 00:07:51 +00001815\begin{cfuncdesc}{int}{PyDict_CheckExact}{PyObject *p}
1816 Return true if \var{p} is a dict object, but not an instance of a
1817 subtype of the dict type.
1818 \versionadded{2.4}
1819\end{cfuncdesc}
1820
Fred Drake3adf79e2001-10-12 19:01:43 +00001821\begin{cfuncdesc}{PyObject*}{PyDict_New}{}
1822 Returns a new empty dictionary, or \NULL{} on failure.
1823\end{cfuncdesc}
1824
1825\begin{cfuncdesc}{PyObject*}{PyDictProxy_New}{PyObject *dict}
1826 Return a proxy object for a mapping which enforces read-only
1827 behavior. This is normally used to create a proxy to prevent
1828 modification of the dictionary for non-dynamic class types.
1829 \versionadded{2.2}
1830\end{cfuncdesc}
1831
1832\begin{cfuncdesc}{void}{PyDict_Clear}{PyObject *p}
1833 Empties an existing dictionary of all key-value pairs.
1834\end{cfuncdesc}
1835
Raymond Hettingerbc0f2ab2003-11-25 21:12:14 +00001836\begin{cfuncdesc}{int}{PyDict_Contains}{PyObject *p, PyObject *key}
1837 Determine if dictionary \var{p} contains \var{key}. If an item
1838 in \var{p} is matches \var{key}, return \code{1}, otherwise return
1839 \code{0}. On error, return \code{-1}. This is equivalent to the
1840 Python expression \samp{\var{key} in \var{p}}.
1841 \versionadded{2.4}
1842\end{cfuncdesc}
1843
Fred Drake3adf79e2001-10-12 19:01:43 +00001844\begin{cfuncdesc}{PyObject*}{PyDict_Copy}{PyObject *p}
1845 Returns a new dictionary that contains the same key-value pairs as
1846 \var{p}.
1847 \versionadded{1.6}
1848\end{cfuncdesc}
1849
1850\begin{cfuncdesc}{int}{PyDict_SetItem}{PyObject *p, PyObject *key,
1851 PyObject *val}
1852 Inserts \var{value} into the dictionary \var{p} with a key of
1853 \var{key}. \var{key} must be hashable; if it isn't,
1854 \exception{TypeError} will be raised.
1855 Returns \code{0} on success or \code{-1} on failure.
1856\end{cfuncdesc}
1857
1858\begin{cfuncdesc}{int}{PyDict_SetItemString}{PyObject *p,
1859 char *key,
1860 PyObject *val}
1861 Inserts \var{value} into the dictionary \var{p} using \var{key} as a
1862 key. \var{key} should be a \ctype{char*}. The key object is created
1863 using \code{PyString_FromString(\var{key})}. Returns \code{0} on
1864 success or \code{-1} on failure.
1865 \ttindex{PyString_FromString()}
1866\end{cfuncdesc}
1867
1868\begin{cfuncdesc}{int}{PyDict_DelItem}{PyObject *p, PyObject *key}
1869 Removes the entry in dictionary \var{p} with key \var{key}.
1870 \var{key} must be hashable; if it isn't, \exception{TypeError} is
Skip Montanaroa23bc422002-01-23 08:18:30 +00001871 raised. Returns \code{0} on success or \code{-1} on failure.
Fred Drake3adf79e2001-10-12 19:01:43 +00001872\end{cfuncdesc}
1873
1874\begin{cfuncdesc}{int}{PyDict_DelItemString}{PyObject *p, char *key}
1875 Removes the entry in dictionary \var{p} which has a key specified by
1876 the string \var{key}. Returns \code{0} on success or \code{-1} on
1877 failure.
1878\end{cfuncdesc}
1879
1880\begin{cfuncdesc}{PyObject*}{PyDict_GetItem}{PyObject *p, PyObject *key}
1881 Returns the object from dictionary \var{p} which has a key
1882 \var{key}. Returns \NULL{} if the key \var{key} is not present, but
1883 \emph{without} setting an exception.
1884\end{cfuncdesc}
1885
1886\begin{cfuncdesc}{PyObject*}{PyDict_GetItemString}{PyObject *p, char *key}
1887 This is the same as \cfunction{PyDict_GetItem()}, but \var{key} is
1888 specified as a \ctype{char*}, rather than a \ctype{PyObject*}.
1889\end{cfuncdesc}
1890
1891\begin{cfuncdesc}{PyObject*}{PyDict_Items}{PyObject *p}
1892 Returns a \ctype{PyListObject} containing all the items from the
1893 dictionary, as in the dictinoary method \method{items()} (see the
1894 \citetitle[../lib/lib.html]{Python Library Reference}).
1895\end{cfuncdesc}
1896
1897\begin{cfuncdesc}{PyObject*}{PyDict_Keys}{PyObject *p}
1898 Returns a \ctype{PyListObject} containing all the keys from the
1899 dictionary, as in the dictionary method \method{keys()} (see the
1900 \citetitle[../lib/lib.html]{Python Library Reference}).
1901\end{cfuncdesc}
1902
1903\begin{cfuncdesc}{PyObject*}{PyDict_Values}{PyObject *p}
1904 Returns a \ctype{PyListObject} containing all the values from the
1905 dictionary \var{p}, as in the dictionary method \method{values()}
1906 (see the \citetitle[../lib/lib.html]{Python Library Reference}).
1907\end{cfuncdesc}
1908
1909\begin{cfuncdesc}{int}{PyDict_Size}{PyObject *p}
1910 Returns the number of items in the dictionary. This is equivalent
1911 to \samp{len(\var{p})} on a dictionary.\bifuncindex{len}
1912\end{cfuncdesc}
1913
1914\begin{cfuncdesc}{int}{PyDict_Next}{PyObject *p, int *ppos,
1915 PyObject **pkey, PyObject **pvalue}
1916 Iterate over all key-value pairs in the dictionary \var{p}. The
1917 \ctype{int} referred to by \var{ppos} must be initialized to
1918 \code{0} prior to the first call to this function to start the
1919 iteration; the function returns true for each pair in the
1920 dictionary, and false once all pairs have been reported. The
1921 parameters \var{pkey} and \var{pvalue} should either point to
1922 \ctype{PyObject*} variables that will be filled in with each key and
Skip Montanaroea3ceaa2002-01-23 10:54:41 +00001923 value, respectively, or may be \NULL. Any references returned through
Raymond Hettinger54693242003-12-13 19:48:41 +00001924 them are borrowed. \var{ppos} should not be altered during iteration.
1925 Its value represents offsets within the internal dictionary structure,
1926 and since the structure is sparse, the offsets are not consecutive.
Fred Drake3adf79e2001-10-12 19:01:43 +00001927
1928 For example:
1929
1930\begin{verbatim}
1931PyObject *key, *value;
1932int pos = 0;
1933
1934while (PyDict_Next(self->dict, &pos, &key, &value)) {
1935 /* do something interesting with the values... */
1936 ...
1937}
1938\end{verbatim}
1939
1940 The dictionary \var{p} should not be mutated during iteration. It
1941 is safe (since Python 2.1) to modify the values of the keys as you
1942 iterate over the dictionary, but only so long as the set of keys
1943 does not change. For example:
1944
1945\begin{verbatim}
1946PyObject *key, *value;
1947int pos = 0;
1948
1949while (PyDict_Next(self->dict, &pos, &key, &value)) {
1950 int i = PyInt_AS_LONG(value) + 1;
1951 PyObject *o = PyInt_FromLong(i);
1952 if (o == NULL)
1953 return -1;
1954 if (PyDict_SetItem(self->dict, key, o) < 0) {
1955 Py_DECREF(o);
1956 return -1;
1957 }
1958 Py_DECREF(o);
1959}
1960\end{verbatim}
1961\end{cfuncdesc}
1962
1963\begin{cfuncdesc}{int}{PyDict_Merge}{PyObject *a, PyObject *b, int override}
Tim Petersf582b822001-12-11 18:51:08 +00001964 Iterate over mapping object \var{b} adding key-value pairs to dictionary
1965 \var{a}.
1966 \var{b} may be a dictionary, or any object supporting
1967 \function{PyMapping_Keys()} and \function{PyObject_GetItem()}.
1968 If \var{override} is true, existing pairs in \var{a} will
Fred Drake3adf79e2001-10-12 19:01:43 +00001969 be replaced if a matching key is found in \var{b}, otherwise pairs
1970 will only be added if there is not a matching key in \var{a}.
Tim Petersf582b822001-12-11 18:51:08 +00001971 Return \code{0} on success or \code{-1} if an exception was
Fred Drake3adf79e2001-10-12 19:01:43 +00001972 raised.
1973\versionadded{2.2}
1974\end{cfuncdesc}
1975
1976\begin{cfuncdesc}{int}{PyDict_Update}{PyObject *a, PyObject *b}
1977 This is the same as \code{PyDict_Merge(\var{a}, \var{b}, 1)} in C,
Tim Petersf582b822001-12-11 18:51:08 +00001978 or \code{\var{a}.update(\var{b})} in Python. Return \code{0} on
Fred Drake3adf79e2001-10-12 19:01:43 +00001979 success or \code{-1} if an exception was raised.
1980 \versionadded{2.2}
1981\end{cfuncdesc}
1982
Tim Petersf582b822001-12-11 18:51:08 +00001983\begin{cfuncdesc}{int}{PyDict_MergeFromSeq2}{PyObject *a, PyObject *seq2,
1984 int override}
1985 Update or merge into dictionary \var{a}, from the key-value pairs in
1986 \var{seq2}. \var{seq2} must be an iterable object producing
1987 iterable objects of length 2, viewed as key-value pairs. In case of
1988 duplicate keys, the last wins if \var{override} is true, else the
1989 first wins.
1990 Return \code{0} on success or \code{-1} if an exception
1991 was raised.
1992 Equivalent Python (except for the return value):
1993
1994\begin{verbatim}
1995def PyDict_MergeFromSeq2(a, seq2, override):
1996 for key, value in seq2:
1997 if override or key not in a:
1998 a[key] = value
1999\end{verbatim}
2000
2001 \versionadded{2.2}
2002\end{cfuncdesc}
Fred Drake3adf79e2001-10-12 19:01:43 +00002003
Fred Drake54e62942001-12-11 19:40:16 +00002004
Fred Drake3adf79e2001-10-12 19:01:43 +00002005\section{Other Objects \label{otherObjects}}
2006
2007\subsection{File Objects \label{fileObjects}}
2008
2009\obindex{file}
2010Python's built-in file objects are implemented entirely on the
2011\ctype{FILE*} support from the C standard library. This is an
2012implementation detail and may change in future releases of Python.
2013
2014\begin{ctypedesc}{PyFileObject}
2015 This subtype of \ctype{PyObject} represents a Python file object.
2016\end{ctypedesc}
2017
2018\begin{cvardesc}{PyTypeObject}{PyFile_Type}
2019 This instance of \ctype{PyTypeObject} represents the Python file
2020 type. This is exposed to Python programs as \code{types.FileType}.
2021 \withsubitem{(in module types)}{\ttindex{FileType}}
2022\end{cvardesc}
2023
2024\begin{cfuncdesc}{int}{PyFile_Check}{PyObject *p}
2025 Returns true if its argument is a \ctype{PyFileObject} or a subtype
2026 of \ctype{PyFileObject}.
2027 \versionchanged[Allowed subtypes to be accepted]{2.2}
2028\end{cfuncdesc}
2029
2030\begin{cfuncdesc}{int}{PyFile_CheckExact}{PyObject *p}
2031 Returns true if its argument is a \ctype{PyFileObject}, but not a
2032 subtype of \ctype{PyFileObject}.
2033 \versionadded{2.2}
2034\end{cfuncdesc}
2035
2036\begin{cfuncdesc}{PyObject*}{PyFile_FromString}{char *filename, char *mode}
2037 On success, returns a new file object that is opened on the file
2038 given by \var{filename}, with a file mode given by \var{mode}, where
2039 \var{mode} has the same semantics as the standard C routine
2040 \cfunction{fopen()}\ttindex{fopen()}. On failure, returns \NULL.
2041\end{cfuncdesc}
2042
2043\begin{cfuncdesc}{PyObject*}{PyFile_FromFile}{FILE *fp,
2044 char *name, char *mode,
2045 int (*close)(FILE*)}
2046 Creates a new \ctype{PyFileObject} from the already-open standard C
2047 file pointer, \var{fp}. The function \var{close} will be called
2048 when the file should be closed. Returns \NULL{} on failure.
2049\end{cfuncdesc}
2050
2051\begin{cfuncdesc}{FILE*}{PyFile_AsFile}{PyFileObject *p}
2052 Returns the file object associated with \var{p} as a \ctype{FILE*}.
2053\end{cfuncdesc}
2054
2055\begin{cfuncdesc}{PyObject*}{PyFile_GetLine}{PyObject *p, int n}
2056 Equivalent to \code{\var{p}.readline(\optional{\var{n}})}, this
2057 function reads one line from the object \var{p}. \var{p} may be a
2058 file object or any object with a \method{readline()} method. If
2059 \var{n} is \code{0}, exactly one line is read, regardless of the
2060 length of the line. If \var{n} is greater than \code{0}, no more
2061 than \var{n} bytes will be read from the file; a partial line can be
2062 returned. In both cases, an empty string is returned if the end of
2063 the file is reached immediately. If \var{n} is less than \code{0},
2064 however, one line is read regardless of length, but
2065 \exception{EOFError} is raised if the end of the file is reached
2066 immediately.
2067 \withsubitem{(built-in exception)}{\ttindex{EOFError}}
2068\end{cfuncdesc}
2069
2070\begin{cfuncdesc}{PyObject*}{PyFile_Name}{PyObject *p}
2071 Returns the name of the file specified by \var{p} as a string
2072 object.
2073\end{cfuncdesc}
2074
2075\begin{cfuncdesc}{void}{PyFile_SetBufSize}{PyFileObject *p, int n}
2076 Available on systems with \cfunction{setvbuf()}\ttindex{setvbuf()}
2077 only. This should only be called immediately after file object
2078 creation.
2079\end{cfuncdesc}
2080
Martin v. Löwis5467d4c2003-05-10 07:10:12 +00002081\begin{cfuncdesc}{int}{PyFile_Encoding}{PyFileObject *p, char *enc}
2082 Set the file's encoding for Unicode output to \var{enc}. Return
2083 1 on success and 0 on failure.
2084 \versionadded{2.3}
2085\end{cfuncdesc}
2086
Fred Drake3adf79e2001-10-12 19:01:43 +00002087\begin{cfuncdesc}{int}{PyFile_SoftSpace}{PyObject *p, int newflag}
2088 This function exists for internal use by the interpreter. Sets the
2089 \member{softspace} attribute of \var{p} to \var{newflag} and
2090 \withsubitem{(file attribute)}{\ttindex{softspace}}returns the
2091 previous value. \var{p} does not have to be a file object for this
2092 function to work properly; any object is supported (thought its only
2093 interesting if the \member{softspace} attribute can be set). This
2094 function clears any errors, and will return \code{0} as the previous
2095 value if the attribute either does not exist or if there were errors
2096 in retrieving it. There is no way to detect errors from this
2097 function, but doing so should not be needed.
2098\end{cfuncdesc}
2099
2100\begin{cfuncdesc}{int}{PyFile_WriteObject}{PyObject *obj, PyFileObject *p,
2101 int flags}
2102 Writes object \var{obj} to file object \var{p}. The only supported
2103 flag for \var{flags} is
2104 \constant{Py_PRINT_RAW}\ttindex{Py_PRINT_RAW}; if given, the
2105 \function{str()} of the object is written instead of the
2106 \function{repr()}. Returns \code{0} on success or \code{-1} on
2107 failure; the appropriate exception will be set.
2108\end{cfuncdesc}
2109
Fred Drake454af892001-11-29 22:42:59 +00002110\begin{cfuncdesc}{int}{PyFile_WriteString}{const char *s, PyFileObject *p}
Fred Drake3adf79e2001-10-12 19:01:43 +00002111 Writes string \var{s} to file object \var{p}. Returns \code{0} on
2112 success or \code{-1} on failure; the appropriate exception will be
2113 set.
2114\end{cfuncdesc}
2115
2116
2117\subsection{Instance Objects \label{instanceObjects}}
2118
2119\obindex{instance}
2120There are very few functions specific to instance objects.
2121
2122\begin{cvardesc}{PyTypeObject}{PyInstance_Type}
2123 Type object for class instances.
2124\end{cvardesc}
2125
2126\begin{cfuncdesc}{int}{PyInstance_Check}{PyObject *obj}
2127 Returns true if \var{obj} is an instance.
2128\end{cfuncdesc}
2129
2130\begin{cfuncdesc}{PyObject*}{PyInstance_New}{PyObject *class,
2131 PyObject *arg,
2132 PyObject *kw}
2133 Create a new instance of a specific class. The parameters \var{arg}
2134 and \var{kw} are used as the positional and keyword parameters to
2135 the object's constructor.
2136\end{cfuncdesc}
2137
2138\begin{cfuncdesc}{PyObject*}{PyInstance_NewRaw}{PyObject *class,
2139 PyObject *dict}
2140 Create a new instance of a specific class without calling it's
2141 constructor. \var{class} is the class of new object. The
2142 \var{dict} parameter will be used as the object's \member{__dict__};
2143 if \NULL, a new dictionary will be created for the instance.
2144\end{cfuncdesc}
2145
2146
2147\subsection{Method Objects \label{method-objects}}
2148
2149\obindex{method}
2150There are some useful functions that are useful for working with
2151method objects.
2152
2153\begin{cvardesc}{PyTypeObject}{PyMethod_Type}
2154 This instance of \ctype{PyTypeObject} represents the Python method
2155 type. This is exposed to Python programs as \code{types.MethodType}.
2156 \withsubitem{(in module types)}{\ttindex{MethodType}}
2157\end{cvardesc}
2158
2159\begin{cfuncdesc}{int}{PyMethod_Check}{PyObject *o}
2160 Return true if \var{o} is a method object (has type
2161 \cdata{PyMethod_Type}). The parameter must not be \NULL.
2162\end{cfuncdesc}
2163
2164\begin{cfuncdesc}{PyObject*}{PyMethod_New}{PyObject *func.
2165 PyObject *self, PyObject *class}
2166 Return a new method object, with \var{func} being any callable
2167 object; this is the function that will be called when the method is
2168 called. If this method should be bound to an instance, \var{self}
2169 should be the instance and \var{class} should be the class of
2170 \var{self}, otherwise \var{self} should be \NULL{} and \var{class}
2171 should be the class which provides the unbound method..
2172\end{cfuncdesc}
2173
2174\begin{cfuncdesc}{PyObject*}{PyMethod_Class}{PyObject *meth}
2175 Return the class object from which the method \var{meth} was
2176 created; if this was created from an instance, it will be the class
2177 of the instance.
2178\end{cfuncdesc}
2179
2180\begin{cfuncdesc}{PyObject*}{PyMethod_GET_CLASS}{PyObject *meth}
2181 Macro version of \cfunction{PyMethod_Class()} which avoids error
2182 checking.
2183\end{cfuncdesc}
2184
2185\begin{cfuncdesc}{PyObject*}{PyMethod_Function}{PyObject *meth}
2186 Return the function object associated with the method \var{meth}.
2187\end{cfuncdesc}
2188
2189\begin{cfuncdesc}{PyObject*}{PyMethod_GET_FUNCTION}{PyObject *meth}
2190 Macro version of \cfunction{PyMethod_Function()} which avoids error
2191 checking.
2192\end{cfuncdesc}
2193
2194\begin{cfuncdesc}{PyObject*}{PyMethod_Self}{PyObject *meth}
2195 Return the instance associated with the method \var{meth} if it is
2196 bound, otherwise return \NULL.
2197\end{cfuncdesc}
2198
2199\begin{cfuncdesc}{PyObject*}{PyMethod_GET_SELF}{PyObject *meth}
2200 Macro version of \cfunction{PyMethod_Self()} which avoids error
2201 checking.
2202\end{cfuncdesc}
2203
2204
2205\subsection{Module Objects \label{moduleObjects}}
2206
2207\obindex{module}
2208There are only a few functions special to module objects.
2209
2210\begin{cvardesc}{PyTypeObject}{PyModule_Type}
2211 This instance of \ctype{PyTypeObject} represents the Python module
2212 type. This is exposed to Python programs as
2213 \code{types.ModuleType}.
2214 \withsubitem{(in module types)}{\ttindex{ModuleType}}
2215\end{cvardesc}
2216
2217\begin{cfuncdesc}{int}{PyModule_Check}{PyObject *p}
2218 Returns true if \var{p} is a module object, or a subtype of a module
2219 object.
2220 \versionchanged[Allowed subtypes to be accepted]{2.2}
2221\end{cfuncdesc}
2222
2223\begin{cfuncdesc}{int}{PyModule_CheckExact}{PyObject *p}
2224 Returns true if \var{p} is a module object, but not a subtype of
2225 \cdata{PyModule_Type}.
2226 \versionadded{2.2}
2227\end{cfuncdesc}
2228
2229\begin{cfuncdesc}{PyObject*}{PyModule_New}{char *name}
2230 Return a new module object with the \member{__name__} attribute set
2231 to \var{name}. Only the module's \member{__doc__} and
2232 \member{__name__} attributes are filled in; the caller is
2233 responsible for providing a \member{__file__} attribute.
2234 \withsubitem{(module attribute)}{
2235 \ttindex{__name__}\ttindex{__doc__}\ttindex{__file__}}
2236\end{cfuncdesc}
2237
2238\begin{cfuncdesc}{PyObject*}{PyModule_GetDict}{PyObject *module}
2239 Return the dictionary object that implements \var{module}'s
2240 namespace; this object is the same as the \member{__dict__}
2241 attribute of the module object. This function never fails.
2242 \withsubitem{(module attribute)}{\ttindex{__dict__}}
Fred Drakef495ef72002-04-12 19:32:07 +00002243 It is recommended extensions use other \cfunction{PyModule_*()}
2244 and \cfunction{PyObject_*()} functions rather than directly
2245 manipulate a module's \member{__dict__}.
Fred Drake3adf79e2001-10-12 19:01:43 +00002246\end{cfuncdesc}
2247
2248\begin{cfuncdesc}{char*}{PyModule_GetName}{PyObject *module}
2249 Return \var{module}'s \member{__name__} value. If the module does
2250 not provide one, or if it is not a string, \exception{SystemError}
2251 is raised and \NULL{} is returned.
2252 \withsubitem{(module attribute)}{\ttindex{__name__}}
2253 \withsubitem{(built-in exception)}{\ttindex{SystemError}}
2254\end{cfuncdesc}
2255
2256\begin{cfuncdesc}{char*}{PyModule_GetFilename}{PyObject *module}
2257 Return the name of the file from which \var{module} was loaded using
2258 \var{module}'s \member{__file__} attribute. If this is not defined,
2259 or if it is not a string, raise \exception{SystemError} and return
2260 \NULL.
2261 \withsubitem{(module attribute)}{\ttindex{__file__}}
2262 \withsubitem{(built-in exception)}{\ttindex{SystemError}}
2263\end{cfuncdesc}
2264
2265\begin{cfuncdesc}{int}{PyModule_AddObject}{PyObject *module,
2266 char *name, PyObject *value}
2267 Add an object to \var{module} as \var{name}. This is a convenience
2268 function which can be used from the module's initialization
2269 function. This steals a reference to \var{value}. Returns
2270 \code{-1} on error, \code{0} on success.
2271 \versionadded{2.0}
2272\end{cfuncdesc}
2273
2274\begin{cfuncdesc}{int}{PyModule_AddIntConstant}{PyObject *module,
Martin v. Löwisdd07e592004-06-02 12:45:27 +00002275 char *name, long value}
Fred Drake3adf79e2001-10-12 19:01:43 +00002276 Add an integer constant to \var{module} as \var{name}. This
2277 convenience function can be used from the module's initialization
2278 function. Returns \code{-1} on error, \code{0} on success.
2279 \versionadded{2.0}
2280\end{cfuncdesc}
2281
2282\begin{cfuncdesc}{int}{PyModule_AddStringConstant}{PyObject *module,
2283 char *name, char *value}
2284 Add a string constant to \var{module} as \var{name}. This
2285 convenience function can be used from the module's initialization
2286 function. The string \var{value} must be null-terminated. Returns
2287 \code{-1} on error, \code{0} on success.
2288 \versionadded{2.0}
2289\end{cfuncdesc}
2290
2291
2292\subsection{Iterator Objects \label{iterator-objects}}
2293
2294Python provides two general-purpose iterator objects. The first, a
2295sequence iterator, works with an arbitrary sequence supporting the
2296\method{__getitem__()} method. The second works with a callable
2297object and a sentinel value, calling the callable for each item in the
2298sequence, and ending the iteration when the sentinel value is
2299returned.
2300
2301\begin{cvardesc}{PyTypeObject}{PySeqIter_Type}
2302 Type object for iterator objects returned by
2303 \cfunction{PySeqIter_New()} and the one-argument form of the
2304 \function{iter()} built-in function for built-in sequence types.
2305 \versionadded{2.2}
2306\end{cvardesc}
2307
2308\begin{cfuncdesc}{int}{PySeqIter_Check}{op}
2309 Return true if the type of \var{op} is \cdata{PySeqIter_Type}.
2310 \versionadded{2.2}
2311\end{cfuncdesc}
2312
2313\begin{cfuncdesc}{PyObject*}{PySeqIter_New}{PyObject *seq}
2314 Return an iterator that works with a general sequence object,
2315 \var{seq}. The iteration ends when the sequence raises
2316 \exception{IndexError} for the subscripting operation.
2317 \versionadded{2.2}
2318\end{cfuncdesc}
2319
2320\begin{cvardesc}{PyTypeObject}{PyCallIter_Type}
2321 Type object for iterator objects returned by
2322 \cfunction{PyCallIter_New()} and the two-argument form of the
2323 \function{iter()} built-in function.
2324 \versionadded{2.2}
2325\end{cvardesc}
2326
2327\begin{cfuncdesc}{int}{PyCallIter_Check}{op}
2328 Return true if the type of \var{op} is \cdata{PyCallIter_Type}.
2329 \versionadded{2.2}
2330\end{cfuncdesc}
2331
2332\begin{cfuncdesc}{PyObject*}{PyCallIter_New}{PyObject *callable,
2333 PyObject *sentinel}
2334 Return a new iterator. The first parameter, \var{callable}, can be
2335 any Python callable object that can be called with no parameters;
2336 each call to it should return the next item in the iteration. When
2337 \var{callable} returns a value equal to \var{sentinel}, the
2338 iteration will be terminated.
2339 \versionadded{2.2}
2340\end{cfuncdesc}
2341
2342
2343\subsection{Descriptor Objects \label{descriptor-objects}}
2344
Fred Drake54e62942001-12-11 19:40:16 +00002345``Descriptors'' are objects that describe some attribute of an object.
2346They are found in the dictionary of type objects.
2347
Fred Drake3adf79e2001-10-12 19:01:43 +00002348\begin{cvardesc}{PyTypeObject}{PyProperty_Type}
Fred Drake54e62942001-12-11 19:40:16 +00002349 The type object for the built-in descriptor types.
Fred Drake3adf79e2001-10-12 19:01:43 +00002350 \versionadded{2.2}
2351\end{cvardesc}
2352
2353\begin{cfuncdesc}{PyObject*}{PyDescr_NewGetSet}{PyTypeObject *type,
2354 PyGetSetDef *getset}
2355 \versionadded{2.2}
2356\end{cfuncdesc}
2357
2358\begin{cfuncdesc}{PyObject*}{PyDescr_NewMember}{PyTypeObject *type,
2359 PyMemberDef *meth}
2360 \versionadded{2.2}
2361\end{cfuncdesc}
2362
2363\begin{cfuncdesc}{PyObject*}{PyDescr_NewMethod}{PyTypeObject *type,
2364 PyMethodDef *meth}
2365 \versionadded{2.2}
2366\end{cfuncdesc}
2367
2368\begin{cfuncdesc}{PyObject*}{PyDescr_NewWrapper}{PyTypeObject *type,
2369 struct wrapperbase *wrapper,
2370 void *wrapped}
2371 \versionadded{2.2}
2372\end{cfuncdesc}
2373
Thomas Heller8178a222004-02-09 10:47:11 +00002374\begin{cfuncdesc}{PyObject*}{PyDescr_NewClassMethod}{PyTypeObject *type,
2375 PyMethodDef *method}
2376 \versionadded{2.3}
2377\end{cfuncdesc}
2378
Fred Drake3adf79e2001-10-12 19:01:43 +00002379\begin{cfuncdesc}{int}{PyDescr_IsData}{PyObject *descr}
2380 Returns true if the descriptor objects \var{descr} describes a data
2381 attribute, or false if it describes a method. \var{descr} must be a
2382 descriptor object; there is no error checking.
2383 \versionadded{2.2}
2384\end{cfuncdesc}
2385
2386\begin{cfuncdesc}{PyObject*}{PyWrapper_New}{PyObject *, PyObject *}
2387 \versionadded{2.2}
2388\end{cfuncdesc}
2389
2390
2391\subsection{Slice Objects \label{slice-objects}}
2392
2393\begin{cvardesc}{PyTypeObject}{PySlice_Type}
2394 The type object for slice objects. This is the same as
2395 \code{types.SliceType}.
2396 \withsubitem{(in module types)}{\ttindex{SliceType}}
2397\end{cvardesc}
2398
2399\begin{cfuncdesc}{int}{PySlice_Check}{PyObject *ob}
2400 Returns true if \var{ob} is a slice object; \var{ob} must not be
2401 \NULL.
2402\end{cfuncdesc}
2403
2404\begin{cfuncdesc}{PyObject*}{PySlice_New}{PyObject *start, PyObject *stop,
2405 PyObject *step}
2406 Return a new slice object with the given values. The \var{start},
2407 \var{stop}, and \var{step} parameters are used as the values of the
2408 slice object attributes of the same names. Any of the values may be
2409 \NULL, in which case the \code{None} will be used for the
2410 corresponding attribute. Returns \NULL{} if the new object could
2411 not be allocated.
2412\end{cfuncdesc}
2413
2414\begin{cfuncdesc}{int}{PySlice_GetIndices}{PySliceObject *slice, int length,
2415 int *start, int *stop, int *step}
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002416Retrieve the start, stop and step indices from the slice object
2417\var{slice}, assuming a sequence of length \var{length}. Treats
2418indices greater than \var{length} as errors.
2419
2420Returns 0 on success and -1 on error with no exception set (unless one
2421of the indices was not \constant{None} and failed to be converted to
2422an integer, in which case -1 is returned with an exception set).
2423
2424You probably do not want to use this function. If you want to use
2425slice objects in versions of Python prior to 2.3, you would probably
2426do well to incorporate the source of \cfunction{PySlice_GetIndicesEx},
2427suitably renamed, in the source of your extension.
2428\end{cfuncdesc}
2429
2430\begin{cfuncdesc}{int}{PySlice_GetIndicesEx}{PySliceObject *slice, int length,
2431 int *start, int *stop, int *step,
2432 int *slicelength}
2433Usable replacement for \cfunction{PySlice_GetIndices}. Retrieve the
2434start, stop, and step indices from the slice object \var{slice}
2435assuming a sequence of length \var{length}, and store the length of
2436the slice in \var{slicelength}. Out of bounds indices are clipped in
2437a manner consistent with the handling of normal slices.
2438
2439Returns 0 on success and -1 on error with exception set.
2440
2441\versionadded{2.3}
Fred Drake3adf79e2001-10-12 19:01:43 +00002442\end{cfuncdesc}
2443
2444
2445\subsection{Weak Reference Objects \label{weakref-objects}}
2446
2447Python supports \emph{weak references} as first-class objects. There
2448are two specific object types which directly implement weak
2449references. The first is a simple reference object, and the second
2450acts as a proxy for the original object as much as it can.
2451
2452\begin{cfuncdesc}{int}{PyWeakref_Check}{ob}
2453 Return true if \var{ob} is either a reference or proxy object.
2454 \versionadded{2.2}
2455\end{cfuncdesc}
2456
2457\begin{cfuncdesc}{int}{PyWeakref_CheckRef}{ob}
2458 Return true if \var{ob} is a reference object.
2459 \versionadded{2.2}
2460\end{cfuncdesc}
2461
2462\begin{cfuncdesc}{int}{PyWeakref_CheckProxy}{ob}
2463 Return true if \var{ob} is a proxy object.
2464 \versionadded{2.2}
2465\end{cfuncdesc}
2466
2467\begin{cfuncdesc}{PyObject*}{PyWeakref_NewRef}{PyObject *ob,
2468 PyObject *callback}
2469 Return a weak reference object for the object \var{ob}. This will
2470 always return a new reference, but is not guaranteed to create a new
2471 object; an existing reference object may be returned. The second
2472 parameter, \var{callback}, can be a callable object that receives
2473 notification when \var{ob} is garbage collected; it should accept a
Raymond Hettinger5232f502004-03-25 08:51:36 +00002474 single parameter, which will be the weak reference object itself.
Fred Drake3adf79e2001-10-12 19:01:43 +00002475 \var{callback} may also be \code{None} or \NULL. If \var{ob}
2476 is not a weakly-referencable object, or if \var{callback} is not
2477 callable, \code{None}, or \NULL, this will return \NULL{} and
2478 raise \exception{TypeError}.
2479 \versionadded{2.2}
2480\end{cfuncdesc}
2481
2482\begin{cfuncdesc}{PyObject*}{PyWeakref_NewProxy}{PyObject *ob,
2483 PyObject *callback}
2484 Return a weak reference proxy object for the object \var{ob}. This
2485 will always return a new reference, but is not guaranteed to create
2486 a new object; an existing proxy object may be returned. The second
2487 parameter, \var{callback}, can be a callable object that receives
2488 notification when \var{ob} is garbage collected; it should accept a
Raymond Hettinger5232f502004-03-25 08:51:36 +00002489 single parameter, which will be the weak reference object itself.
Fred Drake3adf79e2001-10-12 19:01:43 +00002490 \var{callback} may also be \code{None} or \NULL. If \var{ob} is not
2491 a weakly-referencable object, or if \var{callback} is not callable,
2492 \code{None}, or \NULL, this will return \NULL{} and raise
2493 \exception{TypeError}.
2494 \versionadded{2.2}
2495\end{cfuncdesc}
2496
2497\begin{cfuncdesc}{PyObject*}{PyWeakref_GetObject}{PyObject *ref}
2498 Returns the referenced object from a weak reference, \var{ref}. If
Ka-Ping Yeebd379e92003-03-28 18:07:16 +00002499 the referent is no longer live, returns \code{None}.
Fred Drake3adf79e2001-10-12 19:01:43 +00002500 \versionadded{2.2}
2501\end{cfuncdesc}
2502
2503\begin{cfuncdesc}{PyObject*}{PyWeakref_GET_OBJECT}{PyObject *ref}
2504 Similar to \cfunction{PyWeakref_GetObject()}, but implemented as a
2505 macro that does no error checking.
2506 \versionadded{2.2}
2507\end{cfuncdesc}
2508
2509
2510\subsection{CObjects \label{cObjects}}
2511
2512\obindex{CObject}
2513Refer to \emph{Extending and Embedding the Python Interpreter},
Fred Drake54e62942001-12-11 19:40:16 +00002514section~1.12, ``Providing a C API for an Extension Module,'' for more
Fred Drake3adf79e2001-10-12 19:01:43 +00002515information on using these objects.
2516
2517
2518\begin{ctypedesc}{PyCObject}
2519 This subtype of \ctype{PyObject} represents an opaque value, useful
2520 for C extension modules who need to pass an opaque value (as a
2521 \ctype{void*} pointer) through Python code to other C code. It is
2522 often used to make a C function pointer defined in one module
2523 available to other modules, so the regular import mechanism can be
2524 used to access C APIs defined in dynamically loaded modules.
2525\end{ctypedesc}
2526
2527\begin{cfuncdesc}{int}{PyCObject_Check}{PyObject *p}
Martin v. Löwis01a74b22003-10-19 18:30:01 +00002528 Return true if its argument is a \ctype{PyCObject}.
Fred Drake3adf79e2001-10-12 19:01:43 +00002529\end{cfuncdesc}
2530
Tim Petersf582b822001-12-11 18:51:08 +00002531\begin{cfuncdesc}{PyObject*}{PyCObject_FromVoidPtr}{void* cobj,
Fred Drake54e62942001-12-11 19:40:16 +00002532 void (*destr)(void *)}
Martin v. Löwis01a74b22003-10-19 18:30:01 +00002533 Create a \ctype{PyCObject} from the \code{void *}\var{cobj}. The
Fred Drake3adf79e2001-10-12 19:01:43 +00002534 \var{destr} function will be called when the object is reclaimed,
2535 unless it is \NULL.
2536\end{cfuncdesc}
2537
2538\begin{cfuncdesc}{PyObject*}{PyCObject_FromVoidPtrAndDesc}{void* cobj,
2539 void* desc, void (*destr)(void *, void *)}
Martin v. Löwis01a74b22003-10-19 18:30:01 +00002540 Create a \ctype{PyCObject} from the \ctype{void *}\var{cobj}. The
Fred Drake3adf79e2001-10-12 19:01:43 +00002541 \var{destr} function will be called when the object is reclaimed.
2542 The \var{desc} argument can be used to pass extra callback data for
2543 the destructor function.
2544\end{cfuncdesc}
2545
2546\begin{cfuncdesc}{void*}{PyCObject_AsVoidPtr}{PyObject* self}
Martin v. Löwis01a74b22003-10-19 18:30:01 +00002547 Return the object \ctype{void *} that the \ctype{PyCObject}
Fred Drake3adf79e2001-10-12 19:01:43 +00002548 \var{self} was created with.
2549\end{cfuncdesc}
2550
2551\begin{cfuncdesc}{void*}{PyCObject_GetDesc}{PyObject* self}
Martin v. Löwis01a74b22003-10-19 18:30:01 +00002552 Return the description \ctype{void *} that the \ctype{PyCObject}
Fred Drake3adf79e2001-10-12 19:01:43 +00002553 \var{self} was created with.
2554\end{cfuncdesc}
Fred Drakecd8474e2001-11-26 21:29:17 +00002555
Martin v. Löwis01a74b22003-10-19 18:30:01 +00002556\begin{cfuncdesc}{int}{PyCObject_SetVoidPtr}{PyObject* self, void* cobj}
2557 Set the void pointer inside \var{self} to \var{cobj}.
2558 The \ctype{PyCObject} must not have an associated destructor.
2559 Return true on success, false on failure.
2560\end{cfuncdesc}
2561
Fred Drakecd8474e2001-11-26 21:29:17 +00002562
2563\subsection{Cell Objects \label{cell-objects}}
2564
2565``Cell'' objects are used to implement variables referenced by
2566multiple scopes. For each such variable, a cell object is created to
2567store the value; the local variables of each stack frame that
2568references the value contains a reference to the cells from outer
2569scopes which also use that variable. When the value is accessed, the
2570value contained in the cell is used instead of the cell object
2571itself. This de-referencing of the cell object requires support from
2572the generated byte-code; these are not automatically de-referenced
2573when accessed. Cell objects are not likely to be useful elsewhere.
2574
Fred Drake54e62942001-12-11 19:40:16 +00002575\begin{ctypedesc}{PyCellObject}
2576 The C structure used for cell objects.
2577\end{ctypedesc}
2578
Fred Drakecd8474e2001-11-26 21:29:17 +00002579\begin{cvardesc}{PyTypeObject}{PyCell_Type}
2580 The type object corresponding to cell objects
2581\end{cvardesc}
2582
2583\begin{cfuncdesc}{int}{PyCell_Check}{ob}
2584 Return true if \var{ob} is a cell object; \var{ob} must not be
2585 \NULL.
2586\end{cfuncdesc}
2587
2588\begin{cfuncdesc}{PyObject*}{PyCell_New}{PyObject *ob}
2589 Create and return a new cell object containing the value \var{ob}.
2590 The parameter may be \NULL.
2591\end{cfuncdesc}
2592
2593\begin{cfuncdesc}{PyObject*}{PyCell_Get}{PyObject *cell}
2594 Return the contents of the cell \var{cell}.
2595\end{cfuncdesc}
2596
2597\begin{cfuncdesc}{PyObject*}{PyCell_GET}{PyObject *cell}
2598 Return the contents of the cell \var{cell}, but without checking
Raymond Hettingerf4bb1f92003-08-23 03:38:11 +00002599 that \var{cell} is non-\NULL{} and a cell object.
Fred Drakecd8474e2001-11-26 21:29:17 +00002600\end{cfuncdesc}
2601
2602\begin{cfuncdesc}{int}{PyCell_Set}{PyObject *cell, PyObject *value}
2603 Set the contents of the cell object \var{cell} to \var{value}. This
2604 releases the reference to any current content of the cell.
2605 \var{value} may be \NULL. \var{cell} must be non-\NULL; if it is
2606 not a cell object, \code{-1} will be returned. On success, \code{0}
2607 will be returned.
2608\end{cfuncdesc}
2609
2610\begin{cfuncdesc}{void}{PyCell_SET}{PyObject *cell, PyObject *value}
2611 Sets the value of the cell object \var{cell} to \var{value}. No
2612 reference counts are adjusted, and no checks are made for safety;
2613 \var{cell} must be non-\NULL{} and must be a cell object.
2614\end{cfuncdesc}
Martin v. Löwise440e472004-06-01 15:22:42 +00002615
2616
2617\subsection{Generator Objects \label{gen-objects}}
2618
2619Generator objects are what Python uses to implement generator iterators.
2620They are normally created by iterating over a function that yields values,
2621rather than explicitly calling \cfunction{PyGen_New}.
2622
2623\begin{ctypedesc}{PyGenObject}
2624 The C structure used for generator objects.
2625\end{ctypedesc}
2626
2627\begin{cvardesc}{PyTypeObject}{PyGen_Type}
2628 The type object corresponding to generator objects
2629\end{cvardesc}
2630
2631\begin{cfuncdesc}{int}{PyGen_Check}{ob}
2632 Return true if \var{ob} is a generator object; \var{ob} must not be
2633 \NULL.
2634\end{cfuncdesc}
2635
2636\begin{cfuncdesc}{int}{PyGen_CheckExact}{ob}
2637 Return true if \var{ob}'s type is \var{PyGen_Type}
2638 is a generator object; \var{ob} must not be
2639 \NULL.
2640\end{cfuncdesc}
2641
2642\begin{cfuncdesc}{PyObject*}{PyGen_New}{PyFrameObject *frame}
2643 Create and return a new generator object based on the \var{frame} object.
2644 The parameter must not be \NULL.
2645\end{cfuncdesc}