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