blob: 6cd4be49ce7b1e82b0bb999c15db0e4664665d41 [file] [log] [blame]
Georg Brandl116aa622007-08-15 14:28:22 +00001.. highlightlang:: c
2
3
4.. _concrete:
5
6**********************
7Concrete Objects Layer
8**********************
9
10The functions in this chapter are specific to certain Python object types.
11Passing them an object of the wrong type is not a good idea; if you receive an
12object from a Python program and you are not sure that it has the right type,
13you must perform a type check first; for example, to check that an object is a
14dictionary, use :cfunc:`PyDict_Check`. The chapter is structured like the
15"family tree" of Python object types.
16
17.. warning::
18
19 While the functions described in this chapter carefully check the type of the
20 objects which are passed in, many of them do not check for *NULL* being passed
21 instead of a valid object. Allowing *NULL* to be passed in can cause memory
22 access violations and immediate termination of the interpreter.
23
24
25.. _fundamental:
26
27Fundamental Objects
28===================
29
30This section describes Python type objects and the singleton object ``None``.
31
32
33.. _typeobjects:
34
35Type Objects
36------------
37
38.. index:: object: type
39
40
41.. ctype:: PyTypeObject
42
43 The C structure of the objects used to describe built-in types.
44
45
46.. cvar:: PyObject* PyType_Type
47
48 .. index:: single: TypeType (in module types)
49
50 This is the type object for type objects; it is the same object as ``type`` and
51 ``types.TypeType`` in the Python layer.
52
53
54.. cfunction:: int PyType_Check(PyObject *o)
55
56 Return true if the object *o* is a type object, including instances of types
57 derived from the standard type object. Return false in all other cases.
58
59
60.. cfunction:: int PyType_CheckExact(PyObject *o)
61
62 Return true if the object *o* is a type object, but not a subtype of the
63 standard type object. Return false in all other cases.
64
Georg Brandl116aa622007-08-15 14:28:22 +000065
66.. cfunction:: int PyType_HasFeature(PyObject *o, int feature)
67
68 Return true if the type object *o* sets the feature *feature*. Type features
69 are denoted by single bit flags.
70
71
72.. cfunction:: int PyType_IS_GC(PyObject *o)
73
74 Return true if the type object includes support for the cycle detector; this
75 tests the type flag :const:`Py_TPFLAGS_HAVE_GC`.
76
Georg Brandl116aa622007-08-15 14:28:22 +000077
78.. cfunction:: int PyType_IsSubtype(PyTypeObject *a, PyTypeObject *b)
79
80 Return true if *a* is a subtype of *b*.
81
Georg Brandl116aa622007-08-15 14:28:22 +000082
83.. cfunction:: PyObject* PyType_GenericAlloc(PyTypeObject *type, Py_ssize_t nitems)
84
Georg Brandl321976b2007-09-01 12:33:24 +000085 XXX: Document.
Georg Brandl116aa622007-08-15 14:28:22 +000086
87
88.. cfunction:: PyObject* PyType_GenericNew(PyTypeObject *type, PyObject *args, PyObject *kwds)
89
Georg Brandl321976b2007-09-01 12:33:24 +000090 XXX: Document.
Georg Brandl116aa622007-08-15 14:28:22 +000091
92
93.. cfunction:: int PyType_Ready(PyTypeObject *type)
94
95 Finalize a type object. This should be called on all type objects to finish
96 their initialization. This function is responsible for adding inherited slots
97 from a type's base class. Return ``0`` on success, or return ``-1`` and sets an
98 exception on error.
99
Georg Brandl116aa622007-08-15 14:28:22 +0000100
101.. _noneobject:
102
103The None Object
104---------------
105
106.. index:: object: None
107
108Note that the :ctype:`PyTypeObject` for ``None`` is not directly exposed in the
109Python/C API. Since ``None`` is a singleton, testing for object identity (using
110``==`` in C) is sufficient. There is no :cfunc:`PyNone_Check` function for the
111same reason.
112
113
114.. cvar:: PyObject* Py_None
115
116 The Python ``None`` object, denoting lack of value. This object has no methods.
117 It needs to be treated just like any other object with respect to reference
118 counts.
119
120
121.. cmacro:: Py_RETURN_NONE
122
Georg Brandl321976b2007-09-01 12:33:24 +0000123 Properly handle returning :cdata:`Py_None` from within a C function (that is,
124 increment the reference count of None and return it.)
Georg Brandl116aa622007-08-15 14:28:22 +0000125
126
127.. _numericobjects:
128
129Numeric Objects
130===============
131
132.. index:: object: numeric
133
134
135.. _intobjects:
136
137Plain Integer Objects
138---------------------
139
140.. index:: object: integer
141
142
143.. ctype:: PyIntObject
144
145 This subtype of :ctype:`PyObject` represents a Python integer object.
146
147
148.. cvar:: PyTypeObject PyInt_Type
149
150 .. index:: single: IntType (in modules types)
151
152 This instance of :ctype:`PyTypeObject` represents the Python plain integer type.
153 This is the same object as ``int`` and ``types.IntType``.
154
155
156.. cfunction:: int PyInt_Check(PyObject *o)
157
158 Return true if *o* is of type :cdata:`PyInt_Type` or a subtype of
159 :cdata:`PyInt_Type`.
160
Georg Brandl116aa622007-08-15 14:28:22 +0000161
162.. cfunction:: int PyInt_CheckExact(PyObject *o)
163
164 Return true if *o* is of type :cdata:`PyInt_Type`, but not a subtype of
165 :cdata:`PyInt_Type`.
166
Georg Brandl116aa622007-08-15 14:28:22 +0000167
168.. cfunction:: PyObject* PyInt_FromString(char *str, char **pend, int base)
169
170 Return a new :ctype:`PyIntObject` or :ctype:`PyLongObject` based on the string
171 value in *str*, which is interpreted according to the radix in *base*. If
172 *pend* is non-*NULL*, ``*pend`` will point to the first character in *str* which
173 follows the representation of the number. If *base* is ``0``, the radix will be
174 determined based on the leading characters of *str*: if *str* starts with
175 ``'0x'`` or ``'0X'``, radix 16 will be used; if *str* starts with ``'0'``, radix
176 8 will be used; otherwise radix 10 will be used. If *base* is not ``0``, it
177 must be between ``2`` and ``36``, inclusive. Leading spaces are ignored. If
178 there are no digits, :exc:`ValueError` will be raised. If the string represents
179 a number too large to be contained within the machine's :ctype:`long int` type
180 and overflow warnings are being suppressed, a :ctype:`PyLongObject` will be
181 returned. If overflow warnings are not being suppressed, *NULL* will be
182 returned in this case.
183
184
185.. cfunction:: PyObject* PyInt_FromLong(long ival)
186
187 Create a new integer object with a value of *ival*.
188
189 The current implementation keeps an array of integer objects for all integers
190 between ``-5`` and ``256``, when you create an int in that range you actually
191 just get back a reference to the existing object. So it should be possible to
192 change the value of ``1``. I suspect the behaviour of Python in this case is
193 undefined. :-)
194
195
196.. cfunction:: PyObject* PyInt_FromSsize_t(Py_ssize_t ival)
197
198 Create a new integer object with a value of *ival*. If the value exceeds
199 ``LONG_MAX``, a long integer object is returned.
200
Georg Brandl116aa622007-08-15 14:28:22 +0000201
202.. cfunction:: long PyInt_AsLong(PyObject *io)
203
204 Will first attempt to cast the object to a :ctype:`PyIntObject`, if it is not
205 already one, and then return its value. If there is an error, ``-1`` is
206 returned, and the caller should check ``PyErr_Occurred()`` to find out whether
207 there was an error, or whether the value just happened to be -1.
208
209
210.. cfunction:: long PyInt_AS_LONG(PyObject *io)
211
212 Return the value of the object *io*. No error checking is performed.
213
214
215.. cfunction:: unsigned long PyInt_AsUnsignedLongMask(PyObject *io)
216
217 Will first attempt to cast the object to a :ctype:`PyIntObject` or
218 :ctype:`PyLongObject`, if it is not already one, and then return its value as
219 unsigned long. This function does not check for overflow.
220
Georg Brandl116aa622007-08-15 14:28:22 +0000221
222.. cfunction:: unsigned PY_LONG_LONG PyInt_AsUnsignedLongLongMask(PyObject *io)
223
224 Will first attempt to cast the object to a :ctype:`PyIntObject` or
225 :ctype:`PyLongObject`, if it is not already one, and then return its value as
226 unsigned long long, without checking for overflow.
227
Georg Brandl116aa622007-08-15 14:28:22 +0000228
229.. cfunction:: Py_ssize_t PyInt_AsSsize_t(PyObject *io)
230
231 Will first attempt to cast the object to a :ctype:`PyIntObject` or
232 :ctype:`PyLongObject`, if it is not already one, and then return its value as
233 :ctype:`Py_ssize_t`.
234
Georg Brandl116aa622007-08-15 14:28:22 +0000235
236.. cfunction:: long PyInt_GetMax()
237
238 .. index:: single: LONG_MAX
239
240 Return the system's idea of the largest integer it can handle
241 (:const:`LONG_MAX`, as defined in the system header files).
242
243
244.. _boolobjects:
245
246Boolean Objects
247---------------
248
249Booleans in Python are implemented as a subclass of integers. There are only
250two booleans, :const:`Py_False` and :const:`Py_True`. As such, the normal
251creation and deletion functions don't apply to booleans. The following macros
252are available, however.
253
254
255.. cfunction:: int PyBool_Check(PyObject *o)
256
257 Return true if *o* is of type :cdata:`PyBool_Type`.
258
Georg Brandl116aa622007-08-15 14:28:22 +0000259
260.. cvar:: PyObject* Py_False
261
262 The Python ``False`` object. This object has no methods. It needs to be
263 treated just like any other object with respect to reference counts.
264
265
266.. cvar:: PyObject* Py_True
267
268 The Python ``True`` object. This object has no methods. It needs to be treated
269 just like any other object with respect to reference counts.
270
271
272.. cmacro:: Py_RETURN_FALSE
273
274 Return :const:`Py_False` from a function, properly incrementing its reference
275 count.
276
Georg Brandl116aa622007-08-15 14:28:22 +0000277
278.. cmacro:: Py_RETURN_TRUE
279
280 Return :const:`Py_True` from a function, properly incrementing its reference
281 count.
282
Georg Brandl116aa622007-08-15 14:28:22 +0000283
284.. cfunction:: PyObject* PyBool_FromLong(long v)
285
286 Return a new reference to :const:`Py_True` or :const:`Py_False` depending on the
287 truth value of *v*.
288
Georg Brandl116aa622007-08-15 14:28:22 +0000289
290.. _longobjects:
291
292Long Integer Objects
293--------------------
294
295.. index:: object: long integer
296
297
298.. ctype:: PyLongObject
299
300 This subtype of :ctype:`PyObject` represents a Python long integer object.
301
302
303.. cvar:: PyTypeObject PyLong_Type
304
305 .. index:: single: LongType (in modules types)
306
307 This instance of :ctype:`PyTypeObject` represents the Python long integer type.
308 This is the same object as ``long`` and ``types.LongType``.
309
310
311.. cfunction:: int PyLong_Check(PyObject *p)
312
313 Return true if its argument is a :ctype:`PyLongObject` or a subtype of
314 :ctype:`PyLongObject`.
315
Georg Brandl116aa622007-08-15 14:28:22 +0000316
317.. cfunction:: int PyLong_CheckExact(PyObject *p)
318
319 Return true if its argument is a :ctype:`PyLongObject`, but not a subtype of
320 :ctype:`PyLongObject`.
321
Georg Brandl116aa622007-08-15 14:28:22 +0000322
323.. cfunction:: PyObject* PyLong_FromLong(long v)
324
325 Return a new :ctype:`PyLongObject` object from *v*, or *NULL* on failure.
326
327
328.. cfunction:: PyObject* PyLong_FromUnsignedLong(unsigned long v)
329
330 Return a new :ctype:`PyLongObject` object from a C :ctype:`unsigned long`, or
331 *NULL* on failure.
332
333
334.. cfunction:: PyObject* PyLong_FromLongLong(PY_LONG_LONG v)
335
336 Return a new :ctype:`PyLongObject` object from a C :ctype:`long long`, or *NULL*
337 on failure.
338
339
340.. cfunction:: PyObject* PyLong_FromUnsignedLongLong(unsigned PY_LONG_LONG v)
341
342 Return a new :ctype:`PyLongObject` object from a C :ctype:`unsigned long long`,
343 or *NULL* on failure.
344
345
346.. cfunction:: PyObject* PyLong_FromDouble(double v)
347
348 Return a new :ctype:`PyLongObject` object from the integer part of *v*, or
349 *NULL* on failure.
350
351
352.. cfunction:: PyObject* PyLong_FromString(char *str, char **pend, int base)
353
354 Return a new :ctype:`PyLongObject` based on the string value in *str*, which is
355 interpreted according to the radix in *base*. If *pend* is non-*NULL*,
356 ``*pend`` will point to the first character in *str* which follows the
357 representation of the number. If *base* is ``0``, the radix will be determined
358 based on the leading characters of *str*: if *str* starts with ``'0x'`` or
359 ``'0X'``, radix 16 will be used; if *str* starts with ``'0'``, radix 8 will be
360 used; otherwise radix 10 will be used. If *base* is not ``0``, it must be
361 between ``2`` and ``36``, inclusive. Leading spaces are ignored. If there are
362 no digits, :exc:`ValueError` will be raised.
363
364
365.. cfunction:: PyObject* PyLong_FromUnicode(Py_UNICODE *u, Py_ssize_t length, int base)
366
367 Convert a sequence of Unicode digits to a Python long integer value. The first
368 parameter, *u*, points to the first character of the Unicode string, *length*
369 gives the number of characters, and *base* is the radix for the conversion. The
370 radix must be in the range [2, 36]; if it is out of range, :exc:`ValueError`
371 will be raised.
372
Georg Brandl116aa622007-08-15 14:28:22 +0000373
374.. cfunction:: PyObject* PyLong_FromVoidPtr(void *p)
375
376 Create a Python integer or long integer from the pointer *p*. The pointer value
377 can be retrieved from the resulting value using :cfunc:`PyLong_AsVoidPtr`.
Georg Brandl321976b2007-09-01 12:33:24 +0000378 If the integer is larger than LONG_MAX, a positive long integer is returned.
Georg Brandl116aa622007-08-15 14:28:22 +0000379
380
381.. cfunction:: long PyLong_AsLong(PyObject *pylong)
382
383 .. index::
384 single: LONG_MAX
385 single: OverflowError (built-in exception)
386
387 Return a C :ctype:`long` representation of the contents of *pylong*. If
388 *pylong* is greater than :const:`LONG_MAX`, an :exc:`OverflowError` is raised.
389
390
391.. cfunction:: unsigned long PyLong_AsUnsignedLong(PyObject *pylong)
392
393 .. index::
394 single: ULONG_MAX
395 single: OverflowError (built-in exception)
396
397 Return a C :ctype:`unsigned long` representation of the contents of *pylong*.
398 If *pylong* is greater than :const:`ULONG_MAX`, an :exc:`OverflowError` is
399 raised.
400
401
402.. cfunction:: PY_LONG_LONG PyLong_AsLongLong(PyObject *pylong)
403
404 Return a C :ctype:`long long` from a Python long integer. If *pylong* cannot be
405 represented as a :ctype:`long long`, an :exc:`OverflowError` will be raised.
406
Georg Brandl116aa622007-08-15 14:28:22 +0000407
408.. cfunction:: unsigned PY_LONG_LONG PyLong_AsUnsignedLongLong(PyObject *pylong)
409
410 Return a C :ctype:`unsigned long long` from a Python long integer. If *pylong*
411 cannot be represented as an :ctype:`unsigned long long`, an :exc:`OverflowError`
412 will be raised if the value is positive, or a :exc:`TypeError` will be raised if
413 the value is negative.
414
Georg Brandl116aa622007-08-15 14:28:22 +0000415
416.. cfunction:: unsigned long PyLong_AsUnsignedLongMask(PyObject *io)
417
418 Return a C :ctype:`unsigned long` from a Python long integer, without checking
419 for overflow.
420
Georg Brandl116aa622007-08-15 14:28:22 +0000421
422.. cfunction:: unsigned PY_LONG_LONG PyLong_AsUnsignedLongLongMask(PyObject *io)
423
424 Return a C :ctype:`unsigned long long` from a Python long integer, without
425 checking for overflow.
426
Georg Brandl116aa622007-08-15 14:28:22 +0000427
428.. cfunction:: double PyLong_AsDouble(PyObject *pylong)
429
430 Return a C :ctype:`double` representation of the contents of *pylong*. If
431 *pylong* cannot be approximately represented as a :ctype:`double`, an
432 :exc:`OverflowError` exception is raised and ``-1.0`` will be returned.
433
434
435.. cfunction:: void* PyLong_AsVoidPtr(PyObject *pylong)
436
437 Convert a Python integer or long integer *pylong* to a C :ctype:`void` pointer.
438 If *pylong* cannot be converted, an :exc:`OverflowError` will be raised. This
439 is only assured to produce a usable :ctype:`void` pointer for values created
440 with :cfunc:`PyLong_FromVoidPtr`.
441
Georg Brandl321976b2007-09-01 12:33:24 +0000442 For values outside 0..LONG_MAX, both signed and unsigned integers are acccepted.
Georg Brandl116aa622007-08-15 14:28:22 +0000443
444
445.. _floatobjects:
446
447Floating Point Objects
448----------------------
449
450.. index:: object: floating point
451
452
453.. ctype:: PyFloatObject
454
455 This subtype of :ctype:`PyObject` represents a Python floating point object.
456
457
458.. cvar:: PyTypeObject PyFloat_Type
459
460 .. index:: single: FloatType (in modules types)
461
462 This instance of :ctype:`PyTypeObject` represents the Python floating point
463 type. This is the same object as ``float`` and ``types.FloatType``.
464
465
466.. cfunction:: int PyFloat_Check(PyObject *p)
467
468 Return true if its argument is a :ctype:`PyFloatObject` or a subtype of
469 :ctype:`PyFloatObject`.
470
Georg Brandl116aa622007-08-15 14:28:22 +0000471
472.. cfunction:: int PyFloat_CheckExact(PyObject *p)
473
474 Return true if its argument is a :ctype:`PyFloatObject`, but not a subtype of
475 :ctype:`PyFloatObject`.
476
Georg Brandl116aa622007-08-15 14:28:22 +0000477
478.. cfunction:: PyObject* PyFloat_FromString(PyObject *str)
479
480 Create a :ctype:`PyFloatObject` object based on the string value in *str*, or
481 *NULL* on failure.
482
483
484.. cfunction:: PyObject* PyFloat_FromDouble(double v)
485
486 Create a :ctype:`PyFloatObject` object from *v*, or *NULL* on failure.
487
488
489.. cfunction:: double PyFloat_AsDouble(PyObject *pyfloat)
490
491 Return a C :ctype:`double` representation of the contents of *pyfloat*. If
492 *pyfloat* is not a Python floating point object but has a :meth:`__float__`
493 method, this method will first be called to convert *pyfloat* into a float.
494
495
496.. cfunction:: double PyFloat_AS_DOUBLE(PyObject *pyfloat)
497
498 Return a C :ctype:`double` representation of the contents of *pyfloat*, but
499 without error checking.
500
501
502.. _complexobjects:
503
504Complex Number Objects
505----------------------
506
507.. index:: object: complex number
508
509Python's complex number objects are implemented as two distinct types when
510viewed from the C API: one is the Python object exposed to Python programs, and
511the other is a C structure which represents the actual complex number value.
512The API provides functions for working with both.
513
514
515Complex Numbers as C Structures
516^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
517
518Note that the functions which accept these structures as parameters and return
519them as results do so *by value* rather than dereferencing them through
520pointers. This is consistent throughout the API.
521
522
523.. ctype:: Py_complex
524
525 The C structure which corresponds to the value portion of a Python complex
526 number object. Most of the functions for dealing with complex number objects
527 use structures of this type as input or output values, as appropriate. It is
528 defined as::
529
530 typedef struct {
531 double real;
532 double imag;
533 } Py_complex;
534
535
536.. cfunction:: Py_complex _Py_c_sum(Py_complex left, Py_complex right)
537
538 Return the sum of two complex numbers, using the C :ctype:`Py_complex`
539 representation.
540
541
542.. cfunction:: Py_complex _Py_c_diff(Py_complex left, Py_complex right)
543
544 Return the difference between two complex numbers, using the C
545 :ctype:`Py_complex` representation.
546
547
548.. cfunction:: Py_complex _Py_c_neg(Py_complex complex)
549
550 Return the negation of the complex number *complex*, using the C
551 :ctype:`Py_complex` representation.
552
553
554.. cfunction:: Py_complex _Py_c_prod(Py_complex left, Py_complex right)
555
556 Return the product of two complex numbers, using the C :ctype:`Py_complex`
557 representation.
558
559
560.. cfunction:: Py_complex _Py_c_quot(Py_complex dividend, Py_complex divisor)
561
562 Return the quotient of two complex numbers, using the C :ctype:`Py_complex`
563 representation.
564
565
566.. cfunction:: Py_complex _Py_c_pow(Py_complex num, Py_complex exp)
567
568 Return the exponentiation of *num* by *exp*, using the C :ctype:`Py_complex`
569 representation.
570
571
572Complex Numbers as Python Objects
573^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
574
575
576.. ctype:: PyComplexObject
577
578 This subtype of :ctype:`PyObject` represents a Python complex number object.
579
580
581.. cvar:: PyTypeObject PyComplex_Type
582
583 This instance of :ctype:`PyTypeObject` represents the Python complex number
584 type. It is the same object as ``complex`` and ``types.ComplexType``.
585
586
587.. cfunction:: int PyComplex_Check(PyObject *p)
588
589 Return true if its argument is a :ctype:`PyComplexObject` or a subtype of
590 :ctype:`PyComplexObject`.
591
Georg Brandl116aa622007-08-15 14:28:22 +0000592
593.. cfunction:: int PyComplex_CheckExact(PyObject *p)
594
595 Return true if its argument is a :ctype:`PyComplexObject`, but not a subtype of
596 :ctype:`PyComplexObject`.
597
Georg Brandl116aa622007-08-15 14:28:22 +0000598
599.. cfunction:: PyObject* PyComplex_FromCComplex(Py_complex v)
600
601 Create a new Python complex number object from a C :ctype:`Py_complex` value.
602
603
604.. cfunction:: PyObject* PyComplex_FromDoubles(double real, double imag)
605
606 Return a new :ctype:`PyComplexObject` object from *real* and *imag*.
607
608
609.. cfunction:: double PyComplex_RealAsDouble(PyObject *op)
610
611 Return the real part of *op* as a C :ctype:`double`.
612
613
614.. cfunction:: double PyComplex_ImagAsDouble(PyObject *op)
615
616 Return the imaginary part of *op* as a C :ctype:`double`.
617
618
619.. cfunction:: Py_complex PyComplex_AsCComplex(PyObject *op)
620
621 Return the :ctype:`Py_complex` value of the complex number *op*.
622
Georg Brandl321976b2007-09-01 12:33:24 +0000623 If *op* is not a Python complex number object but has a :meth:`__complex__`
624 method, this method will first be called to convert *op* to a Python complex
625 number object.
Georg Brandl116aa622007-08-15 14:28:22 +0000626
627
628.. _sequenceobjects:
629
630Sequence Objects
631================
632
633.. index:: object: sequence
634
635Generic operations on sequence objects were discussed in the previous chapter;
636this section deals with the specific kinds of sequence objects that are
637intrinsic to the Python language.
638
639
640.. _stringobjects:
641
642String Objects
643--------------
644
645These functions raise :exc:`TypeError` when expecting a string parameter and are
646called with a non-string parameter.
647
648.. index:: object: string
649
650
651.. ctype:: PyStringObject
652
653 This subtype of :ctype:`PyObject` represents a Python string object.
654
655
656.. cvar:: PyTypeObject PyString_Type
657
658 .. index:: single: StringType (in module types)
659
660 This instance of :ctype:`PyTypeObject` represents the Python string type; it is
661 the same object as ``str`` and ``types.StringType`` in the Python layer. .
662
663
664.. cfunction:: int PyString_Check(PyObject *o)
665
666 Return true if the object *o* is a string object or an instance of a subtype of
667 the string type.
668
Georg Brandl116aa622007-08-15 14:28:22 +0000669
670.. cfunction:: int PyString_CheckExact(PyObject *o)
671
672 Return true if the object *o* is a string object, but not an instance of a
673 subtype of the string type.
674
Georg Brandl116aa622007-08-15 14:28:22 +0000675
676.. cfunction:: PyObject* PyString_FromString(const char *v)
677
678 Return a new string object with a copy of the string *v* as value on success,
679 and *NULL* on failure. The parameter *v* must not be *NULL*; it will not be
680 checked.
681
682
683.. cfunction:: PyObject* PyString_FromStringAndSize(const char *v, Py_ssize_t len)
684
685 Return a new string object with a copy of the string *v* as value and length
686 *len* on success, and *NULL* on failure. If *v* is *NULL*, the contents of the
687 string are uninitialized.
688
689
690.. cfunction:: PyObject* PyString_FromFormat(const char *format, ...)
691
692 Take a C :cfunc:`printf`\ -style *format* string and a variable number of
693 arguments, calculate the size of the resulting Python string and return a string
694 with the values formatted into it. The variable arguments must be C types and
695 must correspond exactly to the format characters in the *format* string. The
696 following format characters are allowed:
697
Georg Brandl321976b2007-09-01 12:33:24 +0000698 .. % XXX: This should be exactly the same as the table in PyErr_Format.
Georg Brandl116aa622007-08-15 14:28:22 +0000699 .. % One should just refer to the other.
Georg Brandl321976b2007-09-01 12:33:24 +0000700 .. % XXX: The descriptions for %zd and %zu are wrong, but the truth is complicated
Georg Brandl116aa622007-08-15 14:28:22 +0000701 .. % because not all compilers support the %z width modifier -- we fake it
702 .. % when necessary via interpolating PY_FORMAT_SIZE_T.
703 .. % %u, %lu, %zu should have "new in Python 2.5" blurbs.
704
705 +-------------------+---------------+--------------------------------+
706 | Format Characters | Type | Comment |
707 +===================+===============+================================+
708 | :attr:`%%` | *n/a* | The literal % character. |
709 +-------------------+---------------+--------------------------------+
710 | :attr:`%c` | int | A single character, |
711 | | | represented as an C int. |
712 +-------------------+---------------+--------------------------------+
713 | :attr:`%d` | int | Exactly equivalent to |
714 | | | ``printf("%d")``. |
715 +-------------------+---------------+--------------------------------+
716 | :attr:`%u` | unsigned int | Exactly equivalent to |
717 | | | ``printf("%u")``. |
718 +-------------------+---------------+--------------------------------+
719 | :attr:`%ld` | long | Exactly equivalent to |
720 | | | ``printf("%ld")``. |
721 +-------------------+---------------+--------------------------------+
722 | :attr:`%lu` | unsigned long | Exactly equivalent to |
723 | | | ``printf("%lu")``. |
724 +-------------------+---------------+--------------------------------+
725 | :attr:`%zd` | Py_ssize_t | Exactly equivalent to |
726 | | | ``printf("%zd")``. |
727 +-------------------+---------------+--------------------------------+
728 | :attr:`%zu` | size_t | Exactly equivalent to |
729 | | | ``printf("%zu")``. |
730 +-------------------+---------------+--------------------------------+
731 | :attr:`%i` | int | Exactly equivalent to |
732 | | | ``printf("%i")``. |
733 +-------------------+---------------+--------------------------------+
734 | :attr:`%x` | int | Exactly equivalent to |
735 | | | ``printf("%x")``. |
736 +-------------------+---------------+--------------------------------+
737 | :attr:`%s` | char\* | A null-terminated C character |
738 | | | array. |
739 +-------------------+---------------+--------------------------------+
740 | :attr:`%p` | void\* | The hex representation of a C |
741 | | | pointer. Mostly equivalent to |
742 | | | ``printf("%p")`` except that |
743 | | | it is guaranteed to start with |
744 | | | the literal ``0x`` regardless |
745 | | | of what the platform's |
746 | | | ``printf`` yields. |
747 +-------------------+---------------+--------------------------------+
748
749 An unrecognized format character causes all the rest of the format string to be
750 copied as-is to the result string, and any extra arguments discarded.
751
752
753.. cfunction:: PyObject* PyString_FromFormatV(const char *format, va_list vargs)
754
755 Identical to :func:`PyString_FromFormat` except that it takes exactly two
756 arguments.
757
758
759.. cfunction:: Py_ssize_t PyString_Size(PyObject *string)
760
761 Return the length of the string in string object *string*.
762
763
764.. cfunction:: Py_ssize_t PyString_GET_SIZE(PyObject *string)
765
766 Macro form of :cfunc:`PyString_Size` but without error checking.
767
768
769.. cfunction:: char* PyString_AsString(PyObject *string)
770
771 Return a NUL-terminated representation of the contents of *string*. The pointer
772 refers to the internal buffer of *string*, not a copy. The data must not be
773 modified in any way, unless the string was just created using
774 ``PyString_FromStringAndSize(NULL, size)``. It must not be deallocated. If
775 *string* is a Unicode object, this function computes the default encoding of
776 *string* and operates on that. If *string* is not a string object at all,
777 :cfunc:`PyString_AsString` returns *NULL* and raises :exc:`TypeError`.
778
779
780.. cfunction:: char* PyString_AS_STRING(PyObject *string)
781
782 Macro form of :cfunc:`PyString_AsString` but without error checking. Only
783 string objects are supported; no Unicode objects should be passed.
784
785
786.. cfunction:: int PyString_AsStringAndSize(PyObject *obj, char **buffer, Py_ssize_t *length)
787
788 Return a NUL-terminated representation of the contents of the object *obj*
789 through the output variables *buffer* and *length*.
790
791 The function accepts both string and Unicode objects as input. For Unicode
792 objects it returns the default encoded version of the object. If *length* is
793 *NULL*, the resulting buffer may not contain NUL characters; if it does, the
794 function returns ``-1`` and a :exc:`TypeError` is raised.
795
796 The buffer refers to an internal string buffer of *obj*, not a copy. The data
797 must not be modified in any way, unless the string was just created using
798 ``PyString_FromStringAndSize(NULL, size)``. It must not be deallocated. If
799 *string* is a Unicode object, this function computes the default encoding of
800 *string* and operates on that. If *string* is not a string object at all,
801 :cfunc:`PyString_AsStringAndSize` returns ``-1`` and raises :exc:`TypeError`.
802
803
804.. cfunction:: void PyString_Concat(PyObject **string, PyObject *newpart)
805
806 Create a new string object in *\*string* containing the contents of *newpart*
807 appended to *string*; the caller will own the new reference. The reference to
808 the old value of *string* will be stolen. If the new string cannot be created,
809 the old reference to *string* will still be discarded and the value of
810 *\*string* will be set to *NULL*; the appropriate exception will be set.
811
812
813.. cfunction:: void PyString_ConcatAndDel(PyObject **string, PyObject *newpart)
814
815 Create a new string object in *\*string* containing the contents of *newpart*
816 appended to *string*. This version decrements the reference count of *newpart*.
817
818
819.. cfunction:: int _PyString_Resize(PyObject **string, Py_ssize_t newsize)
820
821 A way to resize a string object even though it is "immutable". Only use this to
822 build up a brand new string object; don't use this if the string may already be
823 known in other parts of the code. It is an error to call this function if the
824 refcount on the input string object is not one. Pass the address of an existing
825 string object as an lvalue (it may be written into), and the new size desired.
826 On success, *\*string* holds the resized string object and ``0`` is returned;
827 the address in *\*string* may differ from its input value. If the reallocation
828 fails, the original string object at *\*string* is deallocated, *\*string* is
829 set to *NULL*, a memory exception is set, and ``-1`` is returned.
830
831
832.. cfunction:: PyObject* PyString_Format(PyObject *format, PyObject *args)
833
834 Return a new string object from *format* and *args*. Analogous to ``format %
835 args``. The *args* argument must be a tuple.
836
837
838.. cfunction:: void PyString_InternInPlace(PyObject **string)
839
840 Intern the argument *\*string* in place. The argument must be the address of a
841 pointer variable pointing to a Python string object. If there is an existing
842 interned string that is the same as *\*string*, it sets *\*string* to it
843 (decrementing the reference count of the old string object and incrementing the
844 reference count of the interned string object), otherwise it leaves *\*string*
845 alone and interns it (incrementing its reference count). (Clarification: even
846 though there is a lot of talk about reference counts, think of this function as
847 reference-count-neutral; you own the object after the call if and only if you
848 owned it before the call.)
849
850
851.. cfunction:: PyObject* PyString_InternFromString(const char *v)
852
853 A combination of :cfunc:`PyString_FromString` and
854 :cfunc:`PyString_InternInPlace`, returning either a new string object that has
855 been interned, or a new ("owned") reference to an earlier interned string object
856 with the same value.
857
858
859.. cfunction:: PyObject* PyString_Decode(const char *s, Py_ssize_t size, const char *encoding, const char *errors)
860
861 Create an object by decoding *size* bytes of the encoded buffer *s* using the
862 codec registered for *encoding*. *encoding* and *errors* have the same meaning
863 as the parameters of the same name in the :func:`unicode` built-in function.
864 The codec to be used is looked up using the Python codec registry. Return
865 *NULL* if an exception was raised by the codec.
866
867
868.. cfunction:: PyObject* PyString_AsDecodedObject(PyObject *str, const char *encoding, const char *errors)
869
870 Decode a string object by passing it to the codec registered for *encoding* and
871 return the result as Python object. *encoding* and *errors* have the same
872 meaning as the parameters of the same name in the string :meth:`encode` method.
873 The codec to be used is looked up using the Python codec registry. Return *NULL*
874 if an exception was raised by the codec.
875
876
877.. cfunction:: PyObject* PyString_Encode(const char *s, Py_ssize_t size, const char *encoding, const char *errors)
878
879 Encode the :ctype:`char` buffer of the given size by passing it to the codec
880 registered for *encoding* and return a Python object. *encoding* and *errors*
881 have the same meaning as the parameters of the same name in the string
882 :meth:`encode` method. The codec to be used is looked up using the Python codec
883 registry. Return *NULL* if an exception was raised by the codec.
884
885
886.. cfunction:: PyObject* PyString_AsEncodedObject(PyObject *str, const char *encoding, const char *errors)
887
888 Encode a string object using the codec registered for *encoding* and return the
889 result as Python object. *encoding* and *errors* have the same meaning as the
890 parameters of the same name in the string :meth:`encode` method. The codec to be
891 used is looked up using the Python codec registry. Return *NULL* if an exception
892 was raised by the codec.
893
894
895.. _unicodeobjects:
896
897Unicode Objects
898---------------
899
900.. sectionauthor:: Marc-Andre Lemburg <mal@lemburg.com>
901
902
903These are the basic Unicode object types used for the Unicode implementation in
904Python:
905
906.. % --- Unicode Type -------------------------------------------------------
907
908
909.. ctype:: Py_UNICODE
910
911 This type represents the storage type which is used by Python internally as
912 basis for holding Unicode ordinals. Python's default builds use a 16-bit type
913 for :ctype:`Py_UNICODE` and store Unicode values internally as UCS2. It is also
914 possible to build a UCS4 version of Python (most recent Linux distributions come
915 with UCS4 builds of Python). These builds then use a 32-bit type for
916 :ctype:`Py_UNICODE` and store Unicode data internally as UCS4. On platforms
917 where :ctype:`wchar_t` is available and compatible with the chosen Python
918 Unicode build variant, :ctype:`Py_UNICODE` is a typedef alias for
919 :ctype:`wchar_t` to enhance native platform compatibility. On all other
920 platforms, :ctype:`Py_UNICODE` is a typedef alias for either :ctype:`unsigned
921 short` (UCS2) or :ctype:`unsigned long` (UCS4).
922
923Note that UCS2 and UCS4 Python builds are not binary compatible. Please keep
924this in mind when writing extensions or interfaces.
925
926
927.. ctype:: PyUnicodeObject
928
929 This subtype of :ctype:`PyObject` represents a Python Unicode object.
930
931
932.. cvar:: PyTypeObject PyUnicode_Type
933
934 This instance of :ctype:`PyTypeObject` represents the Python Unicode type. It
Collin Winterd1d9a892007-08-28 06:09:47 +0000935 is exposed to Python code as ``str``.
Georg Brandl116aa622007-08-15 14:28:22 +0000936
937The following APIs are really C macros and can be used to do fast checks and to
938access internal read-only data of Unicode objects:
939
940
941.. cfunction:: int PyUnicode_Check(PyObject *o)
942
943 Return true if the object *o* is a Unicode object or an instance of a Unicode
944 subtype.
945
Georg Brandl116aa622007-08-15 14:28:22 +0000946
947.. cfunction:: int PyUnicode_CheckExact(PyObject *o)
948
949 Return true if the object *o* is a Unicode object, but not an instance of a
950 subtype.
951
Georg Brandl116aa622007-08-15 14:28:22 +0000952
953.. cfunction:: Py_ssize_t PyUnicode_GET_SIZE(PyObject *o)
954
955 Return the size of the object. *o* has to be a :ctype:`PyUnicodeObject` (not
956 checked).
957
958
959.. cfunction:: Py_ssize_t PyUnicode_GET_DATA_SIZE(PyObject *o)
960
961 Return the size of the object's internal buffer in bytes. *o* has to be a
962 :ctype:`PyUnicodeObject` (not checked).
963
964
965.. cfunction:: Py_UNICODE* PyUnicode_AS_UNICODE(PyObject *o)
966
967 Return a pointer to the internal :ctype:`Py_UNICODE` buffer of the object. *o*
968 has to be a :ctype:`PyUnicodeObject` (not checked).
969
970
971.. cfunction:: const char* PyUnicode_AS_DATA(PyObject *o)
972
973 Return a pointer to the internal buffer of the object. *o* has to be a
974 :ctype:`PyUnicodeObject` (not checked).
975
976Unicode provides many different character properties. The most often needed ones
977are available through these macros which are mapped to C functions depending on
978the Python configuration.
979
980.. % --- Unicode character properties ---------------------------------------
981
982
983.. cfunction:: int Py_UNICODE_ISSPACE(Py_UNICODE ch)
984
985 Return 1 or 0 depending on whether *ch* is a whitespace character.
986
987
988.. cfunction:: int Py_UNICODE_ISLOWER(Py_UNICODE ch)
989
990 Return 1 or 0 depending on whether *ch* is a lowercase character.
991
992
993.. cfunction:: int Py_UNICODE_ISUPPER(Py_UNICODE ch)
994
995 Return 1 or 0 depending on whether *ch* is an uppercase character.
996
997
998.. cfunction:: int Py_UNICODE_ISTITLE(Py_UNICODE ch)
999
1000 Return 1 or 0 depending on whether *ch* is a titlecase character.
1001
1002
1003.. cfunction:: int Py_UNICODE_ISLINEBREAK(Py_UNICODE ch)
1004
1005 Return 1 or 0 depending on whether *ch* is a linebreak character.
1006
1007
1008.. cfunction:: int Py_UNICODE_ISDECIMAL(Py_UNICODE ch)
1009
1010 Return 1 or 0 depending on whether *ch* is a decimal character.
1011
1012
1013.. cfunction:: int Py_UNICODE_ISDIGIT(Py_UNICODE ch)
1014
1015 Return 1 or 0 depending on whether *ch* is a digit character.
1016
1017
1018.. cfunction:: int Py_UNICODE_ISNUMERIC(Py_UNICODE ch)
1019
1020 Return 1 or 0 depending on whether *ch* is a numeric character.
1021
1022
1023.. cfunction:: int Py_UNICODE_ISALPHA(Py_UNICODE ch)
1024
1025 Return 1 or 0 depending on whether *ch* is an alphabetic character.
1026
1027
1028.. cfunction:: int Py_UNICODE_ISALNUM(Py_UNICODE ch)
1029
1030 Return 1 or 0 depending on whether *ch* is an alphanumeric character.
1031
1032These APIs can be used for fast direct character conversions:
1033
1034
1035.. cfunction:: Py_UNICODE Py_UNICODE_TOLOWER(Py_UNICODE ch)
1036
1037 Return the character *ch* converted to lower case.
1038
1039
1040.. cfunction:: Py_UNICODE Py_UNICODE_TOUPPER(Py_UNICODE ch)
1041
1042 Return the character *ch* converted to upper case.
1043
1044
1045.. cfunction:: Py_UNICODE Py_UNICODE_TOTITLE(Py_UNICODE ch)
1046
1047 Return the character *ch* converted to title case.
1048
1049
1050.. cfunction:: int Py_UNICODE_TODECIMAL(Py_UNICODE ch)
1051
1052 Return the character *ch* converted to a decimal positive integer. Return
1053 ``-1`` if this is not possible. This macro does not raise exceptions.
1054
1055
1056.. cfunction:: int Py_UNICODE_TODIGIT(Py_UNICODE ch)
1057
1058 Return the character *ch* converted to a single digit integer. Return ``-1`` if
1059 this is not possible. This macro does not raise exceptions.
1060
1061
1062.. cfunction:: double Py_UNICODE_TONUMERIC(Py_UNICODE ch)
1063
1064 Return the character *ch* converted to a double. Return ``-1.0`` if this is not
1065 possible. This macro does not raise exceptions.
1066
1067To create Unicode objects and access their basic sequence properties, use these
1068APIs:
1069
1070.. % --- Plain Py_UNICODE ---------------------------------------------------
1071
1072
1073.. cfunction:: PyObject* PyUnicode_FromUnicode(const Py_UNICODE *u, Py_ssize_t size)
1074
1075 Create a Unicode Object from the Py_UNICODE buffer *u* of the given size. *u*
1076 may be *NULL* which causes the contents to be undefined. It is the user's
1077 responsibility to fill in the needed data. The buffer is copied into the new
1078 object. If the buffer is not *NULL*, the return value might be a shared object.
1079 Therefore, modification of the resulting Unicode object is only allowed when *u*
1080 is *NULL*.
1081
1082
1083.. cfunction:: PyObject* PyUnicode_FromStringAndSize(const char *u, Py_ssize_t size)
1084
1085 Create a Unicode Object from the char buffer *u*. The bytes will be interpreted
1086 as being UTF-8 encoded. *u* may also be *NULL* which
1087 causes the contents to be undefined. It is the user's responsibility to fill in
1088 the needed data. The buffer is copied into the new object. If the buffer is not
1089 *NULL*, the return value might be a shared object. Therefore, modification of
1090 the resulting Unicode object is only allowed when *u* is *NULL*.
1091
Georg Brandl116aa622007-08-15 14:28:22 +00001092
1093.. cfunction:: PyObject *PyUnicode_FromString(const char *u)
1094
1095 Create a Unicode object from an UTF-8 encoded null-terminated char buffer
1096 *u*.
1097
Georg Brandl116aa622007-08-15 14:28:22 +00001098
1099.. cfunction:: PyObject* PyUnicode_FromFormat(const char *format, ...)
1100
1101 Take a C :cfunc:`printf`\ -style *format* string and a variable number of
1102 arguments, calculate the size of the resulting Python unicode string and return
1103 a string with the values formatted into it. The variable arguments must be C
1104 types and must correspond exactly to the format characters in the *format*
1105 string. The following format characters are allowed:
1106
1107 .. % The descriptions for %zd and %zu are wrong, but the truth is complicated
1108 .. % because not all compilers support the %z width modifier -- we fake it
1109 .. % when necessary via interpolating PY_FORMAT_SIZE_T.
1110
1111 +-------------------+---------------------+--------------------------------+
1112 | Format Characters | Type | Comment |
1113 +===================+=====================+================================+
1114 | :attr:`%%` | *n/a* | The literal % character. |
1115 +-------------------+---------------------+--------------------------------+
1116 | :attr:`%c` | int | A single character, |
1117 | | | represented as an C int. |
1118 +-------------------+---------------------+--------------------------------+
1119 | :attr:`%d` | int | Exactly equivalent to |
1120 | | | ``printf("%d")``. |
1121 +-------------------+---------------------+--------------------------------+
1122 | :attr:`%u` | unsigned int | Exactly equivalent to |
1123 | | | ``printf("%u")``. |
1124 +-------------------+---------------------+--------------------------------+
1125 | :attr:`%ld` | long | Exactly equivalent to |
1126 | | | ``printf("%ld")``. |
1127 +-------------------+---------------------+--------------------------------+
1128 | :attr:`%lu` | unsigned long | Exactly equivalent to |
1129 | | | ``printf("%lu")``. |
1130 +-------------------+---------------------+--------------------------------+
1131 | :attr:`%zd` | Py_ssize_t | Exactly equivalent to |
1132 | | | ``printf("%zd")``. |
1133 +-------------------+---------------------+--------------------------------+
1134 | :attr:`%zu` | size_t | Exactly equivalent to |
1135 | | | ``printf("%zu")``. |
1136 +-------------------+---------------------+--------------------------------+
1137 | :attr:`%i` | int | Exactly equivalent to |
1138 | | | ``printf("%i")``. |
1139 +-------------------+---------------------+--------------------------------+
1140 | :attr:`%x` | int | Exactly equivalent to |
1141 | | | ``printf("%x")``. |
1142 +-------------------+---------------------+--------------------------------+
1143 | :attr:`%s` | char\* | A null-terminated C character |
1144 | | | array. |
1145 +-------------------+---------------------+--------------------------------+
1146 | :attr:`%p` | void\* | The hex representation of a C |
1147 | | | pointer. Mostly equivalent to |
1148 | | | ``printf("%p")`` except that |
1149 | | | it is guaranteed to start with |
1150 | | | the literal ``0x`` regardless |
1151 | | | of what the platform's |
1152 | | | ``printf`` yields. |
1153 +-------------------+---------------------+--------------------------------+
1154 | :attr:`%U` | PyObject\* | A unicode object. |
1155 +-------------------+---------------------+--------------------------------+
1156 | :attr:`%V` | PyObject\*, char \* | A unicode object (which may be |
1157 | | | *NULL*) and a null-terminated |
1158 | | | C character array as a second |
1159 | | | parameter (which will be used, |
1160 | | | if the first parameter is |
1161 | | | *NULL*). |
1162 +-------------------+---------------------+--------------------------------+
1163 | :attr:`%S` | PyObject\* | The result of calling |
1164 | | | :func:`PyObject_Unicode`. |
1165 +-------------------+---------------------+--------------------------------+
1166 | :attr:`%R` | PyObject\* | The result of calling |
1167 | | | :func:`PyObject_Repr`. |
1168 +-------------------+---------------------+--------------------------------+
1169
1170 An unrecognized format character causes all the rest of the format string to be
1171 copied as-is to the result string, and any extra arguments discarded.
1172
Georg Brandl116aa622007-08-15 14:28:22 +00001173
1174.. cfunction:: PyObject* PyUnicode_FromFormatV(const char *format, va_list vargs)
1175
1176 Identical to :func:`PyUnicode_FromFormat` except that it takes exactly two
1177 arguments.
1178
Georg Brandl116aa622007-08-15 14:28:22 +00001179
1180.. cfunction:: Py_UNICODE* PyUnicode_AsUnicode(PyObject *unicode)
1181
1182 Return a read-only pointer to the Unicode object's internal :ctype:`Py_UNICODE`
1183 buffer, *NULL* if *unicode* is not a Unicode object.
1184
1185
1186.. cfunction:: Py_ssize_t PyUnicode_GetSize(PyObject *unicode)
1187
1188 Return the length of the Unicode object.
1189
1190
1191.. cfunction:: PyObject* PyUnicode_FromEncodedObject(PyObject *obj, const char *encoding, const char *errors)
1192
1193 Coerce an encoded object *obj* to an Unicode object and return a reference with
1194 incremented refcount.
1195
1196 String and other char buffer compatible objects are decoded according to the
1197 given encoding and using the error handling defined by errors. Both can be
1198 *NULL* to have the interface use the default values (see the next section for
1199 details).
1200
1201 All other objects, including Unicode objects, cause a :exc:`TypeError` to be
1202 set.
1203
1204 The API returns *NULL* if there was an error. The caller is responsible for
1205 decref'ing the returned objects.
1206
1207
1208.. cfunction:: PyObject* PyUnicode_FromObject(PyObject *obj)
1209
1210 Shortcut for ``PyUnicode_FromEncodedObject(obj, NULL, "strict")`` which is used
1211 throughout the interpreter whenever coercion to Unicode is needed.
1212
1213If the platform supports :ctype:`wchar_t` and provides a header file wchar.h,
1214Python can interface directly to this type using the following functions.
1215Support is optimized if Python's own :ctype:`Py_UNICODE` type is identical to
1216the system's :ctype:`wchar_t`.
1217
1218.. % --- wchar_t support for platforms which support it ---------------------
1219
1220
1221.. cfunction:: PyObject* PyUnicode_FromWideChar(const wchar_t *w, Py_ssize_t size)
1222
1223 Create a Unicode object from the :ctype:`wchar_t` buffer *w* of the given size.
1224 Return *NULL* on failure.
1225
1226
1227.. cfunction:: Py_ssize_t PyUnicode_AsWideChar(PyUnicodeObject *unicode, wchar_t *w, Py_ssize_t size)
1228
1229 Copy the Unicode object contents into the :ctype:`wchar_t` buffer *w*. At most
1230 *size* :ctype:`wchar_t` characters are copied (excluding a possibly trailing
1231 0-termination character). Return the number of :ctype:`wchar_t` characters
1232 copied or -1 in case of an error. Note that the resulting :ctype:`wchar_t`
1233 string may or may not be 0-terminated. It is the responsibility of the caller
1234 to make sure that the :ctype:`wchar_t` string is 0-terminated in case this is
1235 required by the application.
1236
1237
1238.. _builtincodecs:
1239
1240Built-in Codecs
1241^^^^^^^^^^^^^^^
1242
1243Python provides a set of builtin codecs which are written in C for speed. All of
1244these codecs are directly usable via the following functions.
1245
1246Many of the following APIs take two arguments encoding and errors. These
1247parameters encoding and errors have the same semantics as the ones of the
1248builtin unicode() Unicode object constructor.
1249
1250Setting encoding to *NULL* causes the default encoding to be used which is
1251ASCII. The file system calls should use :cdata:`Py_FileSystemDefaultEncoding`
1252as the encoding for file names. This variable should be treated as read-only: On
1253some systems, it will be a pointer to a static string, on others, it will change
1254at run-time (such as when the application invokes setlocale).
1255
1256Error handling is set by errors which may also be set to *NULL* meaning to use
1257the default handling defined for the codec. Default error handling for all
1258builtin codecs is "strict" (:exc:`ValueError` is raised).
1259
1260The codecs all use a similar interface. Only deviation from the following
1261generic ones are documented for simplicity.
1262
1263These are the generic codec APIs:
1264
1265.. % --- Generic Codecs -----------------------------------------------------
1266
1267
1268.. cfunction:: PyObject* PyUnicode_Decode(const char *s, Py_ssize_t size, const char *encoding, const char *errors)
1269
1270 Create a Unicode object by decoding *size* bytes of the encoded string *s*.
1271 *encoding* and *errors* have the same meaning as the parameters of the same name
1272 in the :func:`unicode` builtin function. The codec to be used is looked up
1273 using the Python codec registry. Return *NULL* if an exception was raised by
1274 the codec.
1275
1276
1277.. cfunction:: PyObject* PyUnicode_Encode(const Py_UNICODE *s, Py_ssize_t size, const char *encoding, const char *errors)
1278
1279 Encode the :ctype:`Py_UNICODE` buffer of the given size and return a Python
1280 string object. *encoding* and *errors* have the same meaning as the parameters
1281 of the same name in the Unicode :meth:`encode` method. The codec to be used is
1282 looked up using the Python codec registry. Return *NULL* if an exception was
1283 raised by the codec.
1284
1285
1286.. cfunction:: PyObject* PyUnicode_AsEncodedString(PyObject *unicode, const char *encoding, const char *errors)
1287
1288 Encode a Unicode object and return the result as Python string object.
1289 *encoding* and *errors* have the same meaning as the parameters of the same name
1290 in the Unicode :meth:`encode` method. The codec to be used is looked up using
1291 the Python codec registry. Return *NULL* if an exception was raised by the
1292 codec.
1293
1294These are the UTF-8 codec APIs:
1295
1296.. % --- UTF-8 Codecs -------------------------------------------------------
1297
1298
1299.. cfunction:: PyObject* PyUnicode_DecodeUTF8(const char *s, Py_ssize_t size, const char *errors)
1300
1301 Create a Unicode object by decoding *size* bytes of the UTF-8 encoded string
1302 *s*. Return *NULL* if an exception was raised by the codec.
1303
1304
1305.. cfunction:: PyObject* PyUnicode_DecodeUTF8Stateful(const char *s, Py_ssize_t size, const char *errors, Py_ssize_t *consumed)
1306
1307 If *consumed* is *NULL*, behave like :cfunc:`PyUnicode_DecodeUTF8`. If
1308 *consumed* is not *NULL*, trailing incomplete UTF-8 byte sequences will not be
1309 treated as an error. Those bytes will not be decoded and the number of bytes
1310 that have been decoded will be stored in *consumed*.
1311
Georg Brandl116aa622007-08-15 14:28:22 +00001312
1313.. cfunction:: PyObject* PyUnicode_EncodeUTF8(const Py_UNICODE *s, Py_ssize_t size, const char *errors)
1314
1315 Encode the :ctype:`Py_UNICODE` buffer of the given size using UTF-8 and return a
1316 Python string object. Return *NULL* if an exception was raised by the codec.
1317
1318
1319.. cfunction:: PyObject* PyUnicode_AsUTF8String(PyObject *unicode)
1320
1321 Encode a Unicode objects using UTF-8 and return the result as Python string
1322 object. Error handling is "strict". Return *NULL* if an exception was raised
1323 by the codec.
1324
Walter Dörwald41980ca2007-08-16 21:55:45 +00001325These are the UTF-32 codec APIs:
1326
1327.. % --- UTF-32 Codecs ------------------------------------------------------ */
1328
1329
1330.. cfunction:: PyObject* PyUnicode_DecodeUTF32(const char *s, Py_ssize_t size, const char *errors, int *byteorder)
1331
1332 Decode *length* bytes from a UTF-32 encoded buffer string and return the
1333 corresponding Unicode object. *errors* (if non-*NULL*) defines the error
1334 handling. It defaults to "strict".
1335
1336 If *byteorder* is non-*NULL*, the decoder starts decoding using the given byte
1337 order::
1338
1339 *byteorder == -1: little endian
1340 *byteorder == 0: native order
1341 *byteorder == 1: big endian
1342
1343 and then switches if the first four bytes of the input data are a byte order mark
1344 (BOM) and the specified byte order is native order. This BOM is not copied into
1345 the resulting Unicode string. After completion, *\*byteorder* is set to the
1346 current byte order at the end of input data.
1347
1348 In a narrow build codepoints outside the BMP will be decoded as surrogate pairs.
1349
1350 If *byteorder* is *NULL*, the codec starts in native order mode.
1351
1352 Return *NULL* if an exception was raised by the codec.
1353
Walter Dörwald41980ca2007-08-16 21:55:45 +00001354
1355.. cfunction:: PyObject* PyUnicode_DecodeUTF32Stateful(const char *s, Py_ssize_t size, const char *errors, int *byteorder, Py_ssize_t *consumed)
1356
1357 If *consumed* is *NULL*, behave like :cfunc:`PyUnicode_DecodeUTF32`. If
1358 *consumed* is not *NULL*, :cfunc:`PyUnicode_DecodeUTF32Stateful` will not treat
1359 trailing incomplete UTF-32 byte sequences (such as a number of bytes not divisible
1360 by four) as an error. Those bytes will not be decoded and the number of bytes
1361 that have been decoded will be stored in *consumed*.
1362
Walter Dörwald41980ca2007-08-16 21:55:45 +00001363
1364.. cfunction:: PyObject* PyUnicode_EncodeUTF32(const Py_UNICODE *s, Py_ssize_t size, const char *errors, int byteorder)
1365
1366 Return a Python bytes object holding the UTF-32 encoded value of the Unicode
1367 data in *s*. If *byteorder* is not ``0``, output is written according to the
1368 following byte order::
1369
1370 byteorder == -1: little endian
1371 byteorder == 0: native byte order (writes a BOM mark)
1372 byteorder == 1: big endian
1373
1374 If byteorder is ``0``, the output string will always start with the Unicode BOM
1375 mark (U+FEFF). In the other two modes, no BOM mark is prepended.
1376
1377 If *Py_UNICODE_WIDE* is not defined, surrogate pairs will be output
1378 as a single codepoint.
1379
1380 Return *NULL* if an exception was raised by the codec.
1381
1382
1383.. cfunction:: PyObject* PyUnicode_AsUTF32String(PyObject *unicode)
1384
1385 Return a Python string using the UTF-32 encoding in native byte order. The
1386 string always starts with a BOM mark. Error handling is "strict". Return
1387 *NULL* if an exception was raised by the codec.
1388
Walter Dörwald19e62382007-08-17 16:23:21 +00001389
Georg Brandl116aa622007-08-15 14:28:22 +00001390These are the UTF-16 codec APIs:
1391
1392.. % --- UTF-16 Codecs ------------------------------------------------------ */
1393
1394
1395.. cfunction:: PyObject* PyUnicode_DecodeUTF16(const char *s, Py_ssize_t size, const char *errors, int *byteorder)
1396
1397 Decode *length* bytes from a UTF-16 encoded buffer string and return the
1398 corresponding Unicode object. *errors* (if non-*NULL*) defines the error
1399 handling. It defaults to "strict".
1400
1401 If *byteorder* is non-*NULL*, the decoder starts decoding using the given byte
1402 order::
1403
1404 *byteorder == -1: little endian
1405 *byteorder == 0: native order
1406 *byteorder == 1: big endian
1407
1408 and then switches if the first two bytes of the input data are a byte order mark
1409 (BOM) and the specified byte order is native order. This BOM is not copied into
1410 the resulting Unicode string. After completion, *\*byteorder* is set to the
Walter Dörwaldd9a15792007-08-16 16:55:51 +00001411 current byte order at the end of input data.
Georg Brandl116aa622007-08-15 14:28:22 +00001412
1413 If *byteorder* is *NULL*, the codec starts in native order mode.
1414
1415 Return *NULL* if an exception was raised by the codec.
1416
1417
1418.. cfunction:: PyObject* PyUnicode_DecodeUTF16Stateful(const char *s, Py_ssize_t size, const char *errors, int *byteorder, Py_ssize_t *consumed)
1419
1420 If *consumed* is *NULL*, behave like :cfunc:`PyUnicode_DecodeUTF16`. If
1421 *consumed* is not *NULL*, :cfunc:`PyUnicode_DecodeUTF16Stateful` will not treat
1422 trailing incomplete UTF-16 byte sequences (such as an odd number of bytes or a
1423 split surrogate pair) as an error. Those bytes will not be decoded and the
1424 number of bytes that have been decoded will be stored in *consumed*.
1425
Georg Brandl116aa622007-08-15 14:28:22 +00001426
1427.. cfunction:: PyObject* PyUnicode_EncodeUTF16(const Py_UNICODE *s, Py_ssize_t size, const char *errors, int byteorder)
1428
1429 Return a Python string object holding the UTF-16 encoded value of the Unicode
1430 data in *s*. If *byteorder* is not ``0``, output is written according to the
1431 following byte order::
1432
1433 byteorder == -1: little endian
1434 byteorder == 0: native byte order (writes a BOM mark)
1435 byteorder == 1: big endian
1436
1437 If byteorder is ``0``, the output string will always start with the Unicode BOM
1438 mark (U+FEFF). In the other two modes, no BOM mark is prepended.
1439
1440 If *Py_UNICODE_WIDE* is defined, a single :ctype:`Py_UNICODE` value may get
1441 represented as a surrogate pair. If it is not defined, each :ctype:`Py_UNICODE`
1442 values is interpreted as an UCS-2 character.
1443
1444 Return *NULL* if an exception was raised by the codec.
1445
1446
1447.. cfunction:: PyObject* PyUnicode_AsUTF16String(PyObject *unicode)
1448
1449 Return a Python string using the UTF-16 encoding in native byte order. The
1450 string always starts with a BOM mark. Error handling is "strict". Return
1451 *NULL* if an exception was raised by the codec.
1452
1453These are the "Unicode Escape" codec APIs:
1454
1455.. % --- Unicode-Escape Codecs ----------------------------------------------
1456
1457
1458.. cfunction:: PyObject* PyUnicode_DecodeUnicodeEscape(const char *s, Py_ssize_t size, const char *errors)
1459
1460 Create a Unicode object by decoding *size* bytes of the Unicode-Escape encoded
1461 string *s*. Return *NULL* if an exception was raised by the codec.
1462
1463
1464.. cfunction:: PyObject* PyUnicode_EncodeUnicodeEscape(const Py_UNICODE *s, Py_ssize_t size)
1465
1466 Encode the :ctype:`Py_UNICODE` buffer of the given size using Unicode-Escape and
1467 return a Python string object. Return *NULL* if an exception was raised by the
1468 codec.
1469
1470
1471.. cfunction:: PyObject* PyUnicode_AsUnicodeEscapeString(PyObject *unicode)
1472
1473 Encode a Unicode objects using Unicode-Escape and return the result as Python
1474 string object. Error handling is "strict". Return *NULL* if an exception was
1475 raised by the codec.
1476
1477These are the "Raw Unicode Escape" codec APIs:
1478
1479.. % --- Raw-Unicode-Escape Codecs ------------------------------------------
1480
1481
1482.. cfunction:: PyObject* PyUnicode_DecodeRawUnicodeEscape(const char *s, Py_ssize_t size, const char *errors)
1483
1484 Create a Unicode object by decoding *size* bytes of the Raw-Unicode-Escape
1485 encoded string *s*. Return *NULL* if an exception was raised by the codec.
1486
1487
1488.. cfunction:: PyObject* PyUnicode_EncodeRawUnicodeEscape(const Py_UNICODE *s, Py_ssize_t size, const char *errors)
1489
1490 Encode the :ctype:`Py_UNICODE` buffer of the given size using Raw-Unicode-Escape
1491 and return a Python string object. Return *NULL* if an exception was raised by
1492 the codec.
1493
1494
1495.. cfunction:: PyObject* PyUnicode_AsRawUnicodeEscapeString(PyObject *unicode)
1496
1497 Encode a Unicode objects using Raw-Unicode-Escape and return the result as
1498 Python string object. Error handling is "strict". Return *NULL* if an exception
1499 was raised by the codec.
1500
1501These are the Latin-1 codec APIs: Latin-1 corresponds to the first 256 Unicode
1502ordinals and only these are accepted by the codecs during encoding.
1503
1504.. % --- Latin-1 Codecs -----------------------------------------------------
1505
1506
1507.. cfunction:: PyObject* PyUnicode_DecodeLatin1(const char *s, Py_ssize_t size, const char *errors)
1508
1509 Create a Unicode object by decoding *size* bytes of the Latin-1 encoded string
1510 *s*. Return *NULL* if an exception was raised by the codec.
1511
1512
1513.. cfunction:: PyObject* PyUnicode_EncodeLatin1(const Py_UNICODE *s, Py_ssize_t size, const char *errors)
1514
1515 Encode the :ctype:`Py_UNICODE` buffer of the given size using Latin-1 and return
1516 a Python string object. Return *NULL* if an exception was raised by the codec.
1517
1518
1519.. cfunction:: PyObject* PyUnicode_AsLatin1String(PyObject *unicode)
1520
1521 Encode a Unicode objects using Latin-1 and return the result as Python string
1522 object. Error handling is "strict". Return *NULL* if an exception was raised
1523 by the codec.
1524
1525These are the ASCII codec APIs. Only 7-bit ASCII data is accepted. All other
1526codes generate errors.
1527
1528.. % --- ASCII Codecs -------------------------------------------------------
1529
1530
1531.. cfunction:: PyObject* PyUnicode_DecodeASCII(const char *s, Py_ssize_t size, const char *errors)
1532
1533 Create a Unicode object by decoding *size* bytes of the ASCII encoded string
1534 *s*. Return *NULL* if an exception was raised by the codec.
1535
1536
1537.. cfunction:: PyObject* PyUnicode_EncodeASCII(const Py_UNICODE *s, Py_ssize_t size, const char *errors)
1538
1539 Encode the :ctype:`Py_UNICODE` buffer of the given size using ASCII and return a
1540 Python string object. Return *NULL* if an exception was raised by the codec.
1541
1542
1543.. cfunction:: PyObject* PyUnicode_AsASCIIString(PyObject *unicode)
1544
1545 Encode a Unicode objects using ASCII and return the result as Python string
1546 object. Error handling is "strict". Return *NULL* if an exception was raised
1547 by the codec.
1548
1549These are the mapping codec APIs:
1550
1551.. % --- Character Map Codecs -----------------------------------------------
1552
1553This codec is special in that it can be used to implement many different codecs
1554(and this is in fact what was done to obtain most of the standard codecs
1555included in the :mod:`encodings` package). The codec uses mapping to encode and
1556decode characters.
1557
1558Decoding mappings must map single string characters to single Unicode
1559characters, integers (which are then interpreted as Unicode ordinals) or None
1560(meaning "undefined mapping" and causing an error).
1561
1562Encoding mappings must map single Unicode characters to single string
1563characters, integers (which are then interpreted as Latin-1 ordinals) or None
1564(meaning "undefined mapping" and causing an error).
1565
1566The mapping objects provided must only support the __getitem__ mapping
1567interface.
1568
1569If a character lookup fails with a LookupError, the character is copied as-is
1570meaning that its ordinal value will be interpreted as Unicode or Latin-1 ordinal
1571resp. Because of this, mappings only need to contain those mappings which map
1572characters to different code points.
1573
1574
1575.. cfunction:: PyObject* PyUnicode_DecodeCharmap(const char *s, Py_ssize_t size, PyObject *mapping, const char *errors)
1576
1577 Create a Unicode object by decoding *size* bytes of the encoded string *s* using
1578 the given *mapping* object. Return *NULL* if an exception was raised by the
1579 codec. If *mapping* is *NULL* latin-1 decoding will be done. Else it can be a
1580 dictionary mapping byte or a unicode string, which is treated as a lookup table.
1581 Byte values greater that the length of the string and U+FFFE "characters" are
1582 treated as "undefined mapping".
1583
Georg Brandl116aa622007-08-15 14:28:22 +00001584
1585.. cfunction:: PyObject* PyUnicode_EncodeCharmap(const Py_UNICODE *s, Py_ssize_t size, PyObject *mapping, const char *errors)
1586
1587 Encode the :ctype:`Py_UNICODE` buffer of the given size using the given
1588 *mapping* object and return a Python string object. Return *NULL* if an
1589 exception was raised by the codec.
1590
1591
1592.. cfunction:: PyObject* PyUnicode_AsCharmapString(PyObject *unicode, PyObject *mapping)
1593
1594 Encode a Unicode objects using the given *mapping* object and return the result
1595 as Python string object. Error handling is "strict". Return *NULL* if an
1596 exception was raised by the codec.
1597
1598The following codec API is special in that maps Unicode to Unicode.
1599
1600
1601.. cfunction:: PyObject* PyUnicode_TranslateCharmap(const Py_UNICODE *s, Py_ssize_t size, PyObject *table, const char *errors)
1602
1603 Translate a :ctype:`Py_UNICODE` buffer of the given length by applying a
1604 character mapping *table* to it and return the resulting Unicode object. Return
1605 *NULL* when an exception was raised by the codec.
1606
1607 The *mapping* table must map Unicode ordinal integers to Unicode ordinal
1608 integers or None (causing deletion of the character).
1609
1610 Mapping tables need only provide the :meth:`__getitem__` interface; dictionaries
1611 and sequences work well. Unmapped character ordinals (ones which cause a
1612 :exc:`LookupError`) are left untouched and are copied as-is.
1613
1614These are the MBCS codec APIs. They are currently only available on Windows and
1615use the Win32 MBCS converters to implement the conversions. Note that MBCS (or
1616DBCS) is a class of encodings, not just one. The target encoding is defined by
1617the user settings on the machine running the codec.
1618
1619.. % --- MBCS codecs for Windows --------------------------------------------
1620
1621
1622.. cfunction:: PyObject* PyUnicode_DecodeMBCS(const char *s, Py_ssize_t size, const char *errors)
1623
1624 Create a Unicode object by decoding *size* bytes of the MBCS encoded string *s*.
1625 Return *NULL* if an exception was raised by the codec.
1626
1627
1628.. cfunction:: PyObject* PyUnicode_DecodeMBCSStateful(const char *s, int size, const char *errors, int *consumed)
1629
1630 If *consumed* is *NULL*, behave like :cfunc:`PyUnicode_DecodeMBCS`. If
1631 *consumed* is not *NULL*, :cfunc:`PyUnicode_DecodeMBCSStateful` will not decode
1632 trailing lead byte and the number of bytes that have been decoded will be stored
1633 in *consumed*.
1634
Georg Brandl116aa622007-08-15 14:28:22 +00001635
1636.. cfunction:: PyObject* PyUnicode_EncodeMBCS(const Py_UNICODE *s, Py_ssize_t size, const char *errors)
1637
1638 Encode the :ctype:`Py_UNICODE` buffer of the given size using MBCS and return a
1639 Python string object. Return *NULL* if an exception was raised by the codec.
1640
1641
1642.. cfunction:: PyObject* PyUnicode_AsMBCSString(PyObject *unicode)
1643
1644 Encode a Unicode objects using MBCS and return the result as Python string
1645 object. Error handling is "strict". Return *NULL* if an exception was raised
1646 by the codec.
1647
1648.. % --- Methods & Slots ----------------------------------------------------
1649
1650
1651.. _unicodemethodsandslots:
1652
1653Methods and Slot Functions
1654^^^^^^^^^^^^^^^^^^^^^^^^^^
1655
1656The following APIs are capable of handling Unicode objects and strings on input
1657(we refer to them as strings in the descriptions) and return Unicode objects or
1658integers as appropriate.
1659
1660They all return *NULL* or ``-1`` if an exception occurs.
1661
1662
1663.. cfunction:: PyObject* PyUnicode_Concat(PyObject *left, PyObject *right)
1664
1665 Concat two strings giving a new Unicode string.
1666
1667
1668.. cfunction:: PyObject* PyUnicode_Split(PyObject *s, PyObject *sep, Py_ssize_t maxsplit)
1669
1670 Split a string giving a list of Unicode strings. If sep is *NULL*, splitting
1671 will be done at all whitespace substrings. Otherwise, splits occur at the given
1672 separator. At most *maxsplit* splits will be done. If negative, no limit is
1673 set. Separators are not included in the resulting list.
1674
1675
1676.. cfunction:: PyObject* PyUnicode_Splitlines(PyObject *s, int keepend)
1677
1678 Split a Unicode string at line breaks, returning a list of Unicode strings.
1679 CRLF is considered to be one line break. If *keepend* is 0, the Line break
1680 characters are not included in the resulting strings.
1681
1682
1683.. cfunction:: PyObject* PyUnicode_Translate(PyObject *str, PyObject *table, const char *errors)
1684
1685 Translate a string by applying a character mapping table to it and return the
1686 resulting Unicode object.
1687
1688 The mapping table must map Unicode ordinal integers to Unicode ordinal integers
1689 or None (causing deletion of the character).
1690
1691 Mapping tables need only provide the :meth:`__getitem__` interface; dictionaries
1692 and sequences work well. Unmapped character ordinals (ones which cause a
1693 :exc:`LookupError`) are left untouched and are copied as-is.
1694
1695 *errors* has the usual meaning for codecs. It may be *NULL* which indicates to
1696 use the default error handling.
1697
1698
1699.. cfunction:: PyObject* PyUnicode_Join(PyObject *separator, PyObject *seq)
1700
1701 Join a sequence of strings using the given separator and return the resulting
1702 Unicode string.
1703
1704
1705.. cfunction:: int PyUnicode_Tailmatch(PyObject *str, PyObject *substr, Py_ssize_t start, Py_ssize_t end, int direction)
1706
1707 Return 1 if *substr* matches *str*[*start*:*end*] at the given tail end
1708 (*direction* == -1 means to do a prefix match, *direction* == 1 a suffix match),
1709 0 otherwise. Return ``-1`` if an error occurred.
1710
1711
1712.. cfunction:: Py_ssize_t PyUnicode_Find(PyObject *str, PyObject *substr, Py_ssize_t start, Py_ssize_t end, int direction)
1713
1714 Return the first position of *substr* in *str*[*start*:*end*] using the given
1715 *direction* (*direction* == 1 means to do a forward search, *direction* == -1 a
1716 backward search). The return value is the index of the first match; a value of
1717 ``-1`` indicates that no match was found, and ``-2`` indicates that an error
1718 occurred and an exception has been set.
1719
1720
1721.. cfunction:: Py_ssize_t PyUnicode_Count(PyObject *str, PyObject *substr, Py_ssize_t start, Py_ssize_t end)
1722
1723 Return the number of non-overlapping occurrences of *substr* in
1724 ``str[start:end]``. Return ``-1`` if an error occurred.
1725
1726
1727.. cfunction:: PyObject* PyUnicode_Replace(PyObject *str, PyObject *substr, PyObject *replstr, Py_ssize_t maxcount)
1728
1729 Replace at most *maxcount* occurrences of *substr* in *str* with *replstr* and
1730 return the resulting Unicode object. *maxcount* == -1 means replace all
1731 occurrences.
1732
1733
1734.. cfunction:: int PyUnicode_Compare(PyObject *left, PyObject *right)
1735
1736 Compare two strings and return -1, 0, 1 for less than, equal, and greater than,
1737 respectively.
1738
1739
1740.. cfunction:: int PyUnicode_RichCompare(PyObject *left, PyObject *right, int op)
1741
1742 Rich compare two unicode strings and return one of the following:
1743
1744 * ``NULL`` in case an exception was raised
1745 * :const:`Py_True` or :const:`Py_False` for successful comparisons
1746 * :const:`Py_NotImplemented` in case the type combination is unknown
1747
1748 Note that :const:`Py_EQ` and :const:`Py_NE` comparisons can cause a
1749 :exc:`UnicodeWarning` in case the conversion of the arguments to Unicode fails
1750 with a :exc:`UnicodeDecodeError`.
1751
1752 Possible values for *op* are :const:`Py_GT`, :const:`Py_GE`, :const:`Py_EQ`,
1753 :const:`Py_NE`, :const:`Py_LT`, and :const:`Py_LE`.
1754
1755
1756.. cfunction:: PyObject* PyUnicode_Format(PyObject *format, PyObject *args)
1757
1758 Return a new string object from *format* and *args*; this is analogous to
1759 ``format % args``. The *args* argument must be a tuple.
1760
1761
1762.. cfunction:: int PyUnicode_Contains(PyObject *container, PyObject *element)
1763
1764 Check whether *element* is contained in *container* and return true or false
1765 accordingly.
1766
1767 *element* has to coerce to a one element Unicode string. ``-1`` is returned if
1768 there was an error.
1769
1770
1771.. cfunction:: void PyUnicode_InternInPlace(PyObject **string)
1772
1773 Intern the argument *\*string* in place. The argument must be the address of a
1774 pointer variable pointing to a Python unicode string object. If there is an
1775 existing interned string that is the same as *\*string*, it sets *\*string* to
1776 it (decrementing the reference count of the old string object and incrementing
1777 the reference count of the interned string object), otherwise it leaves
1778 *\*string* alone and interns it (incrementing its reference count).
1779 (Clarification: even though there is a lot of talk about reference counts, think
1780 of this function as reference-count-neutral; you own the object after the call
1781 if and only if you owned it before the call.)
1782
1783
1784.. cfunction:: PyObject* PyUnicode_InternFromString(const char *v)
1785
1786 A combination of :cfunc:`PyUnicode_FromString` and
1787 :cfunc:`PyUnicode_InternInPlace`, returning either a new unicode string object
1788 that has been interned, or a new ("owned") reference to an earlier interned
1789 string object with the same value.
1790
1791
1792.. _bufferobjects:
1793
1794Buffer Objects
1795--------------
1796
1797.. sectionauthor:: Greg Stein <gstein@lyra.org>
1798
1799
1800.. index::
1801 object: buffer
1802 single: buffer interface
1803
1804Python objects implemented in C can export a group of functions called the
1805"buffer interface." These functions can be used by an object to expose its data
1806in a raw, byte-oriented format. Clients of the object can use the buffer
1807interface to access the object data directly, without needing to copy it first.
1808
1809Two examples of objects that support the buffer interface are strings and
1810arrays. The string object exposes the character contents in the buffer
1811interface's byte-oriented form. An array can also expose its contents, but it
1812should be noted that array elements may be multi-byte values.
1813
1814An example user of the buffer interface is the file object's :meth:`write`
1815method. Any object that can export a series of bytes through the buffer
1816interface can be written to a file. There are a number of format codes to
1817:cfunc:`PyArg_ParseTuple` that operate against an object's buffer interface,
1818returning data from the target object.
1819
1820.. index:: single: PyBufferProcs
1821
1822More information on the buffer interface is provided in the section
1823:ref:`buffer-structs`, under the description for :ctype:`PyBufferProcs`.
1824
1825A "buffer object" is defined in the :file:`bufferobject.h` header (included by
1826:file:`Python.h`). These objects look very similar to string objects at the
1827Python programming level: they support slicing, indexing, concatenation, and
1828some other standard string operations. However, their data can come from one of
1829two sources: from a block of memory, or from another object which exports the
1830buffer interface.
1831
1832Buffer objects are useful as a way to expose the data from another object's
1833buffer interface to the Python programmer. They can also be used as a zero-copy
1834slicing mechanism. Using their ability to reference a block of memory, it is
1835possible to expose any data to the Python programmer quite easily. The memory
1836could be a large, constant array in a C extension, it could be a raw block of
1837memory for manipulation before passing to an operating system library, or it
1838could be used to pass around structured data in its native, in-memory format.
1839
1840
1841.. ctype:: PyBufferObject
1842
1843 This subtype of :ctype:`PyObject` represents a buffer object.
1844
1845
1846.. cvar:: PyTypeObject PyBuffer_Type
1847
1848 .. index:: single: BufferType (in module types)
1849
1850 The instance of :ctype:`PyTypeObject` which represents the Python buffer type;
1851 it is the same object as ``buffer`` and ``types.BufferType`` in the Python
1852 layer. .
1853
1854
1855.. cvar:: int Py_END_OF_BUFFER
1856
1857 This constant may be passed as the *size* parameter to
1858 :cfunc:`PyBuffer_FromObject` or :cfunc:`PyBuffer_FromReadWriteObject`. It
1859 indicates that the new :ctype:`PyBufferObject` should refer to *base* object
1860 from the specified *offset* to the end of its exported buffer. Using this
1861 enables the caller to avoid querying the *base* object for its length.
1862
1863
1864.. cfunction:: int PyBuffer_Check(PyObject *p)
1865
1866 Return true if the argument has type :cdata:`PyBuffer_Type`.
1867
1868
1869.. cfunction:: PyObject* PyBuffer_FromObject(PyObject *base, Py_ssize_t offset, Py_ssize_t size)
1870
1871 Return a new read-only buffer object. This raises :exc:`TypeError` if *base*
1872 doesn't support the read-only buffer protocol or doesn't provide exactly one
1873 buffer segment, or it raises :exc:`ValueError` if *offset* is less than zero.
1874 The buffer will hold a reference to the *base* object, and the buffer's contents
1875 will refer to the *base* object's buffer interface, starting as position
1876 *offset* and extending for *size* bytes. If *size* is :const:`Py_END_OF_BUFFER`,
1877 then the new buffer's contents extend to the length of the *base* object's
1878 exported buffer data.
1879
1880
1881.. cfunction:: PyObject* PyBuffer_FromReadWriteObject(PyObject *base, Py_ssize_t offset, Py_ssize_t size)
1882
1883 Return a new writable buffer object. Parameters and exceptions are similar to
1884 those for :cfunc:`PyBuffer_FromObject`. If the *base* object does not export
Sean Reifscheider54cf12b2007-09-17 17:55:36 +00001885 the writable buffer protocol, then :exc:`TypeError` is raised.
Georg Brandl116aa622007-08-15 14:28:22 +00001886
1887
1888.. cfunction:: PyObject* PyBuffer_FromMemory(void *ptr, Py_ssize_t size)
1889
1890 Return a new read-only buffer object that reads from a specified location in
1891 memory, with a specified size. The caller is responsible for ensuring that the
1892 memory buffer, passed in as *ptr*, is not deallocated while the returned buffer
1893 object exists. Raises :exc:`ValueError` if *size* is less than zero. Note that
1894 :const:`Py_END_OF_BUFFER` may *not* be passed for the *size* parameter;
1895 :exc:`ValueError` will be raised in that case.
1896
1897
1898.. cfunction:: PyObject* PyBuffer_FromReadWriteMemory(void *ptr, Py_ssize_t size)
1899
1900 Similar to :cfunc:`PyBuffer_FromMemory`, but the returned buffer is writable.
1901
1902
1903.. cfunction:: PyObject* PyBuffer_New(Py_ssize_t size)
1904
1905 Return a new writable buffer object that maintains its own memory buffer of
1906 *size* bytes. :exc:`ValueError` is returned if *size* is not zero or positive.
1907 Note that the memory buffer (as returned by :cfunc:`PyObject_AsWriteBuffer`) is
1908 not specifically aligned.
1909
1910
1911.. _tupleobjects:
1912
1913Tuple Objects
1914-------------
1915
1916.. index:: object: tuple
1917
1918
1919.. ctype:: PyTupleObject
1920
1921 This subtype of :ctype:`PyObject` represents a Python tuple object.
1922
1923
1924.. cvar:: PyTypeObject PyTuple_Type
1925
1926 .. index:: single: TupleType (in module types)
1927
1928 This instance of :ctype:`PyTypeObject` represents the Python tuple type; it is
1929 the same object as ``tuple`` and ``types.TupleType`` in the Python layer..
1930
1931
1932.. cfunction:: int PyTuple_Check(PyObject *p)
1933
1934 Return true if *p* is a tuple object or an instance of a subtype of the tuple
1935 type.
1936
Georg Brandl116aa622007-08-15 14:28:22 +00001937
1938.. cfunction:: int PyTuple_CheckExact(PyObject *p)
1939
1940 Return true if *p* is a tuple object, but not an instance of a subtype of the
1941 tuple type.
1942
Georg Brandl116aa622007-08-15 14:28:22 +00001943
1944.. cfunction:: PyObject* PyTuple_New(Py_ssize_t len)
1945
1946 Return a new tuple object of size *len*, or *NULL* on failure.
1947
1948
1949.. cfunction:: PyObject* PyTuple_Pack(Py_ssize_t n, ...)
1950
1951 Return a new tuple object of size *n*, or *NULL* on failure. The tuple values
1952 are initialized to the subsequent *n* C arguments pointing to Python objects.
1953 ``PyTuple_Pack(2, a, b)`` is equivalent to ``Py_BuildValue("(OO)", a, b)``.
1954
Georg Brandl116aa622007-08-15 14:28:22 +00001955
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001956.. cfunction:: Py_ssize_t PyTuple_Size(PyObject *p)
Georg Brandl116aa622007-08-15 14:28:22 +00001957
1958 Take a pointer to a tuple object, and return the size of that tuple.
1959
1960
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001961.. cfunction:: Py_ssize_t PyTuple_GET_SIZE(PyObject *p)
Georg Brandl116aa622007-08-15 14:28:22 +00001962
1963 Return the size of the tuple *p*, which must be non-*NULL* and point to a tuple;
1964 no error checking is performed.
1965
1966
1967.. cfunction:: PyObject* PyTuple_GetItem(PyObject *p, Py_ssize_t pos)
1968
1969 Return the object at position *pos* in the tuple pointed to by *p*. If *pos* is
1970 out of bounds, return *NULL* and sets an :exc:`IndexError` exception.
1971
1972
1973.. cfunction:: PyObject* PyTuple_GET_ITEM(PyObject *p, Py_ssize_t pos)
1974
1975 Like :cfunc:`PyTuple_GetItem`, but does no checking of its arguments.
1976
1977
1978.. cfunction:: PyObject* PyTuple_GetSlice(PyObject *p, Py_ssize_t low, Py_ssize_t high)
1979
1980 Take a slice of the tuple pointed to by *p* from *low* to *high* and return it
1981 as a new tuple.
1982
1983
1984.. cfunction:: int PyTuple_SetItem(PyObject *p, Py_ssize_t pos, PyObject *o)
1985
1986 Insert a reference to object *o* at position *pos* of the tuple pointed to by
1987 *p*. Return ``0`` on success.
1988
1989 .. note::
1990
1991 This function "steals" a reference to *o*.
1992
1993
1994.. cfunction:: void PyTuple_SET_ITEM(PyObject *p, Py_ssize_t pos, PyObject *o)
1995
1996 Like :cfunc:`PyTuple_SetItem`, but does no error checking, and should *only* be
1997 used to fill in brand new tuples.
1998
1999 .. note::
2000
2001 This function "steals" a reference to *o*.
2002
2003
2004.. cfunction:: int _PyTuple_Resize(PyObject **p, Py_ssize_t newsize)
2005
2006 Can be used to resize a tuple. *newsize* will be the new length of the tuple.
2007 Because tuples are *supposed* to be immutable, this should only be used if there
2008 is only one reference to the object. Do *not* use this if the tuple may already
2009 be known to some other part of the code. The tuple will always grow or shrink
2010 at the end. Think of this as destroying the old tuple and creating a new one,
2011 only more efficiently. Returns ``0`` on success. Client code should never
2012 assume that the resulting value of ``*p`` will be the same as before calling
2013 this function. If the object referenced by ``*p`` is replaced, the original
2014 ``*p`` is destroyed. On failure, returns ``-1`` and sets ``*p`` to *NULL*, and
2015 raises :exc:`MemoryError` or :exc:`SystemError`.
2016
Georg Brandl116aa622007-08-15 14:28:22 +00002017
2018.. _listobjects:
2019
2020List Objects
2021------------
2022
2023.. index:: object: list
2024
2025
2026.. ctype:: PyListObject
2027
2028 This subtype of :ctype:`PyObject` represents a Python list object.
2029
2030
2031.. cvar:: PyTypeObject PyList_Type
2032
2033 .. index:: single: ListType (in module types)
2034
2035 This instance of :ctype:`PyTypeObject` represents the Python list type. This is
2036 the same object as ``list`` and ``types.ListType`` in the Python layer.
2037
2038
2039.. cfunction:: int PyList_Check(PyObject *p)
2040
2041 Return true if *p* is a list object or an instance of a subtype of the list
2042 type.
2043
Georg Brandl116aa622007-08-15 14:28:22 +00002044
2045.. cfunction:: int PyList_CheckExact(PyObject *p)
2046
2047 Return true if *p* is a list object, but not an instance of a subtype of the
2048 list type.
2049
Georg Brandl116aa622007-08-15 14:28:22 +00002050
2051.. cfunction:: PyObject* PyList_New(Py_ssize_t len)
2052
2053 Return a new list of length *len* on success, or *NULL* on failure.
2054
2055 .. note::
2056
2057 If *length* is greater than zero, the returned list object's items are set to
2058 ``NULL``. Thus you cannot use abstract API functions such as
2059 :cfunc:`PySequence_SetItem` or expose the object to Python code before setting
2060 all items to a real object with :cfunc:`PyList_SetItem`.
2061
2062
2063.. cfunction:: Py_ssize_t PyList_Size(PyObject *list)
2064
2065 .. index:: builtin: len
2066
2067 Return the length of the list object in *list*; this is equivalent to
2068 ``len(list)`` on a list object.
2069
2070
2071.. cfunction:: Py_ssize_t PyList_GET_SIZE(PyObject *list)
2072
2073 Macro form of :cfunc:`PyList_Size` without error checking.
2074
2075
2076.. cfunction:: PyObject* PyList_GetItem(PyObject *list, Py_ssize_t index)
2077
2078 Return the object at position *pos* in the list pointed to by *p*. The position
2079 must be positive, indexing from the end of the list is not supported. If *pos*
2080 is out of bounds, return *NULL* and set an :exc:`IndexError` exception.
2081
2082
2083.. cfunction:: PyObject* PyList_GET_ITEM(PyObject *list, Py_ssize_t i)
2084
2085 Macro form of :cfunc:`PyList_GetItem` without error checking.
2086
2087
2088.. cfunction:: int PyList_SetItem(PyObject *list, Py_ssize_t index, PyObject *item)
2089
2090 Set the item at index *index* in list to *item*. Return ``0`` on success or
2091 ``-1`` on failure.
2092
2093 .. note::
2094
2095 This function "steals" a reference to *item* and discards a reference to an item
2096 already in the list at the affected position.
2097
2098
2099.. cfunction:: void PyList_SET_ITEM(PyObject *list, Py_ssize_t i, PyObject *o)
2100
2101 Macro form of :cfunc:`PyList_SetItem` without error checking. This is normally
2102 only used to fill in new lists where there is no previous content.
2103
2104 .. note::
2105
2106 This function "steals" a reference to *item*, and, unlike
2107 :cfunc:`PyList_SetItem`, does *not* discard a reference to any item that it
2108 being replaced; any reference in *list* at position *i* will be leaked.
2109
2110
2111.. cfunction:: int PyList_Insert(PyObject *list, Py_ssize_t index, PyObject *item)
2112
2113 Insert the item *item* into list *list* in front of index *index*. Return ``0``
2114 if successful; return ``-1`` and set an exception if unsuccessful. Analogous to
2115 ``list.insert(index, item)``.
2116
2117
2118.. cfunction:: int PyList_Append(PyObject *list, PyObject *item)
2119
2120 Append the object *item* at the end of list *list*. Return ``0`` if successful;
2121 return ``-1`` and set an exception if unsuccessful. Analogous to
2122 ``list.append(item)``.
2123
2124
2125.. cfunction:: PyObject* PyList_GetSlice(PyObject *list, Py_ssize_t low, Py_ssize_t high)
2126
2127 Return a list of the objects in *list* containing the objects *between* *low*
2128 and *high*. Return *NULL* and set an exception if unsuccessful. Analogous to
2129 ``list[low:high]``.
2130
2131
2132.. cfunction:: int PyList_SetSlice(PyObject *list, Py_ssize_t low, Py_ssize_t high, PyObject *itemlist)
2133
2134 Set the slice of *list* between *low* and *high* to the contents of *itemlist*.
2135 Analogous to ``list[low:high] = itemlist``. The *itemlist* may be *NULL*,
2136 indicating the assignment of an empty list (slice deletion). Return ``0`` on
2137 success, ``-1`` on failure.
2138
2139
2140.. cfunction:: int PyList_Sort(PyObject *list)
2141
2142 Sort the items of *list* in place. Return ``0`` on success, ``-1`` on failure.
2143 This is equivalent to ``list.sort()``.
2144
2145
2146.. cfunction:: int PyList_Reverse(PyObject *list)
2147
2148 Reverse the items of *list* in place. Return ``0`` on success, ``-1`` on
2149 failure. This is the equivalent of ``list.reverse()``.
2150
2151
2152.. cfunction:: PyObject* PyList_AsTuple(PyObject *list)
2153
2154 .. index:: builtin: tuple
2155
2156 Return a new tuple object containing the contents of *list*; equivalent to
2157 ``tuple(list)``.
2158
2159
2160.. _mapobjects:
2161
2162Mapping Objects
2163===============
2164
2165.. index:: object: mapping
2166
2167
2168.. _dictobjects:
2169
2170Dictionary Objects
2171------------------
2172
2173.. index:: object: dictionary
2174
2175
2176.. ctype:: PyDictObject
2177
2178 This subtype of :ctype:`PyObject` represents a Python dictionary object.
2179
2180
2181.. cvar:: PyTypeObject PyDict_Type
2182
2183 .. index::
2184 single: DictType (in module types)
2185 single: DictionaryType (in module types)
2186
2187 This instance of :ctype:`PyTypeObject` represents the Python dictionary type.
2188 This is exposed to Python programs as ``dict`` and ``types.DictType``.
2189
2190
2191.. cfunction:: int PyDict_Check(PyObject *p)
2192
2193 Return true if *p* is a dict object or an instance of a subtype of the dict
2194 type.
2195
Georg Brandl116aa622007-08-15 14:28:22 +00002196
2197.. cfunction:: int PyDict_CheckExact(PyObject *p)
2198
2199 Return true if *p* is a dict object, but not an instance of a subtype of the
2200 dict type.
2201
Georg Brandl116aa622007-08-15 14:28:22 +00002202
2203.. cfunction:: PyObject* PyDict_New()
2204
2205 Return a new empty dictionary, or *NULL* on failure.
2206
2207
2208.. cfunction:: PyObject* PyDictProxy_New(PyObject *dict)
2209
2210 Return a proxy object for a mapping which enforces read-only behavior. This is
2211 normally used to create a proxy to prevent modification of the dictionary for
2212 non-dynamic class types.
2213
Georg Brandl116aa622007-08-15 14:28:22 +00002214
2215.. cfunction:: void PyDict_Clear(PyObject *p)
2216
2217 Empty an existing dictionary of all key-value pairs.
2218
2219
2220.. cfunction:: int PyDict_Contains(PyObject *p, PyObject *key)
2221
2222 Determine if dictionary *p* contains *key*. If an item in *p* is matches *key*,
2223 return ``1``, otherwise return ``0``. On error, return ``-1``. This is
2224 equivalent to the Python expression ``key in p``.
2225
Georg Brandl116aa622007-08-15 14:28:22 +00002226
2227.. cfunction:: PyObject* PyDict_Copy(PyObject *p)
2228
2229 Return a new dictionary that contains the same key-value pairs as *p*.
2230
Georg Brandl116aa622007-08-15 14:28:22 +00002231
2232.. cfunction:: int PyDict_SetItem(PyObject *p, PyObject *key, PyObject *val)
2233
2234 Insert *value* into the dictionary *p* with a key of *key*. *key* must be
2235 hashable; if it isn't, :exc:`TypeError` will be raised. Return ``0`` on success
2236 or ``-1`` on failure.
2237
2238
2239.. cfunction:: int PyDict_SetItemString(PyObject *p, const char *key, PyObject *val)
2240
2241 .. index:: single: PyString_FromString()
2242
2243 Insert *value* into the dictionary *p* using *key* as a key. *key* should be a
2244 :ctype:`char\*`. The key object is created using ``PyString_FromString(key)``.
2245 Return ``0`` on success or ``-1`` on failure.
2246
2247
2248.. cfunction:: int PyDict_DelItem(PyObject *p, PyObject *key)
2249
2250 Remove the entry in dictionary *p* with key *key*. *key* must be hashable; if it
2251 isn't, :exc:`TypeError` is raised. Return ``0`` on success or ``-1`` on
2252 failure.
2253
2254
2255.. cfunction:: int PyDict_DelItemString(PyObject *p, char *key)
2256
2257 Remove the entry in dictionary *p* which has a key specified by the string
2258 *key*. Return ``0`` on success or ``-1`` on failure.
2259
2260
2261.. cfunction:: PyObject* PyDict_GetItem(PyObject *p, PyObject *key)
2262
2263 Return the object from dictionary *p* which has a key *key*. Return *NULL* if
2264 the key *key* is not present, but *without* setting an exception.
2265
2266
2267.. cfunction:: PyObject* PyDict_GetItemString(PyObject *p, const char *key)
2268
2269 This is the same as :cfunc:`PyDict_GetItem`, but *key* is specified as a
2270 :ctype:`char\*`, rather than a :ctype:`PyObject\*`.
2271
2272
2273.. cfunction:: PyObject* PyDict_Items(PyObject *p)
2274
2275 Return a :ctype:`PyListObject` containing all the items from the dictionary, as
2276 in the dictionary method :meth:`dict.items`.
2277
2278
2279.. cfunction:: PyObject* PyDict_Keys(PyObject *p)
2280
2281 Return a :ctype:`PyListObject` containing all the keys from the dictionary, as
2282 in the dictionary method :meth:`dict.keys`.
2283
2284
2285.. cfunction:: PyObject* PyDict_Values(PyObject *p)
2286
2287 Return a :ctype:`PyListObject` containing all the values from the dictionary
2288 *p*, as in the dictionary method :meth:`dict.values`.
2289
2290
2291.. cfunction:: Py_ssize_t PyDict_Size(PyObject *p)
2292
2293 .. index:: builtin: len
2294
2295 Return the number of items in the dictionary. This is equivalent to ``len(p)``
2296 on a dictionary.
2297
2298
2299.. cfunction:: int PyDict_Next(PyObject *p, Py_ssize_t *ppos, PyObject **pkey, PyObject **pvalue)
2300
2301 Iterate over all key-value pairs in the dictionary *p*. The :ctype:`int`
2302 referred to by *ppos* must be initialized to ``0`` prior to the first call to
2303 this function to start the iteration; the function returns true for each pair in
2304 the dictionary, and false once all pairs have been reported. The parameters
2305 *pkey* and *pvalue* should either point to :ctype:`PyObject\*` variables that
2306 will be filled in with each key and value, respectively, or may be *NULL*. Any
2307 references returned through them are borrowed. *ppos* should not be altered
2308 during iteration. Its value represents offsets within the internal dictionary
2309 structure, and since the structure is sparse, the offsets are not consecutive.
2310
2311 For example::
2312
2313 PyObject *key, *value;
2314 Py_ssize_t pos = 0;
2315
2316 while (PyDict_Next(self->dict, &pos, &key, &value)) {
2317 /* do something interesting with the values... */
2318 ...
2319 }
2320
2321 The dictionary *p* should not be mutated during iteration. It is safe (since
2322 Python 2.1) to modify the values of the keys as you iterate over the dictionary,
2323 but only so long as the set of keys does not change. For example::
2324
2325 PyObject *key, *value;
2326 Py_ssize_t pos = 0;
2327
2328 while (PyDict_Next(self->dict, &pos, &key, &value)) {
2329 int i = PyInt_AS_LONG(value) + 1;
2330 PyObject *o = PyInt_FromLong(i);
2331 if (o == NULL)
2332 return -1;
2333 if (PyDict_SetItem(self->dict, key, o) < 0) {
2334 Py_DECREF(o);
2335 return -1;
2336 }
2337 Py_DECREF(o);
2338 }
2339
2340
2341.. cfunction:: int PyDict_Merge(PyObject *a, PyObject *b, int override)
2342
2343 Iterate over mapping object *b* adding key-value pairs to dictionary *a*. *b*
2344 may be a dictionary, or any object supporting :func:`PyMapping_Keys` and
2345 :func:`PyObject_GetItem`. If *override* is true, existing pairs in *a* will be
2346 replaced if a matching key is found in *b*, otherwise pairs will only be added
2347 if there is not a matching key in *a*. Return ``0`` on success or ``-1`` if an
2348 exception was raised.
2349
Georg Brandl116aa622007-08-15 14:28:22 +00002350
2351.. cfunction:: int PyDict_Update(PyObject *a, PyObject *b)
2352
2353 This is the same as ``PyDict_Merge(a, b, 1)`` in C, or ``a.update(b)`` in
2354 Python. Return ``0`` on success or ``-1`` if an exception was raised.
2355
Georg Brandl116aa622007-08-15 14:28:22 +00002356
2357.. cfunction:: int PyDict_MergeFromSeq2(PyObject *a, PyObject *seq2, int override)
2358
2359 Update or merge into dictionary *a*, from the key-value pairs in *seq2*. *seq2*
2360 must be an iterable object producing iterable objects of length 2, viewed as
2361 key-value pairs. In case of duplicate keys, the last wins if *override* is
2362 true, else the first wins. Return ``0`` on success or ``-1`` if an exception was
2363 raised. Equivalent Python (except for the return value)::
2364
2365 def PyDict_MergeFromSeq2(a, seq2, override):
2366 for key, value in seq2:
2367 if override or key not in a:
2368 a[key] = value
2369
Georg Brandl116aa622007-08-15 14:28:22 +00002370
2371.. _otherobjects:
2372
2373Other Objects
2374=============
2375
Georg Brandl116aa622007-08-15 14:28:22 +00002376.. _fileobjects:
2377
2378File Objects
2379------------
2380
2381.. index:: object: file
2382
2383Python's built-in file objects are implemented entirely on the :ctype:`FILE\*`
2384support from the C standard library. This is an implementation detail and may
2385change in future releases of Python.
2386
2387
2388.. ctype:: PyFileObject
2389
2390 This subtype of :ctype:`PyObject` represents a Python file object.
2391
2392
2393.. cvar:: PyTypeObject PyFile_Type
2394
2395 .. index:: single: FileType (in module types)
2396
2397 This instance of :ctype:`PyTypeObject` represents the Python file type. This is
2398 exposed to Python programs as ``file`` and ``types.FileType``.
2399
2400
2401.. cfunction:: int PyFile_Check(PyObject *p)
2402
2403 Return true if its argument is a :ctype:`PyFileObject` or a subtype of
2404 :ctype:`PyFileObject`.
2405
Georg Brandl116aa622007-08-15 14:28:22 +00002406
2407.. cfunction:: int PyFile_CheckExact(PyObject *p)
2408
2409 Return true if its argument is a :ctype:`PyFileObject`, but not a subtype of
2410 :ctype:`PyFileObject`.
2411
Georg Brandl116aa622007-08-15 14:28:22 +00002412
2413.. cfunction:: PyObject* PyFile_FromString(char *filename, char *mode)
2414
2415 .. index:: single: fopen()
2416
2417 On success, return a new file object that is opened on the file given by
2418 *filename*, with a file mode given by *mode*, where *mode* has the same
2419 semantics as the standard C routine :cfunc:`fopen`. On failure, return *NULL*.
2420
2421
2422.. cfunction:: PyObject* PyFile_FromFile(FILE *fp, char *name, char *mode, int (*close)(FILE*))
2423
2424 Create a new :ctype:`PyFileObject` from the already-open standard C file
2425 pointer, *fp*. The function *close* will be called when the file should be
2426 closed. Return *NULL* on failure.
2427
2428
2429.. cfunction:: FILE* PyFile_AsFile(PyObject *p)
2430
2431 Return the file object associated with *p* as a :ctype:`FILE\*`.
2432
2433
2434.. cfunction:: PyObject* PyFile_GetLine(PyObject *p, int n)
2435
2436 .. index:: single: EOFError (built-in exception)
2437
2438 Equivalent to ``p.readline([n])``, this function reads one line from the
2439 object *p*. *p* may be a file object or any object with a :meth:`readline`
2440 method. If *n* is ``0``, exactly one line is read, regardless of the length of
2441 the line. If *n* is greater than ``0``, no more than *n* bytes will be read
2442 from the file; a partial line can be returned. In both cases, an empty string
2443 is returned if the end of the file is reached immediately. If *n* is less than
2444 ``0``, however, one line is read regardless of length, but :exc:`EOFError` is
2445 raised if the end of the file is reached immediately.
2446
2447
2448.. cfunction:: PyObject* PyFile_Name(PyObject *p)
2449
2450 Return the name of the file specified by *p* as a string object.
2451
2452
2453.. cfunction:: void PyFile_SetBufSize(PyFileObject *p, int n)
2454
2455 .. index:: single: setvbuf()
2456
2457 Available on systems with :cfunc:`setvbuf` only. This should only be called
2458 immediately after file object creation.
2459
2460
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002461.. cfunction:: int PyFile_SetEncoding(PyFileObject *p, const char *enc)
Georg Brandl116aa622007-08-15 14:28:22 +00002462
2463 Set the file's encoding for Unicode output to *enc*. Return 1 on success and 0
2464 on failure.
2465
Georg Brandl116aa622007-08-15 14:28:22 +00002466
2467.. cfunction:: int PyFile_SoftSpace(PyObject *p, int newflag)
2468
2469 .. index:: single: softspace (file attribute)
2470
2471 This function exists for internal use by the interpreter. Set the
2472 :attr:`softspace` attribute of *p* to *newflag* and return the previous value.
2473 *p* does not have to be a file object for this function to work properly; any
2474 object is supported (thought its only interesting if the :attr:`softspace`
2475 attribute can be set). This function clears any errors, and will return ``0``
2476 as the previous value if the attribute either does not exist or if there were
2477 errors in retrieving it. There is no way to detect errors from this function,
2478 but doing so should not be needed.
2479
2480
2481.. cfunction:: int PyFile_WriteObject(PyObject *obj, PyObject *p, int flags)
2482
2483 .. index:: single: Py_PRINT_RAW
2484
2485 Write object *obj* to file object *p*. The only supported flag for *flags* is
2486 :const:`Py_PRINT_RAW`; if given, the :func:`str` of the object is written
2487 instead of the :func:`repr`. Return ``0`` on success or ``-1`` on failure; the
2488 appropriate exception will be set.
2489
2490
2491.. cfunction:: int PyFile_WriteString(const char *s, PyObject *p)
2492
2493 Write string *s* to file object *p*. Return ``0`` on success or ``-1`` on
2494 failure; the appropriate exception will be set.
2495
2496
Georg Brandl116aa622007-08-15 14:28:22 +00002497.. _function-objects:
2498
2499Function Objects
2500----------------
2501
2502.. index:: object: function
2503
2504There are a few functions specific to Python functions.
2505
2506
2507.. ctype:: PyFunctionObject
2508
2509 The C structure used for functions.
2510
2511
2512.. cvar:: PyTypeObject PyFunction_Type
2513
2514 .. index:: single: MethodType (in module types)
2515
2516 This is an instance of :ctype:`PyTypeObject` and represents the Python function
2517 type. It is exposed to Python programmers as ``types.FunctionType``.
2518
2519
2520.. cfunction:: int PyFunction_Check(PyObject *o)
2521
2522 Return true if *o* is a function object (has type :cdata:`PyFunction_Type`).
2523 The parameter must not be *NULL*.
2524
2525
2526.. cfunction:: PyObject* PyFunction_New(PyObject *code, PyObject *globals)
2527
2528 Return a new function object associated with the code object *code*. *globals*
2529 must be a dictionary with the global variables accessible to the function.
2530
2531 The function's docstring, name and *__module__* are retrieved from the code
2532 object, the argument defaults and closure are set to *NULL*.
2533
2534
2535.. cfunction:: PyObject* PyFunction_GetCode(PyObject *op)
2536
2537 Return the code object associated with the function object *op*.
2538
2539
2540.. cfunction:: PyObject* PyFunction_GetGlobals(PyObject *op)
2541
2542 Return the globals dictionary associated with the function object *op*.
2543
2544
2545.. cfunction:: PyObject* PyFunction_GetModule(PyObject *op)
2546
2547 Return the *__module__* attribute of the function object *op*. This is normally
2548 a string containing the module name, but can be set to any other object by
2549 Python code.
2550
2551
2552.. cfunction:: PyObject* PyFunction_GetDefaults(PyObject *op)
2553
2554 Return the argument default values of the function object *op*. This can be a
2555 tuple of arguments or *NULL*.
2556
2557
2558.. cfunction:: int PyFunction_SetDefaults(PyObject *op, PyObject *defaults)
2559
2560 Set the argument default values for the function object *op*. *defaults* must be
2561 *Py_None* or a tuple.
2562
2563 Raises :exc:`SystemError` and returns ``-1`` on failure.
2564
2565
2566.. cfunction:: PyObject* PyFunction_GetClosure(PyObject *op)
2567
2568 Return the closure associated with the function object *op*. This can be *NULL*
2569 or a tuple of cell objects.
2570
2571
2572.. cfunction:: int PyFunction_SetClosure(PyObject *op, PyObject *closure)
2573
2574 Set the closure associated with the function object *op*. *closure* must be
2575 *Py_None* or a tuple of cell objects.
2576
2577 Raises :exc:`SystemError` and returns ``-1`` on failure.
2578
2579
2580.. _method-objects:
2581
2582Method Objects
2583--------------
2584
2585.. index:: object: method
2586
2587There are some useful functions that are useful for working with method objects.
2588
2589
2590.. cvar:: PyTypeObject PyMethod_Type
2591
2592 .. index:: single: MethodType (in module types)
2593
2594 This instance of :ctype:`PyTypeObject` represents the Python method type. This
2595 is exposed to Python programs as ``types.MethodType``.
2596
2597
2598.. cfunction:: int PyMethod_Check(PyObject *o)
2599
2600 Return true if *o* is a method object (has type :cdata:`PyMethod_Type`). The
2601 parameter must not be *NULL*.
2602
2603
2604.. cfunction:: PyObject* PyMethod_New(PyObject *func, PyObject *self, PyObject *class)
2605
2606 Return a new method object, with *func* being any callable object; this is the
2607 function that will be called when the method is called. If this method should
2608 be bound to an instance, *self* should be the instance and *class* should be the
2609 class of *self*, otherwise *self* should be *NULL* and *class* should be the
2610 class which provides the unbound method..
2611
2612
2613.. cfunction:: PyObject* PyMethod_Class(PyObject *meth)
2614
2615 Return the class object from which the method *meth* was created; if this was
2616 created from an instance, it will be the class of the instance.
2617
2618
2619.. cfunction:: PyObject* PyMethod_GET_CLASS(PyObject *meth)
2620
2621 Macro version of :cfunc:`PyMethod_Class` which avoids error checking.
2622
2623
2624.. cfunction:: PyObject* PyMethod_Function(PyObject *meth)
2625
2626 Return the function object associated with the method *meth*.
2627
2628
2629.. cfunction:: PyObject* PyMethod_GET_FUNCTION(PyObject *meth)
2630
2631 Macro version of :cfunc:`PyMethod_Function` which avoids error checking.
2632
2633
2634.. cfunction:: PyObject* PyMethod_Self(PyObject *meth)
2635
2636 Return the instance associated with the method *meth* if it is bound, otherwise
2637 return *NULL*.
2638
2639
2640.. cfunction:: PyObject* PyMethod_GET_SELF(PyObject *meth)
2641
2642 Macro version of :cfunc:`PyMethod_Self` which avoids error checking.
2643
2644
2645.. _moduleobjects:
2646
2647Module Objects
2648--------------
2649
2650.. index:: object: module
2651
2652There are only a few functions special to module objects.
2653
2654
2655.. cvar:: PyTypeObject PyModule_Type
2656
2657 .. index:: single: ModuleType (in module types)
2658
2659 This instance of :ctype:`PyTypeObject` represents the Python module type. This
2660 is exposed to Python programs as ``types.ModuleType``.
2661
2662
2663.. cfunction:: int PyModule_Check(PyObject *p)
2664
2665 Return true if *p* is a module object, or a subtype of a module object.
2666
Georg Brandl116aa622007-08-15 14:28:22 +00002667
2668.. cfunction:: int PyModule_CheckExact(PyObject *p)
2669
2670 Return true if *p* is a module object, but not a subtype of
2671 :cdata:`PyModule_Type`.
2672
Georg Brandl116aa622007-08-15 14:28:22 +00002673
2674.. cfunction:: PyObject* PyModule_New(const char *name)
2675
2676 .. index::
2677 single: __name__ (module attribute)
2678 single: __doc__ (module attribute)
2679 single: __file__ (module attribute)
2680
2681 Return a new module object with the :attr:`__name__` attribute set to *name*.
2682 Only the module's :attr:`__doc__` and :attr:`__name__` attributes are filled in;
2683 the caller is responsible for providing a :attr:`__file__` attribute.
2684
2685
2686.. cfunction:: PyObject* PyModule_GetDict(PyObject *module)
2687
2688 .. index:: single: __dict__ (module attribute)
2689
2690 Return the dictionary object that implements *module*'s namespace; this object
2691 is the same as the :attr:`__dict__` attribute of the module object. This
2692 function never fails. It is recommended extensions use other
2693 :cfunc:`PyModule_\*` and :cfunc:`PyObject_\*` functions rather than directly
2694 manipulate a module's :attr:`__dict__`.
2695
2696
2697.. cfunction:: char* PyModule_GetName(PyObject *module)
2698
2699 .. index::
2700 single: __name__ (module attribute)
2701 single: SystemError (built-in exception)
2702
2703 Return *module*'s :attr:`__name__` value. If the module does not provide one,
2704 or if it is not a string, :exc:`SystemError` is raised and *NULL* is returned.
2705
2706
2707.. cfunction:: char* PyModule_GetFilename(PyObject *module)
2708
2709 .. index::
2710 single: __file__ (module attribute)
2711 single: SystemError (built-in exception)
2712
2713 Return the name of the file from which *module* was loaded using *module*'s
2714 :attr:`__file__` attribute. If this is not defined, or if it is not a string,
2715 raise :exc:`SystemError` and return *NULL*.
2716
2717
2718.. cfunction:: int PyModule_AddObject(PyObject *module, const char *name, PyObject *value)
2719
2720 Add an object to *module* as *name*. This is a convenience function which can
2721 be used from the module's initialization function. This steals a reference to
2722 *value*. Return ``-1`` on error, ``0`` on success.
2723
Georg Brandl116aa622007-08-15 14:28:22 +00002724
2725.. cfunction:: int PyModule_AddIntConstant(PyObject *module, const char *name, long value)
2726
2727 Add an integer constant to *module* as *name*. This convenience function can be
2728 used from the module's initialization function. Return ``-1`` on error, ``0`` on
2729 success.
2730
Georg Brandl116aa622007-08-15 14:28:22 +00002731
2732.. cfunction:: int PyModule_AddStringConstant(PyObject *module, const char *name, const char *value)
2733
2734 Add a string constant to *module* as *name*. This convenience function can be
2735 used from the module's initialization function. The string *value* must be
2736 null-terminated. Return ``-1`` on error, ``0`` on success.
2737
Georg Brandl116aa622007-08-15 14:28:22 +00002738
2739.. _iterator-objects:
2740
2741Iterator Objects
2742----------------
2743
2744Python provides two general-purpose iterator objects. The first, a sequence
2745iterator, works with an arbitrary sequence supporting the :meth:`__getitem__`
2746method. The second works with a callable object and a sentinel value, calling
2747the callable for each item in the sequence, and ending the iteration when the
2748sentinel value is returned.
2749
2750
2751.. cvar:: PyTypeObject PySeqIter_Type
2752
2753 Type object for iterator objects returned by :cfunc:`PySeqIter_New` and the
2754 one-argument form of the :func:`iter` built-in function for built-in sequence
2755 types.
2756
Georg Brandl116aa622007-08-15 14:28:22 +00002757
2758.. cfunction:: int PySeqIter_Check(op)
2759
2760 Return true if the type of *op* is :cdata:`PySeqIter_Type`.
2761
Georg Brandl116aa622007-08-15 14:28:22 +00002762
2763.. cfunction:: PyObject* PySeqIter_New(PyObject *seq)
2764
2765 Return an iterator that works with a general sequence object, *seq*. The
2766 iteration ends when the sequence raises :exc:`IndexError` for the subscripting
2767 operation.
2768
Georg Brandl116aa622007-08-15 14:28:22 +00002769
2770.. cvar:: PyTypeObject PyCallIter_Type
2771
2772 Type object for iterator objects returned by :cfunc:`PyCallIter_New` and the
2773 two-argument form of the :func:`iter` built-in function.
2774
Georg Brandl116aa622007-08-15 14:28:22 +00002775
2776.. cfunction:: int PyCallIter_Check(op)
2777
2778 Return true if the type of *op* is :cdata:`PyCallIter_Type`.
2779
Georg Brandl116aa622007-08-15 14:28:22 +00002780
2781.. cfunction:: PyObject* PyCallIter_New(PyObject *callable, PyObject *sentinel)
2782
2783 Return a new iterator. The first parameter, *callable*, can be any Python
2784 callable object that can be called with no parameters; each call to it should
2785 return the next item in the iteration. When *callable* returns a value equal to
2786 *sentinel*, the iteration will be terminated.
2787
Georg Brandl116aa622007-08-15 14:28:22 +00002788
2789.. _descriptor-objects:
2790
2791Descriptor Objects
2792------------------
2793
2794"Descriptors" are objects that describe some attribute of an object. They are
2795found in the dictionary of type objects.
2796
Georg Brandl321976b2007-09-01 12:33:24 +00002797.. XXX document these!
Georg Brandl116aa622007-08-15 14:28:22 +00002798
2799.. cvar:: PyTypeObject PyProperty_Type
2800
2801 The type object for the built-in descriptor types.
2802
Georg Brandl116aa622007-08-15 14:28:22 +00002803
2804.. cfunction:: PyObject* PyDescr_NewGetSet(PyTypeObject *type, struct PyGetSetDef *getset)
2805
Georg Brandl116aa622007-08-15 14:28:22 +00002806
2807.. cfunction:: PyObject* PyDescr_NewMember(PyTypeObject *type, struct PyMemberDef *meth)
2808
Georg Brandl116aa622007-08-15 14:28:22 +00002809
2810.. cfunction:: PyObject* PyDescr_NewMethod(PyTypeObject *type, struct PyMethodDef *meth)
2811
Georg Brandl116aa622007-08-15 14:28:22 +00002812
2813.. cfunction:: PyObject* PyDescr_NewWrapper(PyTypeObject *type, struct wrapperbase *wrapper, void *wrapped)
2814
Georg Brandl116aa622007-08-15 14:28:22 +00002815
2816.. cfunction:: PyObject* PyDescr_NewClassMethod(PyTypeObject *type, PyMethodDef *method)
2817
Georg Brandl116aa622007-08-15 14:28:22 +00002818
2819.. cfunction:: int PyDescr_IsData(PyObject *descr)
2820
2821 Return true if the descriptor objects *descr* describes a data attribute, or
2822 false if it describes a method. *descr* must be a descriptor object; there is
2823 no error checking.
2824
Georg Brandl116aa622007-08-15 14:28:22 +00002825
2826.. cfunction:: PyObject* PyWrapper_New(PyObject *, PyObject *)
2827
Georg Brandl116aa622007-08-15 14:28:22 +00002828
2829.. _slice-objects:
2830
2831Slice Objects
2832-------------
2833
2834
2835.. cvar:: PyTypeObject PySlice_Type
2836
2837 .. index:: single: SliceType (in module types)
2838
2839 The type object for slice objects. This is the same as ``slice`` and
2840 ``types.SliceType``.
2841
2842
2843.. cfunction:: int PySlice_Check(PyObject *ob)
2844
2845 Return true if *ob* is a slice object; *ob* must not be *NULL*.
2846
2847
2848.. cfunction:: PyObject* PySlice_New(PyObject *start, PyObject *stop, PyObject *step)
2849
2850 Return a new slice object with the given values. The *start*, *stop*, and
2851 *step* parameters are used as the values of the slice object attributes of the
2852 same names. Any of the values may be *NULL*, in which case the ``None`` will be
2853 used for the corresponding attribute. Return *NULL* if the new object could not
2854 be allocated.
2855
2856
2857.. cfunction:: int PySlice_GetIndices(PySliceObject *slice, Py_ssize_t length, Py_ssize_t *start, Py_ssize_t *stop, Py_ssize_t *step)
2858
2859 Retrieve the start, stop and step indices from the slice object *slice*,
2860 assuming a sequence of length *length*. Treats indices greater than *length* as
2861 errors.
2862
2863 Returns 0 on success and -1 on error with no exception set (unless one of the
2864 indices was not :const:`None` and failed to be converted to an integer, in which
2865 case -1 is returned with an exception set).
2866
2867 You probably do not want to use this function. If you want to use slice objects
2868 in versions of Python prior to 2.3, you would probably do well to incorporate
2869 the source of :cfunc:`PySlice_GetIndicesEx`, suitably renamed, in the source of
2870 your extension.
2871
2872
2873.. cfunction:: int PySlice_GetIndicesEx(PySliceObject *slice, Py_ssize_t length, Py_ssize_t *start, Py_ssize_t *stop, Py_ssize_t *step, Py_ssize_t *slicelength)
2874
2875 Usable replacement for :cfunc:`PySlice_GetIndices`. Retrieve the start, stop,
2876 and step indices from the slice object *slice* assuming a sequence of length
2877 *length*, and store the length of the slice in *slicelength*. Out of bounds
2878 indices are clipped in a manner consistent with the handling of normal slices.
2879
2880 Returns 0 on success and -1 on error with exception set.
2881
Georg Brandl116aa622007-08-15 14:28:22 +00002882
2883.. _weakrefobjects:
2884
2885Weak Reference Objects
2886----------------------
2887
2888Python supports *weak references* as first-class objects. There are two
2889specific object types which directly implement weak references. The first is a
2890simple reference object, and the second acts as a proxy for the original object
2891as much as it can.
2892
2893
2894.. cfunction:: int PyWeakref_Check(ob)
2895
2896 Return true if *ob* is either a reference or proxy object.
2897
Georg Brandl116aa622007-08-15 14:28:22 +00002898
2899.. cfunction:: int PyWeakref_CheckRef(ob)
2900
2901 Return true if *ob* is a reference object.
2902
Georg Brandl116aa622007-08-15 14:28:22 +00002903
2904.. cfunction:: int PyWeakref_CheckProxy(ob)
2905
2906 Return true if *ob* is a proxy object.
2907
Georg Brandl116aa622007-08-15 14:28:22 +00002908
2909.. cfunction:: PyObject* PyWeakref_NewRef(PyObject *ob, PyObject *callback)
2910
2911 Return a weak reference object for the object *ob*. This will always return
2912 a new reference, but is not guaranteed to create a new object; an existing
2913 reference object may be returned. The second parameter, *callback*, can be a
2914 callable object that receives notification when *ob* is garbage collected; it
2915 should accept a single parameter, which will be the weak reference object
2916 itself. *callback* may also be ``None`` or *NULL*. If *ob* is not a
2917 weakly-referencable object, or if *callback* is not callable, ``None``, or
2918 *NULL*, this will return *NULL* and raise :exc:`TypeError`.
2919
Georg Brandl116aa622007-08-15 14:28:22 +00002920
2921.. cfunction:: PyObject* PyWeakref_NewProxy(PyObject *ob, PyObject *callback)
2922
2923 Return a weak reference proxy object for the object *ob*. This will always
2924 return a new reference, but is not guaranteed to create a new object; an
2925 existing proxy object may be returned. The second parameter, *callback*, can
2926 be a callable object that receives notification when *ob* is garbage
2927 collected; it should accept a single parameter, which will be the weak
2928 reference object itself. *callback* may also be ``None`` or *NULL*. If *ob*
2929 is not a weakly-referencable object, or if *callback* is not callable,
2930 ``None``, or *NULL*, this will return *NULL* and raise :exc:`TypeError`.
2931
Georg Brandl116aa622007-08-15 14:28:22 +00002932
2933.. cfunction:: PyObject* PyWeakref_GetObject(PyObject *ref)
2934
2935 Return the referenced object from a weak reference, *ref*. If the referent is
2936 no longer live, returns ``None``.
2937
Georg Brandl116aa622007-08-15 14:28:22 +00002938
2939.. cfunction:: PyObject* PyWeakref_GET_OBJECT(PyObject *ref)
2940
2941 Similar to :cfunc:`PyWeakref_GetObject`, but implemented as a macro that does no
2942 error checking.
2943
Georg Brandl116aa622007-08-15 14:28:22 +00002944
2945.. _cobjects:
2946
2947CObjects
2948--------
2949
2950.. index:: object: CObject
2951
2952Refer to *Extending and Embedding the Python Interpreter*, section 1.12,
2953"Providing a C API for an Extension Module," for more information on using these
2954objects.
2955
2956
2957.. ctype:: PyCObject
2958
2959 This subtype of :ctype:`PyObject` represents an opaque value, useful for C
2960 extension modules who need to pass an opaque value (as a :ctype:`void\*`
2961 pointer) through Python code to other C code. It is often used to make a C
2962 function pointer defined in one module available to other modules, so the
2963 regular import mechanism can be used to access C APIs defined in dynamically
2964 loaded modules.
2965
2966
2967.. cfunction:: int PyCObject_Check(PyObject *p)
2968
2969 Return true if its argument is a :ctype:`PyCObject`.
2970
2971
2972.. cfunction:: PyObject* PyCObject_FromVoidPtr(void* cobj, void (*destr)(void *))
2973
2974 Create a :ctype:`PyCObject` from the ``void *`` *cobj*. The *destr* function
2975 will be called when the object is reclaimed, unless it is *NULL*.
2976
2977
2978.. cfunction:: PyObject* PyCObject_FromVoidPtrAndDesc(void* cobj, void* desc, void (*destr)(void *, void *))
2979
2980 Create a :ctype:`PyCObject` from the :ctype:`void \*` *cobj*. The *destr*
2981 function will be called when the object is reclaimed. The *desc* argument can
2982 be used to pass extra callback data for the destructor function.
2983
2984
2985.. cfunction:: void* PyCObject_AsVoidPtr(PyObject* self)
2986
2987 Return the object :ctype:`void \*` that the :ctype:`PyCObject` *self* was
2988 created with.
2989
2990
2991.. cfunction:: void* PyCObject_GetDesc(PyObject* self)
2992
2993 Return the description :ctype:`void \*` that the :ctype:`PyCObject` *self* was
2994 created with.
2995
2996
2997.. cfunction:: int PyCObject_SetVoidPtr(PyObject* self, void* cobj)
2998
2999 Set the void pointer inside *self* to *cobj*. The :ctype:`PyCObject` must not
3000 have an associated destructor. Return true on success, false on failure.
3001
3002
3003.. _cell-objects:
3004
3005Cell Objects
3006------------
3007
3008"Cell" objects are used to implement variables referenced by multiple scopes.
3009For each such variable, a cell object is created to store the value; the local
3010variables of each stack frame that references the value contains a reference to
3011the cells from outer scopes which also use that variable. When the value is
3012accessed, the value contained in the cell is used instead of the cell object
3013itself. This de-referencing of the cell object requires support from the
3014generated byte-code; these are not automatically de-referenced when accessed.
3015Cell objects are not likely to be useful elsewhere.
3016
3017
3018.. ctype:: PyCellObject
3019
3020 The C structure used for cell objects.
3021
3022
3023.. cvar:: PyTypeObject PyCell_Type
3024
3025 The type object corresponding to cell objects.
3026
3027
3028.. cfunction:: int PyCell_Check(ob)
3029
3030 Return true if *ob* is a cell object; *ob* must not be *NULL*.
3031
3032
3033.. cfunction:: PyObject* PyCell_New(PyObject *ob)
3034
3035 Create and return a new cell object containing the value *ob*. The parameter may
3036 be *NULL*.
3037
3038
3039.. cfunction:: PyObject* PyCell_Get(PyObject *cell)
3040
3041 Return the contents of the cell *cell*.
3042
3043
3044.. cfunction:: PyObject* PyCell_GET(PyObject *cell)
3045
3046 Return the contents of the cell *cell*, but without checking that *cell* is
3047 non-*NULL* and a cell object.
3048
3049
3050.. cfunction:: int PyCell_Set(PyObject *cell, PyObject *value)
3051
3052 Set the contents of the cell object *cell* to *value*. This releases the
3053 reference to any current content of the cell. *value* may be *NULL*. *cell*
3054 must be non-*NULL*; if it is not a cell object, ``-1`` will be returned. On
3055 success, ``0`` will be returned.
3056
3057
3058.. cfunction:: void PyCell_SET(PyObject *cell, PyObject *value)
3059
3060 Sets the value of the cell object *cell* to *value*. No reference counts are
3061 adjusted, and no checks are made for safety; *cell* must be non-*NULL* and must
3062 be a cell object.
3063
3064
3065.. _gen-objects:
3066
3067Generator Objects
3068-----------------
3069
3070Generator objects are what Python uses to implement generator iterators. They
3071are normally created by iterating over a function that yields values, rather
3072than explicitly calling :cfunc:`PyGen_New`.
3073
3074
3075.. ctype:: PyGenObject
3076
3077 The C structure used for generator objects.
3078
3079
3080.. cvar:: PyTypeObject PyGen_Type
3081
3082 The type object corresponding to generator objects
3083
3084
3085.. cfunction:: int PyGen_Check(ob)
3086
3087 Return true if *ob* is a generator object; *ob* must not be *NULL*.
3088
3089
3090.. cfunction:: int PyGen_CheckExact(ob)
3091
3092 Return true if *ob*'s type is *PyGen_Type* is a generator object; *ob* must not
3093 be *NULL*.
3094
3095
3096.. cfunction:: PyObject* PyGen_New(PyFrameObject *frame)
3097
3098 Create and return a new generator object based on the *frame* object. A
3099 reference to *frame* is stolen by this function. The parameter must not be
3100 *NULL*.
3101
3102
3103.. _datetimeobjects:
3104
3105DateTime Objects
3106----------------
3107
3108Various date and time objects are supplied by the :mod:`datetime` module.
3109Before using any of these functions, the header file :file:`datetime.h` must be
3110included in your source (note that this is not included by :file:`Python.h`),
3111and the macro :cfunc:`PyDateTime_IMPORT` must be invoked. The macro puts a
3112pointer to a C structure into a static variable, ``PyDateTimeAPI``, that is
3113used by the following macros.
3114
3115Type-check macros:
3116
Georg Brandl116aa622007-08-15 14:28:22 +00003117.. cfunction:: int PyDate_Check(PyObject *ob)
3118
3119 Return true if *ob* is of type :cdata:`PyDateTime_DateType` or a subtype of
3120 :cdata:`PyDateTime_DateType`. *ob* must not be *NULL*.
3121
Georg Brandl116aa622007-08-15 14:28:22 +00003122
3123.. cfunction:: int PyDate_CheckExact(PyObject *ob)
3124
3125 Return true if *ob* is of type :cdata:`PyDateTime_DateType`. *ob* must not be
3126 *NULL*.
3127
Georg Brandl116aa622007-08-15 14:28:22 +00003128
3129.. cfunction:: int PyDateTime_Check(PyObject *ob)
3130
3131 Return true if *ob* is of type :cdata:`PyDateTime_DateTimeType` or a subtype of
3132 :cdata:`PyDateTime_DateTimeType`. *ob* must not be *NULL*.
3133
Georg Brandl116aa622007-08-15 14:28:22 +00003134
3135.. cfunction:: int PyDateTime_CheckExact(PyObject *ob)
3136
3137 Return true if *ob* is of type :cdata:`PyDateTime_DateTimeType`. *ob* must not
3138 be *NULL*.
3139
Georg Brandl116aa622007-08-15 14:28:22 +00003140
3141.. cfunction:: int PyTime_Check(PyObject *ob)
3142
3143 Return true if *ob* is of type :cdata:`PyDateTime_TimeType` or a subtype of
3144 :cdata:`PyDateTime_TimeType`. *ob* must not be *NULL*.
3145
Georg Brandl116aa622007-08-15 14:28:22 +00003146
3147.. cfunction:: int PyTime_CheckExact(PyObject *ob)
3148
3149 Return true if *ob* is of type :cdata:`PyDateTime_TimeType`. *ob* must not be
3150 *NULL*.
3151
Georg Brandl116aa622007-08-15 14:28:22 +00003152
3153.. cfunction:: int PyDelta_Check(PyObject *ob)
3154
3155 Return true if *ob* is of type :cdata:`PyDateTime_DeltaType` or a subtype of
3156 :cdata:`PyDateTime_DeltaType`. *ob* must not be *NULL*.
3157
Georg Brandl116aa622007-08-15 14:28:22 +00003158
3159.. cfunction:: int PyDelta_CheckExact(PyObject *ob)
3160
3161 Return true if *ob* is of type :cdata:`PyDateTime_DeltaType`. *ob* must not be
3162 *NULL*.
3163
Georg Brandl116aa622007-08-15 14:28:22 +00003164
3165.. cfunction:: int PyTZInfo_Check(PyObject *ob)
3166
3167 Return true if *ob* is of type :cdata:`PyDateTime_TZInfoType` or a subtype of
3168 :cdata:`PyDateTime_TZInfoType`. *ob* must not be *NULL*.
3169
Georg Brandl116aa622007-08-15 14:28:22 +00003170
3171.. cfunction:: int PyTZInfo_CheckExact(PyObject *ob)
3172
3173 Return true if *ob* is of type :cdata:`PyDateTime_TZInfoType`. *ob* must not be
3174 *NULL*.
3175
Georg Brandl116aa622007-08-15 14:28:22 +00003176
3177Macros to create objects:
3178
Georg Brandl116aa622007-08-15 14:28:22 +00003179.. cfunction:: PyObject* PyDate_FromDate(int year, int month, int day)
3180
3181 Return a ``datetime.date`` object with the specified year, month and day.
3182
Georg Brandl116aa622007-08-15 14:28:22 +00003183
3184.. cfunction:: PyObject* PyDateTime_FromDateAndTime(int year, int month, int day, int hour, int minute, int second, int usecond)
3185
3186 Return a ``datetime.datetime`` object with the specified year, month, day, hour,
3187 minute, second and microsecond.
3188
Georg Brandl116aa622007-08-15 14:28:22 +00003189
3190.. cfunction:: PyObject* PyTime_FromTime(int hour, int minute, int second, int usecond)
3191
3192 Return a ``datetime.time`` object with the specified hour, minute, second and
3193 microsecond.
3194
Georg Brandl116aa622007-08-15 14:28:22 +00003195
3196.. cfunction:: PyObject* PyDelta_FromDSU(int days, int seconds, int useconds)
3197
3198 Return a ``datetime.timedelta`` object representing the given number of days,
3199 seconds and microseconds. Normalization is performed so that the resulting
3200 number of microseconds and seconds lie in the ranges documented for
3201 ``datetime.timedelta`` objects.
3202
Georg Brandl116aa622007-08-15 14:28:22 +00003203
3204Macros to extract fields from date objects. The argument must be an instance of
3205:cdata:`PyDateTime_Date`, including subclasses (such as
3206:cdata:`PyDateTime_DateTime`). The argument must not be *NULL*, and the type is
3207not checked:
3208
Georg Brandl116aa622007-08-15 14:28:22 +00003209.. cfunction:: int PyDateTime_GET_YEAR(PyDateTime_Date *o)
3210
3211 Return the year, as a positive int.
3212
Georg Brandl116aa622007-08-15 14:28:22 +00003213
3214.. cfunction:: int PyDateTime_GET_MONTH(PyDateTime_Date *o)
3215
3216 Return the month, as an int from 1 through 12.
3217
Georg Brandl116aa622007-08-15 14:28:22 +00003218
3219.. cfunction:: int PyDateTime_GET_DAY(PyDateTime_Date *o)
3220
3221 Return the day, as an int from 1 through 31.
3222
Georg Brandl116aa622007-08-15 14:28:22 +00003223
3224Macros to extract fields from datetime objects. The argument must be an
3225instance of :cdata:`PyDateTime_DateTime`, including subclasses. The argument
3226must not be *NULL*, and the type is not checked:
3227
Georg Brandl116aa622007-08-15 14:28:22 +00003228.. cfunction:: int PyDateTime_DATE_GET_HOUR(PyDateTime_DateTime *o)
3229
3230 Return the hour, as an int from 0 through 23.
3231
Georg Brandl116aa622007-08-15 14:28:22 +00003232
3233.. cfunction:: int PyDateTime_DATE_GET_MINUTE(PyDateTime_DateTime *o)
3234
3235 Return the minute, as an int from 0 through 59.
3236
Georg Brandl116aa622007-08-15 14:28:22 +00003237
3238.. cfunction:: int PyDateTime_DATE_GET_SECOND(PyDateTime_DateTime *o)
3239
3240 Return the second, as an int from 0 through 59.
3241
Georg Brandl116aa622007-08-15 14:28:22 +00003242
3243.. cfunction:: int PyDateTime_DATE_GET_MICROSECOND(PyDateTime_DateTime *o)
3244
3245 Return the microsecond, as an int from 0 through 999999.
3246
Georg Brandl116aa622007-08-15 14:28:22 +00003247
3248Macros to extract fields from time objects. The argument must be an instance of
3249:cdata:`PyDateTime_Time`, including subclasses. The argument must not be *NULL*,
3250and the type is not checked:
3251
Georg Brandl116aa622007-08-15 14:28:22 +00003252.. cfunction:: int PyDateTime_TIME_GET_HOUR(PyDateTime_Time *o)
3253
3254 Return the hour, as an int from 0 through 23.
3255
Georg Brandl116aa622007-08-15 14:28:22 +00003256
3257.. cfunction:: int PyDateTime_TIME_GET_MINUTE(PyDateTime_Time *o)
3258
3259 Return the minute, as an int from 0 through 59.
3260
Georg Brandl116aa622007-08-15 14:28:22 +00003261
3262.. cfunction:: int PyDateTime_TIME_GET_SECOND(PyDateTime_Time *o)
3263
3264 Return the second, as an int from 0 through 59.
3265
Georg Brandl116aa622007-08-15 14:28:22 +00003266
3267.. cfunction:: int PyDateTime_TIME_GET_MICROSECOND(PyDateTime_Time *o)
3268
3269 Return the microsecond, as an int from 0 through 999999.
3270
Georg Brandl116aa622007-08-15 14:28:22 +00003271
3272Macros for the convenience of modules implementing the DB API:
3273
Georg Brandl116aa622007-08-15 14:28:22 +00003274.. cfunction:: PyObject* PyDateTime_FromTimestamp(PyObject *args)
3275
3276 Create and return a new ``datetime.datetime`` object given an argument tuple
3277 suitable for passing to ``datetime.datetime.fromtimestamp()``.
3278
Georg Brandl116aa622007-08-15 14:28:22 +00003279
3280.. cfunction:: PyObject* PyDate_FromTimestamp(PyObject *args)
3281
3282 Create and return a new ``datetime.date`` object given an argument tuple
3283 suitable for passing to ``datetime.date.fromtimestamp()``.
3284
Georg Brandl116aa622007-08-15 14:28:22 +00003285
3286.. _setobjects:
3287
3288Set Objects
3289-----------
3290
3291.. sectionauthor:: Raymond D. Hettinger <python@rcn.com>
3292
3293
3294.. index::
3295 object: set
3296 object: frozenset
3297
Georg Brandl116aa622007-08-15 14:28:22 +00003298This section details the public API for :class:`set` and :class:`frozenset`
3299objects. Any functionality not listed below is best accessed using the either
3300the abstract object protocol (including :cfunc:`PyObject_CallMethod`,
3301:cfunc:`PyObject_RichCompareBool`, :cfunc:`PyObject_Hash`,
3302:cfunc:`PyObject_Repr`, :cfunc:`PyObject_IsTrue`, :cfunc:`PyObject_Print`, and
3303:cfunc:`PyObject_GetIter`) or the abstract number protocol (including
3304:cfunc:`PyNumber_And`, :cfunc:`PyNumber_Subtract`, :cfunc:`PyNumber_Or`,
3305:cfunc:`PyNumber_Xor`, :cfunc:`PyNumber_InPlaceAnd`,
3306:cfunc:`PyNumber_InPlaceSubtract`, :cfunc:`PyNumber_InPlaceOr`, and
3307:cfunc:`PyNumber_InPlaceXor`).
3308
3309
3310.. ctype:: PySetObject
3311
3312 This subtype of :ctype:`PyObject` is used to hold the internal data for both
3313 :class:`set` and :class:`frozenset` objects. It is like a :ctype:`PyDictObject`
3314 in that it is a fixed size for small sets (much like tuple storage) and will
3315 point to a separate, variable sized block of memory for medium and large sized
3316 sets (much like list storage). None of the fields of this structure should be
3317 considered public and are subject to change. All access should be done through
3318 the documented API rather than by manipulating the values in the structure.
3319
3320
3321.. cvar:: PyTypeObject PySet_Type
3322
3323 This is an instance of :ctype:`PyTypeObject` representing the Python
3324 :class:`set` type.
3325
3326
3327.. cvar:: PyTypeObject PyFrozenSet_Type
3328
3329 This is an instance of :ctype:`PyTypeObject` representing the Python
3330 :class:`frozenset` type.
3331
3332The following type check macros work on pointers to any Python object. Likewise,
3333the constructor functions work with any iterable Python object.
3334
3335
3336.. cfunction:: int PyAnySet_Check(PyObject *p)
3337
3338 Return true if *p* is a :class:`set` object, a :class:`frozenset` object, or an
3339 instance of a subtype.
3340
3341
3342.. cfunction:: int PyAnySet_CheckExact(PyObject *p)
3343
3344 Return true if *p* is a :class:`set` object or a :class:`frozenset` object but
3345 not an instance of a subtype.
3346
3347
3348.. cfunction:: int PyFrozenSet_CheckExact(PyObject *p)
3349
3350 Return true if *p* is a :class:`frozenset` object but not an instance of a
3351 subtype.
3352
3353
3354.. cfunction:: PyObject* PySet_New(PyObject *iterable)
3355
3356 Return a new :class:`set` containing objects returned by the *iterable*. The
3357 *iterable* may be *NULL* to create a new empty set. Return the new set on
3358 success or *NULL* on failure. Raise :exc:`TypeError` if *iterable* is not
3359 actually iterable. The constructor is also useful for copying a set
3360 (``c=set(s)``).
3361
3362
3363.. cfunction:: PyObject* PyFrozenSet_New(PyObject *iterable)
3364
3365 Return a new :class:`frozenset` containing objects returned by the *iterable*.
3366 The *iterable* may be *NULL* to create a new empty frozenset. Return the new
3367 set on success or *NULL* on failure. Raise :exc:`TypeError` if *iterable* is
3368 not actually iterable.
3369
3370The following functions and macros are available for instances of :class:`set`
3371or :class:`frozenset` or instances of their subtypes.
3372
3373
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003374.. cfunction:: Py_ssize_t PySet_Size(PyObject *anyset)
Georg Brandl116aa622007-08-15 14:28:22 +00003375
3376 .. index:: builtin: len
3377
3378 Return the length of a :class:`set` or :class:`frozenset` object. Equivalent to
3379 ``len(anyset)``. Raises a :exc:`PyExc_SystemError` if *anyset* is not a
3380 :class:`set`, :class:`frozenset`, or an instance of a subtype.
3381
3382
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003383.. cfunction:: Py_ssize_t PySet_GET_SIZE(PyObject *anyset)
Georg Brandl116aa622007-08-15 14:28:22 +00003384
3385 Macro form of :cfunc:`PySet_Size` without error checking.
3386
3387
3388.. cfunction:: int PySet_Contains(PyObject *anyset, PyObject *key)
3389
3390 Return 1 if found, 0 if not found, and -1 if an error is encountered. Unlike
3391 the Python :meth:`__contains__` method, this function does not automatically
3392 convert unhashable sets into temporary frozensets. Raise a :exc:`TypeError` if
3393 the *key* is unhashable. Raise :exc:`PyExc_SystemError` if *anyset* is not a
3394 :class:`set`, :class:`frozenset`, or an instance of a subtype.
3395
3396The following functions are available for instances of :class:`set` or its
3397subtypes but not for instances of :class:`frozenset` or its subtypes.
3398
3399
3400.. cfunction:: int PySet_Add(PyObject *set, PyObject *key)
3401
3402 Add *key* to a :class:`set` instance. Does not apply to :class:`frozenset`
3403 instances. Return 0 on success or -1 on failure. Raise a :exc:`TypeError` if
3404 the *key* is unhashable. Raise a :exc:`MemoryError` if there is no room to grow.
3405 Raise a :exc:`SystemError` if *set* is an not an instance of :class:`set` or its
3406 subtype.
3407
3408
3409.. cfunction:: int PySet_Discard(PyObject *set, PyObject *key)
3410
3411 Return 1 if found and removed, 0 if not found (no action taken), and -1 if an
3412 error is encountered. Does not raise :exc:`KeyError` for missing keys. Raise a
3413 :exc:`TypeError` if the *key* is unhashable. Unlike the Python :meth:`discard`
3414 method, this function does not automatically convert unhashable sets into
3415 temporary frozensets. Raise :exc:`PyExc_SystemError` if *set* is an not an
3416 instance of :class:`set` or its subtype.
3417
3418
3419.. cfunction:: PyObject* PySet_Pop(PyObject *set)
3420
3421 Return a new reference to an arbitrary object in the *set*, and removes the
3422 object from the *set*. Return *NULL* on failure. Raise :exc:`KeyError` if the
3423 set is empty. Raise a :exc:`SystemError` if *set* is an not an instance of
3424 :class:`set` or its subtype.
3425
3426
3427.. cfunction:: int PySet_Clear(PyObject *set)
3428
3429 Empty an existing set of all elements.
3430