blob: c233ed4ed6d0361f7ab219cc6b116d39a52c9ee2 [file] [log] [blame]
Fred Drake3adf79e2001-10-12 19:01:43 +00001\chapter{Concrete Objects Layer \label{concrete}}
2
3
4The functions in this chapter are specific to certain Python object
5types. Passing them an object of the wrong type is not a good idea;
6if you receive an object from a Python program and you are not sure
7that it has the right type, you must perform a type check first;
8for example, to check that an object is a dictionary, use
9\cfunction{PyDict_Check()}. The chapter is structured like the
10``family tree'' of Python object types.
11
12\warning{While the functions described in this chapter carefully check
13the type of the objects which are passed in, many of them do not check
14for \NULL{} being passed instead of a valid object. Allowing \NULL{}
15to be passed in can cause memory access violations and immediate
16termination of the interpreter.}
17
18
19\section{Fundamental Objects \label{fundamental}}
20
Tim Petersf582b822001-12-11 18:51:08 +000021This section describes Python type objects and the singleton object
Fred Drake3adf79e2001-10-12 19:01:43 +000022\code{None}.
23
24
25\subsection{Type Objects \label{typeObjects}}
26
27\obindex{type}
28\begin{ctypedesc}{PyTypeObject}
29 The C structure of the objects used to describe built-in types.
30\end{ctypedesc}
31
32\begin{cvardesc}{PyObject*}{PyType_Type}
33 This is the type object for type objects; it is the same object as
34 \code{types.TypeType} in the Python layer.
35 \withsubitem{(in module types)}{\ttindex{TypeType}}
36\end{cvardesc}
37
38\begin{cfuncdesc}{int}{PyType_Check}{PyObject *o}
Fred Drakee3c764b2002-04-10 17:52:52 +000039 Returns true if the object \var{o} is a type object, including
40 instances of types derived from the standard type object. Returns
41 false in all other cases.
42\end{cfuncdesc}
43
44\begin{cfuncdesc}{int}{PyType_CheckExact}{PyObject *o}
45 Returns true if the object \var{o} is a type object, but not a
46 subtype of the standard type object. Returns false in all other
47 cases.
48 \versionadded{2.2}
Fred Drake3adf79e2001-10-12 19:01:43 +000049\end{cfuncdesc}
50
51\begin{cfuncdesc}{int}{PyType_HasFeature}{PyObject *o, int feature}
52 Returns true if the type object \var{o} sets the feature
53 \var{feature}. Type features are denoted by single bit flags.
54\end{cfuncdesc}
55
Fred Drakee3c764b2002-04-10 17:52:52 +000056\begin{cfuncdesc}{int}{PyType_IS_GC}{PyObject *o}
57 Return true if the type object includes support for the cycle
58 detector; this tests the type flag \constant{Py_TPFLAGS_HAVE_GC}.
59 \versionadded{2.0}
60\end{cfuncdesc}
61
Fred Drake3adf79e2001-10-12 19:01:43 +000062\begin{cfuncdesc}{int}{PyType_IsSubtype}{PyTypeObject *a, PyTypeObject *b}
63 Returns true if \var{a} is a subtype of \var{b}.
64 \versionadded{2.2}
65\end{cfuncdesc}
66
67\begin{cfuncdesc}{PyObject*}{PyType_GenericAlloc}{PyTypeObject *type,
68 int nitems}
69 \versionadded{2.2}
70\end{cfuncdesc}
71
72\begin{cfuncdesc}{PyObject*}{PyType_GenericNew}{PyTypeObject *type,
73 PyObject *args, PyObject *kwds}
74 \versionadded{2.2}
75\end{cfuncdesc}
76
77\begin{cfuncdesc}{int}{PyType_Ready}{PyTypeObject *type}
Fred Drake28de8d42002-04-12 16:15:10 +000078 Finalize a type object. This should be called on all type objects
79 to finish their initialization. This function is responsible for
80 adding inherited slots from a type's base class. Returns \code{0}
81 on success, or returns \code{-1} and sets an exception on error.
Fred Drake3adf79e2001-10-12 19:01:43 +000082 \versionadded{2.2}
83\end{cfuncdesc}
84
85
86\subsection{The None Object \label{noneObject}}
87
88\obindex{None@\texttt{None}}
89Note that the \ctype{PyTypeObject} for \code{None} is not directly
90exposed in the Python/C API. Since \code{None} is a singleton,
91testing for object identity (using \samp{==} in C) is sufficient.
92There is no \cfunction{PyNone_Check()} function for the same reason.
93
94\begin{cvardesc}{PyObject*}{Py_None}
95 The Python \code{None} object, denoting lack of value. This object
Fred Drake6ccdccd2002-03-12 20:12:54 +000096 has no methods. It needs to be treated just like any other object
97 with respect to reference counts.
Fred Drake3adf79e2001-10-12 19:01:43 +000098\end{cvardesc}
99
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
853These APIs can be used for fast direct character conversions:
854
855\begin{cfuncdesc}{Py_UNICODE}{Py_UNICODE_TOLOWER}{Py_UNICODE ch}
856 Returns the character \var{ch} converted to lower case.
857\end{cfuncdesc}
858
859\begin{cfuncdesc}{Py_UNICODE}{Py_UNICODE_TOUPPER}{Py_UNICODE ch}
860 Returns the character \var{ch} converted to upper case.
861\end{cfuncdesc}
862
863\begin{cfuncdesc}{Py_UNICODE}{Py_UNICODE_TOTITLE}{Py_UNICODE ch}
864 Returns the character \var{ch} converted to title case.
865\end{cfuncdesc}
866
867\begin{cfuncdesc}{int}{Py_UNICODE_TODECIMAL}{Py_UNICODE ch}
868 Returns the character \var{ch} converted to a decimal positive
869 integer. Returns \code{-1} if this is not possible. Does not raise
870 exceptions.
871\end{cfuncdesc}
872
873\begin{cfuncdesc}{int}{Py_UNICODE_TODIGIT}{Py_UNICODE ch}
874 Returns the character \var{ch} converted to a single digit integer.
875 Returns \code{-1} if this is not possible. Does not raise
876 exceptions.
877\end{cfuncdesc}
878
879\begin{cfuncdesc}{double}{Py_UNICODE_TONUMERIC}{Py_UNICODE ch}
880 Returns the character \var{ch} converted to a (positive) double.
881 Returns \code{-1.0} if this is not possible. Does not raise
882 exceptions.
883\end{cfuncdesc}
884
885% --- Plain Py_UNICODE ---------------------------------------------------
886
887To create Unicode objects and access their basic sequence properties,
888use these APIs:
889
890\begin{cfuncdesc}{PyObject*}{PyUnicode_FromUnicode}{const Py_UNICODE *u,
Tim Petersf582b822001-12-11 18:51:08 +0000891 int size}
Fred Drake3adf79e2001-10-12 19:01:43 +0000892 Create a Unicode Object from the Py_UNICODE buffer \var{u} of the
893 given size. \var{u} may be \NULL{} which causes the contents to be
894 undefined. It is the user's responsibility to fill in the needed
895 data. The buffer is copied into the new object. If the buffer is
896 not \NULL, the return value might be a shared object. Therefore,
897 modification of the resulting Unicode object is only allowed when
898 \var{u} is \NULL.
899\end{cfuncdesc}
900
901\begin{cfuncdesc}{Py_UNICODE*}{PyUnicode_AsUnicode}{PyObject *unicode}
902 Return a read-only pointer to the Unicode object's internal
903 \ctype{Py_UNICODE} buffer, \NULL{} if \var{unicode} is not a Unicode
904 object.
905\end{cfuncdesc}
906
907\begin{cfuncdesc}{int}{PyUnicode_GetSize}{PyObject *unicode}
908 Return the length of the Unicode object.
909\end{cfuncdesc}
910
911\begin{cfuncdesc}{PyObject*}{PyUnicode_FromEncodedObject}{PyObject *obj,
912 const char *encoding,
913 const char *errors}
914 Coerce an encoded object \var{obj} to an Unicode object and return a
915 reference with incremented refcount.
916
917 Coercion is done in the following way:
918
919\begin{enumerate}
920\item Unicode objects are passed back as-is with incremented
921 refcount. \note{These cannot be decoded; passing a non-\NULL{}
922 value for encoding will result in a \exception{TypeError}.}
923
924\item String and other char buffer compatible objects are decoded
925 according to the given encoding and using the error handling
926 defined by errors. Both can be \NULL{} to have the interface
927 use the default values (see the next section for details).
928
929\item All other objects cause an exception.
930\end{enumerate}
931
932 The API returns \NULL{} if there was an error. The caller is
933 responsible for decref'ing the returned objects.
934\end{cfuncdesc}
935
936\begin{cfuncdesc}{PyObject*}{PyUnicode_FromObject}{PyObject *obj}
937 Shortcut for \code{PyUnicode_FromEncodedObject(obj, NULL, "strict")}
938 which is used throughout the interpreter whenever coercion to
939 Unicode is needed.
940\end{cfuncdesc}
941
942% --- wchar_t support for platforms which support it ---------------------
943
944If the platform supports \ctype{wchar_t} and provides a header file
945wchar.h, Python can interface directly to this type using the
946following functions. Support is optimized if Python's own
947\ctype{Py_UNICODE} type is identical to the system's \ctype{wchar_t}.
948
949\begin{cfuncdesc}{PyObject*}{PyUnicode_FromWideChar}{const wchar_t *w,
950 int size}
Thomas Heller541703b2002-04-29 17:28:43 +0000951 Create a Unicode object from the \ctype{wchar_t} buffer \var{w} of
Fred Drake3adf79e2001-10-12 19:01:43 +0000952 the given size. Returns \NULL{} on failure.
953\end{cfuncdesc}
954
955\begin{cfuncdesc}{int}{PyUnicode_AsWideChar}{PyUnicodeObject *unicode,
956 wchar_t *w,
957 int size}
Thomas Heller541703b2002-04-29 17:28:43 +0000958 Copies the Unicode object contents into the \ctype{wchar_t} buffer
959 \var{w}. At most \var{size} \ctype{wchar_t} characters are copied.
960 Returns the number of \ctype{wchar_t} characters copied or -1 in
Fred Drake3adf79e2001-10-12 19:01:43 +0000961 case of an error.
962\end{cfuncdesc}
963
964
965\subsubsection{Built-in Codecs \label{builtinCodecs}}
966
967Python provides a set of builtin codecs which are written in C
968for speed. All of these codecs are directly usable via the
969following functions.
970
971Many of the following APIs take two arguments encoding and
972errors. These parameters encoding and errors have the same semantics
973as the ones of the builtin unicode() Unicode object constructor.
974
975Setting encoding to \NULL{} causes the default encoding to be used
976which is \ASCII. The file system calls should use
977\cdata{Py_FileSystemDefaultEncoding} as the encoding for file
978names. This variable should be treated as read-only: On some systems,
979it will be a pointer to a static string, on others, it will change at
Raymond Hettingercb2da432003-10-12 18:24:34 +0000980run-time (such as when the application invokes setlocale).
Fred Drake3adf79e2001-10-12 19:01:43 +0000981
982Error handling is set by errors which may also be set to \NULL{}
983meaning to use the default handling defined for the codec. Default
984error handling for all builtin codecs is ``strict''
985(\exception{ValueError} is raised).
986
987The codecs all use a similar interface. Only deviation from the
988following generic ones are documented for simplicity.
989
990% --- Generic Codecs -----------------------------------------------------
991
992These are the generic codec APIs:
993
994\begin{cfuncdesc}{PyObject*}{PyUnicode_Decode}{const char *s,
995 int size,
996 const char *encoding,
997 const char *errors}
998 Create a Unicode object by decoding \var{size} bytes of the encoded
999 string \var{s}. \var{encoding} and \var{errors} have the same
1000 meaning as the parameters of the same name in the
1001 \function{unicode()} builtin function. The codec to be used is
1002 looked up using the Python codec registry. Returns \NULL{} if an
1003 exception was raised by the codec.
1004\end{cfuncdesc}
1005
1006\begin{cfuncdesc}{PyObject*}{PyUnicode_Encode}{const Py_UNICODE *s,
1007 int size,
1008 const char *encoding,
1009 const char *errors}
1010 Encodes the \ctype{Py_UNICODE} buffer of the given size and returns
1011 a Python string object. \var{encoding} and \var{errors} have the
1012 same meaning as the parameters of the same name in the Unicode
1013 \method{encode()} method. The codec to be used is looked up using
1014 the Python codec registry. Returns \NULL{} if an exception was
1015 raised by the codec.
1016\end{cfuncdesc}
1017
1018\begin{cfuncdesc}{PyObject*}{PyUnicode_AsEncodedString}{PyObject *unicode,
1019 const char *encoding,
1020 const char *errors}
1021 Encodes a Unicode object and returns the result as Python string
1022 object. \var{encoding} and \var{errors} have the same meaning as the
1023 parameters of the same name in the Unicode \method{encode()} method.
1024 The codec to be used is looked up using the Python codec registry.
1025 Returns \NULL{} if an exception was raised by the codec.
1026\end{cfuncdesc}
1027
1028% --- UTF-8 Codecs -------------------------------------------------------
1029
1030These are the UTF-8 codec APIs:
1031
1032\begin{cfuncdesc}{PyObject*}{PyUnicode_DecodeUTF8}{const char *s,
1033 int size,
1034 const char *errors}
1035 Creates a Unicode object by decoding \var{size} bytes of the UTF-8
1036 encoded string \var{s}. Returns \NULL{} if an exception was raised
1037 by the codec.
1038\end{cfuncdesc}
1039
1040\begin{cfuncdesc}{PyObject*}{PyUnicode_EncodeUTF8}{const Py_UNICODE *s,
1041 int size,
1042 const char *errors}
1043 Encodes the \ctype{Py_UNICODE} buffer of the given size using UTF-8
1044 and returns a Python string object. Returns \NULL{} if an exception
1045 was raised by the codec.
1046\end{cfuncdesc}
1047
1048\begin{cfuncdesc}{PyObject*}{PyUnicode_AsUTF8String}{PyObject *unicode}
1049 Encodes a Unicode objects using UTF-8 and returns the result as
1050 Python string object. Error handling is ``strict''. Returns
1051 \NULL{} if an exception was raised by the codec.
1052\end{cfuncdesc}
1053
1054% --- UTF-16 Codecs ------------------------------------------------------ */
1055
1056These are the UTF-16 codec APIs:
1057
1058\begin{cfuncdesc}{PyObject*}{PyUnicode_DecodeUTF16}{const char *s,
1059 int size,
1060 const char *errors,
1061 int *byteorder}
1062 Decodes \var{length} bytes from a UTF-16 encoded buffer string and
1063 returns the corresponding Unicode object. \var{errors} (if
1064 non-\NULL) defines the error handling. It defaults to ``strict''.
1065
1066 If \var{byteorder} is non-\NULL, the decoder starts decoding using
1067 the given byte order:
1068
1069\begin{verbatim}
1070 *byteorder == -1: little endian
1071 *byteorder == 0: native order
1072 *byteorder == 1: big endian
1073\end{verbatim}
1074
1075 and then switches according to all byte order marks (BOM) it finds
1076 in the input data. BOMs are not copied into the resulting Unicode
1077 string. After completion, \var{*byteorder} is set to the current
1078 byte order at the end of input data.
1079
1080 If \var{byteorder} is \NULL, the codec starts in native order mode.
1081
1082 Returns \NULL{} if an exception was raised by the codec.
1083\end{cfuncdesc}
1084
1085\begin{cfuncdesc}{PyObject*}{PyUnicode_EncodeUTF16}{const Py_UNICODE *s,
1086 int size,
1087 const char *errors,
1088 int byteorder}
1089 Returns a Python string object holding the UTF-16 encoded value of
1090 the Unicode data in \var{s}. If \var{byteorder} is not \code{0},
1091 output is written according to the following byte order:
1092
1093\begin{verbatim}
1094 byteorder == -1: little endian
1095 byteorder == 0: native byte order (writes a BOM mark)
1096 byteorder == 1: big endian
1097\end{verbatim}
1098
1099 If byteorder is \code{0}, the output string will always start with
1100 the Unicode BOM mark (U+FEFF). In the other two modes, no BOM mark
1101 is prepended.
1102
1103 Note that \ctype{Py_UNICODE} data is being interpreted as UTF-16
1104 reduced to UCS-2. This trick makes it possible to add full UTF-16
1105 capabilities at a later point without comprimising the APIs.
1106
1107 Returns \NULL{} if an exception was raised by the codec.
1108\end{cfuncdesc}
1109
1110\begin{cfuncdesc}{PyObject*}{PyUnicode_AsUTF16String}{PyObject *unicode}
1111 Returns a Python string using the UTF-16 encoding in native byte
1112 order. The string always starts with a BOM mark. Error handling is
1113 ``strict''. Returns \NULL{} if an exception was raised by the
1114 codec.
1115\end{cfuncdesc}
1116
1117% --- Unicode-Escape Codecs ----------------------------------------------
1118
Martin v. Löwis95cf84a2003-10-19 07:32:24 +00001119These are the ``Unicode Escape'' codec APIs:
Fred Drake3adf79e2001-10-12 19:01:43 +00001120
1121\begin{cfuncdesc}{PyObject*}{PyUnicode_DecodeUnicodeEscape}{const char *s,
1122 int size,
1123 const char *errors}
1124 Creates a Unicode object by decoding \var{size} bytes of the
1125 Unicode-Escape encoded string \var{s}. Returns \NULL{} if an
1126 exception was raised by the codec.
1127\end{cfuncdesc}
1128
1129\begin{cfuncdesc}{PyObject*}{PyUnicode_EncodeUnicodeEscape}{const Py_UNICODE *s,
1130 int size,
1131 const char *errors}
1132 Encodes the \ctype{Py_UNICODE} buffer of the given size using
1133 Unicode-Escape and returns a Python string object. Returns \NULL{}
1134 if an exception was raised by the codec.
1135\end{cfuncdesc}
1136
1137\begin{cfuncdesc}{PyObject*}{PyUnicode_AsUnicodeEscapeString}{PyObject *unicode}
1138 Encodes a Unicode objects using Unicode-Escape and returns the
1139 result as Python string object. Error handling is ``strict''.
1140 Returns \NULL{} if an exception was raised by the codec.
1141\end{cfuncdesc}
1142
1143% --- Raw-Unicode-Escape Codecs ------------------------------------------
1144
Martin v. Löwis95cf84a2003-10-19 07:32:24 +00001145These are the ``Raw Unicode Escape'' codec APIs:
Fred Drake3adf79e2001-10-12 19:01:43 +00001146
1147\begin{cfuncdesc}{PyObject*}{PyUnicode_DecodeRawUnicodeEscape}{const char *s,
1148 int size,
1149 const char *errors}
1150 Creates a Unicode object by decoding \var{size} bytes of the
Martin v. Löwis95cf84a2003-10-19 07:32:24 +00001151 Raw-Unicode-Escape encoded string \var{s}. Returns \NULL{} if an
Fred Drake3adf79e2001-10-12 19:01:43 +00001152 exception was raised by the codec.
1153\end{cfuncdesc}
1154
1155\begin{cfuncdesc}{PyObject*}{PyUnicode_EncodeRawUnicodeEscape}{const Py_UNICODE *s,
1156 int size,
1157 const char *errors}
1158 Encodes the \ctype{Py_UNICODE} buffer of the given size using
1159 Raw-Unicode-Escape and returns a Python string object. Returns
1160 \NULL{} if an exception was raised by the codec.
1161\end{cfuncdesc}
1162
1163\begin{cfuncdesc}{PyObject*}{PyUnicode_AsRawUnicodeEscapeString}{PyObject *unicode}
1164 Encodes a Unicode objects using Raw-Unicode-Escape and returns the
1165 result as Python string object. Error handling is ``strict''.
1166 Returns \NULL{} if an exception was raised by the codec.
1167\end{cfuncdesc}
1168
Tim Petersf582b822001-12-11 18:51:08 +00001169% --- Latin-1 Codecs -----------------------------------------------------
Fred Drake3adf79e2001-10-12 19:01:43 +00001170
1171These are the Latin-1 codec APIs:
1172Latin-1 corresponds to the first 256 Unicode ordinals and only these
1173are accepted by the codecs during encoding.
1174
1175\begin{cfuncdesc}{PyObject*}{PyUnicode_DecodeLatin1}{const char *s,
1176 int size,
1177 const char *errors}
1178 Creates a Unicode object by decoding \var{size} bytes of the Latin-1
1179 encoded string \var{s}. Returns \NULL{} if an exception was raised
1180 by the codec.
1181\end{cfuncdesc}
1182
1183\begin{cfuncdesc}{PyObject*}{PyUnicode_EncodeLatin1}{const Py_UNICODE *s,
1184 int size,
1185 const char *errors}
1186 Encodes the \ctype{Py_UNICODE} buffer of the given size using
1187 Latin-1 and returns a Python string object. Returns \NULL{} if an
1188 exception was raised by the codec.
1189\end{cfuncdesc}
1190
1191\begin{cfuncdesc}{PyObject*}{PyUnicode_AsLatin1String}{PyObject *unicode}
1192 Encodes a Unicode objects using Latin-1 and returns the result as
1193 Python string object. Error handling is ``strict''. Returns
1194 \NULL{} if an exception was raised by the codec.
1195\end{cfuncdesc}
1196
Tim Petersf582b822001-12-11 18:51:08 +00001197% --- ASCII Codecs -------------------------------------------------------
Fred Drake3adf79e2001-10-12 19:01:43 +00001198
1199These are the \ASCII{} codec APIs. Only 7-bit \ASCII{} data is
1200accepted. All other codes generate errors.
1201
1202\begin{cfuncdesc}{PyObject*}{PyUnicode_DecodeASCII}{const char *s,
1203 int size,
1204 const char *errors}
1205 Creates a Unicode object by decoding \var{size} bytes of the
1206 \ASCII{} encoded string \var{s}. Returns \NULL{} if an exception
1207 was raised by the codec.
1208\end{cfuncdesc}
1209
1210\begin{cfuncdesc}{PyObject*}{PyUnicode_EncodeASCII}{const Py_UNICODE *s,
1211 int size,
1212 const char *errors}
1213 Encodes the \ctype{Py_UNICODE} buffer of the given size using
1214 \ASCII{} and returns a Python string object. Returns \NULL{} if an
1215 exception was raised by the codec.
1216\end{cfuncdesc}
1217
1218\begin{cfuncdesc}{PyObject*}{PyUnicode_AsASCIIString}{PyObject *unicode}
1219 Encodes a Unicode objects using \ASCII{} and returns the result as
1220 Python string object. Error handling is ``strict''. Returns
1221 \NULL{} if an exception was raised by the codec.
1222\end{cfuncdesc}
1223
Tim Petersf582b822001-12-11 18:51:08 +00001224% --- Character Map Codecs -----------------------------------------------
Fred Drake3adf79e2001-10-12 19:01:43 +00001225
1226These are the mapping codec APIs:
1227
1228This codec is special in that it can be used to implement many
1229different codecs (and this is in fact what was done to obtain most of
1230the standard codecs included in the \module{encodings} package). The
1231codec uses mapping to encode and decode characters.
1232
1233Decoding mappings must map single string characters to single Unicode
1234characters, integers (which are then interpreted as Unicode ordinals)
Tim Petersf582b822001-12-11 18:51:08 +00001235or None (meaning "undefined mapping" and causing an error).
Fred Drake3adf79e2001-10-12 19:01:43 +00001236
1237Encoding mappings must map single Unicode characters to single string
1238characters, integers (which are then interpreted as Latin-1 ordinals)
1239or None (meaning "undefined mapping" and causing an error).
1240
1241The mapping objects provided must only support the __getitem__ mapping
1242interface.
1243
1244If a character lookup fails with a LookupError, the character is
1245copied as-is meaning that its ordinal value will be interpreted as
1246Unicode or Latin-1 ordinal resp. Because of this, mappings only need
1247to contain those mappings which map characters to different code
1248points.
1249
1250\begin{cfuncdesc}{PyObject*}{PyUnicode_DecodeCharmap}{const char *s,
1251 int size,
1252 PyObject *mapping,
1253 const char *errors}
1254 Creates a Unicode object by decoding \var{size} bytes of the encoded
1255 string \var{s} using the given \var{mapping} object. Returns
1256 \NULL{} if an exception was raised by the codec.
1257\end{cfuncdesc}
1258
1259\begin{cfuncdesc}{PyObject*}{PyUnicode_EncodeCharmap}{const Py_UNICODE *s,
1260 int size,
1261 PyObject *mapping,
1262 const char *errors}
1263 Encodes the \ctype{Py_UNICODE} buffer of the given size using the
1264 given \var{mapping} object and returns a Python string object.
1265 Returns \NULL{} if an exception was raised by the codec.
1266\end{cfuncdesc}
1267
1268\begin{cfuncdesc}{PyObject*}{PyUnicode_AsCharmapString}{PyObject *unicode,
1269 PyObject *mapping}
1270 Encodes a Unicode objects using the given \var{mapping} object and
1271 returns the result as Python string object. Error handling is
1272 ``strict''. Returns \NULL{} if an exception was raised by the
1273 codec.
1274\end{cfuncdesc}
1275
1276The following codec API is special in that maps Unicode to Unicode.
1277
1278\begin{cfuncdesc}{PyObject*}{PyUnicode_TranslateCharmap}{const Py_UNICODE *s,
1279 int size,
1280 PyObject *table,
1281 const char *errors}
1282 Translates a \ctype{Py_UNICODE} buffer of the given length by
1283 applying a character mapping \var{table} to it and returns the
1284 resulting Unicode object. Returns \NULL{} when an exception was
1285 raised by the codec.
1286
1287 The \var{mapping} table must map Unicode ordinal integers to Unicode
1288 ordinal integers or None (causing deletion of the character).
1289
1290 Mapping tables need only provide the method{__getitem__()}
1291 interface; dictionaries and sequences work well. Unmapped character
1292 ordinals (ones which cause a \exception{LookupError}) are left
1293 untouched and are copied as-is.
1294\end{cfuncdesc}
1295
1296% --- MBCS codecs for Windows --------------------------------------------
1297
1298These are the MBCS codec APIs. They are currently only available on
1299Windows and use the Win32 MBCS converters to implement the
1300conversions. Note that MBCS (or DBCS) is a class of encodings, not
1301just one. The target encoding is defined by the user settings on the
1302machine running the codec.
1303
1304\begin{cfuncdesc}{PyObject*}{PyUnicode_DecodeMBCS}{const char *s,
1305 int size,
1306 const char *errors}
1307 Creates a Unicode object by decoding \var{size} bytes of the MBCS
1308 encoded string \var{s}. Returns \NULL{} if an exception was
1309 raised by the codec.
1310\end{cfuncdesc}
1311
1312\begin{cfuncdesc}{PyObject*}{PyUnicode_EncodeMBCS}{const Py_UNICODE *s,
1313 int size,
1314 const char *errors}
1315 Encodes the \ctype{Py_UNICODE} buffer of the given size using MBCS
1316 and returns a Python string object. Returns \NULL{} if an exception
1317 was raised by the codec.
1318\end{cfuncdesc}
1319
1320\begin{cfuncdesc}{PyObject*}{PyUnicode_AsMBCSString}{PyObject *unicode}
1321 Encodes a Unicode objects using MBCS and returns the result as
1322 Python string object. Error handling is ``strict''. Returns
1323 \NULL{} if an exception was raised by the codec.
1324\end{cfuncdesc}
1325
1326% --- Methods & Slots ----------------------------------------------------
1327
1328\subsubsection{Methods and Slot Functions \label{unicodeMethodsAndSlots}}
1329
1330The following APIs are capable of handling Unicode objects and strings
1331on input (we refer to them as strings in the descriptions) and return
Martin v. Löwis95cf84a2003-10-19 07:32:24 +00001332Unicode objects or integers as appropriate.
Fred Drake3adf79e2001-10-12 19:01:43 +00001333
1334They all return \NULL{} or \code{-1} if an exception occurs.
1335
1336\begin{cfuncdesc}{PyObject*}{PyUnicode_Concat}{PyObject *left,
1337 PyObject *right}
1338 Concat two strings giving a new Unicode string.
1339\end{cfuncdesc}
1340
1341\begin{cfuncdesc}{PyObject*}{PyUnicode_Split}{PyObject *s,
1342 PyObject *sep,
1343 int maxsplit}
1344 Split a string giving a list of Unicode strings. If sep is \NULL,
1345 splitting will be done at all whitespace substrings. Otherwise,
1346 splits occur at the given separator. At most \var{maxsplit} splits
1347 will be done. If negative, no limit is set. Separators are not
1348 included in the resulting list.
1349\end{cfuncdesc}
1350
1351\begin{cfuncdesc}{PyObject*}{PyUnicode_Splitlines}{PyObject *s,
Martin v. Löwis24b88812003-03-30 16:40:42 +00001352 int keepend}
Fred Drake3adf79e2001-10-12 19:01:43 +00001353 Split a Unicode string at line breaks, returning a list of Unicode
Martin v. Löwis24b88812003-03-30 16:40:42 +00001354 strings. CRLF is considered to be one line break. If \var{keepend}
1355 is 0, the Line break characters are not included in the resulting
1356 strings.
Fred Drake3adf79e2001-10-12 19:01:43 +00001357\end{cfuncdesc}
1358
1359\begin{cfuncdesc}{PyObject*}{PyUnicode_Translate}{PyObject *str,
1360 PyObject *table,
1361 const char *errors}
1362 Translate a string by applying a character mapping table to it and
1363 return the resulting Unicode object.
1364
1365 The mapping table must map Unicode ordinal integers to Unicode
1366 ordinal integers or None (causing deletion of the character).
1367
1368 Mapping tables need only provide the \method{__getitem__()}
1369 interface; dictionaries and sequences work well. Unmapped character
1370 ordinals (ones which cause a \exception{LookupError}) are left
1371 untouched and are copied as-is.
1372
1373 \var{errors} has the usual meaning for codecs. It may be \NULL{}
1374 which indicates to use the default error handling.
1375\end{cfuncdesc}
1376
1377\begin{cfuncdesc}{PyObject*}{PyUnicode_Join}{PyObject *separator,
1378 PyObject *seq}
1379 Join a sequence of strings using the given separator and return the
1380 resulting Unicode string.
1381\end{cfuncdesc}
1382
1383\begin{cfuncdesc}{PyObject*}{PyUnicode_Tailmatch}{PyObject *str,
1384 PyObject *substr,
1385 int start,
1386 int end,
1387 int direction}
1388 Return 1 if \var{substr} matches \var{str}[\var{start}:\var{end}] at
1389 the given tail end (\var{direction} == -1 means to do a prefix
1390 match, \var{direction} == 1 a suffix match), 0 otherwise.
1391\end{cfuncdesc}
1392
Fred Drake1d1e1db2002-06-20 22:07:04 +00001393\begin{cfuncdesc}{int}{PyUnicode_Find}{PyObject *str,
1394 PyObject *substr,
1395 int start,
1396 int end,
1397 int direction}
Fred Drake3adf79e2001-10-12 19:01:43 +00001398 Return the first position of \var{substr} in
1399 \var{str}[\var{start}:\var{end}] using the given \var{direction}
1400 (\var{direction} == 1 means to do a forward search,
Fred Drake1d1e1db2002-06-20 22:07:04 +00001401 \var{direction} == -1 a backward search). The return value is the
1402 index of the first match; a value of \code{-1} indicates that no
1403 match was found, and \code{-2} indicates that an error occurred and
1404 an exception has been set.
Fred Drake3adf79e2001-10-12 19:01:43 +00001405\end{cfuncdesc}
1406
Fred Drake1d1e1db2002-06-20 22:07:04 +00001407\begin{cfuncdesc}{int}{PyUnicode_Count}{PyObject *str,
1408 PyObject *substr,
1409 int start,
1410 int end}
1411 Return the number of non-overlapping occurrences of \var{substr} in
1412 \code{\var{str}[\var{start}:\var{end}]}. Returns \code{-1} if an
1413 error occurred.
Fred Drake3adf79e2001-10-12 19:01:43 +00001414\end{cfuncdesc}
1415
1416\begin{cfuncdesc}{PyObject*}{PyUnicode_Replace}{PyObject *str,
1417 PyObject *substr,
1418 PyObject *replstr,
1419 int maxcount}
1420 Replace at most \var{maxcount} occurrences of \var{substr} in
1421 \var{str} with \var{replstr} and return the resulting Unicode object.
1422 \var{maxcount} == -1 means replace all occurrences.
1423\end{cfuncdesc}
1424
1425\begin{cfuncdesc}{int}{PyUnicode_Compare}{PyObject *left, PyObject *right}
1426 Compare two strings and return -1, 0, 1 for less than, equal, and
1427 greater than, respectively.
1428\end{cfuncdesc}
1429
1430\begin{cfuncdesc}{PyObject*}{PyUnicode_Format}{PyObject *format,
1431 PyObject *args}
1432 Returns a new string object from \var{format} and \var{args}; this
1433 is analogous to \code{\var{format} \%\ \var{args}}. The
1434 \var{args} argument must be a tuple.
1435\end{cfuncdesc}
1436
1437\begin{cfuncdesc}{int}{PyUnicode_Contains}{PyObject *container,
1438 PyObject *element}
1439 Checks whether \var{element} is contained in \var{container} and
1440 returns true or false accordingly.
1441
1442 \var{element} has to coerce to a one element Unicode
1443 string. \code{-1} is returned if there was an error.
1444\end{cfuncdesc}
1445
1446
1447\subsection{Buffer Objects \label{bufferObjects}}
1448\sectionauthor{Greg Stein}{gstein@lyra.org}
1449
1450\obindex{buffer}
1451Python objects implemented in C can export a group of functions called
1452the ``buffer\index{buffer interface} interface.'' These functions can
1453be used by an object to expose its data in a raw, byte-oriented
1454format. Clients of the object can use the buffer interface to access
1455the object data directly, without needing to copy it first.
1456
Tim Petersf582b822001-12-11 18:51:08 +00001457Two examples of objects that support
1458the buffer interface are strings and arrays. The string object exposes
Fred Drake3adf79e2001-10-12 19:01:43 +00001459the character contents in the buffer interface's byte-oriented
1460form. An array can also expose its contents, but it should be noted
1461that array elements may be multi-byte values.
1462
1463An example user of the buffer interface is the file object's
1464\method{write()} method. Any object that can export a series of bytes
1465through the buffer interface can be written to a file. There are a
Tim Petersf582b822001-12-11 18:51:08 +00001466number of format codes to \cfunction{PyArg_ParseTuple()} that operate
Fred Drake3adf79e2001-10-12 19:01:43 +00001467against an object's buffer interface, returning data from the target
1468object.
1469
1470More information on the buffer interface is provided in the section
Fred Drake54e62942001-12-11 19:40:16 +00001471``Buffer Object Structures'' (section~\ref{buffer-structs}), under
Fred Drake3adf79e2001-10-12 19:01:43 +00001472the description for \ctype{PyBufferProcs}\ttindex{PyBufferProcs}.
1473
1474A ``buffer object'' is defined in the \file{bufferobject.h} header
1475(included by \file{Python.h}). These objects look very similar to
1476string objects at the Python programming level: they support slicing,
1477indexing, concatenation, and some other standard string
1478operations. However, their data can come from one of two sources: from
1479a block of memory, or from another object which exports the buffer
1480interface.
1481
1482Buffer objects are useful as a way to expose the data from another
1483object's buffer interface to the Python programmer. They can also be
1484used as a zero-copy slicing mechanism. Using their ability to
1485reference a block of memory, it is possible to expose any data to the
1486Python programmer quite easily. The memory could be a large, constant
1487array in a C extension, it could be a raw block of memory for
1488manipulation before passing to an operating system library, or it
1489could be used to pass around structured data in its native, in-memory
1490format.
1491
1492\begin{ctypedesc}{PyBufferObject}
1493 This subtype of \ctype{PyObject} represents a buffer object.
1494\end{ctypedesc}
1495
1496\begin{cvardesc}{PyTypeObject}{PyBuffer_Type}
1497 The instance of \ctype{PyTypeObject} which represents the Python
1498 buffer type; it is the same object as \code{types.BufferType} in the
1499 Python layer.\withsubitem{(in module types)}{\ttindex{BufferType}}.
1500\end{cvardesc}
1501
1502\begin{cvardesc}{int}{Py_END_OF_BUFFER}
1503 This constant may be passed as the \var{size} parameter to
1504 \cfunction{PyBuffer_FromObject()} or
1505 \cfunction{PyBuffer_FromReadWriteObject()}. It indicates that the
1506 new \ctype{PyBufferObject} should refer to \var{base} object from
1507 the specified \var{offset} to the end of its exported buffer. Using
1508 this enables the caller to avoid querying the \var{base} object for
1509 its length.
1510\end{cvardesc}
1511
1512\begin{cfuncdesc}{int}{PyBuffer_Check}{PyObject *p}
1513 Return true if the argument has type \cdata{PyBuffer_Type}.
1514\end{cfuncdesc}
1515
1516\begin{cfuncdesc}{PyObject*}{PyBuffer_FromObject}{PyObject *base,
1517 int offset, int size}
1518 Return a new read-only buffer object. This raises
1519 \exception{TypeError} if \var{base} doesn't support the read-only
1520 buffer protocol or doesn't provide exactly one buffer segment, or it
1521 raises \exception{ValueError} if \var{offset} is less than zero. The
1522 buffer will hold a reference to the \var{base} object, and the
1523 buffer's contents will refer to the \var{base} object's buffer
1524 interface, starting as position \var{offset} and extending for
1525 \var{size} bytes. If \var{size} is \constant{Py_END_OF_BUFFER}, then
1526 the new buffer's contents extend to the length of the \var{base}
1527 object's exported buffer data.
1528\end{cfuncdesc}
1529
1530\begin{cfuncdesc}{PyObject*}{PyBuffer_FromReadWriteObject}{PyObject *base,
1531 int offset,
1532 int size}
1533 Return a new writable buffer object. Parameters and exceptions are
1534 similar to those for \cfunction{PyBuffer_FromObject()}. If the
1535 \var{base} object does not export the writeable buffer protocol,
1536 then \exception{TypeError} is raised.
1537\end{cfuncdesc}
1538
1539\begin{cfuncdesc}{PyObject*}{PyBuffer_FromMemory}{void *ptr, int size}
1540 Return a new read-only buffer object that reads from a specified
1541 location in memory, with a specified size. The caller is
1542 responsible for ensuring that the memory buffer, passed in as
1543 \var{ptr}, is not deallocated while the returned buffer object
1544 exists. Raises \exception{ValueError} if \var{size} is less than
1545 zero. Note that \constant{Py_END_OF_BUFFER} may \emph{not} be
1546 passed for the \var{size} parameter; \exception{ValueError} will be
1547 raised in that case.
1548\end{cfuncdesc}
1549
1550\begin{cfuncdesc}{PyObject*}{PyBuffer_FromReadWriteMemory}{void *ptr, int size}
1551 Similar to \cfunction{PyBuffer_FromMemory()}, but the returned
1552 buffer is writable.
1553\end{cfuncdesc}
1554
1555\begin{cfuncdesc}{PyObject*}{PyBuffer_New}{int size}
1556 Returns a new writable buffer object that maintains its own memory
1557 buffer of \var{size} bytes. \exception{ValueError} is returned if
1558 \var{size} is not zero or positive.
1559\end{cfuncdesc}
1560
1561
1562\subsection{Tuple Objects \label{tupleObjects}}
1563
1564\obindex{tuple}
1565\begin{ctypedesc}{PyTupleObject}
1566 This subtype of \ctype{PyObject} represents a Python tuple object.
1567\end{ctypedesc}
1568
1569\begin{cvardesc}{PyTypeObject}{PyTuple_Type}
1570 This instance of \ctype{PyTypeObject} represents the Python tuple
1571 type; it is the same object as \code{types.TupleType} in the Python
1572 layer.\withsubitem{(in module types)}{\ttindex{TupleType}}.
1573\end{cvardesc}
1574
1575\begin{cfuncdesc}{int}{PyTuple_Check}{PyObject *p}
1576 Return true if \var{p} is a tuple object or an instance of a subtype
1577 of the tuple type.
1578 \versionchanged[Allowed subtypes to be accepted]{2.2}
1579\end{cfuncdesc}
1580
1581\begin{cfuncdesc}{int}{PyTuple_CheckExact}{PyObject *p}
1582 Return true if \var{p} is a tuple object, but not an instance of a
1583 subtype of the tuple type.
1584 \versionadded{2.2}
1585\end{cfuncdesc}
1586
1587\begin{cfuncdesc}{PyObject*}{PyTuple_New}{int len}
1588 Return a new tuple object of size \var{len}, or \NULL{} on failure.
1589\end{cfuncdesc}
1590
Raymond Hettingercb2da432003-10-12 18:24:34 +00001591\begin{cfuncdesc}{PyObject*}{PyTuple_Pack}{int n, \moreargs}
1592 Return a new tuple object of size \var{n}, or \NULL{} on failure.
1593 The tuple values are initialized to the subsequent \var{n} C arguments
1594 pointing to Python objects. \samp{PyTuple_Pack(2, \var{a}, \var{b})}
1595 is equivalent to \samp{Py_BuildValue("(OO)", \var{a}, \var{b})}.
1596 \versionadded{2.4}
1597\end{cfuncdesc}
1598
Fred Drake3adf79e2001-10-12 19:01:43 +00001599\begin{cfuncdesc}{int}{PyTuple_Size}{PyObject *p}
1600 Takes a pointer to a tuple object, and returns the size of that
1601 tuple.
1602\end{cfuncdesc}
1603
1604\begin{cfuncdesc}{int}{PyTuple_GET_SIZE}{PyObject *p}
1605 Return the size of the tuple \var{p}, which must be non-\NULL{} and
1606 point to a tuple; no error checking is performed.
1607\end{cfuncdesc}
1608
1609\begin{cfuncdesc}{PyObject*}{PyTuple_GetItem}{PyObject *p, int pos}
1610 Returns the object at position \var{pos} in the tuple pointed to by
1611 \var{p}. If \var{pos} is out of bounds, returns \NULL{} and sets an
1612 \exception{IndexError} exception.
1613\end{cfuncdesc}
1614
1615\begin{cfuncdesc}{PyObject*}{PyTuple_GET_ITEM}{PyObject *p, int pos}
1616 Like \cfunction{PyTuple_GetItem()}, but does no checking of its
1617 arguments.
1618\end{cfuncdesc}
1619
1620\begin{cfuncdesc}{PyObject*}{PyTuple_GetSlice}{PyObject *p,
1621 int low, int high}
1622 Takes a slice of the tuple pointed to by \var{p} from \var{low} to
1623 \var{high} and returns it as a new tuple.
1624\end{cfuncdesc}
1625
1626\begin{cfuncdesc}{int}{PyTuple_SetItem}{PyObject *p,
1627 int pos, PyObject *o}
1628 Inserts a reference to object \var{o} at position \var{pos} of the
1629 tuple pointed to by \var{p}. It returns \code{0} on success.
1630 \note{This function ``steals'' a reference to \var{o}.}
1631\end{cfuncdesc}
1632
1633\begin{cfuncdesc}{void}{PyTuple_SET_ITEM}{PyObject *p,
1634 int pos, PyObject *o}
1635 Like \cfunction{PyTuple_SetItem()}, but does no error checking, and
1636 should \emph{only} be used to fill in brand new tuples. \note{This
1637 function ``steals'' a reference to \var{o}.}
1638\end{cfuncdesc}
1639
1640\begin{cfuncdesc}{int}{_PyTuple_Resize}{PyObject **p, int newsize}
1641 Can be used to resize a tuple. \var{newsize} will be the new length
1642 of the tuple. Because tuples are \emph{supposed} to be immutable,
1643 this should only be used if there is only one reference to the
1644 object. Do \emph{not} use this if the tuple may already be known to
1645 some other part of the code. The tuple will always grow or shrink
1646 at the end. Think of this as destroying the old tuple and creating
1647 a new one, only more efficiently. Returns \code{0} on success.
1648 Client code should never assume that the resulting value of
1649 \code{*\var{p}} will be the same as before calling this function.
1650 If the object referenced by \code{*\var{p}} is replaced, the
1651 original \code{*\var{p}} is destroyed. On failure, returns
1652 \code{-1} and sets \code{*\var{p}} to \NULL, and raises
1653 \exception{MemoryError} or
1654 \exception{SystemError}.
Tim Petersf582b822001-12-11 18:51:08 +00001655 \versionchanged[Removed unused third parameter, \var{last_is_sticky}]{2.2}
Fred Drake3adf79e2001-10-12 19:01:43 +00001656\end{cfuncdesc}
1657
1658
1659\subsection{List Objects \label{listObjects}}
1660
1661\obindex{list}
1662\begin{ctypedesc}{PyListObject}
1663 This subtype of \ctype{PyObject} represents a Python list object.
1664\end{ctypedesc}
1665
1666\begin{cvardesc}{PyTypeObject}{PyList_Type}
1667 This instance of \ctype{PyTypeObject} represents the Python list
1668 type. This is the same object as \code{types.ListType}.
1669 \withsubitem{(in module types)}{\ttindex{ListType}}
1670\end{cvardesc}
1671
1672\begin{cfuncdesc}{int}{PyList_Check}{PyObject *p}
1673 Returns true if its argument is a \ctype{PyListObject}.
1674\end{cfuncdesc}
1675
1676\begin{cfuncdesc}{PyObject*}{PyList_New}{int len}
1677 Returns a new list of length \var{len} on success, or \NULL{} on
1678 failure.
1679\end{cfuncdesc}
1680
1681\begin{cfuncdesc}{int}{PyList_Size}{PyObject *list}
1682 Returns the length of the list object in \var{list}; this is
1683 equivalent to \samp{len(\var{list})} on a list object.
1684 \bifuncindex{len}
1685\end{cfuncdesc}
1686
1687\begin{cfuncdesc}{int}{PyList_GET_SIZE}{PyObject *list}
1688 Macro form of \cfunction{PyList_Size()} without error checking.
1689\end{cfuncdesc}
1690
1691\begin{cfuncdesc}{PyObject*}{PyList_GetItem}{PyObject *list, int index}
1692 Returns the object at position \var{pos} in the list pointed to by
1693 \var{p}. If \var{pos} is out of bounds, returns \NULL{} and sets an
1694 \exception{IndexError} exception.
1695\end{cfuncdesc}
1696
1697\begin{cfuncdesc}{PyObject*}{PyList_GET_ITEM}{PyObject *list, int i}
1698 Macro form of \cfunction{PyList_GetItem()} without error checking.
1699\end{cfuncdesc}
1700
1701\begin{cfuncdesc}{int}{PyList_SetItem}{PyObject *list, int index,
1702 PyObject *item}
1703 Sets the item at index \var{index} in list to \var{item}. Returns
1704 \code{0} on success or \code{-1} on failure. \note{This function
1705 ``steals'' a reference to \var{item} and discards a reference to an
1706 item already in the list at the affected position.}
1707\end{cfuncdesc}
1708
1709\begin{cfuncdesc}{void}{PyList_SET_ITEM}{PyObject *list, int i,
1710 PyObject *o}
1711 Macro form of \cfunction{PyList_SetItem()} without error checking.
1712 This is normally only used to fill in new lists where there is no
1713 previous content.
1714 \note{This function ``steals'' a reference to \var{item}, and,
1715 unlike \cfunction{PyList_SetItem()}, does \emph{not} discard a
1716 reference to any item that it being replaced; any reference in
1717 \var{list} at position \var{i} will be leaked.}
1718\end{cfuncdesc}
1719
1720\begin{cfuncdesc}{int}{PyList_Insert}{PyObject *list, int index,
1721 PyObject *item}
1722 Inserts the item \var{item} into list \var{list} in front of index
1723 \var{index}. Returns \code{0} if successful; returns \code{-1} and
1724 raises an exception if unsuccessful. Analogous to
1725 \code{\var{list}.insert(\var{index}, \var{item})}.
1726\end{cfuncdesc}
1727
1728\begin{cfuncdesc}{int}{PyList_Append}{PyObject *list, PyObject *item}
1729 Appends the object \var{item} at the end of list \var{list}.
1730 Returns \code{0} if successful; returns \code{-1} and sets an
1731 exception if unsuccessful. Analogous to
1732 \code{\var{list}.append(\var{item})}.
1733\end{cfuncdesc}
1734
1735\begin{cfuncdesc}{PyObject*}{PyList_GetSlice}{PyObject *list,
1736 int low, int high}
1737 Returns a list of the objects in \var{list} containing the objects
1738 \emph{between} \var{low} and \var{high}. Returns \NULL{} and sets
1739 an exception if unsuccessful.
1740 Analogous to \code{\var{list}[\var{low}:\var{high}]}.
1741\end{cfuncdesc}
1742
1743\begin{cfuncdesc}{int}{PyList_SetSlice}{PyObject *list,
1744 int low, int high,
1745 PyObject *itemlist}
1746 Sets the slice of \var{list} between \var{low} and \var{high} to the
1747 contents of \var{itemlist}. Analogous to
Raymond Hettinger9c7ed4c2003-10-26 17:20:07 +00001748 \code{\var{list}[\var{low}:\var{high}] = \var{itemlist}}.
1749 The \var{itemlist} may be \NULL{}, indicating the assignment
1750 of an empty list (slice deletion).
1751 Returns \code{0} on success, \code{-1} on failure.
Fred Drake3adf79e2001-10-12 19:01:43 +00001752\end{cfuncdesc}
1753
1754\begin{cfuncdesc}{int}{PyList_Sort}{PyObject *list}
1755 Sorts the items of \var{list} in place. Returns \code{0} on
1756 success, \code{-1} on failure. This is equivalent to
1757 \samp{\var{list}.sort()}.
1758\end{cfuncdesc}
1759
1760\begin{cfuncdesc}{int}{PyList_Reverse}{PyObject *list}
1761 Reverses the items of \var{list} in place. Returns \code{0} on
1762 success, \code{-1} on failure. This is the equivalent of
1763 \samp{\var{list}.reverse()}.
1764\end{cfuncdesc}
1765
1766\begin{cfuncdesc}{PyObject*}{PyList_AsTuple}{PyObject *list}
1767 Returns a new tuple object containing the contents of \var{list};
1768 equivalent to \samp{tuple(\var{list})}.\bifuncindex{tuple}
1769\end{cfuncdesc}
1770
1771
1772\section{Mapping Objects \label{mapObjects}}
1773
1774\obindex{mapping}
1775
1776
1777\subsection{Dictionary Objects \label{dictObjects}}
1778
1779\obindex{dictionary}
1780\begin{ctypedesc}{PyDictObject}
1781 This subtype of \ctype{PyObject} represents a Python dictionary
1782 object.
1783\end{ctypedesc}
1784
1785\begin{cvardesc}{PyTypeObject}{PyDict_Type}
1786 This instance of \ctype{PyTypeObject} represents the Python
1787 dictionary type. This is exposed to Python programs as
1788 \code{types.DictType} and \code{types.DictionaryType}.
1789 \withsubitem{(in module types)}{\ttindex{DictType}\ttindex{DictionaryType}}
1790\end{cvardesc}
1791
1792\begin{cfuncdesc}{int}{PyDict_Check}{PyObject *p}
1793 Returns true if its argument is a \ctype{PyDictObject}.
1794\end{cfuncdesc}
1795
1796\begin{cfuncdesc}{PyObject*}{PyDict_New}{}
1797 Returns a new empty dictionary, or \NULL{} on failure.
1798\end{cfuncdesc}
1799
1800\begin{cfuncdesc}{PyObject*}{PyDictProxy_New}{PyObject *dict}
1801 Return a proxy object for a mapping which enforces read-only
1802 behavior. This is normally used to create a proxy to prevent
1803 modification of the dictionary for non-dynamic class types.
1804 \versionadded{2.2}
1805\end{cfuncdesc}
1806
1807\begin{cfuncdesc}{void}{PyDict_Clear}{PyObject *p}
1808 Empties an existing dictionary of all key-value pairs.
1809\end{cfuncdesc}
1810
Raymond Hettingerbc0f2ab2003-11-25 21:12:14 +00001811\begin{cfuncdesc}{int}{PyDict_Contains}{PyObject *p, PyObject *key}
1812 Determine if dictionary \var{p} contains \var{key}. If an item
1813 in \var{p} is matches \var{key}, return \code{1}, otherwise return
1814 \code{0}. On error, return \code{-1}. This is equivalent to the
1815 Python expression \samp{\var{key} in \var{p}}.
1816 \versionadded{2.4}
1817\end{cfuncdesc}
1818
Fred Drake3adf79e2001-10-12 19:01:43 +00001819\begin{cfuncdesc}{PyObject*}{PyDict_Copy}{PyObject *p}
1820 Returns a new dictionary that contains the same key-value pairs as
1821 \var{p}.
1822 \versionadded{1.6}
1823\end{cfuncdesc}
1824
1825\begin{cfuncdesc}{int}{PyDict_SetItem}{PyObject *p, PyObject *key,
1826 PyObject *val}
1827 Inserts \var{value} into the dictionary \var{p} with a key of
1828 \var{key}. \var{key} must be hashable; if it isn't,
1829 \exception{TypeError} will be raised.
1830 Returns \code{0} on success or \code{-1} on failure.
1831\end{cfuncdesc}
1832
1833\begin{cfuncdesc}{int}{PyDict_SetItemString}{PyObject *p,
1834 char *key,
1835 PyObject *val}
1836 Inserts \var{value} into the dictionary \var{p} using \var{key} as a
1837 key. \var{key} should be a \ctype{char*}. The key object is created
1838 using \code{PyString_FromString(\var{key})}. Returns \code{0} on
1839 success or \code{-1} on failure.
1840 \ttindex{PyString_FromString()}
1841\end{cfuncdesc}
1842
1843\begin{cfuncdesc}{int}{PyDict_DelItem}{PyObject *p, PyObject *key}
1844 Removes the entry in dictionary \var{p} with key \var{key}.
1845 \var{key} must be hashable; if it isn't, \exception{TypeError} is
Skip Montanaroa23bc422002-01-23 08:18:30 +00001846 raised. Returns \code{0} on success or \code{-1} on failure.
Fred Drake3adf79e2001-10-12 19:01:43 +00001847\end{cfuncdesc}
1848
1849\begin{cfuncdesc}{int}{PyDict_DelItemString}{PyObject *p, char *key}
1850 Removes the entry in dictionary \var{p} which has a key specified by
1851 the string \var{key}. Returns \code{0} on success or \code{-1} on
1852 failure.
1853\end{cfuncdesc}
1854
1855\begin{cfuncdesc}{PyObject*}{PyDict_GetItem}{PyObject *p, PyObject *key}
1856 Returns the object from dictionary \var{p} which has a key
1857 \var{key}. Returns \NULL{} if the key \var{key} is not present, but
1858 \emph{without} setting an exception.
1859\end{cfuncdesc}
1860
1861\begin{cfuncdesc}{PyObject*}{PyDict_GetItemString}{PyObject *p, char *key}
1862 This is the same as \cfunction{PyDict_GetItem()}, but \var{key} is
1863 specified as a \ctype{char*}, rather than a \ctype{PyObject*}.
1864\end{cfuncdesc}
1865
1866\begin{cfuncdesc}{PyObject*}{PyDict_Items}{PyObject *p}
1867 Returns a \ctype{PyListObject} containing all the items from the
1868 dictionary, as in the dictinoary method \method{items()} (see the
1869 \citetitle[../lib/lib.html]{Python Library Reference}).
1870\end{cfuncdesc}
1871
1872\begin{cfuncdesc}{PyObject*}{PyDict_Keys}{PyObject *p}
1873 Returns a \ctype{PyListObject} containing all the keys from the
1874 dictionary, as in the dictionary method \method{keys()} (see the
1875 \citetitle[../lib/lib.html]{Python Library Reference}).
1876\end{cfuncdesc}
1877
1878\begin{cfuncdesc}{PyObject*}{PyDict_Values}{PyObject *p}
1879 Returns a \ctype{PyListObject} containing all the values from the
1880 dictionary \var{p}, as in the dictionary method \method{values()}
1881 (see the \citetitle[../lib/lib.html]{Python Library Reference}).
1882\end{cfuncdesc}
1883
1884\begin{cfuncdesc}{int}{PyDict_Size}{PyObject *p}
1885 Returns the number of items in the dictionary. This is equivalent
1886 to \samp{len(\var{p})} on a dictionary.\bifuncindex{len}
1887\end{cfuncdesc}
1888
1889\begin{cfuncdesc}{int}{PyDict_Next}{PyObject *p, int *ppos,
1890 PyObject **pkey, PyObject **pvalue}
1891 Iterate over all key-value pairs in the dictionary \var{p}. The
1892 \ctype{int} referred to by \var{ppos} must be initialized to
1893 \code{0} prior to the first call to this function to start the
1894 iteration; the function returns true for each pair in the
1895 dictionary, and false once all pairs have been reported. The
1896 parameters \var{pkey} and \var{pvalue} should either point to
1897 \ctype{PyObject*} variables that will be filled in with each key and
Skip Montanaroea3ceaa2002-01-23 10:54:41 +00001898 value, respectively, or may be \NULL. Any references returned through
Raymond Hettinger54693242003-12-13 19:48:41 +00001899 them are borrowed. \var{ppos} should not be altered during iteration.
1900 Its value represents offsets within the internal dictionary structure,
1901 and since the structure is sparse, the offsets are not consecutive.
Fred Drake3adf79e2001-10-12 19:01:43 +00001902
1903 For example:
1904
1905\begin{verbatim}
1906PyObject *key, *value;
1907int pos = 0;
1908
1909while (PyDict_Next(self->dict, &pos, &key, &value)) {
1910 /* do something interesting with the values... */
1911 ...
1912}
1913\end{verbatim}
1914
1915 The dictionary \var{p} should not be mutated during iteration. It
1916 is safe (since Python 2.1) to modify the values of the keys as you
1917 iterate over the dictionary, but only so long as the set of keys
1918 does not change. For example:
1919
1920\begin{verbatim}
1921PyObject *key, *value;
1922int pos = 0;
1923
1924while (PyDict_Next(self->dict, &pos, &key, &value)) {
1925 int i = PyInt_AS_LONG(value) + 1;
1926 PyObject *o = PyInt_FromLong(i);
1927 if (o == NULL)
1928 return -1;
1929 if (PyDict_SetItem(self->dict, key, o) < 0) {
1930 Py_DECREF(o);
1931 return -1;
1932 }
1933 Py_DECREF(o);
1934}
1935\end{verbatim}
1936\end{cfuncdesc}
1937
1938\begin{cfuncdesc}{int}{PyDict_Merge}{PyObject *a, PyObject *b, int override}
Tim Petersf582b822001-12-11 18:51:08 +00001939 Iterate over mapping object \var{b} adding key-value pairs to dictionary
1940 \var{a}.
1941 \var{b} may be a dictionary, or any object supporting
1942 \function{PyMapping_Keys()} and \function{PyObject_GetItem()}.
1943 If \var{override} is true, existing pairs in \var{a} will
Fred Drake3adf79e2001-10-12 19:01:43 +00001944 be replaced if a matching key is found in \var{b}, otherwise pairs
1945 will only be added if there is not a matching key in \var{a}.
Tim Petersf582b822001-12-11 18:51:08 +00001946 Return \code{0} on success or \code{-1} if an exception was
Fred Drake3adf79e2001-10-12 19:01:43 +00001947 raised.
1948\versionadded{2.2}
1949\end{cfuncdesc}
1950
1951\begin{cfuncdesc}{int}{PyDict_Update}{PyObject *a, PyObject *b}
1952 This is the same as \code{PyDict_Merge(\var{a}, \var{b}, 1)} in C,
Tim Petersf582b822001-12-11 18:51:08 +00001953 or \code{\var{a}.update(\var{b})} in Python. Return \code{0} on
Fred Drake3adf79e2001-10-12 19:01:43 +00001954 success or \code{-1} if an exception was raised.
1955 \versionadded{2.2}
1956\end{cfuncdesc}
1957
Tim Petersf582b822001-12-11 18:51:08 +00001958\begin{cfuncdesc}{int}{PyDict_MergeFromSeq2}{PyObject *a, PyObject *seq2,
1959 int override}
1960 Update or merge into dictionary \var{a}, from the key-value pairs in
1961 \var{seq2}. \var{seq2} must be an iterable object producing
1962 iterable objects of length 2, viewed as key-value pairs. In case of
1963 duplicate keys, the last wins if \var{override} is true, else the
1964 first wins.
1965 Return \code{0} on success or \code{-1} if an exception
1966 was raised.
1967 Equivalent Python (except for the return value):
1968
1969\begin{verbatim}
1970def PyDict_MergeFromSeq2(a, seq2, override):
1971 for key, value in seq2:
1972 if override or key not in a:
1973 a[key] = value
1974\end{verbatim}
1975
1976 \versionadded{2.2}
1977\end{cfuncdesc}
Fred Drake3adf79e2001-10-12 19:01:43 +00001978
Fred Drake54e62942001-12-11 19:40:16 +00001979
Fred Drake3adf79e2001-10-12 19:01:43 +00001980\section{Other Objects \label{otherObjects}}
1981
1982\subsection{File Objects \label{fileObjects}}
1983
1984\obindex{file}
1985Python's built-in file objects are implemented entirely on the
1986\ctype{FILE*} support from the C standard library. This is an
1987implementation detail and may change in future releases of Python.
1988
1989\begin{ctypedesc}{PyFileObject}
1990 This subtype of \ctype{PyObject} represents a Python file object.
1991\end{ctypedesc}
1992
1993\begin{cvardesc}{PyTypeObject}{PyFile_Type}
1994 This instance of \ctype{PyTypeObject} represents the Python file
1995 type. This is exposed to Python programs as \code{types.FileType}.
1996 \withsubitem{(in module types)}{\ttindex{FileType}}
1997\end{cvardesc}
1998
1999\begin{cfuncdesc}{int}{PyFile_Check}{PyObject *p}
2000 Returns true if its argument is a \ctype{PyFileObject} or a subtype
2001 of \ctype{PyFileObject}.
2002 \versionchanged[Allowed subtypes to be accepted]{2.2}
2003\end{cfuncdesc}
2004
2005\begin{cfuncdesc}{int}{PyFile_CheckExact}{PyObject *p}
2006 Returns true if its argument is a \ctype{PyFileObject}, but not a
2007 subtype of \ctype{PyFileObject}.
2008 \versionadded{2.2}
2009\end{cfuncdesc}
2010
2011\begin{cfuncdesc}{PyObject*}{PyFile_FromString}{char *filename, char *mode}
2012 On success, returns a new file object that is opened on the file
2013 given by \var{filename}, with a file mode given by \var{mode}, where
2014 \var{mode} has the same semantics as the standard C routine
2015 \cfunction{fopen()}\ttindex{fopen()}. On failure, returns \NULL.
2016\end{cfuncdesc}
2017
2018\begin{cfuncdesc}{PyObject*}{PyFile_FromFile}{FILE *fp,
2019 char *name, char *mode,
2020 int (*close)(FILE*)}
2021 Creates a new \ctype{PyFileObject} from the already-open standard C
2022 file pointer, \var{fp}. The function \var{close} will be called
2023 when the file should be closed. Returns \NULL{} on failure.
2024\end{cfuncdesc}
2025
2026\begin{cfuncdesc}{FILE*}{PyFile_AsFile}{PyFileObject *p}
2027 Returns the file object associated with \var{p} as a \ctype{FILE*}.
2028\end{cfuncdesc}
2029
2030\begin{cfuncdesc}{PyObject*}{PyFile_GetLine}{PyObject *p, int n}
2031 Equivalent to \code{\var{p}.readline(\optional{\var{n}})}, this
2032 function reads one line from the object \var{p}. \var{p} may be a
2033 file object or any object with a \method{readline()} method. If
2034 \var{n} is \code{0}, exactly one line is read, regardless of the
2035 length of the line. If \var{n} is greater than \code{0}, no more
2036 than \var{n} bytes will be read from the file; a partial line can be
2037 returned. In both cases, an empty string is returned if the end of
2038 the file is reached immediately. If \var{n} is less than \code{0},
2039 however, one line is read regardless of length, but
2040 \exception{EOFError} is raised if the end of the file is reached
2041 immediately.
2042 \withsubitem{(built-in exception)}{\ttindex{EOFError}}
2043\end{cfuncdesc}
2044
2045\begin{cfuncdesc}{PyObject*}{PyFile_Name}{PyObject *p}
2046 Returns the name of the file specified by \var{p} as a string
2047 object.
2048\end{cfuncdesc}
2049
2050\begin{cfuncdesc}{void}{PyFile_SetBufSize}{PyFileObject *p, int n}
2051 Available on systems with \cfunction{setvbuf()}\ttindex{setvbuf()}
2052 only. This should only be called immediately after file object
2053 creation.
2054\end{cfuncdesc}
2055
Martin v. Löwis5467d4c2003-05-10 07:10:12 +00002056\begin{cfuncdesc}{int}{PyFile_Encoding}{PyFileObject *p, char *enc}
2057 Set the file's encoding for Unicode output to \var{enc}. Return
2058 1 on success and 0 on failure.
2059 \versionadded{2.3}
2060\end{cfuncdesc}
2061
Fred Drake3adf79e2001-10-12 19:01:43 +00002062\begin{cfuncdesc}{int}{PyFile_SoftSpace}{PyObject *p, int newflag}
2063 This function exists for internal use by the interpreter. Sets the
2064 \member{softspace} attribute of \var{p} to \var{newflag} and
2065 \withsubitem{(file attribute)}{\ttindex{softspace}}returns the
2066 previous value. \var{p} does not have to be a file object for this
2067 function to work properly; any object is supported (thought its only
2068 interesting if the \member{softspace} attribute can be set). This
2069 function clears any errors, and will return \code{0} as the previous
2070 value if the attribute either does not exist or if there were errors
2071 in retrieving it. There is no way to detect errors from this
2072 function, but doing so should not be needed.
2073\end{cfuncdesc}
2074
2075\begin{cfuncdesc}{int}{PyFile_WriteObject}{PyObject *obj, PyFileObject *p,
2076 int flags}
2077 Writes object \var{obj} to file object \var{p}. The only supported
2078 flag for \var{flags} is
2079 \constant{Py_PRINT_RAW}\ttindex{Py_PRINT_RAW}; if given, the
2080 \function{str()} of the object is written instead of the
2081 \function{repr()}. Returns \code{0} on success or \code{-1} on
2082 failure; the appropriate exception will be set.
2083\end{cfuncdesc}
2084
Fred Drake454af892001-11-29 22:42:59 +00002085\begin{cfuncdesc}{int}{PyFile_WriteString}{const char *s, PyFileObject *p}
Fred Drake3adf79e2001-10-12 19:01:43 +00002086 Writes string \var{s} to file object \var{p}. Returns \code{0} on
2087 success or \code{-1} on failure; the appropriate exception will be
2088 set.
2089\end{cfuncdesc}
2090
2091
2092\subsection{Instance Objects \label{instanceObjects}}
2093
2094\obindex{instance}
2095There are very few functions specific to instance objects.
2096
2097\begin{cvardesc}{PyTypeObject}{PyInstance_Type}
2098 Type object for class instances.
2099\end{cvardesc}
2100
2101\begin{cfuncdesc}{int}{PyInstance_Check}{PyObject *obj}
2102 Returns true if \var{obj} is an instance.
2103\end{cfuncdesc}
2104
2105\begin{cfuncdesc}{PyObject*}{PyInstance_New}{PyObject *class,
2106 PyObject *arg,
2107 PyObject *kw}
2108 Create a new instance of a specific class. The parameters \var{arg}
2109 and \var{kw} are used as the positional and keyword parameters to
2110 the object's constructor.
2111\end{cfuncdesc}
2112
2113\begin{cfuncdesc}{PyObject*}{PyInstance_NewRaw}{PyObject *class,
2114 PyObject *dict}
2115 Create a new instance of a specific class without calling it's
2116 constructor. \var{class} is the class of new object. The
2117 \var{dict} parameter will be used as the object's \member{__dict__};
2118 if \NULL, a new dictionary will be created for the instance.
2119\end{cfuncdesc}
2120
2121
2122\subsection{Method Objects \label{method-objects}}
2123
2124\obindex{method}
2125There are some useful functions that are useful for working with
2126method objects.
2127
2128\begin{cvardesc}{PyTypeObject}{PyMethod_Type}
2129 This instance of \ctype{PyTypeObject} represents the Python method
2130 type. This is exposed to Python programs as \code{types.MethodType}.
2131 \withsubitem{(in module types)}{\ttindex{MethodType}}
2132\end{cvardesc}
2133
2134\begin{cfuncdesc}{int}{PyMethod_Check}{PyObject *o}
2135 Return true if \var{o} is a method object (has type
2136 \cdata{PyMethod_Type}). The parameter must not be \NULL.
2137\end{cfuncdesc}
2138
2139\begin{cfuncdesc}{PyObject*}{PyMethod_New}{PyObject *func.
2140 PyObject *self, PyObject *class}
2141 Return a new method object, with \var{func} being any callable
2142 object; this is the function that will be called when the method is
2143 called. If this method should be bound to an instance, \var{self}
2144 should be the instance and \var{class} should be the class of
2145 \var{self}, otherwise \var{self} should be \NULL{} and \var{class}
2146 should be the class which provides the unbound method..
2147\end{cfuncdesc}
2148
2149\begin{cfuncdesc}{PyObject*}{PyMethod_Class}{PyObject *meth}
2150 Return the class object from which the method \var{meth} was
2151 created; if this was created from an instance, it will be the class
2152 of the instance.
2153\end{cfuncdesc}
2154
2155\begin{cfuncdesc}{PyObject*}{PyMethod_GET_CLASS}{PyObject *meth}
2156 Macro version of \cfunction{PyMethod_Class()} which avoids error
2157 checking.
2158\end{cfuncdesc}
2159
2160\begin{cfuncdesc}{PyObject*}{PyMethod_Function}{PyObject *meth}
2161 Return the function object associated with the method \var{meth}.
2162\end{cfuncdesc}
2163
2164\begin{cfuncdesc}{PyObject*}{PyMethod_GET_FUNCTION}{PyObject *meth}
2165 Macro version of \cfunction{PyMethod_Function()} which avoids error
2166 checking.
2167\end{cfuncdesc}
2168
2169\begin{cfuncdesc}{PyObject*}{PyMethod_Self}{PyObject *meth}
2170 Return the instance associated with the method \var{meth} if it is
2171 bound, otherwise return \NULL.
2172\end{cfuncdesc}
2173
2174\begin{cfuncdesc}{PyObject*}{PyMethod_GET_SELF}{PyObject *meth}
2175 Macro version of \cfunction{PyMethod_Self()} which avoids error
2176 checking.
2177\end{cfuncdesc}
2178
2179
2180\subsection{Module Objects \label{moduleObjects}}
2181
2182\obindex{module}
2183There are only a few functions special to module objects.
2184
2185\begin{cvardesc}{PyTypeObject}{PyModule_Type}
2186 This instance of \ctype{PyTypeObject} represents the Python module
2187 type. This is exposed to Python programs as
2188 \code{types.ModuleType}.
2189 \withsubitem{(in module types)}{\ttindex{ModuleType}}
2190\end{cvardesc}
2191
2192\begin{cfuncdesc}{int}{PyModule_Check}{PyObject *p}
2193 Returns true if \var{p} is a module object, or a subtype of a module
2194 object.
2195 \versionchanged[Allowed subtypes to be accepted]{2.2}
2196\end{cfuncdesc}
2197
2198\begin{cfuncdesc}{int}{PyModule_CheckExact}{PyObject *p}
2199 Returns true if \var{p} is a module object, but not a subtype of
2200 \cdata{PyModule_Type}.
2201 \versionadded{2.2}
2202\end{cfuncdesc}
2203
2204\begin{cfuncdesc}{PyObject*}{PyModule_New}{char *name}
2205 Return a new module object with the \member{__name__} attribute set
2206 to \var{name}. Only the module's \member{__doc__} and
2207 \member{__name__} attributes are filled in; the caller is
2208 responsible for providing a \member{__file__} attribute.
2209 \withsubitem{(module attribute)}{
2210 \ttindex{__name__}\ttindex{__doc__}\ttindex{__file__}}
2211\end{cfuncdesc}
2212
2213\begin{cfuncdesc}{PyObject*}{PyModule_GetDict}{PyObject *module}
2214 Return the dictionary object that implements \var{module}'s
2215 namespace; this object is the same as the \member{__dict__}
2216 attribute of the module object. This function never fails.
2217 \withsubitem{(module attribute)}{\ttindex{__dict__}}
Fred Drakef495ef72002-04-12 19:32:07 +00002218 It is recommended extensions use other \cfunction{PyModule_*()}
2219 and \cfunction{PyObject_*()} functions rather than directly
2220 manipulate a module's \member{__dict__}.
Fred Drake3adf79e2001-10-12 19:01:43 +00002221\end{cfuncdesc}
2222
2223\begin{cfuncdesc}{char*}{PyModule_GetName}{PyObject *module}
2224 Return \var{module}'s \member{__name__} value. If the module does
2225 not provide one, or if it is not a string, \exception{SystemError}
2226 is raised and \NULL{} is returned.
2227 \withsubitem{(module attribute)}{\ttindex{__name__}}
2228 \withsubitem{(built-in exception)}{\ttindex{SystemError}}
2229\end{cfuncdesc}
2230
2231\begin{cfuncdesc}{char*}{PyModule_GetFilename}{PyObject *module}
2232 Return the name of the file from which \var{module} was loaded using
2233 \var{module}'s \member{__file__} attribute. If this is not defined,
2234 or if it is not a string, raise \exception{SystemError} and return
2235 \NULL.
2236 \withsubitem{(module attribute)}{\ttindex{__file__}}
2237 \withsubitem{(built-in exception)}{\ttindex{SystemError}}
2238\end{cfuncdesc}
2239
2240\begin{cfuncdesc}{int}{PyModule_AddObject}{PyObject *module,
2241 char *name, PyObject *value}
2242 Add an object to \var{module} as \var{name}. This is a convenience
2243 function which can be used from the module's initialization
2244 function. This steals a reference to \var{value}. Returns
2245 \code{-1} on error, \code{0} on success.
2246 \versionadded{2.0}
2247\end{cfuncdesc}
2248
2249\begin{cfuncdesc}{int}{PyModule_AddIntConstant}{PyObject *module,
2250 char *name, int value}
2251 Add an integer constant to \var{module} as \var{name}. This
2252 convenience function can be used from the module's initialization
2253 function. Returns \code{-1} on error, \code{0} on success.
2254 \versionadded{2.0}
2255\end{cfuncdesc}
2256
2257\begin{cfuncdesc}{int}{PyModule_AddStringConstant}{PyObject *module,
2258 char *name, char *value}
2259 Add a string constant to \var{module} as \var{name}. This
2260 convenience function can be used from the module's initialization
2261 function. The string \var{value} must be null-terminated. Returns
2262 \code{-1} on error, \code{0} on success.
2263 \versionadded{2.0}
2264\end{cfuncdesc}
2265
2266
2267\subsection{Iterator Objects \label{iterator-objects}}
2268
2269Python provides two general-purpose iterator objects. The first, a
2270sequence iterator, works with an arbitrary sequence supporting the
2271\method{__getitem__()} method. The second works with a callable
2272object and a sentinel value, calling the callable for each item in the
2273sequence, and ending the iteration when the sentinel value is
2274returned.
2275
2276\begin{cvardesc}{PyTypeObject}{PySeqIter_Type}
2277 Type object for iterator objects returned by
2278 \cfunction{PySeqIter_New()} and the one-argument form of the
2279 \function{iter()} built-in function for built-in sequence types.
2280 \versionadded{2.2}
2281\end{cvardesc}
2282
2283\begin{cfuncdesc}{int}{PySeqIter_Check}{op}
2284 Return true if the type of \var{op} is \cdata{PySeqIter_Type}.
2285 \versionadded{2.2}
2286\end{cfuncdesc}
2287
2288\begin{cfuncdesc}{PyObject*}{PySeqIter_New}{PyObject *seq}
2289 Return an iterator that works with a general sequence object,
2290 \var{seq}. The iteration ends when the sequence raises
2291 \exception{IndexError} for the subscripting operation.
2292 \versionadded{2.2}
2293\end{cfuncdesc}
2294
2295\begin{cvardesc}{PyTypeObject}{PyCallIter_Type}
2296 Type object for iterator objects returned by
2297 \cfunction{PyCallIter_New()} and the two-argument form of the
2298 \function{iter()} built-in function.
2299 \versionadded{2.2}
2300\end{cvardesc}
2301
2302\begin{cfuncdesc}{int}{PyCallIter_Check}{op}
2303 Return true if the type of \var{op} is \cdata{PyCallIter_Type}.
2304 \versionadded{2.2}
2305\end{cfuncdesc}
2306
2307\begin{cfuncdesc}{PyObject*}{PyCallIter_New}{PyObject *callable,
2308 PyObject *sentinel}
2309 Return a new iterator. The first parameter, \var{callable}, can be
2310 any Python callable object that can be called with no parameters;
2311 each call to it should return the next item in the iteration. When
2312 \var{callable} returns a value equal to \var{sentinel}, the
2313 iteration will be terminated.
2314 \versionadded{2.2}
2315\end{cfuncdesc}
2316
2317
2318\subsection{Descriptor Objects \label{descriptor-objects}}
2319
Fred Drake54e62942001-12-11 19:40:16 +00002320``Descriptors'' are objects that describe some attribute of an object.
2321They are found in the dictionary of type objects.
2322
Fred Drake3adf79e2001-10-12 19:01:43 +00002323\begin{cvardesc}{PyTypeObject}{PyProperty_Type}
Fred Drake54e62942001-12-11 19:40:16 +00002324 The type object for the built-in descriptor types.
Fred Drake3adf79e2001-10-12 19:01:43 +00002325 \versionadded{2.2}
2326\end{cvardesc}
2327
2328\begin{cfuncdesc}{PyObject*}{PyDescr_NewGetSet}{PyTypeObject *type,
2329 PyGetSetDef *getset}
2330 \versionadded{2.2}
2331\end{cfuncdesc}
2332
2333\begin{cfuncdesc}{PyObject*}{PyDescr_NewMember}{PyTypeObject *type,
2334 PyMemberDef *meth}
2335 \versionadded{2.2}
2336\end{cfuncdesc}
2337
2338\begin{cfuncdesc}{PyObject*}{PyDescr_NewMethod}{PyTypeObject *type,
2339 PyMethodDef *meth}
2340 \versionadded{2.2}
2341\end{cfuncdesc}
2342
2343\begin{cfuncdesc}{PyObject*}{PyDescr_NewWrapper}{PyTypeObject *type,
2344 struct wrapperbase *wrapper,
2345 void *wrapped}
2346 \versionadded{2.2}
2347\end{cfuncdesc}
2348
2349\begin{cfuncdesc}{int}{PyDescr_IsData}{PyObject *descr}
2350 Returns true if the descriptor objects \var{descr} describes a data
2351 attribute, or false if it describes a method. \var{descr} must be a
2352 descriptor object; there is no error checking.
2353 \versionadded{2.2}
2354\end{cfuncdesc}
2355
2356\begin{cfuncdesc}{PyObject*}{PyWrapper_New}{PyObject *, PyObject *}
2357 \versionadded{2.2}
2358\end{cfuncdesc}
2359
2360
2361\subsection{Slice Objects \label{slice-objects}}
2362
2363\begin{cvardesc}{PyTypeObject}{PySlice_Type}
2364 The type object for slice objects. This is the same as
2365 \code{types.SliceType}.
2366 \withsubitem{(in module types)}{\ttindex{SliceType}}
2367\end{cvardesc}
2368
2369\begin{cfuncdesc}{int}{PySlice_Check}{PyObject *ob}
2370 Returns true if \var{ob} is a slice object; \var{ob} must not be
2371 \NULL.
2372\end{cfuncdesc}
2373
2374\begin{cfuncdesc}{PyObject*}{PySlice_New}{PyObject *start, PyObject *stop,
2375 PyObject *step}
2376 Return a new slice object with the given values. The \var{start},
2377 \var{stop}, and \var{step} parameters are used as the values of the
2378 slice object attributes of the same names. Any of the values may be
2379 \NULL, in which case the \code{None} will be used for the
2380 corresponding attribute. Returns \NULL{} if the new object could
2381 not be allocated.
2382\end{cfuncdesc}
2383
2384\begin{cfuncdesc}{int}{PySlice_GetIndices}{PySliceObject *slice, int length,
2385 int *start, int *stop, int *step}
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002386Retrieve the start, stop and step indices from the slice object
2387\var{slice}, assuming a sequence of length \var{length}. Treats
2388indices greater than \var{length} as errors.
2389
2390Returns 0 on success and -1 on error with no exception set (unless one
2391of the indices was not \constant{None} and failed to be converted to
2392an integer, in which case -1 is returned with an exception set).
2393
2394You probably do not want to use this function. If you want to use
2395slice objects in versions of Python prior to 2.3, you would probably
2396do well to incorporate the source of \cfunction{PySlice_GetIndicesEx},
2397suitably renamed, in the source of your extension.
2398\end{cfuncdesc}
2399
2400\begin{cfuncdesc}{int}{PySlice_GetIndicesEx}{PySliceObject *slice, int length,
2401 int *start, int *stop, int *step,
2402 int *slicelength}
2403Usable replacement for \cfunction{PySlice_GetIndices}. Retrieve the
2404start, stop, and step indices from the slice object \var{slice}
2405assuming a sequence of length \var{length}, and store the length of
2406the slice in \var{slicelength}. Out of bounds indices are clipped in
2407a manner consistent with the handling of normal slices.
2408
2409Returns 0 on success and -1 on error with exception set.
2410
2411\versionadded{2.3}
Fred Drake3adf79e2001-10-12 19:01:43 +00002412\end{cfuncdesc}
2413
2414
2415\subsection{Weak Reference Objects \label{weakref-objects}}
2416
2417Python supports \emph{weak references} as first-class objects. There
2418are two specific object types which directly implement weak
2419references. The first is a simple reference object, and the second
2420acts as a proxy for the original object as much as it can.
2421
2422\begin{cfuncdesc}{int}{PyWeakref_Check}{ob}
2423 Return true if \var{ob} is either a reference or proxy object.
2424 \versionadded{2.2}
2425\end{cfuncdesc}
2426
2427\begin{cfuncdesc}{int}{PyWeakref_CheckRef}{ob}
2428 Return true if \var{ob} is a reference object.
2429 \versionadded{2.2}
2430\end{cfuncdesc}
2431
2432\begin{cfuncdesc}{int}{PyWeakref_CheckProxy}{ob}
2433 Return true if \var{ob} is a proxy object.
2434 \versionadded{2.2}
2435\end{cfuncdesc}
2436
2437\begin{cfuncdesc}{PyObject*}{PyWeakref_NewRef}{PyObject *ob,
2438 PyObject *callback}
2439 Return a weak reference object for the object \var{ob}. This will
2440 always return a new reference, but is not guaranteed to create a new
2441 object; an existing reference object may be returned. The second
2442 parameter, \var{callback}, can be a callable object that receives
2443 notification when \var{ob} is garbage collected; it should accept a
2444 single paramter, which will be the weak reference object itself.
2445 \var{callback} may also be \code{None} or \NULL. If \var{ob}
2446 is not a weakly-referencable object, or if \var{callback} is not
2447 callable, \code{None}, or \NULL, this will return \NULL{} and
2448 raise \exception{TypeError}.
2449 \versionadded{2.2}
2450\end{cfuncdesc}
2451
2452\begin{cfuncdesc}{PyObject*}{PyWeakref_NewProxy}{PyObject *ob,
2453 PyObject *callback}
2454 Return a weak reference proxy object for the object \var{ob}. This
2455 will always return a new reference, but is not guaranteed to create
2456 a new object; an existing proxy object may be returned. The second
2457 parameter, \var{callback}, can be a callable object that receives
2458 notification when \var{ob} is garbage collected; it should accept a
2459 single paramter, which will be the weak reference object itself.
2460 \var{callback} may also be \code{None} or \NULL. If \var{ob} is not
2461 a weakly-referencable object, or if \var{callback} is not callable,
2462 \code{None}, or \NULL, this will return \NULL{} and raise
2463 \exception{TypeError}.
2464 \versionadded{2.2}
2465\end{cfuncdesc}
2466
2467\begin{cfuncdesc}{PyObject*}{PyWeakref_GetObject}{PyObject *ref}
2468 Returns the referenced object from a weak reference, \var{ref}. If
Ka-Ping Yeebd379e92003-03-28 18:07:16 +00002469 the referent is no longer live, returns \code{None}.
Fred Drake3adf79e2001-10-12 19:01:43 +00002470 \versionadded{2.2}
2471\end{cfuncdesc}
2472
2473\begin{cfuncdesc}{PyObject*}{PyWeakref_GET_OBJECT}{PyObject *ref}
2474 Similar to \cfunction{PyWeakref_GetObject()}, but implemented as a
2475 macro that does no error checking.
2476 \versionadded{2.2}
2477\end{cfuncdesc}
2478
2479
2480\subsection{CObjects \label{cObjects}}
2481
2482\obindex{CObject}
2483Refer to \emph{Extending and Embedding the Python Interpreter},
Fred Drake54e62942001-12-11 19:40:16 +00002484section~1.12, ``Providing a C API for an Extension Module,'' for more
Fred Drake3adf79e2001-10-12 19:01:43 +00002485information on using these objects.
2486
2487
2488\begin{ctypedesc}{PyCObject}
2489 This subtype of \ctype{PyObject} represents an opaque value, useful
2490 for C extension modules who need to pass an opaque value (as a
2491 \ctype{void*} pointer) through Python code to other C code. It is
2492 often used to make a C function pointer defined in one module
2493 available to other modules, so the regular import mechanism can be
2494 used to access C APIs defined in dynamically loaded modules.
2495\end{ctypedesc}
2496
2497\begin{cfuncdesc}{int}{PyCObject_Check}{PyObject *p}
Martin v. Löwis01a74b22003-10-19 18:30:01 +00002498 Return true if its argument is a \ctype{PyCObject}.
Fred Drake3adf79e2001-10-12 19:01:43 +00002499\end{cfuncdesc}
2500
Tim Petersf582b822001-12-11 18:51:08 +00002501\begin{cfuncdesc}{PyObject*}{PyCObject_FromVoidPtr}{void* cobj,
Fred Drake54e62942001-12-11 19:40:16 +00002502 void (*destr)(void *)}
Martin v. Löwis01a74b22003-10-19 18:30:01 +00002503 Create a \ctype{PyCObject} from the \code{void *}\var{cobj}. The
Fred Drake3adf79e2001-10-12 19:01:43 +00002504 \var{destr} function will be called when the object is reclaimed,
2505 unless it is \NULL.
2506\end{cfuncdesc}
2507
2508\begin{cfuncdesc}{PyObject*}{PyCObject_FromVoidPtrAndDesc}{void* cobj,
2509 void* desc, void (*destr)(void *, void *)}
Martin v. Löwis01a74b22003-10-19 18:30:01 +00002510 Create a \ctype{PyCObject} from the \ctype{void *}\var{cobj}. The
Fred Drake3adf79e2001-10-12 19:01:43 +00002511 \var{destr} function will be called when the object is reclaimed.
2512 The \var{desc} argument can be used to pass extra callback data for
2513 the destructor function.
2514\end{cfuncdesc}
2515
2516\begin{cfuncdesc}{void*}{PyCObject_AsVoidPtr}{PyObject* self}
Martin v. Löwis01a74b22003-10-19 18:30:01 +00002517 Return the object \ctype{void *} that the \ctype{PyCObject}
Fred Drake3adf79e2001-10-12 19:01:43 +00002518 \var{self} was created with.
2519\end{cfuncdesc}
2520
2521\begin{cfuncdesc}{void*}{PyCObject_GetDesc}{PyObject* self}
Martin v. Löwis01a74b22003-10-19 18:30:01 +00002522 Return the description \ctype{void *} that the \ctype{PyCObject}
Fred Drake3adf79e2001-10-12 19:01:43 +00002523 \var{self} was created with.
2524\end{cfuncdesc}
Fred Drakecd8474e2001-11-26 21:29:17 +00002525
Martin v. Löwis01a74b22003-10-19 18:30:01 +00002526\begin{cfuncdesc}{int}{PyCObject_SetVoidPtr}{PyObject* self, void* cobj}
2527 Set the void pointer inside \var{self} to \var{cobj}.
2528 The \ctype{PyCObject} must not have an associated destructor.
2529 Return true on success, false on failure.
2530\end{cfuncdesc}
2531
Fred Drakecd8474e2001-11-26 21:29:17 +00002532
2533\subsection{Cell Objects \label{cell-objects}}
2534
2535``Cell'' objects are used to implement variables referenced by
2536multiple scopes. For each such variable, a cell object is created to
2537store the value; the local variables of each stack frame that
2538references the value contains a reference to the cells from outer
2539scopes which also use that variable. When the value is accessed, the
2540value contained in the cell is used instead of the cell object
2541itself. This de-referencing of the cell object requires support from
2542the generated byte-code; these are not automatically de-referenced
2543when accessed. Cell objects are not likely to be useful elsewhere.
2544
Fred Drake54e62942001-12-11 19:40:16 +00002545\begin{ctypedesc}{PyCellObject}
2546 The C structure used for cell objects.
2547\end{ctypedesc}
2548
Fred Drakecd8474e2001-11-26 21:29:17 +00002549\begin{cvardesc}{PyTypeObject}{PyCell_Type}
2550 The type object corresponding to cell objects
2551\end{cvardesc}
2552
2553\begin{cfuncdesc}{int}{PyCell_Check}{ob}
2554 Return true if \var{ob} is a cell object; \var{ob} must not be
2555 \NULL.
2556\end{cfuncdesc}
2557
2558\begin{cfuncdesc}{PyObject*}{PyCell_New}{PyObject *ob}
2559 Create and return a new cell object containing the value \var{ob}.
2560 The parameter may be \NULL.
2561\end{cfuncdesc}
2562
2563\begin{cfuncdesc}{PyObject*}{PyCell_Get}{PyObject *cell}
2564 Return the contents of the cell \var{cell}.
2565\end{cfuncdesc}
2566
2567\begin{cfuncdesc}{PyObject*}{PyCell_GET}{PyObject *cell}
2568 Return the contents of the cell \var{cell}, but without checking
Raymond Hettingerf4bb1f92003-08-23 03:38:11 +00002569 that \var{cell} is non-\NULL{} and a cell object.
Fred Drakecd8474e2001-11-26 21:29:17 +00002570\end{cfuncdesc}
2571
2572\begin{cfuncdesc}{int}{PyCell_Set}{PyObject *cell, PyObject *value}
2573 Set the contents of the cell object \var{cell} to \var{value}. This
2574 releases the reference to any current content of the cell.
2575 \var{value} may be \NULL. \var{cell} must be non-\NULL; if it is
2576 not a cell object, \code{-1} will be returned. On success, \code{0}
2577 will be returned.
2578\end{cfuncdesc}
2579
2580\begin{cfuncdesc}{void}{PyCell_SET}{PyObject *cell, PyObject *value}
2581 Sets the value of the cell object \var{cell} to \var{value}. No
2582 reference counts are adjusted, and no checks are made for safety;
2583 \var{cell} must be non-\NULL{} and must be a cell object.
2584\end{cfuncdesc}