1 \chapter{Concrete Objects Layer
\label{concrete
}}
4 The functions in this chapter are specific to certain Python object
5 types. Passing them an object of the wrong type is not a good idea;
6 if you receive an object from a Python program and you are not sure
7 that it has the right type, you must perform a type check first;
8 for 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.
12 \warning{While the functions described in this chapter carefully check
13 the type of the objects which are passed in, many of them do not check
14 for
\NULL{} being passed instead of a valid object. Allowing
\NULL{}
15 to be passed in can cause memory access violations and immediate
16 termination of the interpreter.
}
19 \section{Fundamental Objects
\label{fundamental
}}
21 This section describes Python type objects and the singleton object
25 \subsection{Type Objects
\label{typeObjects
}}
28 \begin{ctypedesc
}{PyTypeObject
}
29 The C structure of the objects used to describe built-in types.
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
}}
38 \begin{cfuncdesc
}{int
}{PyType_Check
}{PyObject *o
}
39 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.
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
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.
56 \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
}.
62 \begin{cfuncdesc
}{int
}{PyType_IsSubtype
}{PyTypeObject *a, PyTypeObject *b
}
63 Returns true if
\var{a
} is a subtype of
\var{b
}.
67 \begin{cfuncdesc
}{PyObject*
}{PyType_GenericAlloc
}{PyTypeObject *type,
72 \begin{cfuncdesc
}{PyObject*
}{PyType_GenericNew
}{PyTypeObject *type,
73 PyObject *args, PyObject *kwds
}
77 \begin{cfuncdesc
}{int
}{PyType_Ready
}{PyTypeObject *type
}
78 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.
86 \subsection{The None Object
\label{noneObject
}}
89 Note that the
\ctype{PyTypeObject
} for
\code{None
} is not directly
90 exposed in the Python/C API. Since
\code{None
} is a singleton,
91 testing for object identity (using
\samp{==
} in C) is sufficient.
92 There is no
\cfunction{PyNone_Check()
} function for the same reason.
94 \begin{cvardesc
}{PyObject*
}{Py_None
}
95 The Python
\code{None
} object, denoting lack of value. This object
96 has no methods. It needs to be treated just like any other object
97 with respect to reference counts.
100 \begin{csimplemacrodesc
}{Py_RETURN_NONE
}
101 Properly handles returning
\cdata{Py_None
} from within a C function.
102 \end{csimplemacrodesc
}
105 \section{Numeric Objects
\label{numericObjects
}}
110 \subsection{Plain Integer Objects
\label{intObjects
}}
113 \begin{ctypedesc
}{PyIntObject
}
114 This subtype of
\ctype{PyObject
} represents a Python integer
118 \begin{cvardesc
}{PyTypeObject
}{PyInt_Type
}
119 This instance of
\ctype{PyTypeObject
} represents the Python plain
120 integer type. This is the same object as
\code{types.IntType
}.
121 \withsubitem{(in modules types)
}{\ttindex{IntType
}}
124 \begin{cfuncdesc
}{int
}{PyInt_Check
}{PyObject *o
}
125 Returns true if
\var{o
} is of type
\cdata{PyInt_Type
} or a subtype
126 of
\cdata{PyInt_Type
}.
127 \versionchanged[Allowed subtypes to be accepted
]{2.2}
130 \begin{cfuncdesc
}{int
}{PyInt_CheckExact
}{PyObject *o
}
131 Returns true if
\var{o
} is of type
\cdata{PyInt_Type
}, but not a
132 subtype of
\cdata{PyInt_Type
}.
136 \begin{cfuncdesc
}{PyObject*
}{PyInt_FromString
}{char *str, char **pend,
138 Return a new
\ctype{PyIntObject
} or
\ctype{PyLongObject
} based on the
139 string value in
\var{str
}, which is interpreted according to the radix in
140 \var{base
}. If
\var{pend
} is non-
\NULL{},
\code{*
\var{pend
}} will point to
141 the first character in
\var{str
} which follows the representation of the
142 number. If
\var{base
} is
\code{0}, the radix will be determined based on
143 the leading characters of
\var{str
}: if
\var{str
} starts with
\code{'
0x'
}
144 or
\code{'
0X'
}, radix
16 will be used; if
\var{str
} starts with
145 \code{'
0'
}, radix
8 will be used; otherwise radix
10 will be used. If
146 \var{base
} is not
\code{0}, it must be between
\code{2} and
\code{36},
147 inclusive. Leading spaces are ignored. If there are no digits,
148 \exception{ValueError
} will be raised. If the string represents a number
149 too large to be contained within the machine's
\ctype{long int
} type and
150 overflow warnings are being suppressed, a
\ctype{PyLongObject
} will be
151 returned. If overflow warnings are not being suppressed,
\NULL{} will be
152 returned in this case.
155 \begin{cfuncdesc
}{PyObject*
}{PyInt_FromLong
}{long ival
}
156 Creates a new integer object with a value of
\var{ival
}.
158 The current implementation keeps an array of integer objects for all
159 integers between
\code{-
1} and
\code{100}, when you create an int in
160 that range you actually just get back a reference to the existing
161 object. So it should be possible to change the value of
\code{1}. I
162 suspect the behaviour of Python in this case is undefined. :-)
165 \begin{cfuncdesc
}{long
}{PyInt_AsLong
}{PyObject *io
}
166 Will first attempt to cast the object to a
\ctype{PyIntObject
}, if
167 it is not already one, and then return its value.
170 \begin{cfuncdesc
}{long
}{PyInt_AS_LONG
}{PyObject *io
}
171 Returns the value of the object
\var{io
}. No error checking is
175 \begin{cfuncdesc
}{unsigned long
}{PyInt_AsUnsignedLongMask
}{PyObject *io
}
176 Will first attempt to cast the object to a
\ctype{PyIntObject
} or
177 \ctype{PyLongObject
}, if it is not already one, and then return its
178 value as unsigned long. This function does not check for overflow.
182 \begin{cfuncdesc
}{unsigned long long
}{PyInt_AsUnsignedLongLongMask
}{PyObject *io
}
183 Will first attempt to cast the object to a
\ctype{PyIntObject
} or
184 \ctype{PyLongObject
}, if it is not already one, and then return its
185 value as unsigned long long, without checking for overflow.
189 \begin{cfuncdesc
}{long
}{PyInt_GetMax
}{}
190 Returns the system's idea of the largest integer it can handle
191 (
\constant{LONG_MAX
}\ttindex{LONG_MAX
}, as defined in the system
195 \subsection{Boolean Objects
\label{boolObjects
}}
197 Booleans in Python are implemented as a subclass of integers. There
198 are only two booleans,
\constant{Py_False
} and
\constant{Py_True
}. As
199 such, the normal creation and deletion functions don't apply to
200 booleans. The following macros are available, however.
202 \begin{cfuncdesc
}{int
}{PyBool_Check
}{PyObject *o
}
203 Returns true if
\var{o
} is of type
\cdata{PyBool_Type
}.
207 \begin{cvardesc
}{PyObject*
}{Py_False
}
208 The Python
\code{False
} object. This object has no methods. It needs to
209 be treated just like any other object with respect to reference counts.
212 \begin{cvardesc
}{PyObject*
}{Py_True
}
213 The Python
\code{True
} object. This object has no methods. It needs to
214 be treated just like any other object with respect to reference counts.
217 \begin{csimplemacrodesc
}{Py_RETURN_FALSE
}
218 Return
\constant{Py_False
} from a function, properly incrementing its
221 \end{csimplemacrodesc
}
223 \begin{csimplemacrodesc
}{Py_RETURN_TRUE
}
224 Return
\constant{Py_True
} from a function, properly incrementing its
227 \end{csimplemacrodesc
}
229 \begin{cfuncdesc
}{int
}{PyBool_FromLong
}{long v
}
230 Returns
\constant{Py_True
} or
\constant{Py_False
} depending on the
231 truth value of
\var{v
}.
235 \subsection{Long Integer Objects
\label{longObjects
}}
237 \obindex{long integer
}
238 \begin{ctypedesc
}{PyLongObject
}
239 This subtype of
\ctype{PyObject
} represents a Python long integer
243 \begin{cvardesc
}{PyTypeObject
}{PyLong_Type
}
244 This instance of
\ctype{PyTypeObject
} represents the Python long
245 integer type. This is the same object as
\code{types.LongType
}.
246 \withsubitem{(in modules types)
}{\ttindex{LongType
}}
249 \begin{cfuncdesc
}{int
}{PyLong_Check
}{PyObject *p
}
250 Returns true if its argument is a
\ctype{PyLongObject
} or a subtype
251 of
\ctype{PyLongObject
}.
252 \versionchanged[Allowed subtypes to be accepted
]{2.2}
255 \begin{cfuncdesc
}{int
}{PyLong_CheckExact
}{PyObject *p
}
256 Returns true if its argument is a
\ctype{PyLongObject
}, but not a
257 subtype of
\ctype{PyLongObject
}.
261 \begin{cfuncdesc
}{PyObject*
}{PyLong_FromLong
}{long v
}
262 Returns a new
\ctype{PyLongObject
} object from
\var{v
}, or
\NULL{}
266 \begin{cfuncdesc
}{PyObject*
}{PyLong_FromUnsignedLong
}{unsigned long v
}
267 Returns a new
\ctype{PyLongObject
} object from a C
\ctype{unsigned
268 long
}, or
\NULL{} on failure.
271 \begin{cfuncdesc
}{PyObject*
}{PyLong_FromLongLong
}{long long v
}
272 Returns a new
\ctype{PyLongObject
} object from a C
\ctype{long long
},
273 or
\NULL{} on failure.
276 \begin{cfuncdesc
}{PyObject*
}{PyLong_FromUnsignedLongLong
}{unsigned long long v
}
277 Returns a new
\ctype{PyLongObject
} object from a C
\ctype{unsigned
278 long long
}, or
\NULL{} on failure.
281 \begin{cfuncdesc
}{PyObject*
}{PyLong_FromDouble
}{double v
}
282 Returns a new
\ctype{PyLongObject
} object from the integer part of
283 \var{v
}, or
\NULL{} on failure.
286 \begin{cfuncdesc
}{PyObject*
}{PyLong_FromString
}{char *str, char **pend,
288 Return a new
\ctype{PyLongObject
} based on the string value in
289 \var{str
}, which is interpreted according to the radix in
290 \var{base
}. If
\var{pend
} is non-
\NULL{},
\code{*
\var{pend
}} will
291 point to the first character in
\var{str
} which follows the
292 representation of the number. If
\var{base
} is
\code{0}, the radix
293 will be determined based on the leading characters of
\var{str
}: if
294 \var{str
} starts with
\code{'
0x'
} or
\code{'
0X'
}, radix
16 will be
295 used; if
\var{str
} starts with
\code{'
0'
}, radix
8 will be used;
296 otherwise radix
10 will be used. If
\var{base
} is not
\code{0}, it
297 must be between
\code{2} and
\code{36}, inclusive. Leading spaces
298 are ignored. If there are no digits,
\exception{ValueError
} will be
302 \begin{cfuncdesc
}{PyObject*
}{PyLong_FromUnicode
}{Py_UNICODE *u,
303 int length, int base
}
304 Convert a sequence of Unicode digits to a Python long integer
305 value. The first parameter,
\var{u
}, points to the first character
306 of the Unicode string,
\var{length
} gives the number of characters,
307 and
\var{base
} is the radix for the conversion. The radix must be
308 in the range
[2,
36]; if it is out of range,
\exception{ValueError
}
313 \begin{cfuncdesc
}{PyObject*
}{PyLong_FromVoidPtr
}{void *p
}
314 Create a Python integer or long integer from the pointer
\var{p
}.
315 The pointer value can be retrieved from the resulting value using
316 \cfunction{PyLong_AsVoidPtr()
}.
320 \begin{cfuncdesc
}{long
}{PyLong_AsLong
}{PyObject *pylong
}
321 Returns a C
\ctype{long
} representation of the contents of
322 \var{pylong
}. If
\var{pylong
} is greater than
323 \constant{LONG_MAX
}\ttindex{LONG_MAX
}, an
\exception{OverflowError
}
325 \withsubitem{(built-in exception)
}{\ttindex{OverflowError
}}
328 \begin{cfuncdesc
}{unsigned long
}{PyLong_AsUnsignedLong
}{PyObject *pylong
}
329 Returns a C
\ctype{unsigned long
} representation of the contents of
330 \var{pylong
}. If
\var{pylong
} is greater than
331 \constant{ULONG_MAX
}\ttindex{ULONG_MAX
}, an
332 \exception{OverflowError
} is raised.
333 \withsubitem{(built-in exception)
}{\ttindex{OverflowError
}}
336 \begin{cfuncdesc
}{long long
}{PyLong_AsLongLong
}{PyObject *pylong
}
337 Return a C
\ctype{long long
} from a Python long integer. If
338 \var{pylong
} cannot be represented as a
\ctype{long long
}, an
339 \exception{OverflowError
} will be raised.
343 \begin{cfuncdesc
}{unsigned long long
}{PyLong_AsUnsignedLongLong
}{PyObject
345 Return a C
\ctype{unsigned long long
} from a Python long integer.
346 If
\var{pylong
} cannot be represented as an
\ctype{unsigned long
347 long
}, an
\exception{OverflowError
} will be raised if the value is
348 positive, or a
\exception{TypeError
} will be raised if the value is
353 \begin{cfuncdesc
}{unsigned long
}{PyLong_AsUnsignedLongMask
}{PyObject *io
}
354 Return a C
\ctype{unsigned long
} from a Python long integer, without
355 checking for overflow.
359 \begin{cfuncdesc
}{unsigned long
}{PyLong_AsUnsignedLongLongMask
}{PyObject *io
}
360 Return a C
\ctype{unsigned long long
} from a Python long integer, without
361 checking for overflow.
365 \begin{cfuncdesc
}{double
}{PyLong_AsDouble
}{PyObject *pylong
}
366 Returns a C
\ctype{double
} representation of the contents of
367 \var{pylong
}. If
\var{pylong
} cannot be approximately represented
368 as a
\ctype{double
}, an
\exception{OverflowError
} exception is
369 raised and
\code{-
1.0} will be returned.
372 \begin{cfuncdesc
}{void*
}{PyLong_AsVoidPtr
}{PyObject *pylong
}
373 Convert a Python integer or long integer
\var{pylong
} to a C
374 \ctype{void
} pointer. If
\var{pylong
} cannot be converted, an
375 \exception{OverflowError
} will be raised. This is only assured to
376 produce a usable
\ctype{void
} pointer for values created with
377 \cfunction{PyLong_FromVoidPtr()
}.
382 \subsection{Floating Point Objects
\label{floatObjects
}}
384 \obindex{floating point
}
385 \begin{ctypedesc
}{PyFloatObject
}
386 This subtype of
\ctype{PyObject
} represents a Python floating point
390 \begin{cvardesc
}{PyTypeObject
}{PyFloat_Type
}
391 This instance of
\ctype{PyTypeObject
} represents the Python floating
392 point type. This is the same object as
\code{types.FloatType
}.
393 \withsubitem{(in modules types)
}{\ttindex{FloatType
}}
396 \begin{cfuncdesc
}{int
}{PyFloat_Check
}{PyObject *p
}
397 Returns true if its argument is a
\ctype{PyFloatObject
} or a subtype
398 of
\ctype{PyFloatObject
}.
399 \versionchanged[Allowed subtypes to be accepted
]{2.2}
402 \begin{cfuncdesc
}{int
}{PyFloat_CheckExact
}{PyObject *p
}
403 Returns true if its argument is a
\ctype{PyFloatObject
}, but not a
404 subtype of
\ctype{PyFloatObject
}.
408 \begin{cfuncdesc
}{PyObject*
}{PyFloat_FromString
}{PyObject *str, char **pend
}
409 Creates a
\ctype{PyFloatObject
} object based on the string value in
410 \var{str
}, or
\NULL{} on failure. The
\var{pend
} argument is ignored. It
411 remains only for backward compatibility.
414 \begin{cfuncdesc
}{PyObject*
}{PyFloat_FromDouble
}{double v
}
415 Creates a
\ctype{PyFloatObject
} object from
\var{v
}, or
\NULL{} on
419 \begin{cfuncdesc
}{double
}{PyFloat_AsDouble
}{PyObject *pyfloat
}
420 Returns a C
\ctype{double
} representation of the contents of
424 \begin{cfuncdesc
}{double
}{PyFloat_AS_DOUBLE
}{PyObject *pyfloat
}
425 Returns a C
\ctype{double
} representation of the contents of
426 \var{pyfloat
}, but without error checking.
430 \subsection{Complex Number Objects
\label{complexObjects
}}
432 \obindex{complex number
}
433 Python's complex number objects are implemented as two distinct types
434 when viewed from the C API: one is the Python object exposed to
435 Python programs, and the other is a C structure which represents the
436 actual complex number value. The API provides functions for working
439 \subsubsection{Complex Numbers as C Structures
}
441 Note that the functions which accept these structures as parameters
442 and return them as results do so
\emph{by value
} rather than
443 dereferencing them through pointers. This is consistent throughout
446 \begin{ctypedesc
}{Py_complex
}
447 The C structure which corresponds to the value portion of a Python
448 complex number object. Most of the functions for dealing with
449 complex number objects use structures of this type as input or
450 output values, as appropriate. It is defined as:
460 \begin{cfuncdesc
}{Py_complex
}{_Py_c_sum
}{Py_complex left, Py_complex right
}
461 Return the sum of two complex numbers, using the C
462 \ctype{Py_complex
} representation.
465 \begin{cfuncdesc
}{Py_complex
}{_Py_c_diff
}{Py_complex left, Py_complex right
}
466 Return the difference between two complex numbers, using the C
467 \ctype{Py_complex
} representation.
470 \begin{cfuncdesc
}{Py_complex
}{_Py_c_neg
}{Py_complex complex
}
471 Return the negation of the complex number
\var{complex
}, using the C
472 \ctype{Py_complex
} representation.
475 \begin{cfuncdesc
}{Py_complex
}{_Py_c_prod
}{Py_complex left, Py_complex right
}
476 Return the product of two complex numbers, using the C
477 \ctype{Py_complex
} representation.
480 \begin{cfuncdesc
}{Py_complex
}{_Py_c_quot
}{Py_complex dividend,
482 Return the quotient of two complex numbers, using the C
483 \ctype{Py_complex
} representation.
486 \begin{cfuncdesc
}{Py_complex
}{_Py_c_pow
}{Py_complex num, Py_complex exp
}
487 Return the exponentiation of
\var{num
} by
\var{exp
}, using the C
488 \ctype{Py_complex
} representation.
492 \subsubsection{Complex Numbers as Python Objects
}
494 \begin{ctypedesc
}{PyComplexObject
}
495 This subtype of
\ctype{PyObject
} represents a Python complex number
499 \begin{cvardesc
}{PyTypeObject
}{PyComplex_Type
}
500 This instance of
\ctype{PyTypeObject
} represents the Python complex
504 \begin{cfuncdesc
}{int
}{PyComplex_Check
}{PyObject *p
}
505 Returns true if its argument is a
\ctype{PyComplexObject
} or a
506 subtype of
\ctype{PyComplexObject
}.
507 \versionchanged[Allowed subtypes to be accepted
]{2.2}
510 \begin{cfuncdesc
}{int
}{PyComplex_CheckExact
}{PyObject *p
}
511 Returns true if its argument is a
\ctype{PyComplexObject
}, but not a
512 subtype of
\ctype{PyComplexObject
}.
516 \begin{cfuncdesc
}{PyObject*
}{PyComplex_FromCComplex
}{Py_complex v
}
517 Create a new Python complex number object from a C
518 \ctype{Py_complex
} value.
521 \begin{cfuncdesc
}{PyObject*
}{PyComplex_FromDoubles
}{double real, double imag
}
522 Returns a new
\ctype{PyComplexObject
} object from
\var{real
} and
526 \begin{cfuncdesc
}{double
}{PyComplex_RealAsDouble
}{PyObject *op
}
527 Returns the real part of
\var{op
} as a C
\ctype{double
}.
530 \begin{cfuncdesc
}{double
}{PyComplex_ImagAsDouble
}{PyObject *op
}
531 Returns the imaginary part of
\var{op
} as a C
\ctype{double
}.
534 \begin{cfuncdesc
}{Py_complex
}{PyComplex_AsCComplex
}{PyObject *op
}
535 Returns the
\ctype{Py_complex
} value of the complex number
541 \section{Sequence Objects
\label{sequenceObjects
}}
544 Generic operations on sequence objects were discussed in the previous
545 chapter; this section deals with the specific kinds of sequence
546 objects that are intrinsic to the Python language.
549 \subsection{String Objects
\label{stringObjects
}}
551 These functions raise
\exception{TypeError
} when expecting a string
552 parameter and are called with a non-string parameter.
555 \begin{ctypedesc
}{PyStringObject
}
556 This subtype of
\ctype{PyObject
} represents a Python string object.
559 \begin{cvardesc
}{PyTypeObject
}{PyString_Type
}
560 This instance of
\ctype{PyTypeObject
} represents the Python string
561 type; it is the same object as
\code{types.TypeType
} in the Python
563 \withsubitem{(in module types)
}{\ttindex{StringType
}}.
566 \begin{cfuncdesc
}{int
}{PyString_Check
}{PyObject *o
}
567 Returns true if the object
\var{o
} is a string object or an instance
568 of a subtype of the string type.
569 \versionchanged[Allowed subtypes to be accepted
]{2.2}
572 \begin{cfuncdesc
}{int
}{PyString_CheckExact
}{PyObject *o
}
573 Returns true if the object
\var{o
} is a string object, but not an
574 instance of a subtype of the string type.
578 \begin{cfuncdesc
}{PyObject*
}{PyString_FromString
}{const char *v
}
579 Returns a new string object with the value
\var{v
} on success, and
580 \NULL{} on failure. The parameter
\var{v
} must not be
\NULL{}; it
584 \begin{cfuncdesc
}{PyObject*
}{PyString_FromStringAndSize
}{const char *v,
586 Returns a new string object with the value
\var{v
} and length
587 \var{len
} on success, and
\NULL{} on failure. If
\var{v
} is
588 \NULL{}, the contents of the string are uninitialized.
591 \begin{cfuncdesc
}{PyObject*
}{PyString_FromFormat
}{const char *format, ...
}
592 Takes a C
\cfunction{printf()
}-style
\var{format
} string and a
593 variable number of arguments, calculates the size of the resulting
594 Python string and returns a string with the values formatted into
595 it. The variable arguments must be C types and must correspond
596 exactly to the format characters in the
\var{format
} string. The
597 following format characters are allowed:
599 \begin{tableiii
}{l|l|l
}{member
}{Format Characters
}{Type
}{Comment
}
600 \lineiii{\%\%
}{\emph{n/a
}}{The literal \% character.
}
601 \lineiii{\%c
}{int
}{A single character, represented as an C int.
}
602 \lineiii{\%d
}{int
}{Exactly equivalent to
\code{printf("\%d")
}.
}
603 \lineiii{\%ld
}{long
}{Exactly equivalent to
\code{printf("\%ld")
}.
}
604 \lineiii{\%i
}{int
}{Exactly equivalent to
\code{printf("\%i")
}.
}
605 \lineiii{\%x
}{int
}{Exactly equivalent to
\code{printf("\%x")
}.
}
606 \lineiii{\%s
}{char*
}{A null-terminated C character array.
}
607 \lineiii{\%p
}{void*
}{The hex representation of a C pointer.
608 Mostly equivalent to
\code{printf("\%p")
} except that it is
609 guaranteed to start with the literal
\code{0x
} regardless of
610 what the platform's
\code{printf
} yields.
}
614 \begin{cfuncdesc
}{PyObject*
}{PyString_FromFormatV
}{const char *format,
616 Identical to
\function{PyString_FromFormat()
} except that it takes
617 exactly two arguments.
620 \begin{cfuncdesc
}{int
}{PyString_Size
}{PyObject *string
}
621 Returns the length of the string in string object
\var{string
}.
624 \begin{cfuncdesc
}{int
}{PyString_GET_SIZE
}{PyObject *string
}
625 Macro form of
\cfunction{PyString_Size()
} but without error
629 \begin{cfuncdesc
}{char*
}{PyString_AsString
}{PyObject *string
}
630 Returns a NUL-terminated representation of the contents of
631 \var{string
}. The pointer refers to the internal buffer of
632 \var{string
}, not a copy. The data must not be modified in any way,
633 unless the string was just created using
634 \code{PyString_FromStringAndSize(NULL,
\var{size
})
}.
635 It must not be deallocated. If
\var{string
} is a Unicode object,
636 this function computes the default encoding of
\var{string
} and
637 operates on that. If
\var{string
} is not a string object at all,
638 \cfunction{PyString_AsString()
} returns
\NULL{} and raises
639 \exception{TypeError
}.
642 \begin{cfuncdesc
}{char*
}{PyString_AS_STRING
}{PyObject *string
}
643 Macro form of
\cfunction{PyString_AsString()
} but without error
644 checking. Only string objects are supported; no Unicode objects
648 \begin{cfuncdesc
}{int
}{PyString_AsStringAndSize
}{PyObject *obj,
651 Returns a NUL-terminated representation of the contents of the
652 object
\var{obj
} through the output variables
\var{buffer
} and
655 The function accepts both string and Unicode objects as input. For
656 Unicode objects it returns the default encoded version of the
657 object. If
\var{length
} is
\NULL{}, the resulting buffer may not
658 contain NUL characters; if it does, the function returns
\code{-
1}
659 and a
\exception{TypeError
} is raised.
661 The buffer refers to an internal string buffer of
\var{obj
}, not a
662 copy. The data must not be modified in any way, unless the string
663 was just created using
\code{PyString_FromStringAndSize(NULL,
664 \var{size
})
}. It must not be deallocated. If
\var{string
} is a
665 Unicode object, this function computes the default encoding of
666 \var{string
} and operates on that. If
\var{string
} is not a string
667 object at all,
\cfunction{PyString_AsString()
} returns
\NULL{} and
668 raises
\exception{TypeError
}.
671 \begin{cfuncdesc
}{void
}{PyString_Concat
}{PyObject **string,
673 Creates a new string object in
\var{*string
} containing the contents
674 of
\var{newpart
} appended to
\var{string
}; the caller will own the
675 new reference. The reference to the old value of
\var{string
} will
676 be stolen. If the new string cannot be created, the old reference
677 to
\var{string
} will still be discarded and the value of
678 \var{*string
} will be set to
\NULL{}; the appropriate exception will
682 \begin{cfuncdesc
}{void
}{PyString_ConcatAndDel
}{PyObject **string,
684 Creates a new string object in
\var{*string
} containing the contents
685 of
\var{newpart
} appended to
\var{string
}. This version decrements
686 the reference count of
\var{newpart
}.
689 \begin{cfuncdesc
}{int
}{_PyString_Resize
}{PyObject **string, int newsize
}
690 A way to resize a string object even though it is ``immutable''.
691 Only use this to build up a brand new string object; don't use this
692 if the string may already be known in other parts of the code. It
693 is an error to call this function if the refcount on the input string
695 Pass the address of an existing string object as an lvalue (it may
696 be written into), and the new size desired. On success,
\var{*string
}
697 holds the resized string object and
\code{0} is returned; the address in
698 \var{*string
} may differ from its input value. If the
699 reallocation fails, the original string object at
\var{*string
} is
700 deallocated,
\var{*string
} is set to
\NULL{}, a memory exception is set,
701 and
\code{-
1} is returned.
704 \begin{cfuncdesc
}{PyObject*
}{PyString_Format
}{PyObject *format,
706 Returns a new string object from
\var{format
} and
\var{args
}.
707 Analogous to
\code{\var{format
} \%\
\var{args
}}. The
\var{args
}
708 argument must be a tuple.
711 \begin{cfuncdesc
}{void
}{PyString_InternInPlace
}{PyObject **string
}
712 Intern the argument
\var{*string
} in place. The argument must be
713 the address of a pointer variable pointing to a Python string
714 object. If there is an existing interned string that is the same as
715 \var{*string
}, it sets
\var{*string
} to it (decrementing the
716 reference count of the old string object and incrementing the
717 reference count of the interned string object), otherwise it leaves
718 \var{*string
} alone and interns it (incrementing its reference
719 count). (Clarification: even though there is a lot of talk about
720 reference counts, think of this function as reference-count-neutral;
721 you own the object after the call if and only if you owned it before
725 \begin{cfuncdesc
}{PyObject*
}{PyString_InternFromString
}{const char *v
}
726 A combination of
\cfunction{PyString_FromString()
} and
727 \cfunction{PyString_InternInPlace()
}, returning either a new string
728 object that has been interned, or a new (``owned'') reference to an
729 earlier interned string object with the same value.
732 \begin{cfuncdesc
}{PyObject*
}{PyString_Decode
}{const char *s,
734 const char *encoding,
736 Creates an object by decoding
\var{size
} bytes of the encoded
737 buffer
\var{s
} using the codec registered for
738 \var{encoding
}.
\var{encoding
} and
\var{errors
} have the same
739 meaning as the parameters of the same name in the
740 \function{unicode()
} built-in function. The codec to be used is
741 looked up using the Python codec registry. Returns
\NULL{} if
742 an exception was raised by the codec.
745 \begin{cfuncdesc
}{PyObject*
}{PyString_AsDecodedObject
}{PyObject *str,
746 const char *encoding,
748 Decodes a string object by passing it to the codec registered for
749 \var{encoding
} and returns the result as Python
750 object.
\var{encoding
} and
\var{errors
} have the same meaning as the
751 parameters of the same name in the string
\method{encode()
} method.
752 The codec to be used is looked up using the Python codec registry.
753 Returns
\NULL{} if an exception was raised by the codec.
756 \begin{cfuncdesc
}{PyObject*
}{PyString_Encode
}{const char *s,
758 const char *encoding,
760 Encodes the
\ctype{char
} buffer of the given size by passing it to
761 the codec registered for
\var{encoding
} and returns a Python object.
762 \var{encoding
} and
\var{errors
} have the same meaning as the
763 parameters of the same name in the string
\method{encode()
} method.
764 The codec to be used is looked up using the Python codec
765 registry. Returns
\NULL{} if an exception was raised by the
769 \begin{cfuncdesc
}{PyObject*
}{PyString_AsEncodedObject
}{PyObject *str,
770 const char *encoding,
772 Encodes a string object using the codec registered for
773 \var{encoding
} and returns the result as Python object.
774 \var{encoding
} and
\var{errors
} have the same meaning as the
775 parameters of the same name in the string
\method{encode()
} method.
776 The codec to be used is looked up using the Python codec registry.
777 Returns
\NULL{} if an exception was raised by the codec.
781 \subsection{Unicode Objects
\label{unicodeObjects
}}
782 \sectionauthor{Marc-Andre Lemburg
}{mal@lemburg.com
}
784 %--- Unicode Type -------------------------------------------------------
786 These are the basic Unicode object types used for the Unicode
787 implementation in Python:
789 \begin{ctypedesc
}{Py_UNICODE
}
790 This type represents a
16-bit unsigned storage type which is used by
791 Python internally as basis for holding Unicode ordinals. On
792 platforms where
\ctype{wchar_t
} is available and also has
16-bits,
793 \ctype{Py_UNICODE
} is a typedef alias for
\ctype{wchar_t
} to enhance
794 native platform compatibility. On all other platforms,
795 \ctype{Py_UNICODE
} is a typedef alias for
\ctype{unsigned short
}.
798 \begin{ctypedesc
}{PyUnicodeObject
}
799 This subtype of
\ctype{PyObject
} represents a Python Unicode object.
802 \begin{cvardesc
}{PyTypeObject
}{PyUnicode_Type
}
803 This instance of
\ctype{PyTypeObject
} represents the Python Unicode
807 The following APIs are really C macros and can be used to do fast
808 checks and to access internal read-only data of Unicode objects:
810 \begin{cfuncdesc
}{int
}{PyUnicode_Check
}{PyObject *o
}
811 Returns true if the object
\var{o
} is a Unicode object or an
812 instance of a Unicode subtype.
813 \versionchanged[Allowed subtypes to be accepted
]{2.2}
816 \begin{cfuncdesc
}{int
}{PyUnicode_CheckExact
}{PyObject *o
}
817 Returns true if the object
\var{o
} is a Unicode object, but not an
818 instance of a subtype.
822 \begin{cfuncdesc
}{int
}{PyUnicode_GET_SIZE
}{PyObject *o
}
823 Returns the size of the object.
\var{o
} has to be a
824 \ctype{PyUnicodeObject
} (not checked).
827 \begin{cfuncdesc
}{int
}{PyUnicode_GET_DATA_SIZE
}{PyObject *o
}
828 Returns the size of the object's internal buffer in bytes.
\var{o
}
829 has to be a
\ctype{PyUnicodeObject
} (not checked).
832 \begin{cfuncdesc
}{Py_UNICODE*
}{PyUnicode_AS_UNICODE
}{PyObject *o
}
833 Returns a pointer to the internal
\ctype{Py_UNICODE
} buffer of the
834 object.
\var{o
} has to be a
\ctype{PyUnicodeObject
} (not checked).
837 \begin{cfuncdesc
}{const char*
}{PyUnicode_AS_DATA
}{PyObject *o
}
838 Returns a pointer to the internal buffer of the object.
839 \var{o
} has to be a
\ctype{PyUnicodeObject
} (not checked).
842 % --- Unicode character properties ---------------------------------------
844 Unicode provides many different character properties. The most often
845 needed ones are available through these macros which are mapped to C
846 functions depending on the Python configuration.
848 \begin{cfuncdesc
}{int
}{Py_UNICODE_ISSPACE
}{Py_UNICODE ch
}
849 Returns
1/
0 depending on whether
\var{ch
} is a whitespace
853 \begin{cfuncdesc
}{int
}{Py_UNICODE_ISLOWER
}{Py_UNICODE ch
}
854 Returns
1/
0 depending on whether
\var{ch
} is a lowercase character.
857 \begin{cfuncdesc
}{int
}{Py_UNICODE_ISUPPER
}{Py_UNICODE ch
}
858 Returns
1/
0 depending on whether
\var{ch
} is an uppercase
862 \begin{cfuncdesc
}{int
}{Py_UNICODE_ISTITLE
}{Py_UNICODE ch
}
863 Returns
1/
0 depending on whether
\var{ch
} is a titlecase character.
866 \begin{cfuncdesc
}{int
}{Py_UNICODE_ISLINEBREAK
}{Py_UNICODE ch
}
867 Returns
1/
0 depending on whether
\var{ch
} is a linebreak character.
870 \begin{cfuncdesc
}{int
}{Py_UNICODE_ISDECIMAL
}{Py_UNICODE ch
}
871 Returns
1/
0 depending on whether
\var{ch
} is a decimal character.
874 \begin{cfuncdesc
}{int
}{Py_UNICODE_ISDIGIT
}{Py_UNICODE ch
}
875 Returns
1/
0 depending on whether
\var{ch
} is a digit character.
878 \begin{cfuncdesc
}{int
}{Py_UNICODE_ISNUMERIC
}{Py_UNICODE ch
}
879 Returns
1/
0 depending on whether
\var{ch
} is a numeric character.
882 \begin{cfuncdesc
}{int
}{Py_UNICODE_ISALPHA
}{Py_UNICODE ch
}
883 Returns
1/
0 depending on whether
\var{ch
} is an alphabetic
887 \begin{cfuncdesc
}{int
}{Py_UNICODE_ISALNUM
}{Py_UNICODE ch
}
888 Returns
1/
0 depending on whether
\var{ch
} is an alphanumeric
892 These APIs can be used for fast direct character conversions:
894 \begin{cfuncdesc
}{Py_UNICODE
}{Py_UNICODE_TOLOWER
}{Py_UNICODE ch
}
895 Returns the character
\var{ch
} converted to lower case.
898 \begin{cfuncdesc
}{Py_UNICODE
}{Py_UNICODE_TOUPPER
}{Py_UNICODE ch
}
899 Returns the character
\var{ch
} converted to upper case.
902 \begin{cfuncdesc
}{Py_UNICODE
}{Py_UNICODE_TOTITLE
}{Py_UNICODE ch
}
903 Returns the character
\var{ch
} converted to title case.
906 \begin{cfuncdesc
}{int
}{Py_UNICODE_TODECIMAL
}{Py_UNICODE ch
}
907 Returns the character
\var{ch
} converted to a decimal positive
908 integer. Returns
\code{-
1} if this is not possible. Does not raise
912 \begin{cfuncdesc
}{int
}{Py_UNICODE_TODIGIT
}{Py_UNICODE ch
}
913 Returns the character
\var{ch
} converted to a single digit integer.
914 Returns
\code{-
1} if this is not possible. Does not raise
918 \begin{cfuncdesc
}{double
}{Py_UNICODE_TONUMERIC
}{Py_UNICODE ch
}
919 Returns the character
\var{ch
} converted to a (positive) double.
920 Returns
\code{-
1.0} if this is not possible. Does not raise
924 % --- Plain Py_UNICODE ---------------------------------------------------
926 To create Unicode objects and access their basic sequence properties,
929 \begin{cfuncdesc
}{PyObject*
}{PyUnicode_FromUnicode
}{const Py_UNICODE *u,
931 Create a Unicode Object from the Py_UNICODE buffer
\var{u
} of the
932 given size.
\var{u
} may be
\NULL{} which causes the contents to be
933 undefined. It is the user's responsibility to fill in the needed
934 data. The buffer is copied into the new object. If the buffer is
935 not
\NULL{}, the return value might be a shared object. Therefore,
936 modification of the resulting Unicode object is only allowed when
940 \begin{cfuncdesc
}{Py_UNICODE*
}{PyUnicode_AsUnicode
}{PyObject *unicode
}
941 Return a read-only pointer to the Unicode object's internal
942 \ctype{Py_UNICODE
} buffer,
\NULL{} if
\var{unicode
} is not a Unicode
946 \begin{cfuncdesc
}{int
}{PyUnicode_GetSize
}{PyObject *unicode
}
947 Return the length of the Unicode object.
950 \begin{cfuncdesc
}{PyObject*
}{PyUnicode_FromEncodedObject
}{PyObject *obj,
951 const char *encoding,
953 Coerce an encoded object
\var{obj
} to an Unicode object and return a
954 reference with incremented refcount.
956 Coercion is done in the following way:
959 \item Unicode objects are passed back as-is with incremented
960 refcount.
\note{These cannot be decoded; passing a non-
\NULL{}
961 value for encoding will result in a
\exception{TypeError
}.
}
963 \item String and other char buffer compatible objects are decoded
964 according to the given encoding and using the error handling
965 defined by errors. Both can be
\NULL{} to have the interface
966 use the default values (see the next section for details).
968 \item All other objects cause an exception.
971 The API returns
\NULL{} if there was an error. The caller is
972 responsible for decref'ing the returned objects.
975 \begin{cfuncdesc
}{PyObject*
}{PyUnicode_FromObject
}{PyObject *obj
}
976 Shortcut for
\code{PyUnicode_FromEncodedObject(obj, NULL, "strict")
}
977 which is used throughout the interpreter whenever coercion to
981 % --- wchar_t support for platforms which support it ---------------------
983 If the platform supports
\ctype{wchar_t
} and provides a header file
984 wchar.h, Python can interface directly to this type using the
985 following functions. Support is optimized if Python's own
986 \ctype{Py_UNICODE
} type is identical to the system's
\ctype{wchar_t
}.
988 \begin{cfuncdesc
}{PyObject*
}{PyUnicode_FromWideChar
}{const wchar_t *w,
990 Create a Unicode object from the
\ctype{wchar_t
} buffer
\var{w
} of
991 the given size. Returns
\NULL{} on failure.
994 \begin{cfuncdesc
}{int
}{PyUnicode_AsWideChar
}{PyUnicodeObject *unicode,
997 Copies the Unicode object contents into the
\ctype{wchar_t
} buffer
998 \var{w
}. At most
\var{size
} \ctype{wchar_t
} characters are copied
999 (excluding a possibly trailing
0-termination character). Returns
1000 the number of
\ctype{wchar_t
} characters copied or -
1 in case of an
1001 error. Note that the resulting
\ctype{wchar_t
} string may or may
1002 not be
0-terminated. It is the responsibility of the caller to make
1003 sure that the
\ctype{wchar_t
} string is
0-terminated in case this is
1004 required by the application.
1008 \subsubsection{Built-in Codecs
\label{builtinCodecs
}}
1010 Python provides a set of builtin codecs which are written in C
1011 for speed. All of these codecs are directly usable via the
1012 following functions.
1014 Many of the following APIs take two arguments encoding and
1015 errors. These parameters encoding and errors have the same semantics
1016 as the ones of the builtin unicode() Unicode object constructor.
1018 Setting encoding to
\NULL{} causes the default encoding to be used
1019 which is
\ASCII. The file system calls should use
1020 \cdata{Py_FileSystemDefaultEncoding
} as the encoding for file
1021 names. This variable should be treated as read-only: On some systems,
1022 it will be a pointer to a static string, on others, it will change at
1023 run-time (such as when the application invokes setlocale).
1025 Error handling is set by errors which may also be set to
\NULL{}
1026 meaning to use the default handling defined for the codec. Default
1027 error handling for all builtin codecs is ``strict''
1028 (
\exception{ValueError
} is raised).
1030 The codecs all use a similar interface. Only deviation from the
1031 following generic ones are documented for simplicity.
1033 % --- Generic Codecs -----------------------------------------------------
1035 These are the generic codec APIs:
1037 \begin{cfuncdesc
}{PyObject*
}{PyUnicode_Decode
}{const char *s,
1039 const char *encoding,
1041 Create a Unicode object by decoding
\var{size
} bytes of the encoded
1042 string
\var{s
}.
\var{encoding
} and
\var{errors
} have the same
1043 meaning as the parameters of the same name in the
1044 \function{unicode()
} builtin function. The codec to be used is
1045 looked up using the Python codec registry. Returns
\NULL{} if an
1046 exception was raised by the codec.
1049 \begin{cfuncdesc
}{PyObject*
}{PyUnicode_Encode
}{const Py_UNICODE *s,
1051 const char *encoding,
1053 Encodes the
\ctype{Py_UNICODE
} buffer of the given size and returns
1054 a Python string object.
\var{encoding
} and
\var{errors
} have the
1055 same meaning as the parameters of the same name in the Unicode
1056 \method{encode()
} method. The codec to be used is looked up using
1057 the Python codec registry. Returns
\NULL{} if an exception was
1058 raised by the codec.
1061 \begin{cfuncdesc
}{PyObject*
}{PyUnicode_AsEncodedString
}{PyObject *unicode,
1062 const char *encoding,
1064 Encodes a Unicode object and returns the result as Python string
1065 object.
\var{encoding
} and
\var{errors
} have the same meaning as the
1066 parameters of the same name in the Unicode
\method{encode()
} method.
1067 The codec to be used is looked up using the Python codec registry.
1068 Returns
\NULL{} if an exception was raised by the codec.
1071 % --- UTF-8 Codecs -------------------------------------------------------
1073 These are the UTF-
8 codec APIs:
1075 \begin{cfuncdesc
}{PyObject*
}{PyUnicode_DecodeUTF8
}{const char *s,
1078 Creates a Unicode object by decoding
\var{size
} bytes of the UTF-
8
1079 encoded string
\var{s
}. Returns
\NULL{} if an exception was raised
1083 \begin{cfuncdesc
}{PyObject*
}{PyUnicode_DecodeUTF8Stateful
}{const char *s,
1087 If
\var{consumed
} is
\NULL{}, behaves like
\cfunction{PyUnicode_DecodeUTF8()
}.
1088 If
\var{consumed
} is not
\NULL{}, trailing incomplete UTF-
8 byte sequences
1089 will not be treated as an error. Those bytes will not be decoded and the
1090 number of bytes that have been decoded will be stored in
\var{consumed
}.
1094 \begin{cfuncdesc
}{PyObject*
}{PyUnicode_EncodeUTF8
}{const Py_UNICODE *s,
1097 Encodes the
\ctype{Py_UNICODE
} buffer of the given size using UTF-
8
1098 and returns a Python string object. Returns
\NULL{} if an exception
1099 was raised by the codec.
1102 \begin{cfuncdesc
}{PyObject*
}{PyUnicode_AsUTF8String
}{PyObject *unicode
}
1103 Encodes a Unicode objects using UTF-
8 and returns the result as
1104 Python string object. Error handling is ``strict''. Returns
1105 \NULL{} if an exception was raised by the codec.
1108 % --- UTF-16 Codecs ------------------------------------------------------ */
1110 These are the UTF-
16 codec APIs:
1112 \begin{cfuncdesc
}{PyObject*
}{PyUnicode_DecodeUTF16
}{const char *s,
1116 Decodes
\var{length
} bytes from a UTF-
16 encoded buffer string and
1117 returns the corresponding Unicode object.
\var{errors
} (if
1118 non-
\NULL{}) defines the error handling. It defaults to ``strict''.
1120 If
\var{byteorder
} is non-
\NULL{}, the decoder starts decoding using
1121 the given byte order:
1124 *byteorder == -
1: little endian
1125 *byteorder ==
0: native order
1126 *byteorder ==
1: big endian
1129 and then switches according to all byte order marks (BOM) it finds
1130 in the input data. BOMs are not copied into the resulting Unicode
1131 string. After completion,
\var{*byteorder
} is set to the current
1132 byte order at the end of input data.
1134 If
\var{byteorder
} is
\NULL{}, the codec starts in native order mode.
1136 Returns
\NULL{} if an exception was raised by the codec.
1139 \begin{cfuncdesc
}{PyObject*
}{PyUnicode_DecodeUTF16Stateful
}{const char *s,
1144 If
\var{consumed
} is
\NULL{}, behaves like
1145 \cfunction{PyUnicode_DecodeUTF16()
}. If
\var{consumed
} is not
\NULL{},
1146 \cfunction{PyUnicode_DecodeUTF16Stateful()
} will not treat trailing incomplete
1147 UTF-
16 byte sequences (i.e. an odd number of bytes or a split surrogate pair)
1148 as an error. Those bytes will not be decoded and the number of bytes that
1149 have been decoded will be stored in
\var{consumed
}.
1153 \begin{cfuncdesc
}{PyObject*
}{PyUnicode_EncodeUTF16
}{const Py_UNICODE *s,
1157 Returns a Python string object holding the UTF-
16 encoded value of
1158 the Unicode data in
\var{s
}. If
\var{byteorder
} is not
\code{0},
1159 output is written according to the following byte order:
1162 byteorder == -
1: little endian
1163 byteorder ==
0: native byte order (writes a BOM mark)
1164 byteorder ==
1: big endian
1167 If byteorder is
\code{0}, the output string will always start with
1168 the Unicode BOM mark (U+FEFF). In the other two modes, no BOM mark
1171 If
\var{Py_UNICODE_WIDE
} is defined, a single
\ctype{Py_UNICODE
}
1172 value may get represented as a surrogate pair. If it is not
1173 defined, each
\ctype{Py_UNICODE
} values is interpreted as an
1176 Returns
\NULL{} if an exception was raised by the codec.
1179 \begin{cfuncdesc
}{PyObject*
}{PyUnicode_AsUTF16String
}{PyObject *unicode
}
1180 Returns a Python string using the UTF-
16 encoding in native byte
1181 order. The string always starts with a BOM mark. Error handling is
1182 ``strict''. Returns
\NULL{} if an exception was raised by the
1186 % --- Unicode-Escape Codecs ----------------------------------------------
1188 These are the ``Unicode Escape'' codec APIs:
1190 \begin{cfuncdesc
}{PyObject*
}{PyUnicode_DecodeUnicodeEscape
}{const char *s,
1193 Creates a Unicode object by decoding
\var{size
} bytes of the
1194 Unicode-Escape encoded string
\var{s
}. Returns
\NULL{} if an
1195 exception was raised by the codec.
1198 \begin{cfuncdesc
}{PyObject*
}{PyUnicode_EncodeUnicodeEscape
}{const Py_UNICODE *s,
1201 Encodes the
\ctype{Py_UNICODE
} buffer of the given size using
1202 Unicode-Escape and returns a Python string object. Returns
\NULL{}
1203 if an exception was raised by the codec.
1206 \begin{cfuncdesc
}{PyObject*
}{PyUnicode_AsUnicodeEscapeString
}{PyObject *unicode
}
1207 Encodes a Unicode objects using Unicode-Escape and returns the
1208 result as Python string object. Error handling is ``strict''.
1209 Returns
\NULL{} if an exception was raised by the codec.
1212 % --- Raw-Unicode-Escape Codecs ------------------------------------------
1214 These are the ``Raw Unicode Escape'' codec APIs:
1216 \begin{cfuncdesc
}{PyObject*
}{PyUnicode_DecodeRawUnicodeEscape
}{const char *s,
1219 Creates a Unicode object by decoding
\var{size
} bytes of the
1220 Raw-Unicode-Escape encoded string
\var{s
}. Returns
\NULL{} if an
1221 exception was raised by the codec.
1224 \begin{cfuncdesc
}{PyObject*
}{PyUnicode_EncodeRawUnicodeEscape
}{const Py_UNICODE *s,
1227 Encodes the
\ctype{Py_UNICODE
} buffer of the given size using
1228 Raw-Unicode-Escape and returns a Python string object. Returns
1229 \NULL{} if an exception was raised by the codec.
1232 \begin{cfuncdesc
}{PyObject*
}{PyUnicode_AsRawUnicodeEscapeString
}{PyObject *unicode
}
1233 Encodes a Unicode objects using Raw-Unicode-Escape and returns the
1234 result as Python string object. Error handling is ``strict''.
1235 Returns
\NULL{} if an exception was raised by the codec.
1238 % --- Latin-1 Codecs -----------------------------------------------------
1240 These are the Latin-
1 codec APIs:
1241 Latin-
1 corresponds to the first
256 Unicode ordinals and only these
1242 are accepted by the codecs during encoding.
1244 \begin{cfuncdesc
}{PyObject*
}{PyUnicode_DecodeLatin1
}{const char *s,
1247 Creates a Unicode object by decoding
\var{size
} bytes of the Latin-
1
1248 encoded string
\var{s
}. Returns
\NULL{} if an exception was raised
1252 \begin{cfuncdesc
}{PyObject*
}{PyUnicode_EncodeLatin1
}{const Py_UNICODE *s,
1255 Encodes the
\ctype{Py_UNICODE
} buffer of the given size using
1256 Latin-
1 and returns a Python string object. Returns
\NULL{} if an
1257 exception was raised by the codec.
1260 \begin{cfuncdesc
}{PyObject*
}{PyUnicode_AsLatin1String
}{PyObject *unicode
}
1261 Encodes a Unicode objects using Latin-
1 and returns the result as
1262 Python string object. Error handling is ``strict''. Returns
1263 \NULL{} if an exception was raised by the codec.
1266 % --- ASCII Codecs -------------------------------------------------------
1268 These are the
\ASCII{} codec APIs. Only
7-bit
\ASCII{} data is
1269 accepted. All other codes generate errors.
1271 \begin{cfuncdesc
}{PyObject*
}{PyUnicode_DecodeASCII
}{const char *s,
1274 Creates a Unicode object by decoding
\var{size
} bytes of the
1275 \ASCII{} encoded string
\var{s
}. Returns
\NULL{} if an exception
1276 was raised by the codec.
1279 \begin{cfuncdesc
}{PyObject*
}{PyUnicode_EncodeASCII
}{const Py_UNICODE *s,
1282 Encodes the
\ctype{Py_UNICODE
} buffer of the given size using
1283 \ASCII{} and returns a Python string object. Returns
\NULL{} if an
1284 exception was raised by the codec.
1287 \begin{cfuncdesc
}{PyObject*
}{PyUnicode_AsASCIIString
}{PyObject *unicode
}
1288 Encodes a Unicode objects using
\ASCII{} and returns the result as
1289 Python string object. Error handling is ``strict''. Returns
1290 \NULL{} if an exception was raised by the codec.
1293 % --- Character Map Codecs -----------------------------------------------
1295 These are the mapping codec APIs:
1297 This codec is special in that it can be used to implement many
1298 different codecs (and this is in fact what was done to obtain most of
1299 the standard codecs included in the
\module{encodings
} package). The
1300 codec uses mapping to encode and decode characters.
1302 Decoding mappings must map single string characters to single Unicode
1303 characters, integers (which are then interpreted as Unicode ordinals)
1304 or None (meaning "undefined mapping" and causing an error).
1306 Encoding mappings must map single Unicode characters to single string
1307 characters, integers (which are then interpreted as Latin-
1 ordinals)
1308 or None (meaning "undefined mapping" and causing an error).
1310 The mapping objects provided must only support the __getitem__ mapping
1313 If a character lookup fails with a LookupError, the character is
1314 copied as-is meaning that its ordinal value will be interpreted as
1315 Unicode or Latin-
1 ordinal resp. Because of this, mappings only need
1316 to contain those mappings which map characters to different code
1319 \begin{cfuncdesc
}{PyObject*
}{PyUnicode_DecodeCharmap
}{const char *s,
1323 Creates a Unicode object by decoding
\var{size
} bytes of the encoded
1324 string
\var{s
} using the given
\var{mapping
} object. Returns
1325 \NULL{} if an exception was raised by the codec.
1328 \begin{cfuncdesc
}{PyObject*
}{PyUnicode_EncodeCharmap
}{const Py_UNICODE *s,
1332 Encodes the
\ctype{Py_UNICODE
} buffer of the given size using the
1333 given
\var{mapping
} object and returns a Python string object.
1334 Returns
\NULL{} if an exception was raised by the codec.
1337 \begin{cfuncdesc
}{PyObject*
}{PyUnicode_AsCharmapString
}{PyObject *unicode,
1339 Encodes a Unicode objects using the given
\var{mapping
} object and
1340 returns the result as Python string object. Error handling is
1341 ``strict''. Returns
\NULL{} if an exception was raised by the
1345 The following codec API is special in that maps Unicode to Unicode.
1347 \begin{cfuncdesc
}{PyObject*
}{PyUnicode_TranslateCharmap
}{const Py_UNICODE *s,
1351 Translates a
\ctype{Py_UNICODE
} buffer of the given length by
1352 applying a character mapping
\var{table
} to it and returns the
1353 resulting Unicode object. Returns
\NULL{} when an exception was
1354 raised by the codec.
1356 The
\var{mapping
} table must map Unicode ordinal integers to Unicode
1357 ordinal integers or None (causing deletion of the character).
1359 Mapping tables need only provide the method
{__getitem__()
}
1360 interface; dictionaries and sequences work well. Unmapped character
1361 ordinals (ones which cause a
\exception{LookupError
}) are left
1362 untouched and are copied as-is.
1365 % --- MBCS codecs for Windows --------------------------------------------
1367 These are the MBCS codec APIs. They are currently only available on
1368 Windows and use the Win32 MBCS converters to implement the
1369 conversions. Note that MBCS (or DBCS) is a class of encodings, not
1370 just one. The target encoding is defined by the user settings on the
1371 machine running the codec.
1373 \begin{cfuncdesc
}{PyObject*
}{PyUnicode_DecodeMBCS
}{const char *s,
1376 Creates a Unicode object by decoding
\var{size
} bytes of the MBCS
1377 encoded string
\var{s
}. Returns
\NULL{} if an exception was
1378 raised by the codec.
1381 \begin{cfuncdesc
}{PyObject*
}{PyUnicode_EncodeMBCS
}{const Py_UNICODE *s,
1384 Encodes the
\ctype{Py_UNICODE
} buffer of the given size using MBCS
1385 and returns a Python string object. Returns
\NULL{} if an exception
1386 was raised by the codec.
1389 \begin{cfuncdesc
}{PyObject*
}{PyUnicode_AsMBCSString
}{PyObject *unicode
}
1390 Encodes a Unicode objects using MBCS and returns the result as
1391 Python string object. Error handling is ``strict''. Returns
1392 \NULL{} if an exception was raised by the codec.
1395 % --- Methods & Slots ----------------------------------------------------
1397 \subsubsection{Methods and Slot Functions
\label{unicodeMethodsAndSlots
}}
1399 The following APIs are capable of handling Unicode objects and strings
1400 on input (we refer to them as strings in the descriptions) and return
1401 Unicode objects or integers as appropriate.
1403 They all return
\NULL{} or
\code{-
1} if an exception occurs.
1405 \begin{cfuncdesc
}{PyObject*
}{PyUnicode_Concat
}{PyObject *left,
1407 Concat two strings giving a new Unicode string.
1410 \begin{cfuncdesc
}{PyObject*
}{PyUnicode_Split
}{PyObject *s,
1413 Split a string giving a list of Unicode strings. If sep is
\NULL{},
1414 splitting will be done at all whitespace substrings. Otherwise,
1415 splits occur at the given separator. At most
\var{maxsplit
} splits
1416 will be done. If negative, no limit is set. Separators are not
1417 included in the resulting list.
1420 \begin{cfuncdesc
}{PyObject*
}{PyUnicode_Splitlines
}{PyObject *s,
1422 Split a Unicode string at line breaks, returning a list of Unicode
1423 strings. CRLF is considered to be one line break. If
\var{keepend
}
1424 is
0, the Line break characters are not included in the resulting
1428 \begin{cfuncdesc
}{PyObject*
}{PyUnicode_Translate
}{PyObject *str,
1431 Translate a string by applying a character mapping table to it and
1432 return the resulting Unicode object.
1434 The mapping table must map Unicode ordinal integers to Unicode
1435 ordinal integers or None (causing deletion of the character).
1437 Mapping tables need only provide the
\method{__getitem__()
}
1438 interface; dictionaries and sequences work well. Unmapped character
1439 ordinals (ones which cause a
\exception{LookupError
}) are left
1440 untouched and are copied as-is.
1442 \var{errors
} has the usual meaning for codecs. It may be
\NULL{}
1443 which indicates to use the default error handling.
1446 \begin{cfuncdesc
}{PyObject*
}{PyUnicode_Join
}{PyObject *separator,
1448 Join a sequence of strings using the given separator and return the
1449 resulting Unicode string.
1452 \begin{cfuncdesc
}{int
}{PyUnicode_Tailmatch
}{PyObject *str,
1457 Return
1 if
\var{substr
} matches
\var{str
}[\var{start
}:
\var{end
}] at
1458 the given tail end (
\var{direction
} == -
1 means to do a prefix
1459 match,
\var{direction
} ==
1 a suffix match),
0 otherwise.
1460 Returns
\code{-
1} if an error occurred.
1463 \begin{cfuncdesc
}{int
}{PyUnicode_Find
}{PyObject *str,
1468 Return the first position of
\var{substr
} in
1469 \var{str
}[\var{start
}:
\var{end
}] using the given
\var{direction
}
1470 (
\var{direction
} ==
1 means to do a forward search,
1471 \var{direction
} == -
1 a backward search). The return value is the
1472 index of the first match; a value of
\code{-
1} indicates that no
1473 match was found, and
\code{-
2} indicates that an error occurred and
1474 an exception has been set.
1477 \begin{cfuncdesc
}{int
}{PyUnicode_Count
}{PyObject *str,
1481 Return the number of non-overlapping occurrences of
\var{substr
} in
1482 \code{\var{str
}[\var{start
}:
\var{end
}]}. Returns
\code{-
1} if an
1486 \begin{cfuncdesc
}{PyObject*
}{PyUnicode_Replace
}{PyObject *str,
1490 Replace at most
\var{maxcount
} occurrences of
\var{substr
} in
1491 \var{str
} with
\var{replstr
} and return the resulting Unicode object.
1492 \var{maxcount
} == -
1 means replace all occurrences.
1495 \begin{cfuncdesc
}{int
}{PyUnicode_Compare
}{PyObject *left, PyObject *right
}
1496 Compare two strings and return -
1,
0,
1 for less than, equal, and
1497 greater than, respectively.
1500 \begin{cfuncdesc
}{PyObject*
}{PyUnicode_Format
}{PyObject *format,
1502 Returns a new string object from
\var{format
} and
\var{args
}; this
1503 is analogous to
\code{\var{format
} \%\
\var{args
}}. The
1504 \var{args
} argument must be a tuple.
1507 \begin{cfuncdesc
}{int
}{PyUnicode_Contains
}{PyObject *container,
1509 Checks whether
\var{element
} is contained in
\var{container
} and
1510 returns true or false accordingly.
1512 \var{element
} has to coerce to a one element Unicode
1513 string.
\code{-
1} is returned if there was an error.
1517 \subsection{Buffer Objects
\label{bufferObjects
}}
1518 \sectionauthor{Greg Stein
}{gstein@lyra.org
}
1521 Python objects implemented in C can export a group of functions called
1522 the ``buffer
\index{buffer interface
} interface.'' These functions can
1523 be used by an object to expose its data in a raw, byte-oriented
1524 format. Clients of the object can use the buffer interface to access
1525 the object data directly, without needing to copy it first.
1527 Two examples of objects that support
1528 the buffer interface are strings and arrays. The string object exposes
1529 the character contents in the buffer interface's byte-oriented
1530 form. An array can also expose its contents, but it should be noted
1531 that array elements may be multi-byte values.
1533 An example user of the buffer interface is the file object's
1534 \method{write()
} method. Any object that can export a series of bytes
1535 through the buffer interface can be written to a file. There are a
1536 number of format codes to
\cfunction{PyArg_ParseTuple()
} that operate
1537 against an object's buffer interface, returning data from the target
1540 More information on the buffer interface is provided in the section
1541 ``Buffer Object Structures'' (section~
\ref{buffer-structs
}), under
1542 the description for
\ctype{PyBufferProcs
}\ttindex{PyBufferProcs
}.
1544 A ``buffer object'' is defined in the
\file{bufferobject.h
} header
1545 (included by
\file{Python.h
}). These objects look very similar to
1546 string objects at the Python programming level: they support slicing,
1547 indexing, concatenation, and some other standard string
1548 operations. However, their data can come from one of two sources: from
1549 a block of memory, or from another object which exports the buffer
1552 Buffer objects are useful as a way to expose the data from another
1553 object's buffer interface to the Python programmer. They can also be
1554 used as a zero-copy slicing mechanism. Using their ability to
1555 reference a block of memory, it is possible to expose any data to the
1556 Python programmer quite easily. The memory could be a large, constant
1557 array in a C extension, it could be a raw block of memory for
1558 manipulation before passing to an operating system library, or it
1559 could be used to pass around structured data in its native, in-memory
1562 \begin{ctypedesc
}{PyBufferObject
}
1563 This subtype of
\ctype{PyObject
} represents a buffer object.
1566 \begin{cvardesc
}{PyTypeObject
}{PyBuffer_Type
}
1567 The instance of
\ctype{PyTypeObject
} which represents the Python
1568 buffer type; it is the same object as
\code{types.BufferType
} in the
1569 Python layer.
\withsubitem{(in module types)
}{\ttindex{BufferType
}}.
1572 \begin{cvardesc
}{int
}{Py_END_OF_BUFFER
}
1573 This constant may be passed as the
\var{size
} parameter to
1574 \cfunction{PyBuffer_FromObject()
} or
1575 \cfunction{PyBuffer_FromReadWriteObject()
}. It indicates that the
1576 new
\ctype{PyBufferObject
} should refer to
\var{base
} object from
1577 the specified
\var{offset
} to the end of its exported buffer. Using
1578 this enables the caller to avoid querying the
\var{base
} object for
1582 \begin{cfuncdesc
}{int
}{PyBuffer_Check
}{PyObject *p
}
1583 Return true if the argument has type
\cdata{PyBuffer_Type
}.
1586 \begin{cfuncdesc
}{PyObject*
}{PyBuffer_FromObject
}{PyObject *base,
1587 int offset, int size
}
1588 Return a new read-only buffer object. This raises
1589 \exception{TypeError
} if
\var{base
} doesn't support the read-only
1590 buffer protocol or doesn't provide exactly one buffer segment, or it
1591 raises
\exception{ValueError
} if
\var{offset
} is less than zero. The
1592 buffer will hold a reference to the
\var{base
} object, and the
1593 buffer's contents will refer to the
\var{base
} object's buffer
1594 interface, starting as position
\var{offset
} and extending for
1595 \var{size
} bytes. If
\var{size
} is
\constant{Py_END_OF_BUFFER
}, then
1596 the new buffer's contents extend to the length of the
\var{base
}
1597 object's exported buffer data.
1600 \begin{cfuncdesc
}{PyObject*
}{PyBuffer_FromReadWriteObject
}{PyObject *base,
1603 Return a new writable buffer object. Parameters and exceptions are
1604 similar to those for
\cfunction{PyBuffer_FromObject()
}. If the
1605 \var{base
} object does not export the writeable buffer protocol,
1606 then
\exception{TypeError
} is raised.
1609 \begin{cfuncdesc
}{PyObject*
}{PyBuffer_FromMemory
}{void *ptr, int size
}
1610 Return a new read-only buffer object that reads from a specified
1611 location in memory, with a specified size. The caller is
1612 responsible for ensuring that the memory buffer, passed in as
1613 \var{ptr
}, is not deallocated while the returned buffer object
1614 exists. Raises
\exception{ValueError
} if
\var{size
} is less than
1615 zero. Note that
\constant{Py_END_OF_BUFFER
} may
\emph{not
} be
1616 passed for the
\var{size
} parameter;
\exception{ValueError
} will be
1617 raised in that case.
1620 \begin{cfuncdesc
}{PyObject*
}{PyBuffer_FromReadWriteMemory
}{void *ptr, int size
}
1621 Similar to
\cfunction{PyBuffer_FromMemory()
}, but the returned
1625 \begin{cfuncdesc
}{PyObject*
}{PyBuffer_New
}{int size
}
1626 Returns a new writable buffer object that maintains its own memory
1627 buffer of
\var{size
} bytes.
\exception{ValueError
} is returned if
1628 \var{size
} is not zero or positive. Note that the memory buffer (as
1629 returned by
\cfunction{PyObject_AsWriteBuffer()
}) is not specifically
1634 \subsection{Tuple Objects
\label{tupleObjects
}}
1637 \begin{ctypedesc
}{PyTupleObject
}
1638 This subtype of
\ctype{PyObject
} represents a Python tuple object.
1641 \begin{cvardesc
}{PyTypeObject
}{PyTuple_Type
}
1642 This instance of
\ctype{PyTypeObject
} represents the Python tuple
1643 type; it is the same object as
\code{types.TupleType
} in the Python
1644 layer.
\withsubitem{(in module types)
}{\ttindex{TupleType
}}.
1647 \begin{cfuncdesc
}{int
}{PyTuple_Check
}{PyObject *p
}
1648 Return true if
\var{p
} is a tuple object or an instance of a subtype
1650 \versionchanged[Allowed subtypes to be accepted
]{2.2}
1653 \begin{cfuncdesc
}{int
}{PyTuple_CheckExact
}{PyObject *p
}
1654 Return true if
\var{p
} is a tuple object, but not an instance of a
1655 subtype of the tuple type.
1659 \begin{cfuncdesc
}{PyObject*
}{PyTuple_New
}{int len
}
1660 Return a new tuple object of size
\var{len
}, or
\NULL{} on failure.
1663 \begin{cfuncdesc
}{PyObject*
}{PyTuple_Pack
}{int n,
\moreargs}
1664 Return a new tuple object of size
\var{n
}, or
\NULL{} on failure.
1665 The tuple values are initialized to the subsequent
\var{n
} C arguments
1666 pointing to Python objects.
\samp{PyTuple_Pack(
2,
\var{a
},
\var{b
})
}
1667 is equivalent to
\samp{Py_BuildValue("(OO)",
\var{a
},
\var{b
})
}.
1671 \begin{cfuncdesc
}{int
}{PyTuple_Size
}{PyObject *p
}
1672 Takes a pointer to a tuple object, and returns the size of that
1676 \begin{cfuncdesc
}{int
}{PyTuple_GET_SIZE
}{PyObject *p
}
1677 Return the size of the tuple
\var{p
}, which must be non-
\NULL{} and
1678 point to a tuple; no error checking is performed.
1681 \begin{cfuncdesc
}{PyObject*
}{PyTuple_GetItem
}{PyObject *p, int pos
}
1682 Returns the object at position
\var{pos
} in the tuple pointed to by
1683 \var{p
}. If
\var{pos
} is out of bounds, returns
\NULL{} and sets an
1684 \exception{IndexError
} exception.
1687 \begin{cfuncdesc
}{PyObject*
}{PyTuple_GET_ITEM
}{PyObject *p, int pos
}
1688 Like
\cfunction{PyTuple_GetItem()
}, but does no checking of its
1692 \begin{cfuncdesc
}{PyObject*
}{PyTuple_GetSlice
}{PyObject *p,
1694 Takes a slice of the tuple pointed to by
\var{p
} from
\var{low
} to
1695 \var{high
} and returns it as a new tuple.
1698 \begin{cfuncdesc
}{int
}{PyTuple_SetItem
}{PyObject *p,
1699 int pos, PyObject *o
}
1700 Inserts a reference to object
\var{o
} at position
\var{pos
} of the
1701 tuple pointed to by
\var{p
}. It returns
\code{0} on success.
1702 \note{This function ``steals'' a reference to
\var{o
}.
}
1705 \begin{cfuncdesc
}{void
}{PyTuple_SET_ITEM
}{PyObject *p,
1706 int pos, PyObject *o
}
1707 Like
\cfunction{PyTuple_SetItem()
}, but does no error checking, and
1708 should
\emph{only
} be used to fill in brand new tuples.
\note{This
1709 function ``steals'' a reference to
\var{o
}.
}
1712 \begin{cfuncdesc
}{int
}{_PyTuple_Resize
}{PyObject **p, int newsize
}
1713 Can be used to resize a tuple.
\var{newsize
} will be the new length
1714 of the tuple. Because tuples are
\emph{supposed
} to be immutable,
1715 this should only be used if there is only one reference to the
1716 object. Do
\emph{not
} use this if the tuple may already be known to
1717 some other part of the code. The tuple will always grow or shrink
1718 at the end. Think of this as destroying the old tuple and creating
1719 a new one, only more efficiently. Returns
\code{0} on success.
1720 Client code should never assume that the resulting value of
1721 \code{*
\var{p
}} will be the same as before calling this function.
1722 If the object referenced by
\code{*
\var{p
}} is replaced, the
1723 original
\code{*
\var{p
}} is destroyed. On failure, returns
1724 \code{-
1} and sets
\code{*
\var{p
}} to
\NULL{}, and raises
1725 \exception{MemoryError
} or
1726 \exception{SystemError
}.
1727 \versionchanged[Removed unused third parameter,
\var{last_is_sticky
}]{2.2}
1731 \subsection{List Objects
\label{listObjects
}}
1734 \begin{ctypedesc
}{PyListObject
}
1735 This subtype of
\ctype{PyObject
} represents a Python list object.
1738 \begin{cvardesc
}{PyTypeObject
}{PyList_Type
}
1739 This instance of
\ctype{PyTypeObject
} represents the Python list
1740 type. This is the same object as
\code{types.ListType
}.
1741 \withsubitem{(in module types)
}{\ttindex{ListType
}}
1744 \begin{cfuncdesc
}{int
}{PyList_Check
}{PyObject *p
}
1745 Returns true if
\var{p
} is a list object or an instance of a
1746 subtype of the list type.
1747 \versionchanged[Allowed subtypes to be accepted
]{2.2}
1750 \begin{cfuncdesc
}{int
}{PyList_CheckExact
}{PyObject *p
}
1751 Return true if
\var{p
} is a list object, but not an instance of a
1752 subtype of the list type.
1756 \begin{cfuncdesc
}{PyObject*
}{PyList_New
}{int len
}
1757 Returns a new list of length
\var{len
} on success, or
\NULL{} on
1761 \begin{cfuncdesc
}{int
}{PyList_Size
}{PyObject *list
}
1762 Returns the length of the list object in
\var{list
}; this is
1763 equivalent to
\samp{len(
\var{list
})
} on a list object.
1767 \begin{cfuncdesc
}{int
}{PyList_GET_SIZE
}{PyObject *list
}
1768 Macro form of
\cfunction{PyList_Size()
} without error checking.
1771 \begin{cfuncdesc
}{PyObject*
}{PyList_GetItem
}{PyObject *list, int index
}
1772 Returns the object at position
\var{pos
} in the list pointed to by
1773 \var{p
}. If
\var{pos
} is out of bounds, returns
\NULL{} and sets an
1774 \exception{IndexError
} exception.
1777 \begin{cfuncdesc
}{PyObject*
}{PyList_GET_ITEM
}{PyObject *list, int i
}
1778 Macro form of
\cfunction{PyList_GetItem()
} without error checking.
1781 \begin{cfuncdesc
}{int
}{PyList_SetItem
}{PyObject *list, int index,
1783 Sets the item at index
\var{index
} in list to
\var{item
}. Returns
1784 \code{0} on success or
\code{-
1} on failure.
\note{This function
1785 ``steals'' a reference to
\var{item
} and discards a reference to an
1786 item already in the list at the affected position.
}
1789 \begin{cfuncdesc
}{void
}{PyList_SET_ITEM
}{PyObject *list, int i,
1791 Macro form of
\cfunction{PyList_SetItem()
} without error checking.
1792 This is normally only used to fill in new lists where there is no
1794 \note{This function ``steals'' a reference to
\var{item
}, and,
1795 unlike
\cfunction{PyList_SetItem()
}, does
\emph{not
} discard a
1796 reference to any item that it being replaced; any reference in
1797 \var{list
} at position
\var{i
} will be leaked.
}
1800 \begin{cfuncdesc
}{int
}{PyList_Insert
}{PyObject *list, int index,
1802 Inserts the item
\var{item
} into list
\var{list
} in front of index
1803 \var{index
}. Returns
\code{0} if successful; returns
\code{-
1} and
1804 raises an exception if unsuccessful. Analogous to
1805 \code{\var{list
}.insert(
\var{index
},
\var{item
})
}.
1808 \begin{cfuncdesc
}{int
}{PyList_Append
}{PyObject *list, PyObject *item
}
1809 Appends the object
\var{item
} at the end of list
\var{list
}.
1810 Returns
\code{0} if successful; returns
\code{-
1} and sets an
1811 exception if unsuccessful. Analogous to
1812 \code{\var{list
}.append(
\var{item
})
}.
1815 \begin{cfuncdesc
}{PyObject*
}{PyList_GetSlice
}{PyObject *list,
1817 Returns a list of the objects in
\var{list
} containing the objects
1818 \emph{between
} \var{low
} and
\var{high
}. Returns
\NULL{} and sets
1819 an exception if unsuccessful.
1820 Analogous to
\code{\var{list
}[\var{low
}:
\var{high
}]}.
1823 \begin{cfuncdesc
}{int
}{PyList_SetSlice
}{PyObject *list,
1826 Sets the slice of
\var{list
} between
\var{low
} and
\var{high
} to the
1827 contents of
\var{itemlist
}. Analogous to
1828 \code{\var{list
}[\var{low
}:
\var{high
}] =
\var{itemlist
}}.
1829 The
\var{itemlist
} may be
\NULL{}, indicating the assignment
1830 of an empty list (slice deletion).
1831 Returns
\code{0} on success,
\code{-
1} on failure.
1834 \begin{cfuncdesc
}{int
}{PyList_Sort
}{PyObject *list
}
1835 Sorts the items of
\var{list
} in place. Returns
\code{0} on
1836 success,
\code{-
1} on failure. This is equivalent to
1837 \samp{\var{list
}.sort()
}.
1840 \begin{cfuncdesc
}{int
}{PyList_Reverse
}{PyObject *list
}
1841 Reverses the items of
\var{list
} in place. Returns
\code{0} on
1842 success,
\code{-
1} on failure. This is the equivalent of
1843 \samp{\var{list
}.reverse()
}.
1846 \begin{cfuncdesc
}{PyObject*
}{PyList_AsTuple
}{PyObject *list
}
1847 Returns a new tuple object containing the contents of
\var{list
};
1848 equivalent to
\samp{tuple(
\var{list
})
}.
\bifuncindex{tuple
}
1852 \section{Mapping Objects
\label{mapObjects
}}
1857 \subsection{Dictionary Objects
\label{dictObjects
}}
1859 \obindex{dictionary
}
1860 \begin{ctypedesc
}{PyDictObject
}
1861 This subtype of
\ctype{PyObject
} represents a Python dictionary
1865 \begin{cvardesc
}{PyTypeObject
}{PyDict_Type
}
1866 This instance of
\ctype{PyTypeObject
} represents the Python
1867 dictionary type. This is exposed to Python programs as
1868 \code{types.DictType
} and
\code{types.DictionaryType
}.
1869 \withsubitem{(in module types)
}{\ttindex{DictType
}\ttindex{DictionaryType
}}
1872 \begin{cfuncdesc
}{int
}{PyDict_Check
}{PyObject *p
}
1873 Returns true if
\var{p
} is a dict object or an instance of a
1874 subtype of the dict type.
1875 \versionchanged[Allowed subtypes to be accepted
]{2.2}
1878 \begin{cfuncdesc
}{int
}{PyDict_CheckExact
}{PyObject *p
}
1879 Return true if
\var{p
} is a dict object, but not an instance of a
1880 subtype of the dict type.
1884 \begin{cfuncdesc
}{PyObject*
}{PyDict_New
}{}
1885 Returns a new empty dictionary, or
\NULL{} on failure.
1888 \begin{cfuncdesc
}{PyObject*
}{PyDictProxy_New
}{PyObject *dict
}
1889 Return a proxy object for a mapping which enforces read-only
1890 behavior. This is normally used to create a proxy to prevent
1891 modification of the dictionary for non-dynamic class types.
1895 \begin{cfuncdesc
}{void
}{PyDict_Clear
}{PyObject *p
}
1896 Empties an existing dictionary of all key-value pairs.
1899 \begin{cfuncdesc
}{int
}{PyDict_Contains
}{PyObject *p, PyObject *key
}
1900 Determine if dictionary
\var{p
} contains
\var{key
}. If an item
1901 in
\var{p
} is matches
\var{key
}, return
\code{1}, otherwise return
1902 \code{0}. On error, return
\code{-
1}. This is equivalent to the
1903 Python expression
\samp{\var{key
} in
\var{p
}}.
1907 \begin{cfuncdesc
}{PyObject*
}{PyDict_Copy
}{PyObject *p
}
1908 Returns a new dictionary that contains the same key-value pairs as
1913 \begin{cfuncdesc
}{int
}{PyDict_SetItem
}{PyObject *p, PyObject *key,
1915 Inserts
\var{value
} into the dictionary
\var{p
} with a key of
1916 \var{key
}.
\var{key
} must be hashable; if it isn't,
1917 \exception{TypeError
} will be raised.
1918 Returns
\code{0} on success or
\code{-
1} on failure.
1921 \begin{cfuncdesc
}{int
}{PyDict_SetItemString
}{PyObject *p,
1924 Inserts
\var{value
} into the dictionary
\var{p
} using
\var{key
} as a
1925 key.
\var{key
} should be a
\ctype{char*
}. The key object is created
1926 using
\code{PyString_FromString(
\var{key
})
}. Returns
\code{0} on
1927 success or
\code{-
1} on failure.
1928 \ttindex{PyString_FromString()
}
1931 \begin{cfuncdesc
}{int
}{PyDict_DelItem
}{PyObject *p, PyObject *key
}
1932 Removes the entry in dictionary
\var{p
} with key
\var{key
}.
1933 \var{key
} must be hashable; if it isn't,
\exception{TypeError
} is
1934 raised. Returns
\code{0} on success or
\code{-
1} on failure.
1937 \begin{cfuncdesc
}{int
}{PyDict_DelItemString
}{PyObject *p, char *key
}
1938 Removes the entry in dictionary
\var{p
} which has a key specified by
1939 the string
\var{key
}. Returns
\code{0} on success or
\code{-
1} on
1943 \begin{cfuncdesc
}{PyObject*
}{PyDict_GetItem
}{PyObject *p, PyObject *key
}
1944 Returns the object from dictionary
\var{p
} which has a key
1945 \var{key
}. Returns
\NULL{} if the key
\var{key
} is not present, but
1946 \emph{without
} setting an exception.
1949 \begin{cfuncdesc
}{PyObject*
}{PyDict_GetItemString
}{PyObject *p, char *key
}
1950 This is the same as
\cfunction{PyDict_GetItem()
}, but
\var{key
} is
1951 specified as a
\ctype{char*
}, rather than a
\ctype{PyObject*
}.
1954 \begin{cfuncdesc
}{PyObject*
}{PyDict_Items
}{PyObject *p
}
1955 Returns a
\ctype{PyListObject
} containing all the items from the
1956 dictionary, as in the dictionary method
\method{items()
} (see the
1957 \citetitle[../lib/lib.html
]{Python Library Reference
}).
1960 \begin{cfuncdesc
}{PyObject*
}{PyDict_Keys
}{PyObject *p
}
1961 Returns a
\ctype{PyListObject
} containing all the keys from the
1962 dictionary, as in the dictionary method
\method{keys()
} (see the
1963 \citetitle[../lib/lib.html
]{Python Library Reference
}).
1966 \begin{cfuncdesc
}{PyObject*
}{PyDict_Values
}{PyObject *p
}
1967 Returns a
\ctype{PyListObject
} containing all the values from the
1968 dictionary
\var{p
}, as in the dictionary method
\method{values()
}
1969 (see the
\citetitle[../lib/lib.html
]{Python Library Reference
}).
1972 \begin{cfuncdesc
}{int
}{PyDict_Size
}{PyObject *p
}
1973 Returns the number of items in the dictionary. This is equivalent
1974 to
\samp{len(
\var{p
})
} on a dictionary.
\bifuncindex{len
}
1977 \begin{cfuncdesc
}{int
}{PyDict_Next
}{PyObject *p, int *ppos,
1978 PyObject **pkey, PyObject **pvalue
}
1979 Iterate over all key-value pairs in the dictionary
\var{p
}. The
1980 \ctype{int
} referred to by
\var{ppos
} must be initialized to
1981 \code{0} prior to the first call to this function to start the
1982 iteration; the function returns true for each pair in the
1983 dictionary, and false once all pairs have been reported. The
1984 parameters
\var{pkey
} and
\var{pvalue
} should either point to
1985 \ctype{PyObject*
} variables that will be filled in with each key and
1986 value, respectively, or may be
\NULL{}. Any references returned through
1987 them are borrowed.
\var{ppos
} should not be altered during iteration.
1988 Its value represents offsets within the internal dictionary structure,
1989 and since the structure is sparse, the offsets are not consecutive.
1994 PyObject *key, *value;
1997 while (PyDict_Next(self->dict, &pos, &key, &value))
{
1998 /* do something interesting with the values... */
2003 The dictionary
\var{p
} should not be mutated during iteration. It
2004 is safe (since Python
2.1) to modify the values of the keys as you
2005 iterate over the dictionary, but only so long as the set of keys
2006 does not change. For example:
2009 PyObject *key, *value;
2012 while (PyDict_Next(self->dict, &pos, &key, &value))
{
2013 int i = PyInt_AS_LONG(value) +
1;
2014 PyObject *o = PyInt_FromLong(i);
2017 if (PyDict_SetItem(self->dict, key, o) <
0)
{
2026 \begin{cfuncdesc
}{int
}{PyDict_Merge
}{PyObject *a, PyObject *b, int override
}
2027 Iterate over mapping object
\var{b
} adding key-value pairs to dictionary
2029 \var{b
} may be a dictionary, or any object supporting
2030 \function{PyMapping_Keys()
} and
\function{PyObject_GetItem()
}.
2031 If
\var{override
} is true, existing pairs in
\var{a
} will
2032 be replaced if a matching key is found in
\var{b
}, otherwise pairs
2033 will only be added if there is not a matching key in
\var{a
}.
2034 Return
\code{0} on success or
\code{-
1} if an exception was
2039 \begin{cfuncdesc
}{int
}{PyDict_Update
}{PyObject *a, PyObject *b
}
2040 This is the same as
\code{PyDict_Merge(
\var{a
},
\var{b
},
1)
} in C,
2041 or
\code{\var{a
}.update(
\var{b
})
} in Python. Return
\code{0} on
2042 success or
\code{-
1} if an exception was raised.
2046 \begin{cfuncdesc
}{int
}{PyDict_MergeFromSeq2
}{PyObject *a, PyObject *seq2,
2048 Update or merge into dictionary
\var{a
}, from the key-value pairs in
2049 \var{seq2
}.
\var{seq2
} must be an iterable object producing
2050 iterable objects of length
2, viewed as key-value pairs. In case of
2051 duplicate keys, the last wins if
\var{override
} is true, else the
2053 Return
\code{0} on success or
\code{-
1} if an exception
2055 Equivalent Python (except for the return value):
2058 def PyDict_MergeFromSeq2(a, seq2, override):
2059 for key, value in seq2:
2060 if override or key not in a:
2068 \section{Other Objects
\label{otherObjects
}}
2070 \subsection{File Objects
\label{fileObjects
}}
2073 Python's built-in file objects are implemented entirely on the
2074 \ctype{FILE*
} support from the C standard library. This is an
2075 implementation detail and may change in future releases of Python.
2077 \begin{ctypedesc
}{PyFileObject
}
2078 This subtype of
\ctype{PyObject
} represents a Python file object.
2081 \begin{cvardesc
}{PyTypeObject
}{PyFile_Type
}
2082 This instance of
\ctype{PyTypeObject
} represents the Python file
2083 type. This is exposed to Python programs as
\code{types.FileType
}.
2084 \withsubitem{(in module types)
}{\ttindex{FileType
}}
2087 \begin{cfuncdesc
}{int
}{PyFile_Check
}{PyObject *p
}
2088 Returns true if its argument is a
\ctype{PyFileObject
} or a subtype
2089 of
\ctype{PyFileObject
}.
2090 \versionchanged[Allowed subtypes to be accepted
]{2.2}
2093 \begin{cfuncdesc
}{int
}{PyFile_CheckExact
}{PyObject *p
}
2094 Returns true if its argument is a
\ctype{PyFileObject
}, but not a
2095 subtype of
\ctype{PyFileObject
}.
2099 \begin{cfuncdesc
}{PyObject*
}{PyFile_FromString
}{char *filename, char *mode
}
2100 On success, returns a new file object that is opened on the file
2101 given by
\var{filename
}, with a file mode given by
\var{mode
}, where
2102 \var{mode
} has the same semantics as the standard C routine
2103 \cfunction{fopen()
}\ttindex{fopen()
}. On failure, returns
\NULL{}.
2106 \begin{cfuncdesc
}{PyObject*
}{PyFile_FromFile
}{FILE *fp,
2107 char *name, char *mode,
2108 int
(*close)(FILE*)}
2109 Creates a new
\ctype{PyFileObject
} from the already-open standard C
2110 file pointer,
\var{fp
}. The function
\var{close
} will be called
2111 when the file should be closed. Returns
\NULL{} on failure.
2114 \begin{cfuncdesc
}{FILE*
}{PyFile_AsFile
}{PyFileObject *p
}
2115 Returns the file object associated with
\var{p
} as a
\ctype{FILE*
}.
2118 \begin{cfuncdesc
}{PyObject*
}{PyFile_GetLine
}{PyObject *p, int n
}
2119 Equivalent to
\code{\var{p
}.readline(
\optional{\var{n
}})
}, this
2120 function reads one line from the object
\var{p
}.
\var{p
} may be a
2121 file object or any object with a
\method{readline()
} method. If
2122 \var{n
} is
\code{0}, exactly one line is read, regardless of the
2123 length of the line. If
\var{n
} is greater than
\code{0}, no more
2124 than
\var{n
} bytes will be read from the file; a partial line can be
2125 returned. In both cases, an empty string is returned if the end of
2126 the file is reached immediately. If
\var{n
} is less than
\code{0},
2127 however, one line is read regardless of length, but
2128 \exception{EOFError
} is raised if the end of the file is reached
2130 \withsubitem{(built-in exception)
}{\ttindex{EOFError
}}
2133 \begin{cfuncdesc
}{PyObject*
}{PyFile_Name
}{PyObject *p
}
2134 Returns the name of the file specified by
\var{p
} as a string
2138 \begin{cfuncdesc
}{void
}{PyFile_SetBufSize
}{PyFileObject *p, int n
}
2139 Available on systems with
\cfunction{setvbuf()
}\ttindex{setvbuf()
}
2140 only. This should only be called immediately after file object
2144 \begin{cfuncdesc
}{int
}{PyFile_Encoding
}{PyFileObject *p, char *enc
}
2145 Set the file's encoding for Unicode output to
\var{enc
}. Return
2146 1 on success and
0 on failure.
2150 \begin{cfuncdesc
}{int
}{PyFile_SoftSpace
}{PyObject *p, int newflag
}
2151 This function exists for internal use by the interpreter. Sets the
2152 \member{softspace
} attribute of
\var{p
} to
\var{newflag
} and
2153 \withsubitem{(file attribute)
}{\ttindex{softspace
}}returns the
2154 previous value.
\var{p
} does not have to be a file object for this
2155 function to work properly; any object is supported (thought its only
2156 interesting if the
\member{softspace
} attribute can be set). This
2157 function clears any errors, and will return
\code{0} as the previous
2158 value if the attribute either does not exist or if there were errors
2159 in retrieving it. There is no way to detect errors from this
2160 function, but doing so should not be needed.
2163 \begin{cfuncdesc
}{int
}{PyFile_WriteObject
}{PyObject *obj, PyFileObject *p,
2165 Writes object
\var{obj
} to file object
\var{p
}. The only supported
2166 flag for
\var{flags
} is
2167 \constant{Py_PRINT_RAW
}\ttindex{Py_PRINT_RAW
}; if given, the
2168 \function{str()
} of the object is written instead of the
2169 \function{repr()
}. Returns
\code{0} on success or
\code{-
1} on
2170 failure; the appropriate exception will be set.
2173 \begin{cfuncdesc
}{int
}{PyFile_WriteString
}{const char *s, PyFileObject *p
}
2174 Writes string
\var{s
} to file object
\var{p
}. Returns
\code{0} on
2175 success or
\code{-
1} on failure; the appropriate exception will be
2180 \subsection{Instance Objects
\label{instanceObjects
}}
2183 There are very few functions specific to instance objects.
2185 \begin{cvardesc
}{PyTypeObject
}{PyInstance_Type
}
2186 Type object for class instances.
2189 \begin{cfuncdesc
}{int
}{PyInstance_Check
}{PyObject *obj
}
2190 Returns true if
\var{obj
} is an instance.
2193 \begin{cfuncdesc
}{PyObject*
}{PyInstance_New
}{PyObject *class,
2196 Create a new instance of a specific class. The parameters
\var{arg
}
2197 and
\var{kw
} are used as the positional and keyword parameters to
2198 the object's constructor.
2201 \begin{cfuncdesc
}{PyObject*
}{PyInstance_NewRaw
}{PyObject *class,
2203 Create a new instance of a specific class without calling it's
2204 constructor.
\var{class
} is the class of new object. The
2205 \var{dict
} parameter will be used as the object's
\member{__dict__
};
2206 if
\NULL{}, a new dictionary will be created for the instance.
2210 \subsection{Method Objects
\label{method-objects
}}
2213 There are some useful functions that are useful for working with
2216 \begin{cvardesc
}{PyTypeObject
}{PyMethod_Type
}
2217 This instance of
\ctype{PyTypeObject
} represents the Python method
2218 type. This is exposed to Python programs as
\code{types.MethodType
}.
2219 \withsubitem{(in module types)
}{\ttindex{MethodType
}}
2222 \begin{cfuncdesc
}{int
}{PyMethod_Check
}{PyObject *o
}
2223 Return true if
\var{o
} is a method object (has type
2224 \cdata{PyMethod_Type
}). The parameter must not be
\NULL{}.
2227 \begin{cfuncdesc
}{PyObject*
}{PyMethod_New
}{PyObject *func.
2228 PyObject *self, PyObject *class
}
2229 Return a new method object, with
\var{func
} being any callable
2230 object; this is the function that will be called when the method is
2231 called. If this method should be bound to an instance,
\var{self
}
2232 should be the instance and
\var{class
} should be the class of
2233 \var{self
}, otherwise
\var{self
} should be
\NULL{} and
\var{class
}
2234 should be the class which provides the unbound method..
2237 \begin{cfuncdesc
}{PyObject*
}{PyMethod_Class
}{PyObject *meth
}
2238 Return the class object from which the method
\var{meth
} was
2239 created; if this was created from an instance, it will be the class
2243 \begin{cfuncdesc
}{PyObject*
}{PyMethod_GET_CLASS
}{PyObject *meth
}
2244 Macro version of
\cfunction{PyMethod_Class()
} which avoids error
2248 \begin{cfuncdesc
}{PyObject*
}{PyMethod_Function
}{PyObject *meth
}
2249 Return the function object associated with the method
\var{meth
}.
2252 \begin{cfuncdesc
}{PyObject*
}{PyMethod_GET_FUNCTION
}{PyObject *meth
}
2253 Macro version of
\cfunction{PyMethod_Function()
} which avoids error
2257 \begin{cfuncdesc
}{PyObject*
}{PyMethod_Self
}{PyObject *meth
}
2258 Return the instance associated with the method
\var{meth
} if it is
2259 bound, otherwise return
\NULL{}.
2262 \begin{cfuncdesc
}{PyObject*
}{PyMethod_GET_SELF
}{PyObject *meth
}
2263 Macro version of
\cfunction{PyMethod_Self()
} which avoids error
2268 \subsection{Module Objects
\label{moduleObjects
}}
2271 There are only a few functions special to module objects.
2273 \begin{cvardesc
}{PyTypeObject
}{PyModule_Type
}
2274 This instance of
\ctype{PyTypeObject
} represents the Python module
2275 type. This is exposed to Python programs as
2276 \code{types.ModuleType
}.
2277 \withsubitem{(in module types)
}{\ttindex{ModuleType
}}
2280 \begin{cfuncdesc
}{int
}{PyModule_Check
}{PyObject *p
}
2281 Returns true if
\var{p
} is a module object, or a subtype of a module
2283 \versionchanged[Allowed subtypes to be accepted
]{2.2}
2286 \begin{cfuncdesc
}{int
}{PyModule_CheckExact
}{PyObject *p
}
2287 Returns true if
\var{p
} is a module object, but not a subtype of
2288 \cdata{PyModule_Type
}.
2292 \begin{cfuncdesc
}{PyObject*
}{PyModule_New
}{char *name
}
2293 Return a new module object with the
\member{__name__
} attribute set
2294 to
\var{name
}. Only the module's
\member{__doc__
} and
2295 \member{__name__
} attributes are filled in; the caller is
2296 responsible for providing a
\member{__file__
} attribute.
2297 \withsubitem{(module attribute)
}{
2298 \ttindex{__name__
}\ttindex{__doc__
}\ttindex{__file__
}}
2301 \begin{cfuncdesc
}{PyObject*
}{PyModule_GetDict
}{PyObject *module
}
2302 Return the dictionary object that implements
\var{module
}'s
2303 namespace; this object is the same as the
\member{__dict__
}
2304 attribute of the module object. This function never fails.
2305 \withsubitem{(module attribute)
}{\ttindex{__dict__
}}
2306 It is recommended extensions use other
\cfunction{PyModule_*()
}
2307 and
\cfunction{PyObject_*()
} functions rather than directly
2308 manipulate a module's
\member{__dict__
}.
2311 \begin{cfuncdesc
}{char*
}{PyModule_GetName
}{PyObject *module
}
2312 Return
\var{module
}'s
\member{__name__
} value. If the module does
2313 not provide one, or if it is not a string,
\exception{SystemError
}
2314 is raised and
\NULL{} is returned.
2315 \withsubitem{(module attribute)
}{\ttindex{__name__
}}
2316 \withsubitem{(built-in exception)
}{\ttindex{SystemError
}}
2319 \begin{cfuncdesc
}{char*
}{PyModule_GetFilename
}{PyObject *module
}
2320 Return the name of the file from which
\var{module
} was loaded using
2321 \var{module
}'s
\member{__file__
} attribute. If this is not defined,
2322 or if it is not a string, raise
\exception{SystemError
} and return
2324 \withsubitem{(module attribute)
}{\ttindex{__file__
}}
2325 \withsubitem{(built-in exception)
}{\ttindex{SystemError
}}
2328 \begin{cfuncdesc
}{int
}{PyModule_AddObject
}{PyObject *module,
2329 char *name, PyObject *value
}
2330 Add an object to
\var{module
} as
\var{name
}. This is a convenience
2331 function which can be used from the module's initialization
2332 function. This steals a reference to
\var{value
}. Returns
2333 \code{-
1} on error,
\code{0} on success.
2337 \begin{cfuncdesc
}{int
}{PyModule_AddIntConstant
}{PyObject *module,
2338 char *name, long value
}
2339 Add an integer constant to
\var{module
} as
\var{name
}. This
2340 convenience function can be used from the module's initialization
2341 function. Returns
\code{-
1} on error,
\code{0} on success.
2345 \begin{cfuncdesc
}{int
}{PyModule_AddStringConstant
}{PyObject *module,
2346 char *name, char *value
}
2347 Add a string constant to
\var{module
} as
\var{name
}. This
2348 convenience function can be used from the module's initialization
2349 function. The string
\var{value
} must be null-terminated. Returns
2350 \code{-
1} on error,
\code{0} on success.
2355 \subsection{Iterator Objects
\label{iterator-objects
}}
2357 Python provides two general-purpose iterator objects. The first, a
2358 sequence iterator, works with an arbitrary sequence supporting the
2359 \method{__getitem__()
} method. The second works with a callable
2360 object and a sentinel value, calling the callable for each item in the
2361 sequence, and ending the iteration when the sentinel value is
2364 \begin{cvardesc
}{PyTypeObject
}{PySeqIter_Type
}
2365 Type object for iterator objects returned by
2366 \cfunction{PySeqIter_New()
} and the one-argument form of the
2367 \function{iter()
} built-in function for built-in sequence types.
2371 \begin{cfuncdesc
}{int
}{PySeqIter_Check
}{op
}
2372 Return true if the type of
\var{op
} is
\cdata{PySeqIter_Type
}.
2376 \begin{cfuncdesc
}{PyObject*
}{PySeqIter_New
}{PyObject *seq
}
2377 Return an iterator that works with a general sequence object,
2378 \var{seq
}. The iteration ends when the sequence raises
2379 \exception{IndexError
} for the subscripting operation.
2383 \begin{cvardesc
}{PyTypeObject
}{PyCallIter_Type
}
2384 Type object for iterator objects returned by
2385 \cfunction{PyCallIter_New()
} and the two-argument form of the
2386 \function{iter()
} built-in function.
2390 \begin{cfuncdesc
}{int
}{PyCallIter_Check
}{op
}
2391 Return true if the type of
\var{op
} is
\cdata{PyCallIter_Type
}.
2395 \begin{cfuncdesc
}{PyObject*
}{PyCallIter_New
}{PyObject *callable,
2397 Return a new iterator. The first parameter,
\var{callable
}, can be
2398 any Python callable object that can be called with no parameters;
2399 each call to it should return the next item in the iteration. When
2400 \var{callable
} returns a value equal to
\var{sentinel
}, the
2401 iteration will be terminated.
2406 \subsection{Descriptor Objects
\label{descriptor-objects
}}
2408 ``Descriptors'' are objects that describe some attribute of an object.
2409 They are found in the dictionary of type objects.
2411 \begin{cvardesc
}{PyTypeObject
}{PyProperty_Type
}
2412 The type object for the built-in descriptor types.
2416 \begin{cfuncdesc
}{PyObject*
}{PyDescr_NewGetSet
}{PyTypeObject *type,
2417 PyGetSetDef *getset
}
2421 \begin{cfuncdesc
}{PyObject*
}{PyDescr_NewMember
}{PyTypeObject *type,
2426 \begin{cfuncdesc
}{PyObject*
}{PyDescr_NewMethod
}{PyTypeObject *type,
2431 \begin{cfuncdesc
}{PyObject*
}{PyDescr_NewWrapper
}{PyTypeObject *type,
2432 struct wrapperbase *wrapper,
2437 \begin{cfuncdesc
}{PyObject*
}{PyDescr_NewClassMethod
}{PyTypeObject *type,
2438 PyMethodDef *method
}
2442 \begin{cfuncdesc
}{int
}{PyDescr_IsData
}{PyObject *descr
}
2443 Returns true if the descriptor objects
\var{descr
} describes a data
2444 attribute, or false if it describes a method.
\var{descr
} must be a
2445 descriptor object; there is no error checking.
2449 \begin{cfuncdesc
}{PyObject*
}{PyWrapper_New
}{PyObject *, PyObject *
}
2454 \subsection{Slice Objects
\label{slice-objects
}}
2456 \begin{cvardesc
}{PyTypeObject
}{PySlice_Type
}
2457 The type object for slice objects. This is the same as
2458 \code{types.SliceType
}.
2459 \withsubitem{(in module types)
}{\ttindex{SliceType
}}
2462 \begin{cfuncdesc
}{int
}{PySlice_Check
}{PyObject *ob
}
2463 Returns true if
\var{ob
} is a slice object;
\var{ob
} must not be
2467 \begin{cfuncdesc
}{PyObject*
}{PySlice_New
}{PyObject *start, PyObject *stop,
2469 Return a new slice object with the given values. The
\var{start
},
2470 \var{stop
}, and
\var{step
} parameters are used as the values of the
2471 slice object attributes of the same names. Any of the values may be
2472 \NULL{}, in which case the
\code{None
} will be used for the
2473 corresponding attribute. Returns
\NULL{} if the new object could
2477 \begin{cfuncdesc
}{int
}{PySlice_GetIndices
}{PySliceObject *slice, int length,
2478 int *start, int *stop, int *step
}
2479 Retrieve the start, stop and step indices from the slice object
2480 \var{slice
}, assuming a sequence of length
\var{length
}. Treats
2481 indices greater than
\var{length
} as errors.
2483 Returns
0 on success and -
1 on error with no exception set (unless one
2484 of the indices was not
\constant{None
} and failed to be converted to
2485 an integer, in which case -
1 is returned with an exception set).
2487 You probably do not want to use this function. If you want to use
2488 slice objects in versions of Python prior to
2.3, you would probably
2489 do well to incorporate the source of
\cfunction{PySlice_GetIndicesEx
},
2490 suitably renamed, in the source of your extension.
2493 \begin{cfuncdesc
}{int
}{PySlice_GetIndicesEx
}{PySliceObject *slice, int length,
2494 int *start, int *stop, int *step,
2496 Usable replacement for
\cfunction{PySlice_GetIndices
}. Retrieve the
2497 start, stop, and step indices from the slice object
\var{slice
}
2498 assuming a sequence of length
\var{length
}, and store the length of
2499 the slice in
\var{slicelength
}. Out of bounds indices are clipped in
2500 a manner consistent with the handling of normal slices.
2502 Returns
0 on success and -
1 on error with exception set.
2508 \subsection{Weak Reference Objects
\label{weakref-objects
}}
2510 Python supports
\emph{weak references
} as first-class objects. There
2511 are two specific object types which directly implement weak
2512 references. The first is a simple reference object, and the second
2513 acts as a proxy for the original object as much as it can.
2515 \begin{cfuncdesc
}{int
}{PyWeakref_Check
}{ob
}
2516 Return true if
\var{ob
} is either a reference or proxy object.
2520 \begin{cfuncdesc
}{int
}{PyWeakref_CheckRef
}{ob
}
2521 Return true if
\var{ob
} is a reference object.
2525 \begin{cfuncdesc
}{int
}{PyWeakref_CheckProxy
}{ob
}
2526 Return true if
\var{ob
} is a proxy object.
2530 \begin{cfuncdesc
}{PyObject*
}{PyWeakref_NewRef
}{PyObject *ob,
2532 Return a weak reference object for the object
\var{ob
}. This will
2533 always return a new reference, but is not guaranteed to create a new
2534 object; an existing reference object may be returned. The second
2535 parameter,
\var{callback
}, can be a callable object that receives
2536 notification when
\var{ob
} is garbage collected; it should accept a
2537 single parameter, which will be the weak reference object itself.
2538 \var{callback
} may also be
\code{None
} or
\NULL{}. If
\var{ob
}
2539 is not a weakly-referencable object, or if
\var{callback
} is not
2540 callable,
\code{None
}, or
\NULL{}, this will return
\NULL{} and
2541 raise
\exception{TypeError
}.
2545 \begin{cfuncdesc
}{PyObject*
}{PyWeakref_NewProxy
}{PyObject *ob,
2547 Return a weak reference proxy object for the object
\var{ob
}. This
2548 will always return a new reference, but is not guaranteed to create
2549 a new object; an existing proxy object may be returned. The second
2550 parameter,
\var{callback
}, can be a callable object that receives
2551 notification when
\var{ob
} is garbage collected; it should accept a
2552 single parameter, which will be the weak reference object itself.
2553 \var{callback
} may also be
\code{None
} or
\NULL{}. If
\var{ob
} is not
2554 a weakly-referencable object, or if
\var{callback
} is not callable,
2555 \code{None
}, or
\NULL{}, this will return
\NULL{} and raise
2556 \exception{TypeError
}.
2560 \begin{cfuncdesc
}{PyObject*
}{PyWeakref_GetObject
}{PyObject *ref
}
2561 Returns the referenced object from a weak reference,
\var{ref
}. If
2562 the referent is no longer live, returns
\code{None
}.
2566 \begin{cfuncdesc
}{PyObject*
}{PyWeakref_GET_OBJECT
}{PyObject *ref
}
2567 Similar to
\cfunction{PyWeakref_GetObject()
}, but implemented as a
2568 macro that does no error checking.
2573 \subsection{CObjects
\label{cObjects
}}
2576 Refer to
\emph{Extending and Embedding the Python Interpreter
},
2577 section~
1.12, ``Providing a C API for an Extension Module,'' for more
2578 information on using these objects.
2581 \begin{ctypedesc
}{PyCObject
}
2582 This subtype of
\ctype{PyObject
} represents an opaque value, useful
2583 for C extension modules who need to pass an opaque value (as a
2584 \ctype{void*
} pointer) through Python code to other C code. It is
2585 often used to make a C function pointer defined in one module
2586 available to other modules, so the regular import mechanism can be
2587 used to access C APIs defined in dynamically loaded modules.
2590 \begin{cfuncdesc
}{int
}{PyCObject_Check
}{PyObject *p
}
2591 Return true if its argument is a
\ctype{PyCObject
}.
2594 \begin{cfuncdesc
}{PyObject*
}{PyCObject_FromVoidPtr
}{void* cobj,
2595 void
(*destr)(void *)}
2596 Create a
\ctype{PyCObject
} from the
\code{void *
}\var{cobj
}. The
2597 \var{destr
} function will be called when the object is reclaimed,
2598 unless it is
\NULL{}.
2601 \begin{cfuncdesc
}{PyObject*
}{PyCObject_FromVoidPtrAndDesc
}{void* cobj,
2602 void* desc, void
(*destr)(void *, void *)}
2603 Create a
\ctype{PyCObject
} from the
\ctype{void *
}\var{cobj
}. The
2604 \var{destr
} function will be called when the object is reclaimed.
2605 The
\var{desc
} argument can be used to pass extra callback data for
2606 the destructor function.
2609 \begin{cfuncdesc
}{void*
}{PyCObject_AsVoidPtr
}{PyObject* self
}
2610 Return the object
\ctype{void *
} that the
\ctype{PyCObject
}
2611 \var{self
} was created with.
2614 \begin{cfuncdesc
}{void*
}{PyCObject_GetDesc
}{PyObject* self
}
2615 Return the description
\ctype{void *
} that the
\ctype{PyCObject
}
2616 \var{self
} was created with.
2619 \begin{cfuncdesc
}{int
}{PyCObject_SetVoidPtr
}{PyObject* self, void* cobj
}
2620 Set the void pointer inside
\var{self
} to
\var{cobj
}.
2621 The
\ctype{PyCObject
} must not have an associated destructor.
2622 Return true on success, false on failure.
2626 \subsection{Cell Objects
\label{cell-objects
}}
2628 ``Cell'' objects are used to implement variables referenced by
2629 multiple scopes. For each such variable, a cell object is created to
2630 store the value; the local variables of each stack frame that
2631 references the value contains a reference to the cells from outer
2632 scopes which also use that variable. When the value is accessed, the
2633 value contained in the cell is used instead of the cell object
2634 itself. This de-referencing of the cell object requires support from
2635 the generated byte-code; these are not automatically de-referenced
2636 when accessed. Cell objects are not likely to be useful elsewhere.
2638 \begin{ctypedesc
}{PyCellObject
}
2639 The C structure used for cell objects.
2642 \begin{cvardesc
}{PyTypeObject
}{PyCell_Type
}
2643 The type object corresponding to cell objects
2646 \begin{cfuncdesc
}{int
}{PyCell_Check
}{ob
}
2647 Return true if
\var{ob
} is a cell object;
\var{ob
} must not be
2651 \begin{cfuncdesc
}{PyObject*
}{PyCell_New
}{PyObject *ob
}
2652 Create and return a new cell object containing the value
\var{ob
}.
2653 The parameter may be
\NULL{}.
2656 \begin{cfuncdesc
}{PyObject*
}{PyCell_Get
}{PyObject *cell
}
2657 Return the contents of the cell
\var{cell
}.
2660 \begin{cfuncdesc
}{PyObject*
}{PyCell_GET
}{PyObject *cell
}
2661 Return the contents of the cell
\var{cell
}, but without checking
2662 that
\var{cell
} is non-
\NULL{} and a cell object.
2665 \begin{cfuncdesc
}{int
}{PyCell_Set
}{PyObject *cell, PyObject *value
}
2666 Set the contents of the cell object
\var{cell
} to
\var{value
}. This
2667 releases the reference to any current content of the cell.
2668 \var{value
} may be
\NULL{}.
\var{cell
} must be non-
\NULL{}; if it is
2669 not a cell object,
\code{-
1} will be returned. On success,
\code{0}
2673 \begin{cfuncdesc
}{void
}{PyCell_SET
}{PyObject *cell, PyObject *value
}
2674 Sets the value of the cell object
\var{cell
} to
\var{value
}. No
2675 reference counts are adjusted, and no checks are made for safety;
2676 \var{cell
} must be non-
\NULL{} and must be a cell object.
2680 \subsection{Generator Objects
\label{gen-objects
}}
2682 Generator objects are what Python uses to implement generator iterators.
2683 They are normally created by iterating over a function that yields values,
2684 rather than explicitly calling
\cfunction{PyGen_New
}.
2686 \begin{ctypedesc
}{PyGenObject
}
2687 The C structure used for generator objects.
2690 \begin{cvardesc
}{PyTypeObject
}{PyGen_Type
}
2691 The type object corresponding to generator objects
2694 \begin{cfuncdesc
}{int
}{PyGen_Check
}{ob
}
2695 Return true if
\var{ob
} is a generator object;
\var{ob
} must not be
2699 \begin{cfuncdesc
}{int
}{PyGen_CheckExact
}{ob
}
2700 Return true if
\var{ob
}'s type is
\var{PyGen_Type
}
2701 is a generator object;
\var{ob
} must not be
2705 \begin{cfuncdesc
}{PyObject*
}{PyGen_New
}{PyFrameObject *frame
}
2706 Create and return a new generator object based on the
\var{frame
} object.
2707 The parameter must not be
\NULL{}.
2711 \subsection{DateTime Objects
\label{datetime-objects
}}
2713 Various date and time objects are supplied by the
\module{datetime
}
2714 module. Before using any of these functions, the header file
2715 \file{datetime.h
} must be included in your source (note that this is
2716 not include by
\file{Python.h
}), and macro
\cfunction{PyDateTime_IMPORT()
}
2717 must be invoked. The macro arranges to put a pointer to a C structure
2718 in a static variable
\code{PyDateTimeAPI
}, which is used by the following
2723 \begin{cfuncdesc
}{int
}{PyDate_Check
}{PyObject *ob
}
2724 Return true if
\var{ob
} is of type
\cdata{PyDateTime_DateType
} or
2725 a subtype of
\cdata{PyDateTime_DateType
}.
\var{ob
} must not be
2730 \begin{cfuncdesc
}{int
}{PyDate_CheckExact
}{PyObject *ob
}
2731 Return true if
\var{ob
} is of type
\cdata{PyDateTime_DateType
}.
2732 \var{ob
} must not be
\NULL{}.
2736 \begin{cfuncdesc
}{int
}{PyDateTime_Check
}{PyObject *ob
}
2737 Return true if
\var{ob
} is of type
\cdata{PyDateTime_DateTimeType
} or
2738 a subtype of
\cdata{PyDateTime_DateTimeType
}.
\var{ob
} must not be
2743 \begin{cfuncdesc
}{int
}{PyDateTime_CheckExact
}{PyObject *ob
}
2744 Return true if
\var{ob
} is of type
\cdata{PyDateTime_DateTimeType
}.
2745 \var{ob
} must not be
\NULL{}.
2749 \begin{cfuncdesc
}{int
}{PyTime_Check
}{PyObject *ob
}
2750 Return true if
\var{ob
} is of type
\cdata{PyDateTime_TimeType
} or
2751 a subtype of
\cdata{PyDateTime_TimeType
}.
\var{ob
} must not be
2756 \begin{cfuncdesc
}{int
}{PyTime_CheckExact
}{PyObject *ob
}
2757 Return true if
\var{ob
} is of type
\cdata{PyDateTime_TimeType
}.
2758 \var{ob
} must not be
\NULL{}.
2762 \begin{cfuncdesc
}{int
}{PyDelta_Check
}{PyObject *ob
}
2763 Return true if
\var{ob
} is of type
\cdata{PyDateTime_DeltaType
} or
2764 a subtype of
\cdata{PyDateTime_DeltaType
}.
\var{ob
} must not be
2769 \begin{cfuncdesc
}{int
}{PyDelta_CheckExact
}{PyObject *ob
}
2770 Return true if
\var{ob
} is of type
\cdata{PyDateTime_DeltaType
}.
2771 \var{ob
} must not be
\NULL{}.
2775 \begin{cfuncdesc
}{int
}{PyTZInfo_Check
}{PyObject *ob
}
2776 Return true if
\var{ob
} is of type
\cdata{PyDateTime_TZInfoType
} or
2777 a subtype of
\cdata{PyDateTime_TZInfoType
}.
\var{ob
} must not be
2782 \begin{cfuncdesc
}{int
}{PyTZInfo_CheckExact
}{PyObject *ob
}
2783 Return true if
\var{ob
} is of type
\cdata{PyDateTime_TZInfoType
}.
2784 \var{ob
} must not be
\NULL{}.
2788 Macros to create objects:
2790 \begin{cfuncdesc
}{PyObject*
}{PyDate_FromDate
}{int year, int month, int day
}
2791 Return a
\code{datetime.date
} object with the specified year, month
2796 \begin{cfuncdesc
}{PyObject*
}{PyDateTime_FromDateAndTime
}{int year, int month,
2797 int day, int hour, int minute, int second, int usecond
}
2798 Return a
\code{datetime.datetime
} object with the specified year, month,
2799 day, hour, minute, second and microsecond.
2803 \begin{cfuncdesc
}{PyObject*
}{PyTime_FromTime
}{int hour, int minute,
2804 int second, int usecond
}
2805 Return a
\code{datetime.time
} object with the specified hour, minute,
2806 second and microsecond.
2810 \begin{cfuncdesc
}{PyObject*
}{PyDelta_FromDSU
}{int days, int seconds,
2812 Return a
\code{datetime.timedelta
} object representing the given number
2813 of days, seconds and microseconds. Normalization is performed so that
2814 the resulting number of microseconds and seconds lie in the ranges
2815 documented for
\code{datetime.timedelta
} objects.
2819 Macros to extract fields from date objects. The argument must be an
2820 instance of
\cdata{PyDateTime_Date
}, including subclasses (such as
2821 \cdata{PyDateTime_DateTime
}). The argument must not be
\NULL{}, and
2822 the type is not checked:
2824 \begin{cfuncdesc
}{int
}{PyDateTime_GET_YEAR
}{PyDateTime_Date *o
}
2825 Return the year, as a positive int.
2829 \begin{cfuncdesc
}{int
}{PyDateTime_GET_MONTH
}{PyDateTime_Date *o
}
2830 Return the month, as an int from
1 through
12.
2834 \begin{cfuncdesc
}{int
}{PyDateTime_GET_DAY
}{PyDateTime_Date *o
}
2835 Return the day, as an int from
1 through
31.
2839 Macros to extract fields from datetime objects. The argument must be an
2840 instance of
\cdata{PyDateTime_DateTime
}, including subclasses.
2841 The argument must not be
\NULL{}, and the type is not checked:
2843 \begin{cfuncdesc
}{int
}{PyDateTime_DATE_GET_HOUR
}{PyDateTime_DateTime *o
}
2844 Return the hour, as an int from
0 through
23.
2848 \begin{cfuncdesc
}{int
}{PyDateTime_DATE_GET_MINUTE
}{PyDateTime_DateTime *o
}
2849 Return the minute, as an int from
0 through
59.
2853 \begin{cfuncdesc
}{int
}{PyDateTime_DATE_GET_SECOND
}{PyDateTime_DateTime *o
}
2854 Return the second, as an int from
0 through
59.
2858 \begin{cfuncdesc
}{int
}{PyDateTime_DATE_GET_MICROSECOND
}{PyDateTime_DateTime *o
}
2859 Return the microsecond, as an int from
0 through
999999.
2863 Macros to extract fields from time objects. The argument must be an
2864 instance of
\cdata{PyDateTime_Time
}, including subclasses.
2865 The argument must not be
\NULL{}, and the type is not checked:
2867 \begin{cfuncdesc
}{int
}{PyDateTime_TIME_GET_HOUR
}{PyDateTime_Time *o
}
2868 Return the hour, as an int from
0 through
23.
2872 \begin{cfuncdesc
}{int
}{PyDateTime_TIME_GET_MINUTE
}{PyDateTime_Time *o
}
2873 Return the minute, as an int from
0 through
59.
2877 \begin{cfuncdesc
}{int
}{PyDateTime_TIME_GET_SECOND
}{PyDateTime_Time *o
}
2878 Return the second, as an int from
0 through
59.
2882 \begin{cfuncdesc
}{int
}{PyDateTime_TIME_GET_MICROSECOND
}{PyDateTime_Time *o
}
2883 Return the microsecond, as an int from
0 through
999999.
2887 Macros for the convenience of modules implementing the DB API:
2889 \begin{cfuncdesc
}{PyObject*
}{PyDateTime_FromTimestamp
}{PyObject *args
}
2890 Create and return a new
\code{datetime.datetime
} object given an argument
2891 tuple suitable for passing to
\code{datetime.datetime.fromtimestamp()
}.
2895 \begin{cfuncdesc
}{PyObject*
}{PyDate_FromTimestamp
}{PyObject *args
}
2896 Create and return a new
\code{datetime.date
} object given an argument
2897 tuple suitable for passing to
\code{datetime.date.fromtimestamp()
}.