blob: 2f4863a3d71ae8eaa9bd50f06f6a4e649ac00b97 [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
Christian Heimes93852662007-12-01 12:22:32 +0000502.. cfunction:: PyObject* PyFloat_GetInfo(void)
503
504 Return a :ctype:`PyDictObject` object which contains information about the
505 precision, minimum and maximum values of a float. It's a thin wrapper
506 around the header file :file:`float.h`.
507
508
509.. cfunction:: double PyFloat_GetMax(void)
510
511 Return the maximum representable finite float *DBL_MAX* as C :ctype:`double`.
512
513
514.. cfunction:: double PyFloat_GetMin(void)
515
516 Return the minimum normalized positive float *DBL_MIN* as C :ctype:`double`.
517
518
Georg Brandl116aa622007-08-15 14:28:22 +0000519.. _complexobjects:
520
521Complex Number Objects
522----------------------
523
524.. index:: object: complex number
525
526Python's complex number objects are implemented as two distinct types when
527viewed from the C API: one is the Python object exposed to Python programs, and
528the other is a C structure which represents the actual complex number value.
529The API provides functions for working with both.
530
531
532Complex Numbers as C Structures
533^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
534
535Note that the functions which accept these structures as parameters and return
536them as results do so *by value* rather than dereferencing them through
537pointers. This is consistent throughout the API.
538
539
540.. ctype:: Py_complex
541
542 The C structure which corresponds to the value portion of a Python complex
543 number object. Most of the functions for dealing with complex number objects
544 use structures of this type as input or output values, as appropriate. It is
545 defined as::
546
547 typedef struct {
548 double real;
549 double imag;
550 } Py_complex;
551
552
553.. cfunction:: Py_complex _Py_c_sum(Py_complex left, Py_complex right)
554
555 Return the sum of two complex numbers, using the C :ctype:`Py_complex`
556 representation.
557
558
559.. cfunction:: Py_complex _Py_c_diff(Py_complex left, Py_complex right)
560
561 Return the difference between two complex numbers, using the C
562 :ctype:`Py_complex` representation.
563
564
565.. cfunction:: Py_complex _Py_c_neg(Py_complex complex)
566
567 Return the negation of the complex number *complex*, using the C
568 :ctype:`Py_complex` representation.
569
570
571.. cfunction:: Py_complex _Py_c_prod(Py_complex left, Py_complex right)
572
573 Return the product of two complex numbers, using the C :ctype:`Py_complex`
574 representation.
575
576
577.. cfunction:: Py_complex _Py_c_quot(Py_complex dividend, Py_complex divisor)
578
579 Return the quotient of two complex numbers, using the C :ctype:`Py_complex`
580 representation.
581
582
583.. cfunction:: Py_complex _Py_c_pow(Py_complex num, Py_complex exp)
584
585 Return the exponentiation of *num* by *exp*, using the C :ctype:`Py_complex`
586 representation.
587
588
589Complex Numbers as Python Objects
590^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
591
592
593.. ctype:: PyComplexObject
594
595 This subtype of :ctype:`PyObject` represents a Python complex number object.
596
597
598.. cvar:: PyTypeObject PyComplex_Type
599
600 This instance of :ctype:`PyTypeObject` represents the Python complex number
601 type. It is the same object as ``complex`` and ``types.ComplexType``.
602
603
604.. cfunction:: int PyComplex_Check(PyObject *p)
605
606 Return true if its argument is a :ctype:`PyComplexObject` or a subtype of
607 :ctype:`PyComplexObject`.
608
Georg Brandl116aa622007-08-15 14:28:22 +0000609
610.. cfunction:: int PyComplex_CheckExact(PyObject *p)
611
612 Return true if its argument is a :ctype:`PyComplexObject`, but not a subtype of
613 :ctype:`PyComplexObject`.
614
Georg Brandl116aa622007-08-15 14:28:22 +0000615
616.. cfunction:: PyObject* PyComplex_FromCComplex(Py_complex v)
617
618 Create a new Python complex number object from a C :ctype:`Py_complex` value.
619
620
621.. cfunction:: PyObject* PyComplex_FromDoubles(double real, double imag)
622
623 Return a new :ctype:`PyComplexObject` object from *real* and *imag*.
624
625
626.. cfunction:: double PyComplex_RealAsDouble(PyObject *op)
627
628 Return the real part of *op* as a C :ctype:`double`.
629
630
631.. cfunction:: double PyComplex_ImagAsDouble(PyObject *op)
632
633 Return the imaginary part of *op* as a C :ctype:`double`.
634
635
636.. cfunction:: Py_complex PyComplex_AsCComplex(PyObject *op)
637
638 Return the :ctype:`Py_complex` value of the complex number *op*.
639
Georg Brandl321976b2007-09-01 12:33:24 +0000640 If *op* is not a Python complex number object but has a :meth:`__complex__`
641 method, this method will first be called to convert *op* to a Python complex
642 number object.
Georg Brandl116aa622007-08-15 14:28:22 +0000643
644
645.. _sequenceobjects:
646
647Sequence Objects
648================
649
650.. index:: object: sequence
651
652Generic operations on sequence objects were discussed in the previous chapter;
653this section deals with the specific kinds of sequence objects that are
654intrinsic to the Python language.
655
656
657.. _stringobjects:
658
659String Objects
660--------------
661
662These functions raise :exc:`TypeError` when expecting a string parameter and are
663called with a non-string parameter.
664
665.. index:: object: string
666
667
668.. ctype:: PyStringObject
669
670 This subtype of :ctype:`PyObject` represents a Python string object.
671
672
673.. cvar:: PyTypeObject PyString_Type
674
675 .. index:: single: StringType (in module types)
676
677 This instance of :ctype:`PyTypeObject` represents the Python string type; it is
678 the same object as ``str`` and ``types.StringType`` in the Python layer. .
679
680
681.. cfunction:: int PyString_Check(PyObject *o)
682
683 Return true if the object *o* is a string object or an instance of a subtype of
684 the string type.
685
Georg Brandl116aa622007-08-15 14:28:22 +0000686
687.. cfunction:: int PyString_CheckExact(PyObject *o)
688
689 Return true if the object *o* is a string object, but not an instance of a
690 subtype of the string type.
691
Georg Brandl116aa622007-08-15 14:28:22 +0000692
693.. cfunction:: PyObject* PyString_FromString(const char *v)
694
695 Return a new string object with a copy of the string *v* as value on success,
696 and *NULL* on failure. The parameter *v* must not be *NULL*; it will not be
697 checked.
698
699
700.. cfunction:: PyObject* PyString_FromStringAndSize(const char *v, Py_ssize_t len)
701
702 Return a new string object with a copy of the string *v* as value and length
703 *len* on success, and *NULL* on failure. If *v* is *NULL*, the contents of the
704 string are uninitialized.
705
706
707.. cfunction:: PyObject* PyString_FromFormat(const char *format, ...)
708
709 Take a C :cfunc:`printf`\ -style *format* string and a variable number of
710 arguments, calculate the size of the resulting Python string and return a string
711 with the values formatted into it. The variable arguments must be C types and
712 must correspond exactly to the format characters in the *format* string. The
713 following format characters are allowed:
714
Georg Brandl321976b2007-09-01 12:33:24 +0000715 .. % XXX: This should be exactly the same as the table in PyErr_Format.
Georg Brandl116aa622007-08-15 14:28:22 +0000716 .. % One should just refer to the other.
Georg Brandl321976b2007-09-01 12:33:24 +0000717 .. % XXX: The descriptions for %zd and %zu are wrong, but the truth is complicated
Georg Brandl116aa622007-08-15 14:28:22 +0000718 .. % because not all compilers support the %z width modifier -- we fake it
719 .. % when necessary via interpolating PY_FORMAT_SIZE_T.
720 .. % %u, %lu, %zu should have "new in Python 2.5" blurbs.
721
722 +-------------------+---------------+--------------------------------+
723 | Format Characters | Type | Comment |
724 +===================+===============+================================+
725 | :attr:`%%` | *n/a* | The literal % character. |
726 +-------------------+---------------+--------------------------------+
727 | :attr:`%c` | int | A single character, |
728 | | | represented as an C int. |
729 +-------------------+---------------+--------------------------------+
730 | :attr:`%d` | int | Exactly equivalent to |
731 | | | ``printf("%d")``. |
732 +-------------------+---------------+--------------------------------+
733 | :attr:`%u` | unsigned int | Exactly equivalent to |
734 | | | ``printf("%u")``. |
735 +-------------------+---------------+--------------------------------+
736 | :attr:`%ld` | long | Exactly equivalent to |
737 | | | ``printf("%ld")``. |
738 +-------------------+---------------+--------------------------------+
739 | :attr:`%lu` | unsigned long | Exactly equivalent to |
740 | | | ``printf("%lu")``. |
741 +-------------------+---------------+--------------------------------+
742 | :attr:`%zd` | Py_ssize_t | Exactly equivalent to |
743 | | | ``printf("%zd")``. |
744 +-------------------+---------------+--------------------------------+
745 | :attr:`%zu` | size_t | Exactly equivalent to |
746 | | | ``printf("%zu")``. |
747 +-------------------+---------------+--------------------------------+
748 | :attr:`%i` | int | Exactly equivalent to |
749 | | | ``printf("%i")``. |
750 +-------------------+---------------+--------------------------------+
751 | :attr:`%x` | int | Exactly equivalent to |
752 | | | ``printf("%x")``. |
753 +-------------------+---------------+--------------------------------+
754 | :attr:`%s` | char\* | A null-terminated C character |
755 | | | array. |
756 +-------------------+---------------+--------------------------------+
757 | :attr:`%p` | void\* | The hex representation of a C |
758 | | | pointer. Mostly equivalent to |
759 | | | ``printf("%p")`` except that |
760 | | | it is guaranteed to start with |
761 | | | the literal ``0x`` regardless |
762 | | | of what the platform's |
763 | | | ``printf`` yields. |
764 +-------------------+---------------+--------------------------------+
765
766 An unrecognized format character causes all the rest of the format string to be
767 copied as-is to the result string, and any extra arguments discarded.
768
769
770.. cfunction:: PyObject* PyString_FromFormatV(const char *format, va_list vargs)
771
772 Identical to :func:`PyString_FromFormat` except that it takes exactly two
773 arguments.
774
775
776.. cfunction:: Py_ssize_t PyString_Size(PyObject *string)
777
778 Return the length of the string in string object *string*.
779
780
781.. cfunction:: Py_ssize_t PyString_GET_SIZE(PyObject *string)
782
783 Macro form of :cfunc:`PyString_Size` but without error checking.
784
785
786.. cfunction:: char* PyString_AsString(PyObject *string)
787
788 Return a NUL-terminated representation of the contents of *string*. The pointer
789 refers to the internal buffer of *string*, not a copy. The data must not be
790 modified in any way, unless the string was just created using
791 ``PyString_FromStringAndSize(NULL, size)``. It must not be deallocated. If
792 *string* is a Unicode object, this function computes the default encoding of
793 *string* and operates on that. If *string* is not a string object at all,
794 :cfunc:`PyString_AsString` returns *NULL* and raises :exc:`TypeError`.
795
796
797.. cfunction:: char* PyString_AS_STRING(PyObject *string)
798
799 Macro form of :cfunc:`PyString_AsString` but without error checking. Only
800 string objects are supported; no Unicode objects should be passed.
801
802
803.. cfunction:: int PyString_AsStringAndSize(PyObject *obj, char **buffer, Py_ssize_t *length)
804
805 Return a NUL-terminated representation of the contents of the object *obj*
806 through the output variables *buffer* and *length*.
807
808 The function accepts both string and Unicode objects as input. For Unicode
809 objects it returns the default encoded version of the object. If *length* is
810 *NULL*, the resulting buffer may not contain NUL characters; if it does, the
811 function returns ``-1`` and a :exc:`TypeError` is raised.
812
813 The buffer refers to an internal string buffer of *obj*, not a copy. The data
814 must not be modified in any way, unless the string was just created using
815 ``PyString_FromStringAndSize(NULL, size)``. It must not be deallocated. If
816 *string* is a Unicode object, this function computes the default encoding of
817 *string* and operates on that. If *string* is not a string object at all,
818 :cfunc:`PyString_AsStringAndSize` returns ``-1`` and raises :exc:`TypeError`.
819
820
821.. cfunction:: void PyString_Concat(PyObject **string, PyObject *newpart)
822
823 Create a new string object in *\*string* containing the contents of *newpart*
824 appended to *string*; the caller will own the new reference. The reference to
825 the old value of *string* will be stolen. If the new string cannot be created,
826 the old reference to *string* will still be discarded and the value of
827 *\*string* will be set to *NULL*; the appropriate exception will be set.
828
829
830.. cfunction:: void PyString_ConcatAndDel(PyObject **string, PyObject *newpart)
831
832 Create a new string object in *\*string* containing the contents of *newpart*
833 appended to *string*. This version decrements the reference count of *newpart*.
834
835
836.. cfunction:: int _PyString_Resize(PyObject **string, Py_ssize_t newsize)
837
838 A way to resize a string object even though it is "immutable". Only use this to
839 build up a brand new string object; don't use this if the string may already be
840 known in other parts of the code. It is an error to call this function if the
841 refcount on the input string object is not one. Pass the address of an existing
842 string object as an lvalue (it may be written into), and the new size desired.
843 On success, *\*string* holds the resized string object and ``0`` is returned;
844 the address in *\*string* may differ from its input value. If the reallocation
845 fails, the original string object at *\*string* is deallocated, *\*string* is
846 set to *NULL*, a memory exception is set, and ``-1`` is returned.
847
848
849.. cfunction:: PyObject* PyString_Format(PyObject *format, PyObject *args)
850
851 Return a new string object from *format* and *args*. Analogous to ``format %
852 args``. The *args* argument must be a tuple.
853
854
855.. cfunction:: void PyString_InternInPlace(PyObject **string)
856
857 Intern the argument *\*string* in place. The argument must be the address of a
858 pointer variable pointing to a Python string object. If there is an existing
859 interned string that is the same as *\*string*, it sets *\*string* to it
860 (decrementing the reference count of the old string object and incrementing the
861 reference count of the interned string object), otherwise it leaves *\*string*
862 alone and interns it (incrementing its reference count). (Clarification: even
863 though there is a lot of talk about reference counts, think of this function as
864 reference-count-neutral; you own the object after the call if and only if you
865 owned it before the call.)
866
867
868.. cfunction:: PyObject* PyString_InternFromString(const char *v)
869
870 A combination of :cfunc:`PyString_FromString` and
871 :cfunc:`PyString_InternInPlace`, returning either a new string object that has
872 been interned, or a new ("owned") reference to an earlier interned string object
873 with the same value.
874
875
876.. cfunction:: PyObject* PyString_Decode(const char *s, Py_ssize_t size, const char *encoding, const char *errors)
877
878 Create an object by decoding *size* bytes of the encoded buffer *s* using the
879 codec registered for *encoding*. *encoding* and *errors* have the same meaning
880 as the parameters of the same name in the :func:`unicode` built-in function.
881 The codec to be used is looked up using the Python codec registry. Return
882 *NULL* if an exception was raised by the codec.
883
884
885.. cfunction:: PyObject* PyString_AsDecodedObject(PyObject *str, const char *encoding, const char *errors)
886
887 Decode a string object by passing it to the codec registered for *encoding* and
888 return the result as Python object. *encoding* and *errors* have the same
889 meaning as the parameters of the same name in the string :meth:`encode` method.
890 The codec to be used is looked up using the Python codec registry. Return *NULL*
891 if an exception was raised by the codec.
892
893
Georg Brandl116aa622007-08-15 14:28:22 +0000894.. cfunction:: PyObject* PyString_AsEncodedObject(PyObject *str, const char *encoding, const char *errors)
895
896 Encode a string object using the codec registered for *encoding* and return the
897 result as Python object. *encoding* and *errors* have the same meaning as the
898 parameters of the same name in the string :meth:`encode` method. The codec to be
899 used is looked up using the Python codec registry. Return *NULL* if an exception
900 was raised by the codec.
901
902
903.. _unicodeobjects:
904
905Unicode Objects
906---------------
907
908.. sectionauthor:: Marc-Andre Lemburg <mal@lemburg.com>
909
910
911These are the basic Unicode object types used for the Unicode implementation in
912Python:
913
914.. % --- Unicode Type -------------------------------------------------------
915
916
917.. ctype:: Py_UNICODE
918
919 This type represents the storage type which is used by Python internally as
920 basis for holding Unicode ordinals. Python's default builds use a 16-bit type
921 for :ctype:`Py_UNICODE` and store Unicode values internally as UCS2. It is also
922 possible to build a UCS4 version of Python (most recent Linux distributions come
923 with UCS4 builds of Python). These builds then use a 32-bit type for
924 :ctype:`Py_UNICODE` and store Unicode data internally as UCS4. On platforms
925 where :ctype:`wchar_t` is available and compatible with the chosen Python
926 Unicode build variant, :ctype:`Py_UNICODE` is a typedef alias for
927 :ctype:`wchar_t` to enhance native platform compatibility. On all other
928 platforms, :ctype:`Py_UNICODE` is a typedef alias for either :ctype:`unsigned
929 short` (UCS2) or :ctype:`unsigned long` (UCS4).
930
931Note that UCS2 and UCS4 Python builds are not binary compatible. Please keep
932this in mind when writing extensions or interfaces.
933
934
935.. ctype:: PyUnicodeObject
936
937 This subtype of :ctype:`PyObject` represents a Python Unicode object.
938
939
940.. cvar:: PyTypeObject PyUnicode_Type
941
942 This instance of :ctype:`PyTypeObject` represents the Python Unicode type. It
Collin Winterd1d9a892007-08-28 06:09:47 +0000943 is exposed to Python code as ``str``.
Georg Brandl116aa622007-08-15 14:28:22 +0000944
945The following APIs are really C macros and can be used to do fast checks and to
946access internal read-only data of Unicode objects:
947
948
949.. cfunction:: int PyUnicode_Check(PyObject *o)
950
951 Return true if the object *o* is a Unicode object or an instance of a Unicode
952 subtype.
953
Georg Brandl116aa622007-08-15 14:28:22 +0000954
955.. cfunction:: int PyUnicode_CheckExact(PyObject *o)
956
957 Return true if the object *o* is a Unicode object, but not an instance of a
958 subtype.
959
Georg Brandl116aa622007-08-15 14:28:22 +0000960
961.. cfunction:: Py_ssize_t PyUnicode_GET_SIZE(PyObject *o)
962
963 Return the size of the object. *o* has to be a :ctype:`PyUnicodeObject` (not
964 checked).
965
966
967.. cfunction:: Py_ssize_t PyUnicode_GET_DATA_SIZE(PyObject *o)
968
969 Return the size of the object's internal buffer in bytes. *o* has to be a
970 :ctype:`PyUnicodeObject` (not checked).
971
972
973.. cfunction:: Py_UNICODE* PyUnicode_AS_UNICODE(PyObject *o)
974
975 Return a pointer to the internal :ctype:`Py_UNICODE` buffer of the object. *o*
976 has to be a :ctype:`PyUnicodeObject` (not checked).
977
978
979.. cfunction:: const char* PyUnicode_AS_DATA(PyObject *o)
980
981 Return a pointer to the internal buffer of the object. *o* has to be a
982 :ctype:`PyUnicodeObject` (not checked).
983
984Unicode provides many different character properties. The most often needed ones
985are available through these macros which are mapped to C functions depending on
986the Python configuration.
987
988.. % --- Unicode character properties ---------------------------------------
989
990
991.. cfunction:: int Py_UNICODE_ISSPACE(Py_UNICODE ch)
992
993 Return 1 or 0 depending on whether *ch* is a whitespace character.
994
995
996.. cfunction:: int Py_UNICODE_ISLOWER(Py_UNICODE ch)
997
998 Return 1 or 0 depending on whether *ch* is a lowercase character.
999
1000
1001.. cfunction:: int Py_UNICODE_ISUPPER(Py_UNICODE ch)
1002
1003 Return 1 or 0 depending on whether *ch* is an uppercase character.
1004
1005
1006.. cfunction:: int Py_UNICODE_ISTITLE(Py_UNICODE ch)
1007
1008 Return 1 or 0 depending on whether *ch* is a titlecase character.
1009
1010
1011.. cfunction:: int Py_UNICODE_ISLINEBREAK(Py_UNICODE ch)
1012
1013 Return 1 or 0 depending on whether *ch* is a linebreak character.
1014
1015
1016.. cfunction:: int Py_UNICODE_ISDECIMAL(Py_UNICODE ch)
1017
1018 Return 1 or 0 depending on whether *ch* is a decimal character.
1019
1020
1021.. cfunction:: int Py_UNICODE_ISDIGIT(Py_UNICODE ch)
1022
1023 Return 1 or 0 depending on whether *ch* is a digit character.
1024
1025
1026.. cfunction:: int Py_UNICODE_ISNUMERIC(Py_UNICODE ch)
1027
1028 Return 1 or 0 depending on whether *ch* is a numeric character.
1029
1030
1031.. cfunction:: int Py_UNICODE_ISALPHA(Py_UNICODE ch)
1032
1033 Return 1 or 0 depending on whether *ch* is an alphabetic character.
1034
1035
1036.. cfunction:: int Py_UNICODE_ISALNUM(Py_UNICODE ch)
1037
1038 Return 1 or 0 depending on whether *ch* is an alphanumeric character.
1039
1040These APIs can be used for fast direct character conversions:
1041
1042
1043.. cfunction:: Py_UNICODE Py_UNICODE_TOLOWER(Py_UNICODE ch)
1044
1045 Return the character *ch* converted to lower case.
1046
1047
1048.. cfunction:: Py_UNICODE Py_UNICODE_TOUPPER(Py_UNICODE ch)
1049
1050 Return the character *ch* converted to upper case.
1051
1052
1053.. cfunction:: Py_UNICODE Py_UNICODE_TOTITLE(Py_UNICODE ch)
1054
1055 Return the character *ch* converted to title case.
1056
1057
1058.. cfunction:: int Py_UNICODE_TODECIMAL(Py_UNICODE ch)
1059
1060 Return the character *ch* converted to a decimal positive integer. Return
1061 ``-1`` if this is not possible. This macro does not raise exceptions.
1062
1063
1064.. cfunction:: int Py_UNICODE_TODIGIT(Py_UNICODE ch)
1065
1066 Return the character *ch* converted to a single digit integer. Return ``-1`` if
1067 this is not possible. This macro does not raise exceptions.
1068
1069
1070.. cfunction:: double Py_UNICODE_TONUMERIC(Py_UNICODE ch)
1071
1072 Return the character *ch* converted to a double. Return ``-1.0`` if this is not
1073 possible. This macro does not raise exceptions.
1074
1075To create Unicode objects and access their basic sequence properties, use these
1076APIs:
1077
1078.. % --- Plain Py_UNICODE ---------------------------------------------------
1079
1080
1081.. cfunction:: PyObject* PyUnicode_FromUnicode(const Py_UNICODE *u, Py_ssize_t size)
1082
1083 Create a Unicode Object from the Py_UNICODE buffer *u* of the given size. *u*
1084 may be *NULL* which causes the contents to be undefined. It is the user's
1085 responsibility to fill in the needed data. The buffer is copied into the new
1086 object. If the buffer is not *NULL*, the return value might be a shared object.
1087 Therefore, modification of the resulting Unicode object is only allowed when *u*
1088 is *NULL*.
1089
1090
1091.. cfunction:: PyObject* PyUnicode_FromStringAndSize(const char *u, Py_ssize_t size)
1092
1093 Create a Unicode Object from the char buffer *u*. The bytes will be interpreted
1094 as being UTF-8 encoded. *u* may also be *NULL* which
1095 causes the contents to be undefined. It is the user's responsibility to fill in
1096 the needed data. The buffer is copied into the new object. If the buffer is not
1097 *NULL*, the return value might be a shared object. Therefore, modification of
1098 the resulting Unicode object is only allowed when *u* is *NULL*.
1099
Georg Brandl116aa622007-08-15 14:28:22 +00001100
1101.. cfunction:: PyObject *PyUnicode_FromString(const char *u)
1102
1103 Create a Unicode object from an UTF-8 encoded null-terminated char buffer
1104 *u*.
1105
Georg Brandl116aa622007-08-15 14:28:22 +00001106
1107.. cfunction:: PyObject* PyUnicode_FromFormat(const char *format, ...)
1108
1109 Take a C :cfunc:`printf`\ -style *format* string and a variable number of
1110 arguments, calculate the size of the resulting Python unicode string and return
1111 a string with the values formatted into it. The variable arguments must be C
1112 types and must correspond exactly to the format characters in the *format*
1113 string. The following format characters are allowed:
1114
1115 .. % The descriptions for %zd and %zu are wrong, but the truth is complicated
1116 .. % because not all compilers support the %z width modifier -- we fake it
1117 .. % when necessary via interpolating PY_FORMAT_SIZE_T.
1118
1119 +-------------------+---------------------+--------------------------------+
1120 | Format Characters | Type | Comment |
1121 +===================+=====================+================================+
1122 | :attr:`%%` | *n/a* | The literal % character. |
1123 +-------------------+---------------------+--------------------------------+
1124 | :attr:`%c` | int | A single character, |
1125 | | | represented as an C int. |
1126 +-------------------+---------------------+--------------------------------+
1127 | :attr:`%d` | int | Exactly equivalent to |
1128 | | | ``printf("%d")``. |
1129 +-------------------+---------------------+--------------------------------+
1130 | :attr:`%u` | unsigned int | Exactly equivalent to |
1131 | | | ``printf("%u")``. |
1132 +-------------------+---------------------+--------------------------------+
1133 | :attr:`%ld` | long | Exactly equivalent to |
1134 | | | ``printf("%ld")``. |
1135 +-------------------+---------------------+--------------------------------+
1136 | :attr:`%lu` | unsigned long | Exactly equivalent to |
1137 | | | ``printf("%lu")``. |
1138 +-------------------+---------------------+--------------------------------+
1139 | :attr:`%zd` | Py_ssize_t | Exactly equivalent to |
1140 | | | ``printf("%zd")``. |
1141 +-------------------+---------------------+--------------------------------+
1142 | :attr:`%zu` | size_t | Exactly equivalent to |
1143 | | | ``printf("%zu")``. |
1144 +-------------------+---------------------+--------------------------------+
1145 | :attr:`%i` | int | Exactly equivalent to |
1146 | | | ``printf("%i")``. |
1147 +-------------------+---------------------+--------------------------------+
1148 | :attr:`%x` | int | Exactly equivalent to |
1149 | | | ``printf("%x")``. |
1150 +-------------------+---------------------+--------------------------------+
1151 | :attr:`%s` | char\* | A null-terminated C character |
1152 | | | array. |
1153 +-------------------+---------------------+--------------------------------+
1154 | :attr:`%p` | void\* | The hex representation of a C |
1155 | | | pointer. Mostly equivalent to |
1156 | | | ``printf("%p")`` except that |
1157 | | | it is guaranteed to start with |
1158 | | | the literal ``0x`` regardless |
1159 | | | of what the platform's |
1160 | | | ``printf`` yields. |
1161 +-------------------+---------------------+--------------------------------+
1162 | :attr:`%U` | PyObject\* | A unicode object. |
1163 +-------------------+---------------------+--------------------------------+
1164 | :attr:`%V` | PyObject\*, char \* | A unicode object (which may be |
1165 | | | *NULL*) and a null-terminated |
1166 | | | C character array as a second |
1167 | | | parameter (which will be used, |
1168 | | | if the first parameter is |
1169 | | | *NULL*). |
1170 +-------------------+---------------------+--------------------------------+
1171 | :attr:`%S` | PyObject\* | The result of calling |
1172 | | | :func:`PyObject_Unicode`. |
1173 +-------------------+---------------------+--------------------------------+
1174 | :attr:`%R` | PyObject\* | The result of calling |
1175 | | | :func:`PyObject_Repr`. |
1176 +-------------------+---------------------+--------------------------------+
1177
1178 An unrecognized format character causes all the rest of the format string to be
1179 copied as-is to the result string, and any extra arguments discarded.
1180
Georg Brandl116aa622007-08-15 14:28:22 +00001181
1182.. cfunction:: PyObject* PyUnicode_FromFormatV(const char *format, va_list vargs)
1183
1184 Identical to :func:`PyUnicode_FromFormat` except that it takes exactly two
1185 arguments.
1186
Georg Brandl116aa622007-08-15 14:28:22 +00001187
1188.. cfunction:: Py_UNICODE* PyUnicode_AsUnicode(PyObject *unicode)
1189
1190 Return a read-only pointer to the Unicode object's internal :ctype:`Py_UNICODE`
1191 buffer, *NULL* if *unicode* is not a Unicode object.
1192
1193
1194.. cfunction:: Py_ssize_t PyUnicode_GetSize(PyObject *unicode)
1195
1196 Return the length of the Unicode object.
1197
1198
1199.. cfunction:: PyObject* PyUnicode_FromEncodedObject(PyObject *obj, const char *encoding, const char *errors)
1200
1201 Coerce an encoded object *obj* to an Unicode object and return a reference with
1202 incremented refcount.
1203
1204 String and other char buffer compatible objects are decoded according to the
1205 given encoding and using the error handling defined by errors. Both can be
1206 *NULL* to have the interface use the default values (see the next section for
1207 details).
1208
1209 All other objects, including Unicode objects, cause a :exc:`TypeError` to be
1210 set.
1211
1212 The API returns *NULL* if there was an error. The caller is responsible for
1213 decref'ing the returned objects.
1214
1215
1216.. cfunction:: PyObject* PyUnicode_FromObject(PyObject *obj)
1217
1218 Shortcut for ``PyUnicode_FromEncodedObject(obj, NULL, "strict")`` which is used
1219 throughout the interpreter whenever coercion to Unicode is needed.
1220
1221If the platform supports :ctype:`wchar_t` and provides a header file wchar.h,
1222Python can interface directly to this type using the following functions.
1223Support is optimized if Python's own :ctype:`Py_UNICODE` type is identical to
1224the system's :ctype:`wchar_t`.
1225
1226.. % --- wchar_t support for platforms which support it ---------------------
1227
1228
1229.. cfunction:: PyObject* PyUnicode_FromWideChar(const wchar_t *w, Py_ssize_t size)
1230
1231 Create a Unicode object from the :ctype:`wchar_t` buffer *w* of the given size.
1232 Return *NULL* on failure.
1233
1234
1235.. cfunction:: Py_ssize_t PyUnicode_AsWideChar(PyUnicodeObject *unicode, wchar_t *w, Py_ssize_t size)
1236
1237 Copy the Unicode object contents into the :ctype:`wchar_t` buffer *w*. At most
1238 *size* :ctype:`wchar_t` characters are copied (excluding a possibly trailing
1239 0-termination character). Return the number of :ctype:`wchar_t` characters
1240 copied or -1 in case of an error. Note that the resulting :ctype:`wchar_t`
1241 string may or may not be 0-terminated. It is the responsibility of the caller
1242 to make sure that the :ctype:`wchar_t` string is 0-terminated in case this is
1243 required by the application.
1244
1245
1246.. _builtincodecs:
1247
1248Built-in Codecs
1249^^^^^^^^^^^^^^^
1250
1251Python provides a set of builtin codecs which are written in C for speed. All of
1252these codecs are directly usable via the following functions.
1253
1254Many of the following APIs take two arguments encoding and errors. These
1255parameters encoding and errors have the same semantics as the ones of the
1256builtin unicode() Unicode object constructor.
1257
1258Setting encoding to *NULL* causes the default encoding to be used which is
1259ASCII. The file system calls should use :cdata:`Py_FileSystemDefaultEncoding`
1260as the encoding for file names. This variable should be treated as read-only: On
1261some systems, it will be a pointer to a static string, on others, it will change
1262at run-time (such as when the application invokes setlocale).
1263
1264Error handling is set by errors which may also be set to *NULL* meaning to use
1265the default handling defined for the codec. Default error handling for all
1266builtin codecs is "strict" (:exc:`ValueError` is raised).
1267
1268The codecs all use a similar interface. Only deviation from the following
1269generic ones are documented for simplicity.
1270
1271These are the generic codec APIs:
1272
1273.. % --- Generic Codecs -----------------------------------------------------
1274
1275
1276.. cfunction:: PyObject* PyUnicode_Decode(const char *s, Py_ssize_t size, const char *encoding, const char *errors)
1277
1278 Create a Unicode object by decoding *size* bytes of the encoded string *s*.
1279 *encoding* and *errors* have the same meaning as the parameters of the same name
1280 in the :func:`unicode` builtin function. The codec to be used is looked up
1281 using the Python codec registry. Return *NULL* if an exception was raised by
1282 the codec.
1283
1284
1285.. cfunction:: PyObject* PyUnicode_Encode(const Py_UNICODE *s, Py_ssize_t size, const char *encoding, const char *errors)
1286
1287 Encode the :ctype:`Py_UNICODE` buffer of the given size and return a Python
1288 string object. *encoding* and *errors* have the same meaning as the parameters
1289 of the same name in the Unicode :meth:`encode` method. The codec to be used is
1290 looked up using the Python codec registry. Return *NULL* if an exception was
1291 raised by the codec.
1292
1293
1294.. cfunction:: PyObject* PyUnicode_AsEncodedString(PyObject *unicode, const char *encoding, const char *errors)
1295
1296 Encode a Unicode object and return the result as Python string object.
1297 *encoding* and *errors* have the same meaning as the parameters of the same name
1298 in the Unicode :meth:`encode` method. The codec to be used is looked up using
1299 the Python codec registry. Return *NULL* if an exception was raised by the
1300 codec.
1301
1302These are the UTF-8 codec APIs:
1303
1304.. % --- UTF-8 Codecs -------------------------------------------------------
1305
1306
1307.. cfunction:: PyObject* PyUnicode_DecodeUTF8(const char *s, Py_ssize_t size, const char *errors)
1308
1309 Create a Unicode object by decoding *size* bytes of the UTF-8 encoded string
1310 *s*. Return *NULL* if an exception was raised by the codec.
1311
1312
1313.. cfunction:: PyObject* PyUnicode_DecodeUTF8Stateful(const char *s, Py_ssize_t size, const char *errors, Py_ssize_t *consumed)
1314
1315 If *consumed* is *NULL*, behave like :cfunc:`PyUnicode_DecodeUTF8`. If
1316 *consumed* is not *NULL*, trailing incomplete UTF-8 byte sequences will not be
1317 treated as an error. Those bytes will not be decoded and the number of bytes
1318 that have been decoded will be stored in *consumed*.
1319
Georg Brandl116aa622007-08-15 14:28:22 +00001320
1321.. cfunction:: PyObject* PyUnicode_EncodeUTF8(const Py_UNICODE *s, Py_ssize_t size, const char *errors)
1322
1323 Encode the :ctype:`Py_UNICODE` buffer of the given size using UTF-8 and return a
1324 Python string object. Return *NULL* if an exception was raised by the codec.
1325
1326
1327.. cfunction:: PyObject* PyUnicode_AsUTF8String(PyObject *unicode)
1328
1329 Encode a Unicode objects using UTF-8 and return the result as Python string
1330 object. Error handling is "strict". Return *NULL* if an exception was raised
1331 by the codec.
1332
Walter Dörwald41980ca2007-08-16 21:55:45 +00001333These are the UTF-32 codec APIs:
1334
1335.. % --- UTF-32 Codecs ------------------------------------------------------ */
1336
1337
1338.. cfunction:: PyObject* PyUnicode_DecodeUTF32(const char *s, Py_ssize_t size, const char *errors, int *byteorder)
1339
1340 Decode *length* bytes from a UTF-32 encoded buffer string and return the
1341 corresponding Unicode object. *errors* (if non-*NULL*) defines the error
1342 handling. It defaults to "strict".
1343
1344 If *byteorder* is non-*NULL*, the decoder starts decoding using the given byte
1345 order::
1346
1347 *byteorder == -1: little endian
1348 *byteorder == 0: native order
1349 *byteorder == 1: big endian
1350
1351 and then switches if the first four bytes of the input data are a byte order mark
1352 (BOM) and the specified byte order is native order. This BOM is not copied into
1353 the resulting Unicode string. After completion, *\*byteorder* is set to the
1354 current byte order at the end of input data.
1355
1356 In a narrow build codepoints outside the BMP will be decoded as surrogate pairs.
1357
1358 If *byteorder* is *NULL*, the codec starts in native order mode.
1359
1360 Return *NULL* if an exception was raised by the codec.
1361
Walter Dörwald41980ca2007-08-16 21:55:45 +00001362
1363.. cfunction:: PyObject* PyUnicode_DecodeUTF32Stateful(const char *s, Py_ssize_t size, const char *errors, int *byteorder, Py_ssize_t *consumed)
1364
1365 If *consumed* is *NULL*, behave like :cfunc:`PyUnicode_DecodeUTF32`. If
1366 *consumed* is not *NULL*, :cfunc:`PyUnicode_DecodeUTF32Stateful` will not treat
1367 trailing incomplete UTF-32 byte sequences (such as a number of bytes not divisible
1368 by four) as an error. Those bytes will not be decoded and the number of bytes
1369 that have been decoded will be stored in *consumed*.
1370
Walter Dörwald41980ca2007-08-16 21:55:45 +00001371
1372.. cfunction:: PyObject* PyUnicode_EncodeUTF32(const Py_UNICODE *s, Py_ssize_t size, const char *errors, int byteorder)
1373
1374 Return a Python bytes object holding the UTF-32 encoded value of the Unicode
1375 data in *s*. If *byteorder* is not ``0``, output is written according to the
1376 following byte order::
1377
1378 byteorder == -1: little endian
1379 byteorder == 0: native byte order (writes a BOM mark)
1380 byteorder == 1: big endian
1381
1382 If byteorder is ``0``, the output string will always start with the Unicode BOM
1383 mark (U+FEFF). In the other two modes, no BOM mark is prepended.
1384
1385 If *Py_UNICODE_WIDE* is not defined, surrogate pairs will be output
1386 as a single codepoint.
1387
1388 Return *NULL* if an exception was raised by the codec.
1389
1390
1391.. cfunction:: PyObject* PyUnicode_AsUTF32String(PyObject *unicode)
1392
1393 Return a Python string using the UTF-32 encoding in native byte order. The
1394 string always starts with a BOM mark. Error handling is "strict". Return
1395 *NULL* if an exception was raised by the codec.
1396
Walter Dörwald19e62382007-08-17 16:23:21 +00001397
Georg Brandl116aa622007-08-15 14:28:22 +00001398These are the UTF-16 codec APIs:
1399
1400.. % --- UTF-16 Codecs ------------------------------------------------------ */
1401
1402
1403.. cfunction:: PyObject* PyUnicode_DecodeUTF16(const char *s, Py_ssize_t size, const char *errors, int *byteorder)
1404
1405 Decode *length* bytes from a UTF-16 encoded buffer string and return the
1406 corresponding Unicode object. *errors* (if non-*NULL*) defines the error
1407 handling. It defaults to "strict".
1408
1409 If *byteorder* is non-*NULL*, the decoder starts decoding using the given byte
1410 order::
1411
1412 *byteorder == -1: little endian
1413 *byteorder == 0: native order
1414 *byteorder == 1: big endian
1415
1416 and then switches if the first two bytes of the input data are a byte order mark
1417 (BOM) and the specified byte order is native order. This BOM is not copied into
1418 the resulting Unicode string. After completion, *\*byteorder* is set to the
Walter Dörwaldd9a15792007-08-16 16:55:51 +00001419 current byte order at the end of input data.
Georg Brandl116aa622007-08-15 14:28:22 +00001420
1421 If *byteorder* is *NULL*, the codec starts in native order mode.
1422
1423 Return *NULL* if an exception was raised by the codec.
1424
1425
1426.. cfunction:: PyObject* PyUnicode_DecodeUTF16Stateful(const char *s, Py_ssize_t size, const char *errors, int *byteorder, Py_ssize_t *consumed)
1427
1428 If *consumed* is *NULL*, behave like :cfunc:`PyUnicode_DecodeUTF16`. If
1429 *consumed* is not *NULL*, :cfunc:`PyUnicode_DecodeUTF16Stateful` will not treat
1430 trailing incomplete UTF-16 byte sequences (such as an odd number of bytes or a
1431 split surrogate pair) as an error. Those bytes will not be decoded and the
1432 number of bytes that have been decoded will be stored in *consumed*.
1433
Georg Brandl116aa622007-08-15 14:28:22 +00001434
1435.. cfunction:: PyObject* PyUnicode_EncodeUTF16(const Py_UNICODE *s, Py_ssize_t size, const char *errors, int byteorder)
1436
1437 Return a Python string object holding the UTF-16 encoded value of the Unicode
1438 data in *s*. If *byteorder* is not ``0``, output is written according to the
1439 following byte order::
1440
1441 byteorder == -1: little endian
1442 byteorder == 0: native byte order (writes a BOM mark)
1443 byteorder == 1: big endian
1444
1445 If byteorder is ``0``, the output string will always start with the Unicode BOM
1446 mark (U+FEFF). In the other two modes, no BOM mark is prepended.
1447
1448 If *Py_UNICODE_WIDE* is defined, a single :ctype:`Py_UNICODE` value may get
1449 represented as a surrogate pair. If it is not defined, each :ctype:`Py_UNICODE`
1450 values is interpreted as an UCS-2 character.
1451
1452 Return *NULL* if an exception was raised by the codec.
1453
1454
1455.. cfunction:: PyObject* PyUnicode_AsUTF16String(PyObject *unicode)
1456
1457 Return a Python string using the UTF-16 encoding in native byte order. The
1458 string always starts with a BOM mark. Error handling is "strict". Return
1459 *NULL* if an exception was raised by the codec.
1460
1461These are the "Unicode Escape" codec APIs:
1462
1463.. % --- Unicode-Escape Codecs ----------------------------------------------
1464
1465
1466.. cfunction:: PyObject* PyUnicode_DecodeUnicodeEscape(const char *s, Py_ssize_t size, const char *errors)
1467
1468 Create a Unicode object by decoding *size* bytes of the Unicode-Escape encoded
1469 string *s*. Return *NULL* if an exception was raised by the codec.
1470
1471
1472.. cfunction:: PyObject* PyUnicode_EncodeUnicodeEscape(const Py_UNICODE *s, Py_ssize_t size)
1473
1474 Encode the :ctype:`Py_UNICODE` buffer of the given size using Unicode-Escape and
1475 return a Python string object. Return *NULL* if an exception was raised by the
1476 codec.
1477
1478
1479.. cfunction:: PyObject* PyUnicode_AsUnicodeEscapeString(PyObject *unicode)
1480
1481 Encode a Unicode objects using Unicode-Escape and return the result as Python
1482 string object. Error handling is "strict". Return *NULL* if an exception was
1483 raised by the codec.
1484
1485These are the "Raw Unicode Escape" codec APIs:
1486
1487.. % --- Raw-Unicode-Escape Codecs ------------------------------------------
1488
1489
1490.. cfunction:: PyObject* PyUnicode_DecodeRawUnicodeEscape(const char *s, Py_ssize_t size, const char *errors)
1491
1492 Create a Unicode object by decoding *size* bytes of the Raw-Unicode-Escape
1493 encoded string *s*. Return *NULL* if an exception was raised by the codec.
1494
1495
1496.. cfunction:: PyObject* PyUnicode_EncodeRawUnicodeEscape(const Py_UNICODE *s, Py_ssize_t size, const char *errors)
1497
1498 Encode the :ctype:`Py_UNICODE` buffer of the given size using Raw-Unicode-Escape
1499 and return a Python string object. Return *NULL* if an exception was raised by
1500 the codec.
1501
1502
1503.. cfunction:: PyObject* PyUnicode_AsRawUnicodeEscapeString(PyObject *unicode)
1504
1505 Encode a Unicode objects using Raw-Unicode-Escape and return the result as
1506 Python string object. Error handling is "strict". Return *NULL* if an exception
1507 was raised by the codec.
1508
1509These are the Latin-1 codec APIs: Latin-1 corresponds to the first 256 Unicode
1510ordinals and only these are accepted by the codecs during encoding.
1511
1512.. % --- Latin-1 Codecs -----------------------------------------------------
1513
1514
1515.. cfunction:: PyObject* PyUnicode_DecodeLatin1(const char *s, Py_ssize_t size, const char *errors)
1516
1517 Create a Unicode object by decoding *size* bytes of the Latin-1 encoded string
1518 *s*. Return *NULL* if an exception was raised by the codec.
1519
1520
1521.. cfunction:: PyObject* PyUnicode_EncodeLatin1(const Py_UNICODE *s, Py_ssize_t size, const char *errors)
1522
1523 Encode the :ctype:`Py_UNICODE` buffer of the given size using Latin-1 and return
1524 a Python string object. Return *NULL* if an exception was raised by the codec.
1525
1526
1527.. cfunction:: PyObject* PyUnicode_AsLatin1String(PyObject *unicode)
1528
1529 Encode a Unicode objects using Latin-1 and return the result as Python string
1530 object. Error handling is "strict". Return *NULL* if an exception was raised
1531 by the codec.
1532
1533These are the ASCII codec APIs. Only 7-bit ASCII data is accepted. All other
1534codes generate errors.
1535
1536.. % --- ASCII Codecs -------------------------------------------------------
1537
1538
1539.. cfunction:: PyObject* PyUnicode_DecodeASCII(const char *s, Py_ssize_t size, const char *errors)
1540
1541 Create a Unicode object by decoding *size* bytes of the ASCII encoded string
1542 *s*. Return *NULL* if an exception was raised by the codec.
1543
1544
1545.. cfunction:: PyObject* PyUnicode_EncodeASCII(const Py_UNICODE *s, Py_ssize_t size, const char *errors)
1546
1547 Encode the :ctype:`Py_UNICODE` buffer of the given size using ASCII and return a
1548 Python string object. Return *NULL* if an exception was raised by the codec.
1549
1550
1551.. cfunction:: PyObject* PyUnicode_AsASCIIString(PyObject *unicode)
1552
1553 Encode a Unicode objects using ASCII and return the result as Python string
1554 object. Error handling is "strict". Return *NULL* if an exception was raised
1555 by the codec.
1556
1557These are the mapping codec APIs:
1558
1559.. % --- Character Map Codecs -----------------------------------------------
1560
1561This codec is special in that it can be used to implement many different codecs
1562(and this is in fact what was done to obtain most of the standard codecs
1563included in the :mod:`encodings` package). The codec uses mapping to encode and
1564decode characters.
1565
1566Decoding mappings must map single string characters to single Unicode
1567characters, integers (which are then interpreted as Unicode ordinals) or None
1568(meaning "undefined mapping" and causing an error).
1569
1570Encoding mappings must map single Unicode characters to single string
1571characters, integers (which are then interpreted as Latin-1 ordinals) or None
1572(meaning "undefined mapping" and causing an error).
1573
1574The mapping objects provided must only support the __getitem__ mapping
1575interface.
1576
1577If a character lookup fails with a LookupError, the character is copied as-is
1578meaning that its ordinal value will be interpreted as Unicode or Latin-1 ordinal
1579resp. Because of this, mappings only need to contain those mappings which map
1580characters to different code points.
1581
1582
1583.. cfunction:: PyObject* PyUnicode_DecodeCharmap(const char *s, Py_ssize_t size, PyObject *mapping, const char *errors)
1584
1585 Create a Unicode object by decoding *size* bytes of the encoded string *s* using
1586 the given *mapping* object. Return *NULL* if an exception was raised by the
1587 codec. If *mapping* is *NULL* latin-1 decoding will be done. Else it can be a
1588 dictionary mapping byte or a unicode string, which is treated as a lookup table.
1589 Byte values greater that the length of the string and U+FFFE "characters" are
1590 treated as "undefined mapping".
1591
Georg Brandl116aa622007-08-15 14:28:22 +00001592
1593.. cfunction:: PyObject* PyUnicode_EncodeCharmap(const Py_UNICODE *s, Py_ssize_t size, PyObject *mapping, const char *errors)
1594
1595 Encode the :ctype:`Py_UNICODE` buffer of the given size using the given
1596 *mapping* object and return a Python string object. Return *NULL* if an
1597 exception was raised by the codec.
1598
1599
1600.. cfunction:: PyObject* PyUnicode_AsCharmapString(PyObject *unicode, PyObject *mapping)
1601
1602 Encode a Unicode objects using the given *mapping* object and return the result
1603 as Python string object. Error handling is "strict". Return *NULL* if an
1604 exception was raised by the codec.
1605
1606The following codec API is special in that maps Unicode to Unicode.
1607
1608
1609.. cfunction:: PyObject* PyUnicode_TranslateCharmap(const Py_UNICODE *s, Py_ssize_t size, PyObject *table, const char *errors)
1610
1611 Translate a :ctype:`Py_UNICODE` buffer of the given length by applying a
1612 character mapping *table* to it and return the resulting Unicode object. Return
1613 *NULL* when an exception was raised by the codec.
1614
1615 The *mapping* table must map Unicode ordinal integers to Unicode ordinal
1616 integers or None (causing deletion of the character).
1617
1618 Mapping tables need only provide the :meth:`__getitem__` interface; dictionaries
1619 and sequences work well. Unmapped character ordinals (ones which cause a
1620 :exc:`LookupError`) are left untouched and are copied as-is.
1621
1622These are the MBCS codec APIs. They are currently only available on Windows and
1623use the Win32 MBCS converters to implement the conversions. Note that MBCS (or
1624DBCS) is a class of encodings, not just one. The target encoding is defined by
1625the user settings on the machine running the codec.
1626
1627.. % --- MBCS codecs for Windows --------------------------------------------
1628
1629
1630.. cfunction:: PyObject* PyUnicode_DecodeMBCS(const char *s, Py_ssize_t size, const char *errors)
1631
1632 Create a Unicode object by decoding *size* bytes of the MBCS encoded string *s*.
1633 Return *NULL* if an exception was raised by the codec.
1634
1635
1636.. cfunction:: PyObject* PyUnicode_DecodeMBCSStateful(const char *s, int size, const char *errors, int *consumed)
1637
1638 If *consumed* is *NULL*, behave like :cfunc:`PyUnicode_DecodeMBCS`. If
1639 *consumed* is not *NULL*, :cfunc:`PyUnicode_DecodeMBCSStateful` will not decode
1640 trailing lead byte and the number of bytes that have been decoded will be stored
1641 in *consumed*.
1642
Georg Brandl116aa622007-08-15 14:28:22 +00001643
1644.. cfunction:: PyObject* PyUnicode_EncodeMBCS(const Py_UNICODE *s, Py_ssize_t size, const char *errors)
1645
1646 Encode the :ctype:`Py_UNICODE` buffer of the given size using MBCS and return a
1647 Python string object. Return *NULL* if an exception was raised by the codec.
1648
1649
1650.. cfunction:: PyObject* PyUnicode_AsMBCSString(PyObject *unicode)
1651
1652 Encode a Unicode objects using MBCS and return the result as Python string
1653 object. Error handling is "strict". Return *NULL* if an exception was raised
1654 by the codec.
1655
1656.. % --- Methods & Slots ----------------------------------------------------
1657
1658
1659.. _unicodemethodsandslots:
1660
1661Methods and Slot Functions
1662^^^^^^^^^^^^^^^^^^^^^^^^^^
1663
1664The following APIs are capable of handling Unicode objects and strings on input
1665(we refer to them as strings in the descriptions) and return Unicode objects or
1666integers as appropriate.
1667
1668They all return *NULL* or ``-1`` if an exception occurs.
1669
1670
1671.. cfunction:: PyObject* PyUnicode_Concat(PyObject *left, PyObject *right)
1672
1673 Concat two strings giving a new Unicode string.
1674
1675
1676.. cfunction:: PyObject* PyUnicode_Split(PyObject *s, PyObject *sep, Py_ssize_t maxsplit)
1677
1678 Split a string giving a list of Unicode strings. If sep is *NULL*, splitting
1679 will be done at all whitespace substrings. Otherwise, splits occur at the given
1680 separator. At most *maxsplit* splits will be done. If negative, no limit is
1681 set. Separators are not included in the resulting list.
1682
1683
1684.. cfunction:: PyObject* PyUnicode_Splitlines(PyObject *s, int keepend)
1685
1686 Split a Unicode string at line breaks, returning a list of Unicode strings.
1687 CRLF is considered to be one line break. If *keepend* is 0, the Line break
1688 characters are not included in the resulting strings.
1689
1690
1691.. cfunction:: PyObject* PyUnicode_Translate(PyObject *str, PyObject *table, const char *errors)
1692
1693 Translate a string by applying a character mapping table to it and return the
1694 resulting Unicode object.
1695
1696 The mapping table must map Unicode ordinal integers to Unicode ordinal integers
1697 or None (causing deletion of the character).
1698
1699 Mapping tables need only provide the :meth:`__getitem__` interface; dictionaries
1700 and sequences work well. Unmapped character ordinals (ones which cause a
1701 :exc:`LookupError`) are left untouched and are copied as-is.
1702
1703 *errors* has the usual meaning for codecs. It may be *NULL* which indicates to
1704 use the default error handling.
1705
1706
1707.. cfunction:: PyObject* PyUnicode_Join(PyObject *separator, PyObject *seq)
1708
1709 Join a sequence of strings using the given separator and return the resulting
1710 Unicode string.
1711
1712
1713.. cfunction:: int PyUnicode_Tailmatch(PyObject *str, PyObject *substr, Py_ssize_t start, Py_ssize_t end, int direction)
1714
1715 Return 1 if *substr* matches *str*[*start*:*end*] at the given tail end
1716 (*direction* == -1 means to do a prefix match, *direction* == 1 a suffix match),
1717 0 otherwise. Return ``-1`` if an error occurred.
1718
1719
1720.. cfunction:: Py_ssize_t PyUnicode_Find(PyObject *str, PyObject *substr, Py_ssize_t start, Py_ssize_t end, int direction)
1721
1722 Return the first position of *substr* in *str*[*start*:*end*] using the given
1723 *direction* (*direction* == 1 means to do a forward search, *direction* == -1 a
1724 backward search). The return value is the index of the first match; a value of
1725 ``-1`` indicates that no match was found, and ``-2`` indicates that an error
1726 occurred and an exception has been set.
1727
1728
1729.. cfunction:: Py_ssize_t PyUnicode_Count(PyObject *str, PyObject *substr, Py_ssize_t start, Py_ssize_t end)
1730
1731 Return the number of non-overlapping occurrences of *substr* in
1732 ``str[start:end]``. Return ``-1`` if an error occurred.
1733
1734
1735.. cfunction:: PyObject* PyUnicode_Replace(PyObject *str, PyObject *substr, PyObject *replstr, Py_ssize_t maxcount)
1736
1737 Replace at most *maxcount* occurrences of *substr* in *str* with *replstr* and
1738 return the resulting Unicode object. *maxcount* == -1 means replace all
1739 occurrences.
1740
1741
1742.. cfunction:: int PyUnicode_Compare(PyObject *left, PyObject *right)
1743
1744 Compare two strings and return -1, 0, 1 for less than, equal, and greater than,
1745 respectively.
1746
1747
1748.. cfunction:: int PyUnicode_RichCompare(PyObject *left, PyObject *right, int op)
1749
1750 Rich compare two unicode strings and return one of the following:
1751
1752 * ``NULL`` in case an exception was raised
1753 * :const:`Py_True` or :const:`Py_False` for successful comparisons
1754 * :const:`Py_NotImplemented` in case the type combination is unknown
1755
1756 Note that :const:`Py_EQ` and :const:`Py_NE` comparisons can cause a
1757 :exc:`UnicodeWarning` in case the conversion of the arguments to Unicode fails
1758 with a :exc:`UnicodeDecodeError`.
1759
1760 Possible values for *op* are :const:`Py_GT`, :const:`Py_GE`, :const:`Py_EQ`,
1761 :const:`Py_NE`, :const:`Py_LT`, and :const:`Py_LE`.
1762
1763
1764.. cfunction:: PyObject* PyUnicode_Format(PyObject *format, PyObject *args)
1765
1766 Return a new string object from *format* and *args*; this is analogous to
1767 ``format % args``. The *args* argument must be a tuple.
1768
1769
1770.. cfunction:: int PyUnicode_Contains(PyObject *container, PyObject *element)
1771
1772 Check whether *element* is contained in *container* and return true or false
1773 accordingly.
1774
1775 *element* has to coerce to a one element Unicode string. ``-1`` is returned if
1776 there was an error.
1777
1778
1779.. cfunction:: void PyUnicode_InternInPlace(PyObject **string)
1780
1781 Intern the argument *\*string* in place. The argument must be the address of a
1782 pointer variable pointing to a Python unicode string object. If there is an
1783 existing interned string that is the same as *\*string*, it sets *\*string* to
1784 it (decrementing the reference count of the old string object and incrementing
1785 the reference count of the interned string object), otherwise it leaves
1786 *\*string* alone and interns it (incrementing its reference count).
1787 (Clarification: even though there is a lot of talk about reference counts, think
1788 of this function as reference-count-neutral; you own the object after the call
1789 if and only if you owned it before the call.)
1790
1791
1792.. cfunction:: PyObject* PyUnicode_InternFromString(const char *v)
1793
1794 A combination of :cfunc:`PyUnicode_FromString` and
1795 :cfunc:`PyUnicode_InternInPlace`, returning either a new unicode string object
1796 that has been interned, or a new ("owned") reference to an earlier interned
1797 string object with the same value.
1798
1799
1800.. _bufferobjects:
1801
1802Buffer Objects
1803--------------
1804
1805.. sectionauthor:: Greg Stein <gstein@lyra.org>
1806
1807
1808.. index::
1809 object: buffer
1810 single: buffer interface
1811
1812Python objects implemented in C can export a group of functions called the
1813"buffer interface." These functions can be used by an object to expose its data
1814in a raw, byte-oriented format. Clients of the object can use the buffer
1815interface to access the object data directly, without needing to copy it first.
1816
1817Two examples of objects that support the buffer interface are strings and
1818arrays. The string object exposes the character contents in the buffer
1819interface's byte-oriented form. An array can also expose its contents, but it
1820should be noted that array elements may be multi-byte values.
1821
1822An example user of the buffer interface is the file object's :meth:`write`
1823method. Any object that can export a series of bytes through the buffer
1824interface can be written to a file. There are a number of format codes to
1825:cfunc:`PyArg_ParseTuple` that operate against an object's buffer interface,
1826returning data from the target object.
1827
1828.. index:: single: PyBufferProcs
1829
1830More information on the buffer interface is provided in the section
1831:ref:`buffer-structs`, under the description for :ctype:`PyBufferProcs`.
1832
1833A "buffer object" is defined in the :file:`bufferobject.h` header (included by
1834:file:`Python.h`). These objects look very similar to string objects at the
1835Python programming level: they support slicing, indexing, concatenation, and
1836some other standard string operations. However, their data can come from one of
1837two sources: from a block of memory, or from another object which exports the
1838buffer interface.
1839
1840Buffer objects are useful as a way to expose the data from another object's
1841buffer interface to the Python programmer. They can also be used as a zero-copy
1842slicing mechanism. Using their ability to reference a block of memory, it is
1843possible to expose any data to the Python programmer quite easily. The memory
1844could be a large, constant array in a C extension, it could be a raw block of
1845memory for manipulation before passing to an operating system library, or it
1846could be used to pass around structured data in its native, in-memory format.
1847
1848
1849.. ctype:: PyBufferObject
1850
1851 This subtype of :ctype:`PyObject` represents a buffer object.
1852
1853
1854.. cvar:: PyTypeObject PyBuffer_Type
1855
1856 .. index:: single: BufferType (in module types)
1857
1858 The instance of :ctype:`PyTypeObject` which represents the Python buffer type;
1859 it is the same object as ``buffer`` and ``types.BufferType`` in the Python
1860 layer. .
1861
1862
1863.. cvar:: int Py_END_OF_BUFFER
1864
1865 This constant may be passed as the *size* parameter to
1866 :cfunc:`PyBuffer_FromObject` or :cfunc:`PyBuffer_FromReadWriteObject`. It
1867 indicates that the new :ctype:`PyBufferObject` should refer to *base* object
1868 from the specified *offset* to the end of its exported buffer. Using this
1869 enables the caller to avoid querying the *base* object for its length.
1870
1871
1872.. cfunction:: int PyBuffer_Check(PyObject *p)
1873
1874 Return true if the argument has type :cdata:`PyBuffer_Type`.
1875
1876
1877.. cfunction:: PyObject* PyBuffer_FromObject(PyObject *base, Py_ssize_t offset, Py_ssize_t size)
1878
1879 Return a new read-only buffer object. This raises :exc:`TypeError` if *base*
1880 doesn't support the read-only buffer protocol or doesn't provide exactly one
1881 buffer segment, or it raises :exc:`ValueError` if *offset* is less than zero.
1882 The buffer will hold a reference to the *base* object, and the buffer's contents
1883 will refer to the *base* object's buffer interface, starting as position
1884 *offset* and extending for *size* bytes. If *size* is :const:`Py_END_OF_BUFFER`,
1885 then the new buffer's contents extend to the length of the *base* object's
1886 exported buffer data.
1887
1888
1889.. cfunction:: PyObject* PyBuffer_FromReadWriteObject(PyObject *base, Py_ssize_t offset, Py_ssize_t size)
1890
1891 Return a new writable buffer object. Parameters and exceptions are similar to
1892 those for :cfunc:`PyBuffer_FromObject`. If the *base* object does not export
Sean Reifscheider54cf12b2007-09-17 17:55:36 +00001893 the writable buffer protocol, then :exc:`TypeError` is raised.
Georg Brandl116aa622007-08-15 14:28:22 +00001894
1895
1896.. cfunction:: PyObject* PyBuffer_FromMemory(void *ptr, Py_ssize_t size)
1897
1898 Return a new read-only buffer object that reads from a specified location in
1899 memory, with a specified size. The caller is responsible for ensuring that the
1900 memory buffer, passed in as *ptr*, is not deallocated while the returned buffer
1901 object exists. Raises :exc:`ValueError` if *size* is less than zero. Note that
1902 :const:`Py_END_OF_BUFFER` may *not* be passed for the *size* parameter;
1903 :exc:`ValueError` will be raised in that case.
1904
1905
1906.. cfunction:: PyObject* PyBuffer_FromReadWriteMemory(void *ptr, Py_ssize_t size)
1907
1908 Similar to :cfunc:`PyBuffer_FromMemory`, but the returned buffer is writable.
1909
1910
1911.. cfunction:: PyObject* PyBuffer_New(Py_ssize_t size)
1912
1913 Return a new writable buffer object that maintains its own memory buffer of
1914 *size* bytes. :exc:`ValueError` is returned if *size* is not zero or positive.
1915 Note that the memory buffer (as returned by :cfunc:`PyObject_AsWriteBuffer`) is
1916 not specifically aligned.
1917
1918
1919.. _tupleobjects:
1920
1921Tuple Objects
1922-------------
1923
1924.. index:: object: tuple
1925
1926
1927.. ctype:: PyTupleObject
1928
1929 This subtype of :ctype:`PyObject` represents a Python tuple object.
1930
1931
1932.. cvar:: PyTypeObject PyTuple_Type
1933
1934 .. index:: single: TupleType (in module types)
1935
1936 This instance of :ctype:`PyTypeObject` represents the Python tuple type; it is
1937 the same object as ``tuple`` and ``types.TupleType`` in the Python layer..
1938
1939
1940.. cfunction:: int PyTuple_Check(PyObject *p)
1941
1942 Return true if *p* is a tuple object or an instance of a subtype of the tuple
1943 type.
1944
Georg Brandl116aa622007-08-15 14:28:22 +00001945
1946.. cfunction:: int PyTuple_CheckExact(PyObject *p)
1947
1948 Return true if *p* is a tuple object, but not an instance of a subtype of the
1949 tuple type.
1950
Georg Brandl116aa622007-08-15 14:28:22 +00001951
1952.. cfunction:: PyObject* PyTuple_New(Py_ssize_t len)
1953
1954 Return a new tuple object of size *len*, or *NULL* on failure.
1955
1956
1957.. cfunction:: PyObject* PyTuple_Pack(Py_ssize_t n, ...)
1958
1959 Return a new tuple object of size *n*, or *NULL* on failure. The tuple values
1960 are initialized to the subsequent *n* C arguments pointing to Python objects.
1961 ``PyTuple_Pack(2, a, b)`` is equivalent to ``Py_BuildValue("(OO)", a, b)``.
1962
Georg Brandl116aa622007-08-15 14:28:22 +00001963
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001964.. cfunction:: Py_ssize_t PyTuple_Size(PyObject *p)
Georg Brandl116aa622007-08-15 14:28:22 +00001965
1966 Take a pointer to a tuple object, and return the size of that tuple.
1967
1968
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001969.. cfunction:: Py_ssize_t PyTuple_GET_SIZE(PyObject *p)
Georg Brandl116aa622007-08-15 14:28:22 +00001970
1971 Return the size of the tuple *p*, which must be non-*NULL* and point to a tuple;
1972 no error checking is performed.
1973
1974
1975.. cfunction:: PyObject* PyTuple_GetItem(PyObject *p, Py_ssize_t pos)
1976
1977 Return the object at position *pos* in the tuple pointed to by *p*. If *pos* is
1978 out of bounds, return *NULL* and sets an :exc:`IndexError` exception.
1979
1980
1981.. cfunction:: PyObject* PyTuple_GET_ITEM(PyObject *p, Py_ssize_t pos)
1982
1983 Like :cfunc:`PyTuple_GetItem`, but does no checking of its arguments.
1984
1985
1986.. cfunction:: PyObject* PyTuple_GetSlice(PyObject *p, Py_ssize_t low, Py_ssize_t high)
1987
1988 Take a slice of the tuple pointed to by *p* from *low* to *high* and return it
1989 as a new tuple.
1990
1991
1992.. cfunction:: int PyTuple_SetItem(PyObject *p, Py_ssize_t pos, PyObject *o)
1993
1994 Insert a reference to object *o* at position *pos* of the tuple pointed to by
1995 *p*. Return ``0`` on success.
1996
1997 .. note::
1998
1999 This function "steals" a reference to *o*.
2000
2001
2002.. cfunction:: void PyTuple_SET_ITEM(PyObject *p, Py_ssize_t pos, PyObject *o)
2003
2004 Like :cfunc:`PyTuple_SetItem`, but does no error checking, and should *only* be
2005 used to fill in brand new tuples.
2006
2007 .. note::
2008
2009 This function "steals" a reference to *o*.
2010
2011
2012.. cfunction:: int _PyTuple_Resize(PyObject **p, Py_ssize_t newsize)
2013
2014 Can be used to resize a tuple. *newsize* will be the new length of the tuple.
2015 Because tuples are *supposed* to be immutable, this should only be used if there
2016 is only one reference to the object. Do *not* use this if the tuple may already
2017 be known to some other part of the code. The tuple will always grow or shrink
2018 at the end. Think of this as destroying the old tuple and creating a new one,
2019 only more efficiently. Returns ``0`` on success. Client code should never
2020 assume that the resulting value of ``*p`` will be the same as before calling
2021 this function. If the object referenced by ``*p`` is replaced, the original
2022 ``*p`` is destroyed. On failure, returns ``-1`` and sets ``*p`` to *NULL*, and
2023 raises :exc:`MemoryError` or :exc:`SystemError`.
2024
Georg Brandl116aa622007-08-15 14:28:22 +00002025
2026.. _listobjects:
2027
2028List Objects
2029------------
2030
2031.. index:: object: list
2032
2033
2034.. ctype:: PyListObject
2035
2036 This subtype of :ctype:`PyObject` represents a Python list object.
2037
2038
2039.. cvar:: PyTypeObject PyList_Type
2040
2041 .. index:: single: ListType (in module types)
2042
2043 This instance of :ctype:`PyTypeObject` represents the Python list type. This is
2044 the same object as ``list`` and ``types.ListType`` in the Python layer.
2045
2046
2047.. cfunction:: int PyList_Check(PyObject *p)
2048
2049 Return true if *p* is a list object or an instance of a subtype of the list
2050 type.
2051
Georg Brandl116aa622007-08-15 14:28:22 +00002052
2053.. cfunction:: int PyList_CheckExact(PyObject *p)
2054
2055 Return true if *p* is a list object, but not an instance of a subtype of the
2056 list type.
2057
Georg Brandl116aa622007-08-15 14:28:22 +00002058
2059.. cfunction:: PyObject* PyList_New(Py_ssize_t len)
2060
2061 Return a new list of length *len* on success, or *NULL* on failure.
2062
2063 .. note::
2064
2065 If *length* is greater than zero, the returned list object's items are set to
2066 ``NULL``. Thus you cannot use abstract API functions such as
2067 :cfunc:`PySequence_SetItem` or expose the object to Python code before setting
2068 all items to a real object with :cfunc:`PyList_SetItem`.
2069
2070
2071.. cfunction:: Py_ssize_t PyList_Size(PyObject *list)
2072
2073 .. index:: builtin: len
2074
2075 Return the length of the list object in *list*; this is equivalent to
2076 ``len(list)`` on a list object.
2077
2078
2079.. cfunction:: Py_ssize_t PyList_GET_SIZE(PyObject *list)
2080
2081 Macro form of :cfunc:`PyList_Size` without error checking.
2082
2083
2084.. cfunction:: PyObject* PyList_GetItem(PyObject *list, Py_ssize_t index)
2085
2086 Return the object at position *pos* in the list pointed to by *p*. The position
2087 must be positive, indexing from the end of the list is not supported. If *pos*
2088 is out of bounds, return *NULL* and set an :exc:`IndexError` exception.
2089
2090
2091.. cfunction:: PyObject* PyList_GET_ITEM(PyObject *list, Py_ssize_t i)
2092
2093 Macro form of :cfunc:`PyList_GetItem` without error checking.
2094
2095
2096.. cfunction:: int PyList_SetItem(PyObject *list, Py_ssize_t index, PyObject *item)
2097
2098 Set the item at index *index* in list to *item*. Return ``0`` on success or
2099 ``-1`` on failure.
2100
2101 .. note::
2102
2103 This function "steals" a reference to *item* and discards a reference to an item
2104 already in the list at the affected position.
2105
2106
2107.. cfunction:: void PyList_SET_ITEM(PyObject *list, Py_ssize_t i, PyObject *o)
2108
2109 Macro form of :cfunc:`PyList_SetItem` without error checking. This is normally
2110 only used to fill in new lists where there is no previous content.
2111
2112 .. note::
2113
2114 This function "steals" a reference to *item*, and, unlike
2115 :cfunc:`PyList_SetItem`, does *not* discard a reference to any item that it
2116 being replaced; any reference in *list* at position *i* will be leaked.
2117
2118
2119.. cfunction:: int PyList_Insert(PyObject *list, Py_ssize_t index, PyObject *item)
2120
2121 Insert the item *item* into list *list* in front of index *index*. Return ``0``
2122 if successful; return ``-1`` and set an exception if unsuccessful. Analogous to
2123 ``list.insert(index, item)``.
2124
2125
2126.. cfunction:: int PyList_Append(PyObject *list, PyObject *item)
2127
2128 Append the object *item* at the end of list *list*. Return ``0`` if successful;
2129 return ``-1`` and set an exception if unsuccessful. Analogous to
2130 ``list.append(item)``.
2131
2132
2133.. cfunction:: PyObject* PyList_GetSlice(PyObject *list, Py_ssize_t low, Py_ssize_t high)
2134
2135 Return a list of the objects in *list* containing the objects *between* *low*
2136 and *high*. Return *NULL* and set an exception if unsuccessful. Analogous to
2137 ``list[low:high]``.
2138
2139
2140.. cfunction:: int PyList_SetSlice(PyObject *list, Py_ssize_t low, Py_ssize_t high, PyObject *itemlist)
2141
2142 Set the slice of *list* between *low* and *high* to the contents of *itemlist*.
2143 Analogous to ``list[low:high] = itemlist``. The *itemlist* may be *NULL*,
2144 indicating the assignment of an empty list (slice deletion). Return ``0`` on
2145 success, ``-1`` on failure.
2146
2147
2148.. cfunction:: int PyList_Sort(PyObject *list)
2149
2150 Sort the items of *list* in place. Return ``0`` on success, ``-1`` on failure.
2151 This is equivalent to ``list.sort()``.
2152
2153
2154.. cfunction:: int PyList_Reverse(PyObject *list)
2155
2156 Reverse the items of *list* in place. Return ``0`` on success, ``-1`` on
2157 failure. This is the equivalent of ``list.reverse()``.
2158
2159
2160.. cfunction:: PyObject* PyList_AsTuple(PyObject *list)
2161
2162 .. index:: builtin: tuple
2163
2164 Return a new tuple object containing the contents of *list*; equivalent to
2165 ``tuple(list)``.
2166
2167
2168.. _mapobjects:
2169
2170Mapping Objects
2171===============
2172
2173.. index:: object: mapping
2174
2175
2176.. _dictobjects:
2177
2178Dictionary Objects
2179------------------
2180
2181.. index:: object: dictionary
2182
2183
2184.. ctype:: PyDictObject
2185
2186 This subtype of :ctype:`PyObject` represents a Python dictionary object.
2187
2188
2189.. cvar:: PyTypeObject PyDict_Type
2190
2191 .. index::
2192 single: DictType (in module types)
2193 single: DictionaryType (in module types)
2194
2195 This instance of :ctype:`PyTypeObject` represents the Python dictionary type.
2196 This is exposed to Python programs as ``dict`` and ``types.DictType``.
2197
2198
2199.. cfunction:: int PyDict_Check(PyObject *p)
2200
2201 Return true if *p* is a dict object or an instance of a subtype of the dict
2202 type.
2203
Georg Brandl116aa622007-08-15 14:28:22 +00002204
2205.. cfunction:: int PyDict_CheckExact(PyObject *p)
2206
2207 Return true if *p* is a dict object, but not an instance of a subtype of the
2208 dict type.
2209
Georg Brandl116aa622007-08-15 14:28:22 +00002210
2211.. cfunction:: PyObject* PyDict_New()
2212
2213 Return a new empty dictionary, or *NULL* on failure.
2214
2215
2216.. cfunction:: PyObject* PyDictProxy_New(PyObject *dict)
2217
2218 Return a proxy object for a mapping which enforces read-only behavior. This is
2219 normally used to create a proxy to prevent modification of the dictionary for
2220 non-dynamic class types.
2221
Georg Brandl116aa622007-08-15 14:28:22 +00002222
2223.. cfunction:: void PyDict_Clear(PyObject *p)
2224
2225 Empty an existing dictionary of all key-value pairs.
2226
2227
2228.. cfunction:: int PyDict_Contains(PyObject *p, PyObject *key)
2229
2230 Determine if dictionary *p* contains *key*. If an item in *p* is matches *key*,
2231 return ``1``, otherwise return ``0``. On error, return ``-1``. This is
2232 equivalent to the Python expression ``key in p``.
2233
Georg Brandl116aa622007-08-15 14:28:22 +00002234
2235.. cfunction:: PyObject* PyDict_Copy(PyObject *p)
2236
2237 Return a new dictionary that contains the same key-value pairs as *p*.
2238
Georg Brandl116aa622007-08-15 14:28:22 +00002239
2240.. cfunction:: int PyDict_SetItem(PyObject *p, PyObject *key, PyObject *val)
2241
2242 Insert *value* into the dictionary *p* with a key of *key*. *key* must be
Guido van Rossum2cc30da2007-11-02 23:46:40 +00002243 :term:`hashable`; if it isn't, :exc:`TypeError` will be raised. Return ``0``
2244 on success or ``-1`` on failure.
Georg Brandl116aa622007-08-15 14:28:22 +00002245
2246
2247.. cfunction:: int PyDict_SetItemString(PyObject *p, const char *key, PyObject *val)
2248
2249 .. index:: single: PyString_FromString()
2250
2251 Insert *value* into the dictionary *p* using *key* as a key. *key* should be a
2252 :ctype:`char\*`. The key object is created using ``PyString_FromString(key)``.
2253 Return ``0`` on success or ``-1`` on failure.
2254
2255
2256.. cfunction:: int PyDict_DelItem(PyObject *p, PyObject *key)
2257
2258 Remove the entry in dictionary *p* with key *key*. *key* must be hashable; if it
2259 isn't, :exc:`TypeError` is raised. Return ``0`` on success or ``-1`` on
2260 failure.
2261
2262
2263.. cfunction:: int PyDict_DelItemString(PyObject *p, char *key)
2264
2265 Remove the entry in dictionary *p* which has a key specified by the string
2266 *key*. Return ``0`` on success or ``-1`` on failure.
2267
2268
2269.. cfunction:: PyObject* PyDict_GetItem(PyObject *p, PyObject *key)
2270
2271 Return the object from dictionary *p* which has a key *key*. Return *NULL* if
2272 the key *key* is not present, but *without* setting an exception.
2273
2274
2275.. cfunction:: PyObject* PyDict_GetItemString(PyObject *p, const char *key)
2276
2277 This is the same as :cfunc:`PyDict_GetItem`, but *key* is specified as a
2278 :ctype:`char\*`, rather than a :ctype:`PyObject\*`.
2279
2280
2281.. cfunction:: PyObject* PyDict_Items(PyObject *p)
2282
2283 Return a :ctype:`PyListObject` containing all the items from the dictionary, as
2284 in the dictionary method :meth:`dict.items`.
2285
2286
2287.. cfunction:: PyObject* PyDict_Keys(PyObject *p)
2288
2289 Return a :ctype:`PyListObject` containing all the keys from the dictionary, as
2290 in the dictionary method :meth:`dict.keys`.
2291
2292
2293.. cfunction:: PyObject* PyDict_Values(PyObject *p)
2294
2295 Return a :ctype:`PyListObject` containing all the values from the dictionary
2296 *p*, as in the dictionary method :meth:`dict.values`.
2297
2298
2299.. cfunction:: Py_ssize_t PyDict_Size(PyObject *p)
2300
2301 .. index:: builtin: len
2302
2303 Return the number of items in the dictionary. This is equivalent to ``len(p)``
2304 on a dictionary.
2305
2306
2307.. cfunction:: int PyDict_Next(PyObject *p, Py_ssize_t *ppos, PyObject **pkey, PyObject **pvalue)
2308
2309 Iterate over all key-value pairs in the dictionary *p*. The :ctype:`int`
2310 referred to by *ppos* must be initialized to ``0`` prior to the first call to
2311 this function to start the iteration; the function returns true for each pair in
2312 the dictionary, and false once all pairs have been reported. The parameters
2313 *pkey* and *pvalue* should either point to :ctype:`PyObject\*` variables that
2314 will be filled in with each key and value, respectively, or may be *NULL*. Any
2315 references returned through them are borrowed. *ppos* should not be altered
2316 during iteration. Its value represents offsets within the internal dictionary
2317 structure, and since the structure is sparse, the offsets are not consecutive.
2318
2319 For example::
2320
2321 PyObject *key, *value;
2322 Py_ssize_t pos = 0;
2323
2324 while (PyDict_Next(self->dict, &pos, &key, &value)) {
2325 /* do something interesting with the values... */
2326 ...
2327 }
2328
2329 The dictionary *p* should not be mutated during iteration. It is safe (since
2330 Python 2.1) to modify the values of the keys as you iterate over the dictionary,
2331 but only so long as the set of keys does not change. For example::
2332
2333 PyObject *key, *value;
2334 Py_ssize_t pos = 0;
2335
2336 while (PyDict_Next(self->dict, &pos, &key, &value)) {
2337 int i = PyInt_AS_LONG(value) + 1;
2338 PyObject *o = PyInt_FromLong(i);
2339 if (o == NULL)
2340 return -1;
2341 if (PyDict_SetItem(self->dict, key, o) < 0) {
2342 Py_DECREF(o);
2343 return -1;
2344 }
2345 Py_DECREF(o);
2346 }
2347
2348
2349.. cfunction:: int PyDict_Merge(PyObject *a, PyObject *b, int override)
2350
2351 Iterate over mapping object *b* adding key-value pairs to dictionary *a*. *b*
2352 may be a dictionary, or any object supporting :func:`PyMapping_Keys` and
2353 :func:`PyObject_GetItem`. If *override* is true, existing pairs in *a* will be
2354 replaced if a matching key is found in *b*, otherwise pairs will only be added
2355 if there is not a matching key in *a*. Return ``0`` on success or ``-1`` if an
2356 exception was raised.
2357
Georg Brandl116aa622007-08-15 14:28:22 +00002358
2359.. cfunction:: int PyDict_Update(PyObject *a, PyObject *b)
2360
2361 This is the same as ``PyDict_Merge(a, b, 1)`` in C, or ``a.update(b)`` in
2362 Python. Return ``0`` on success or ``-1`` if an exception was raised.
2363
Georg Brandl116aa622007-08-15 14:28:22 +00002364
2365.. cfunction:: int PyDict_MergeFromSeq2(PyObject *a, PyObject *seq2, int override)
2366
2367 Update or merge into dictionary *a*, from the key-value pairs in *seq2*. *seq2*
2368 must be an iterable object producing iterable objects of length 2, viewed as
2369 key-value pairs. In case of duplicate keys, the last wins if *override* is
2370 true, else the first wins. Return ``0`` on success or ``-1`` if an exception was
2371 raised. Equivalent Python (except for the return value)::
2372
2373 def PyDict_MergeFromSeq2(a, seq2, override):
2374 for key, value in seq2:
2375 if override or key not in a:
2376 a[key] = value
2377
Georg Brandl116aa622007-08-15 14:28:22 +00002378
2379.. _otherobjects:
2380
2381Other Objects
2382=============
2383
Georg Brandl116aa622007-08-15 14:28:22 +00002384.. _fileobjects:
2385
2386File Objects
2387------------
2388
2389.. index:: object: file
2390
2391Python's built-in file objects are implemented entirely on the :ctype:`FILE\*`
2392support from the C standard library. This is an implementation detail and may
2393change in future releases of Python.
2394
2395
2396.. ctype:: PyFileObject
2397
2398 This subtype of :ctype:`PyObject` represents a Python file object.
2399
2400
2401.. cvar:: PyTypeObject PyFile_Type
2402
2403 .. index:: single: FileType (in module types)
2404
2405 This instance of :ctype:`PyTypeObject` represents the Python file type. This is
2406 exposed to Python programs as ``file`` and ``types.FileType``.
2407
2408
2409.. cfunction:: int PyFile_Check(PyObject *p)
2410
2411 Return true if its argument is a :ctype:`PyFileObject` or a subtype of
2412 :ctype:`PyFileObject`.
2413
Georg Brandl116aa622007-08-15 14:28:22 +00002414
2415.. cfunction:: int PyFile_CheckExact(PyObject *p)
2416
2417 Return true if its argument is a :ctype:`PyFileObject`, but not a subtype of
2418 :ctype:`PyFileObject`.
2419
Georg Brandl116aa622007-08-15 14:28:22 +00002420
Guido van Rossum2dced8b2007-10-30 17:27:30 +00002421.. cfunction:: PyFile_FromFd(int fd, char *name, char *mode, int buffering, char *encoding, char *newline, int closefd)
Georg Brandl116aa622007-08-15 14:28:22 +00002422
Guido van Rossum40d20bc2007-10-22 00:09:51 +00002423 Create a new :ctype:`PyFileObject` from the file descriptor of an already
2424 opened file *fd*. The arguments *name*, *encoding* and *newline* can be
Guido van Rossum2dced8b2007-10-30 17:27:30 +00002425 *NULL* to use the defaults; *buffering* can be *-1* to use the default.
2426 Return *NULL* on failure.
Georg Brandl116aa622007-08-15 14:28:22 +00002427
Guido van Rossum40d20bc2007-10-22 00:09:51 +00002428 .. warning::
2429
2430 Take care when you are mixing streams and descriptors! For more
Georg Brandl083bea42007-10-23 18:26:17 +00002431 information, see `the GNU C Library docs
Guido van Rossum40d20bc2007-10-22 00:09:51 +00002432 <http://www.gnu.org/software/libc/manual/html_node/Stream_002fDescriptor-Precautions.html#Stream_002fDescriptor-Precautions>`_.
Georg Brandl116aa622007-08-15 14:28:22 +00002433
2434
Guido van Rossum40d20bc2007-10-22 00:09:51 +00002435.. cfunction:: int PyObject_AsFileDescriptor(PyObject *p)
Georg Brandl116aa622007-08-15 14:28:22 +00002436
Georg Brandl083bea42007-10-23 18:26:17 +00002437 Return the file descriptor associated with *p* as an :ctype:`int`. If the
2438 object is an integer or long integer, its value is returned. If not, the
2439 object's :meth:`fileno` method is called if it exists; the method must return
2440 an integer, which is returned as the file descriptor value. Sets an
2441 exception and returns ``-1`` on failure.
Georg Brandl116aa622007-08-15 14:28:22 +00002442
2443
2444.. cfunction:: PyObject* PyFile_GetLine(PyObject *p, int n)
2445
2446 .. index:: single: EOFError (built-in exception)
2447
2448 Equivalent to ``p.readline([n])``, this function reads one line from the
2449 object *p*. *p* may be a file object or any object with a :meth:`readline`
2450 method. If *n* is ``0``, exactly one line is read, regardless of the length of
2451 the line. If *n* is greater than ``0``, no more than *n* bytes will be read
2452 from the file; a partial line can be returned. In both cases, an empty string
2453 is returned if the end of the file is reached immediately. If *n* is less than
2454 ``0``, however, one line is read regardless of length, but :exc:`EOFError` is
2455 raised if the end of the file is reached immediately.
2456
2457
2458.. cfunction:: PyObject* PyFile_Name(PyObject *p)
2459
2460 Return the name of the file specified by *p* as a string object.
2461
2462
2463.. cfunction:: void PyFile_SetBufSize(PyFileObject *p, int n)
2464
2465 .. index:: single: setvbuf()
2466
2467 Available on systems with :cfunc:`setvbuf` only. This should only be called
2468 immediately after file object creation.
2469
2470
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002471.. cfunction:: int PyFile_SetEncoding(PyFileObject *p, const char *enc)
Georg Brandl116aa622007-08-15 14:28:22 +00002472
2473 Set the file's encoding for Unicode output to *enc*. Return 1 on success and 0
2474 on failure.
2475
Georg Brandl116aa622007-08-15 14:28:22 +00002476
2477.. cfunction:: int PyFile_SoftSpace(PyObject *p, int newflag)
2478
2479 .. index:: single: softspace (file attribute)
2480
2481 This function exists for internal use by the interpreter. Set the
2482 :attr:`softspace` attribute of *p* to *newflag* and return the previous value.
2483 *p* does not have to be a file object for this function to work properly; any
2484 object is supported (thought its only interesting if the :attr:`softspace`
2485 attribute can be set). This function clears any errors, and will return ``0``
2486 as the previous value if the attribute either does not exist or if there were
2487 errors in retrieving it. There is no way to detect errors from this function,
2488 but doing so should not be needed.
2489
2490
2491.. cfunction:: int PyFile_WriteObject(PyObject *obj, PyObject *p, int flags)
2492
2493 .. index:: single: Py_PRINT_RAW
2494
2495 Write object *obj* to file object *p*. The only supported flag for *flags* is
2496 :const:`Py_PRINT_RAW`; if given, the :func:`str` of the object is written
2497 instead of the :func:`repr`. Return ``0`` on success or ``-1`` on failure; the
2498 appropriate exception will be set.
2499
2500
2501.. cfunction:: int PyFile_WriteString(const char *s, PyObject *p)
2502
2503 Write string *s* to file object *p*. Return ``0`` on success or ``-1`` on
2504 failure; the appropriate exception will be set.
2505
2506
Georg Brandl116aa622007-08-15 14:28:22 +00002507.. _function-objects:
2508
2509Function Objects
2510----------------
2511
2512.. index:: object: function
2513
2514There are a few functions specific to Python functions.
2515
2516
2517.. ctype:: PyFunctionObject
2518
2519 The C structure used for functions.
2520
2521
2522.. cvar:: PyTypeObject PyFunction_Type
2523
2524 .. index:: single: MethodType (in module types)
2525
2526 This is an instance of :ctype:`PyTypeObject` and represents the Python function
2527 type. It is exposed to Python programmers as ``types.FunctionType``.
2528
2529
2530.. cfunction:: int PyFunction_Check(PyObject *o)
2531
2532 Return true if *o* is a function object (has type :cdata:`PyFunction_Type`).
2533 The parameter must not be *NULL*.
2534
2535
2536.. cfunction:: PyObject* PyFunction_New(PyObject *code, PyObject *globals)
2537
2538 Return a new function object associated with the code object *code*. *globals*
2539 must be a dictionary with the global variables accessible to the function.
2540
2541 The function's docstring, name and *__module__* are retrieved from the code
2542 object, the argument defaults and closure are set to *NULL*.
2543
2544
2545.. cfunction:: PyObject* PyFunction_GetCode(PyObject *op)
2546
2547 Return the code object associated with the function object *op*.
2548
2549
2550.. cfunction:: PyObject* PyFunction_GetGlobals(PyObject *op)
2551
2552 Return the globals dictionary associated with the function object *op*.
2553
2554
2555.. cfunction:: PyObject* PyFunction_GetModule(PyObject *op)
2556
2557 Return the *__module__* attribute of the function object *op*. This is normally
2558 a string containing the module name, but can be set to any other object by
2559 Python code.
2560
2561
2562.. cfunction:: PyObject* PyFunction_GetDefaults(PyObject *op)
2563
2564 Return the argument default values of the function object *op*. This can be a
2565 tuple of arguments or *NULL*.
2566
2567
2568.. cfunction:: int PyFunction_SetDefaults(PyObject *op, PyObject *defaults)
2569
2570 Set the argument default values for the function object *op*. *defaults* must be
2571 *Py_None* or a tuple.
2572
2573 Raises :exc:`SystemError` and returns ``-1`` on failure.
2574
2575
2576.. cfunction:: PyObject* PyFunction_GetClosure(PyObject *op)
2577
2578 Return the closure associated with the function object *op*. This can be *NULL*
2579 or a tuple of cell objects.
2580
2581
2582.. cfunction:: int PyFunction_SetClosure(PyObject *op, PyObject *closure)
2583
2584 Set the closure associated with the function object *op*. *closure* must be
2585 *Py_None* or a tuple of cell objects.
2586
2587 Raises :exc:`SystemError` and returns ``-1`` on failure.
2588
2589
2590.. _method-objects:
2591
2592Method Objects
2593--------------
2594
2595.. index:: object: method
2596
Christian Heimes05a2fc22007-11-30 22:29:24 +00002597Methods are bound function objects. Methods are always bound to an instance of
2598an user-defined class. Unbound methods (methods bound to a class object) are
2599no longer available.
Georg Brandl116aa622007-08-15 14:28:22 +00002600
2601
2602.. cvar:: PyTypeObject PyMethod_Type
2603
2604 .. index:: single: MethodType (in module types)
2605
2606 This instance of :ctype:`PyTypeObject` represents the Python method type. This
2607 is exposed to Python programs as ``types.MethodType``.
2608
2609
2610.. cfunction:: int PyMethod_Check(PyObject *o)
2611
2612 Return true if *o* is a method object (has type :cdata:`PyMethod_Type`). The
2613 parameter must not be *NULL*.
2614
2615
Christian Heimes05a2fc22007-11-30 22:29:24 +00002616.. cfunction:: PyObject* PyMethod_New(PyObject *func, PyObject *self)
Georg Brandl116aa622007-08-15 14:28:22 +00002617
Christian Heimes05a2fc22007-11-30 22:29:24 +00002618 Return a new method object, with *func* being any callable object and *self*
2619 the instance the method should be bound. *func* is is the function that will
2620 be called when the method is called. *self* must not be *NULL*.
Georg Brandl116aa622007-08-15 14:28:22 +00002621
2622
2623.. cfunction:: PyObject* PyMethod_Function(PyObject *meth)
2624
2625 Return the function object associated with the method *meth*.
2626
2627
2628.. cfunction:: PyObject* PyMethod_GET_FUNCTION(PyObject *meth)
2629
2630 Macro version of :cfunc:`PyMethod_Function` which avoids error checking.
2631
2632
2633.. cfunction:: PyObject* PyMethod_Self(PyObject *meth)
2634
Christian Heimes05a2fc22007-11-30 22:29:24 +00002635 Return the instance associated with the method *meth*.
Georg Brandl116aa622007-08-15 14:28:22 +00002636
2637
2638.. cfunction:: PyObject* PyMethod_GET_SELF(PyObject *meth)
2639
2640 Macro version of :cfunc:`PyMethod_Self` which avoids error checking.
2641
2642
2643.. _moduleobjects:
2644
2645Module Objects
2646--------------
2647
2648.. index:: object: module
2649
2650There are only a few functions special to module objects.
2651
2652
2653.. cvar:: PyTypeObject PyModule_Type
2654
2655 .. index:: single: ModuleType (in module types)
2656
2657 This instance of :ctype:`PyTypeObject` represents the Python module type. This
2658 is exposed to Python programs as ``types.ModuleType``.
2659
2660
2661.. cfunction:: int PyModule_Check(PyObject *p)
2662
2663 Return true if *p* is a module object, or a subtype of a module object.
2664
Georg Brandl116aa622007-08-15 14:28:22 +00002665
2666.. cfunction:: int PyModule_CheckExact(PyObject *p)
2667
2668 Return true if *p* is a module object, but not a subtype of
2669 :cdata:`PyModule_Type`.
2670
Georg Brandl116aa622007-08-15 14:28:22 +00002671
2672.. cfunction:: PyObject* PyModule_New(const char *name)
2673
2674 .. index::
2675 single: __name__ (module attribute)
2676 single: __doc__ (module attribute)
2677 single: __file__ (module attribute)
2678
2679 Return a new module object with the :attr:`__name__` attribute set to *name*.
2680 Only the module's :attr:`__doc__` and :attr:`__name__` attributes are filled in;
2681 the caller is responsible for providing a :attr:`__file__` attribute.
2682
2683
2684.. cfunction:: PyObject* PyModule_GetDict(PyObject *module)
2685
2686 .. index:: single: __dict__ (module attribute)
2687
2688 Return the dictionary object that implements *module*'s namespace; this object
2689 is the same as the :attr:`__dict__` attribute of the module object. This
2690 function never fails. It is recommended extensions use other
2691 :cfunc:`PyModule_\*` and :cfunc:`PyObject_\*` functions rather than directly
2692 manipulate a module's :attr:`__dict__`.
2693
2694
2695.. cfunction:: char* PyModule_GetName(PyObject *module)
2696
2697 .. index::
2698 single: __name__ (module attribute)
2699 single: SystemError (built-in exception)
2700
2701 Return *module*'s :attr:`__name__` value. If the module does not provide one,
2702 or if it is not a string, :exc:`SystemError` is raised and *NULL* is returned.
2703
2704
2705.. cfunction:: char* PyModule_GetFilename(PyObject *module)
2706
2707 .. index::
2708 single: __file__ (module attribute)
2709 single: SystemError (built-in exception)
2710
2711 Return the name of the file from which *module* was loaded using *module*'s
2712 :attr:`__file__` attribute. If this is not defined, or if it is not a string,
2713 raise :exc:`SystemError` and return *NULL*.
2714
2715
2716.. cfunction:: int PyModule_AddObject(PyObject *module, const char *name, PyObject *value)
2717
2718 Add an object to *module* as *name*. This is a convenience function which can
2719 be used from the module's initialization function. This steals a reference to
2720 *value*. Return ``-1`` on error, ``0`` on success.
2721
Georg Brandl116aa622007-08-15 14:28:22 +00002722
2723.. cfunction:: int PyModule_AddIntConstant(PyObject *module, const char *name, long value)
2724
2725 Add an integer constant to *module* as *name*. This convenience function can be
2726 used from the module's initialization function. Return ``-1`` on error, ``0`` on
2727 success.
2728
Georg Brandl116aa622007-08-15 14:28:22 +00002729
2730.. cfunction:: int PyModule_AddStringConstant(PyObject *module, const char *name, const char *value)
2731
2732 Add a string constant to *module* as *name*. This convenience function can be
2733 used from the module's initialization function. The string *value* must be
2734 null-terminated. Return ``-1`` on error, ``0`` on success.
2735
Georg Brandl116aa622007-08-15 14:28:22 +00002736
2737.. _iterator-objects:
2738
2739Iterator Objects
2740----------------
2741
2742Python provides two general-purpose iterator objects. The first, a sequence
2743iterator, works with an arbitrary sequence supporting the :meth:`__getitem__`
2744method. The second works with a callable object and a sentinel value, calling
2745the callable for each item in the sequence, and ending the iteration when the
2746sentinel value is returned.
2747
2748
2749.. cvar:: PyTypeObject PySeqIter_Type
2750
2751 Type object for iterator objects returned by :cfunc:`PySeqIter_New` and the
2752 one-argument form of the :func:`iter` built-in function for built-in sequence
2753 types.
2754
Georg Brandl116aa622007-08-15 14:28:22 +00002755
2756.. cfunction:: int PySeqIter_Check(op)
2757
2758 Return true if the type of *op* is :cdata:`PySeqIter_Type`.
2759
Georg Brandl116aa622007-08-15 14:28:22 +00002760
2761.. cfunction:: PyObject* PySeqIter_New(PyObject *seq)
2762
2763 Return an iterator that works with a general sequence object, *seq*. The
2764 iteration ends when the sequence raises :exc:`IndexError` for the subscripting
2765 operation.
2766
Georg Brandl116aa622007-08-15 14:28:22 +00002767
2768.. cvar:: PyTypeObject PyCallIter_Type
2769
2770 Type object for iterator objects returned by :cfunc:`PyCallIter_New` and the
2771 two-argument form of the :func:`iter` built-in function.
2772
Georg Brandl116aa622007-08-15 14:28:22 +00002773
2774.. cfunction:: int PyCallIter_Check(op)
2775
2776 Return true if the type of *op* is :cdata:`PyCallIter_Type`.
2777
Georg Brandl116aa622007-08-15 14:28:22 +00002778
2779.. cfunction:: PyObject* PyCallIter_New(PyObject *callable, PyObject *sentinel)
2780
2781 Return a new iterator. The first parameter, *callable*, can be any Python
2782 callable object that can be called with no parameters; each call to it should
2783 return the next item in the iteration. When *callable* returns a value equal to
2784 *sentinel*, the iteration will be terminated.
2785
Georg Brandl116aa622007-08-15 14:28:22 +00002786
2787.. _descriptor-objects:
2788
2789Descriptor Objects
2790------------------
2791
2792"Descriptors" are objects that describe some attribute of an object. They are
2793found in the dictionary of type objects.
2794
Georg Brandl321976b2007-09-01 12:33:24 +00002795.. XXX document these!
Georg Brandl116aa622007-08-15 14:28:22 +00002796
2797.. cvar:: PyTypeObject PyProperty_Type
2798
2799 The type object for the built-in descriptor types.
2800
Georg Brandl116aa622007-08-15 14:28:22 +00002801
2802.. cfunction:: PyObject* PyDescr_NewGetSet(PyTypeObject *type, struct PyGetSetDef *getset)
2803
Georg Brandl116aa622007-08-15 14:28:22 +00002804
2805.. cfunction:: PyObject* PyDescr_NewMember(PyTypeObject *type, struct PyMemberDef *meth)
2806
Georg Brandl116aa622007-08-15 14:28:22 +00002807
2808.. cfunction:: PyObject* PyDescr_NewMethod(PyTypeObject *type, struct PyMethodDef *meth)
2809
Georg Brandl116aa622007-08-15 14:28:22 +00002810
2811.. cfunction:: PyObject* PyDescr_NewWrapper(PyTypeObject *type, struct wrapperbase *wrapper, void *wrapped)
2812
Georg Brandl116aa622007-08-15 14:28:22 +00002813
2814.. cfunction:: PyObject* PyDescr_NewClassMethod(PyTypeObject *type, PyMethodDef *method)
2815
Georg Brandl116aa622007-08-15 14:28:22 +00002816
2817.. cfunction:: int PyDescr_IsData(PyObject *descr)
2818
2819 Return true if the descriptor objects *descr* describes a data attribute, or
2820 false if it describes a method. *descr* must be a descriptor object; there is
2821 no error checking.
2822
Georg Brandl116aa622007-08-15 14:28:22 +00002823
2824.. cfunction:: PyObject* PyWrapper_New(PyObject *, PyObject *)
2825
Georg Brandl116aa622007-08-15 14:28:22 +00002826
2827.. _slice-objects:
2828
2829Slice Objects
2830-------------
2831
2832
2833.. cvar:: PyTypeObject PySlice_Type
2834
2835 .. index:: single: SliceType (in module types)
2836
2837 The type object for slice objects. This is the same as ``slice`` and
2838 ``types.SliceType``.
2839
2840
2841.. cfunction:: int PySlice_Check(PyObject *ob)
2842
2843 Return true if *ob* is a slice object; *ob* must not be *NULL*.
2844
2845
2846.. cfunction:: PyObject* PySlice_New(PyObject *start, PyObject *stop, PyObject *step)
2847
2848 Return a new slice object with the given values. The *start*, *stop*, and
2849 *step* parameters are used as the values of the slice object attributes of the
2850 same names. Any of the values may be *NULL*, in which case the ``None`` will be
2851 used for the corresponding attribute. Return *NULL* if the new object could not
2852 be allocated.
2853
2854
2855.. cfunction:: int PySlice_GetIndices(PySliceObject *slice, Py_ssize_t length, Py_ssize_t *start, Py_ssize_t *stop, Py_ssize_t *step)
2856
2857 Retrieve the start, stop and step indices from the slice object *slice*,
2858 assuming a sequence of length *length*. Treats indices greater than *length* as
2859 errors.
2860
2861 Returns 0 on success and -1 on error with no exception set (unless one of the
2862 indices was not :const:`None` and failed to be converted to an integer, in which
2863 case -1 is returned with an exception set).
2864
2865 You probably do not want to use this function. If you want to use slice objects
2866 in versions of Python prior to 2.3, you would probably do well to incorporate
2867 the source of :cfunc:`PySlice_GetIndicesEx`, suitably renamed, in the source of
2868 your extension.
2869
2870
2871.. 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)
2872
2873 Usable replacement for :cfunc:`PySlice_GetIndices`. Retrieve the start, stop,
2874 and step indices from the slice object *slice* assuming a sequence of length
2875 *length*, and store the length of the slice in *slicelength*. Out of bounds
2876 indices are clipped in a manner consistent with the handling of normal slices.
2877
2878 Returns 0 on success and -1 on error with exception set.
2879
Georg Brandl116aa622007-08-15 14:28:22 +00002880
2881.. _weakrefobjects:
2882
2883Weak Reference Objects
2884----------------------
2885
2886Python supports *weak references* as first-class objects. There are two
2887specific object types which directly implement weak references. The first is a
2888simple reference object, and the second acts as a proxy for the original object
2889as much as it can.
2890
2891
2892.. cfunction:: int PyWeakref_Check(ob)
2893
2894 Return true if *ob* is either a reference or proxy object.
2895
Georg Brandl116aa622007-08-15 14:28:22 +00002896
2897.. cfunction:: int PyWeakref_CheckRef(ob)
2898
2899 Return true if *ob* is a reference object.
2900
Georg Brandl116aa622007-08-15 14:28:22 +00002901
2902.. cfunction:: int PyWeakref_CheckProxy(ob)
2903
2904 Return true if *ob* is a proxy object.
2905
Georg Brandl116aa622007-08-15 14:28:22 +00002906
2907.. cfunction:: PyObject* PyWeakref_NewRef(PyObject *ob, PyObject *callback)
2908
2909 Return a weak reference object for the object *ob*. This will always return
2910 a new reference, but is not guaranteed to create a new object; an existing
2911 reference object may be returned. The second parameter, *callback*, can be a
2912 callable object that receives notification when *ob* is garbage collected; it
2913 should accept a single parameter, which will be the weak reference object
2914 itself. *callback* may also be ``None`` or *NULL*. If *ob* is not a
2915 weakly-referencable object, or if *callback* is not callable, ``None``, or
2916 *NULL*, this will return *NULL* and raise :exc:`TypeError`.
2917
Georg Brandl116aa622007-08-15 14:28:22 +00002918
2919.. cfunction:: PyObject* PyWeakref_NewProxy(PyObject *ob, PyObject *callback)
2920
2921 Return a weak reference proxy object for the object *ob*. This will always
2922 return a new reference, but is not guaranteed to create a new object; an
2923 existing proxy object may be returned. The second parameter, *callback*, can
2924 be a callable object that receives notification when *ob* is garbage
2925 collected; it should accept a single parameter, which will be the weak
2926 reference object itself. *callback* may also be ``None`` or *NULL*. If *ob*
2927 is not a weakly-referencable object, or if *callback* is not callable,
2928 ``None``, or *NULL*, this will return *NULL* and raise :exc:`TypeError`.
2929
Georg Brandl116aa622007-08-15 14:28:22 +00002930
2931.. cfunction:: PyObject* PyWeakref_GetObject(PyObject *ref)
2932
2933 Return the referenced object from a weak reference, *ref*. If the referent is
2934 no longer live, returns ``None``.
2935
Georg Brandl116aa622007-08-15 14:28:22 +00002936
2937.. cfunction:: PyObject* PyWeakref_GET_OBJECT(PyObject *ref)
2938
2939 Similar to :cfunc:`PyWeakref_GetObject`, but implemented as a macro that does no
2940 error checking.
2941
Georg Brandl116aa622007-08-15 14:28:22 +00002942
2943.. _cobjects:
2944
2945CObjects
2946--------
2947
2948.. index:: object: CObject
2949
2950Refer to *Extending and Embedding the Python Interpreter*, section 1.12,
2951"Providing a C API for an Extension Module," for more information on using these
2952objects.
2953
2954
2955.. ctype:: PyCObject
2956
2957 This subtype of :ctype:`PyObject` represents an opaque value, useful for C
2958 extension modules who need to pass an opaque value (as a :ctype:`void\*`
2959 pointer) through Python code to other C code. It is often used to make a C
2960 function pointer defined in one module available to other modules, so the
2961 regular import mechanism can be used to access C APIs defined in dynamically
2962 loaded modules.
2963
2964
2965.. cfunction:: int PyCObject_Check(PyObject *p)
2966
2967 Return true if its argument is a :ctype:`PyCObject`.
2968
2969
2970.. cfunction:: PyObject* PyCObject_FromVoidPtr(void* cobj, void (*destr)(void *))
2971
2972 Create a :ctype:`PyCObject` from the ``void *`` *cobj*. The *destr* function
2973 will be called when the object is reclaimed, unless it is *NULL*.
2974
2975
2976.. cfunction:: PyObject* PyCObject_FromVoidPtrAndDesc(void* cobj, void* desc, void (*destr)(void *, void *))
2977
2978 Create a :ctype:`PyCObject` from the :ctype:`void \*` *cobj*. The *destr*
2979 function will be called when the object is reclaimed. The *desc* argument can
2980 be used to pass extra callback data for the destructor function.
2981
2982
2983.. cfunction:: void* PyCObject_AsVoidPtr(PyObject* self)
2984
2985 Return the object :ctype:`void \*` that the :ctype:`PyCObject` *self* was
2986 created with.
2987
2988
2989.. cfunction:: void* PyCObject_GetDesc(PyObject* self)
2990
2991 Return the description :ctype:`void \*` that the :ctype:`PyCObject` *self* was
2992 created with.
2993
2994
2995.. cfunction:: int PyCObject_SetVoidPtr(PyObject* self, void* cobj)
2996
2997 Set the void pointer inside *self* to *cobj*. The :ctype:`PyCObject` must not
2998 have an associated destructor. Return true on success, false on failure.
2999
3000
3001.. _cell-objects:
3002
3003Cell Objects
3004------------
3005
3006"Cell" objects are used to implement variables referenced by multiple scopes.
3007For each such variable, a cell object is created to store the value; the local
3008variables of each stack frame that references the value contains a reference to
3009the cells from outer scopes which also use that variable. When the value is
3010accessed, the value contained in the cell is used instead of the cell object
3011itself. This de-referencing of the cell object requires support from the
3012generated byte-code; these are not automatically de-referenced when accessed.
3013Cell objects are not likely to be useful elsewhere.
3014
3015
3016.. ctype:: PyCellObject
3017
3018 The C structure used for cell objects.
3019
3020
3021.. cvar:: PyTypeObject PyCell_Type
3022
3023 The type object corresponding to cell objects.
3024
3025
3026.. cfunction:: int PyCell_Check(ob)
3027
3028 Return true if *ob* is a cell object; *ob* must not be *NULL*.
3029
3030
3031.. cfunction:: PyObject* PyCell_New(PyObject *ob)
3032
3033 Create and return a new cell object containing the value *ob*. The parameter may
3034 be *NULL*.
3035
3036
3037.. cfunction:: PyObject* PyCell_Get(PyObject *cell)
3038
3039 Return the contents of the cell *cell*.
3040
3041
3042.. cfunction:: PyObject* PyCell_GET(PyObject *cell)
3043
3044 Return the contents of the cell *cell*, but without checking that *cell* is
3045 non-*NULL* and a cell object.
3046
3047
3048.. cfunction:: int PyCell_Set(PyObject *cell, PyObject *value)
3049
3050 Set the contents of the cell object *cell* to *value*. This releases the
3051 reference to any current content of the cell. *value* may be *NULL*. *cell*
3052 must be non-*NULL*; if it is not a cell object, ``-1`` will be returned. On
3053 success, ``0`` will be returned.
3054
3055
3056.. cfunction:: void PyCell_SET(PyObject *cell, PyObject *value)
3057
3058 Sets the value of the cell object *cell* to *value*. No reference counts are
3059 adjusted, and no checks are made for safety; *cell* must be non-*NULL* and must
3060 be a cell object.
3061
3062
3063.. _gen-objects:
3064
3065Generator Objects
3066-----------------
3067
3068Generator objects are what Python uses to implement generator iterators. They
3069are normally created by iterating over a function that yields values, rather
3070than explicitly calling :cfunc:`PyGen_New`.
3071
3072
3073.. ctype:: PyGenObject
3074
3075 The C structure used for generator objects.
3076
3077
3078.. cvar:: PyTypeObject PyGen_Type
3079
3080 The type object corresponding to generator objects
3081
3082
3083.. cfunction:: int PyGen_Check(ob)
3084
3085 Return true if *ob* is a generator object; *ob* must not be *NULL*.
3086
3087
3088.. cfunction:: int PyGen_CheckExact(ob)
3089
3090 Return true if *ob*'s type is *PyGen_Type* is a generator object; *ob* must not
3091 be *NULL*.
3092
3093
3094.. cfunction:: PyObject* PyGen_New(PyFrameObject *frame)
3095
3096 Create and return a new generator object based on the *frame* object. A
3097 reference to *frame* is stolen by this function. The parameter must not be
3098 *NULL*.
3099
3100
3101.. _datetimeobjects:
3102
3103DateTime Objects
3104----------------
3105
3106Various date and time objects are supplied by the :mod:`datetime` module.
3107Before using any of these functions, the header file :file:`datetime.h` must be
3108included in your source (note that this is not included by :file:`Python.h`),
3109and the macro :cfunc:`PyDateTime_IMPORT` must be invoked. The macro puts a
3110pointer to a C structure into a static variable, ``PyDateTimeAPI``, that is
3111used by the following macros.
3112
3113Type-check macros:
3114
Georg Brandl116aa622007-08-15 14:28:22 +00003115.. cfunction:: int PyDate_Check(PyObject *ob)
3116
3117 Return true if *ob* is of type :cdata:`PyDateTime_DateType` or a subtype of
3118 :cdata:`PyDateTime_DateType`. *ob* must not be *NULL*.
3119
Georg Brandl116aa622007-08-15 14:28:22 +00003120
3121.. cfunction:: int PyDate_CheckExact(PyObject *ob)
3122
3123 Return true if *ob* is of type :cdata:`PyDateTime_DateType`. *ob* must not be
3124 *NULL*.
3125
Georg Brandl116aa622007-08-15 14:28:22 +00003126
3127.. cfunction:: int PyDateTime_Check(PyObject *ob)
3128
3129 Return true if *ob* is of type :cdata:`PyDateTime_DateTimeType` or a subtype of
3130 :cdata:`PyDateTime_DateTimeType`. *ob* must not be *NULL*.
3131
Georg Brandl116aa622007-08-15 14:28:22 +00003132
3133.. cfunction:: int PyDateTime_CheckExact(PyObject *ob)
3134
3135 Return true if *ob* is of type :cdata:`PyDateTime_DateTimeType`. *ob* must not
3136 be *NULL*.
3137
Georg Brandl116aa622007-08-15 14:28:22 +00003138
3139.. cfunction:: int PyTime_Check(PyObject *ob)
3140
3141 Return true if *ob* is of type :cdata:`PyDateTime_TimeType` or a subtype of
3142 :cdata:`PyDateTime_TimeType`. *ob* must not be *NULL*.
3143
Georg Brandl116aa622007-08-15 14:28:22 +00003144
3145.. cfunction:: int PyTime_CheckExact(PyObject *ob)
3146
3147 Return true if *ob* is of type :cdata:`PyDateTime_TimeType`. *ob* must not be
3148 *NULL*.
3149
Georg Brandl116aa622007-08-15 14:28:22 +00003150
3151.. cfunction:: int PyDelta_Check(PyObject *ob)
3152
3153 Return true if *ob* is of type :cdata:`PyDateTime_DeltaType` or a subtype of
3154 :cdata:`PyDateTime_DeltaType`. *ob* must not be *NULL*.
3155
Georg Brandl116aa622007-08-15 14:28:22 +00003156
3157.. cfunction:: int PyDelta_CheckExact(PyObject *ob)
3158
3159 Return true if *ob* is of type :cdata:`PyDateTime_DeltaType`. *ob* must not be
3160 *NULL*.
3161
Georg Brandl116aa622007-08-15 14:28:22 +00003162
3163.. cfunction:: int PyTZInfo_Check(PyObject *ob)
3164
3165 Return true if *ob* is of type :cdata:`PyDateTime_TZInfoType` or a subtype of
3166 :cdata:`PyDateTime_TZInfoType`. *ob* must not be *NULL*.
3167
Georg Brandl116aa622007-08-15 14:28:22 +00003168
3169.. cfunction:: int PyTZInfo_CheckExact(PyObject *ob)
3170
3171 Return true if *ob* is of type :cdata:`PyDateTime_TZInfoType`. *ob* must not be
3172 *NULL*.
3173
Georg Brandl116aa622007-08-15 14:28:22 +00003174
3175Macros to create objects:
3176
Georg Brandl116aa622007-08-15 14:28:22 +00003177.. cfunction:: PyObject* PyDate_FromDate(int year, int month, int day)
3178
3179 Return a ``datetime.date`` object with the specified year, month and day.
3180
Georg Brandl116aa622007-08-15 14:28:22 +00003181
3182.. cfunction:: PyObject* PyDateTime_FromDateAndTime(int year, int month, int day, int hour, int minute, int second, int usecond)
3183
3184 Return a ``datetime.datetime`` object with the specified year, month, day, hour,
3185 minute, second and microsecond.
3186
Georg Brandl116aa622007-08-15 14:28:22 +00003187
3188.. cfunction:: PyObject* PyTime_FromTime(int hour, int minute, int second, int usecond)
3189
3190 Return a ``datetime.time`` object with the specified hour, minute, second and
3191 microsecond.
3192
Georg Brandl116aa622007-08-15 14:28:22 +00003193
3194.. cfunction:: PyObject* PyDelta_FromDSU(int days, int seconds, int useconds)
3195
3196 Return a ``datetime.timedelta`` object representing the given number of days,
3197 seconds and microseconds. Normalization is performed so that the resulting
3198 number of microseconds and seconds lie in the ranges documented for
3199 ``datetime.timedelta`` objects.
3200
Georg Brandl116aa622007-08-15 14:28:22 +00003201
3202Macros to extract fields from date objects. The argument must be an instance of
3203:cdata:`PyDateTime_Date`, including subclasses (such as
3204:cdata:`PyDateTime_DateTime`). The argument must not be *NULL*, and the type is
3205not checked:
3206
Georg Brandl116aa622007-08-15 14:28:22 +00003207.. cfunction:: int PyDateTime_GET_YEAR(PyDateTime_Date *o)
3208
3209 Return the year, as a positive int.
3210
Georg Brandl116aa622007-08-15 14:28:22 +00003211
3212.. cfunction:: int PyDateTime_GET_MONTH(PyDateTime_Date *o)
3213
3214 Return the month, as an int from 1 through 12.
3215
Georg Brandl116aa622007-08-15 14:28:22 +00003216
3217.. cfunction:: int PyDateTime_GET_DAY(PyDateTime_Date *o)
3218
3219 Return the day, as an int from 1 through 31.
3220
Georg Brandl116aa622007-08-15 14:28:22 +00003221
3222Macros to extract fields from datetime objects. The argument must be an
3223instance of :cdata:`PyDateTime_DateTime`, including subclasses. The argument
3224must not be *NULL*, and the type is not checked:
3225
Georg Brandl116aa622007-08-15 14:28:22 +00003226.. cfunction:: int PyDateTime_DATE_GET_HOUR(PyDateTime_DateTime *o)
3227
3228 Return the hour, as an int from 0 through 23.
3229
Georg Brandl116aa622007-08-15 14:28:22 +00003230
3231.. cfunction:: int PyDateTime_DATE_GET_MINUTE(PyDateTime_DateTime *o)
3232
3233 Return the minute, as an int from 0 through 59.
3234
Georg Brandl116aa622007-08-15 14:28:22 +00003235
3236.. cfunction:: int PyDateTime_DATE_GET_SECOND(PyDateTime_DateTime *o)
3237
3238 Return the second, as an int from 0 through 59.
3239
Georg Brandl116aa622007-08-15 14:28:22 +00003240
3241.. cfunction:: int PyDateTime_DATE_GET_MICROSECOND(PyDateTime_DateTime *o)
3242
3243 Return the microsecond, as an int from 0 through 999999.
3244
Georg Brandl116aa622007-08-15 14:28:22 +00003245
3246Macros to extract fields from time objects. The argument must be an instance of
3247:cdata:`PyDateTime_Time`, including subclasses. The argument must not be *NULL*,
3248and the type is not checked:
3249
Georg Brandl116aa622007-08-15 14:28:22 +00003250.. cfunction:: int PyDateTime_TIME_GET_HOUR(PyDateTime_Time *o)
3251
3252 Return the hour, as an int from 0 through 23.
3253
Georg Brandl116aa622007-08-15 14:28:22 +00003254
3255.. cfunction:: int PyDateTime_TIME_GET_MINUTE(PyDateTime_Time *o)
3256
3257 Return the minute, as an int from 0 through 59.
3258
Georg Brandl116aa622007-08-15 14:28:22 +00003259
3260.. cfunction:: int PyDateTime_TIME_GET_SECOND(PyDateTime_Time *o)
3261
3262 Return the second, as an int from 0 through 59.
3263
Georg Brandl116aa622007-08-15 14:28:22 +00003264
3265.. cfunction:: int PyDateTime_TIME_GET_MICROSECOND(PyDateTime_Time *o)
3266
3267 Return the microsecond, as an int from 0 through 999999.
3268
Georg Brandl116aa622007-08-15 14:28:22 +00003269
3270Macros for the convenience of modules implementing the DB API:
3271
Georg Brandl116aa622007-08-15 14:28:22 +00003272.. cfunction:: PyObject* PyDateTime_FromTimestamp(PyObject *args)
3273
3274 Create and return a new ``datetime.datetime`` object given an argument tuple
3275 suitable for passing to ``datetime.datetime.fromtimestamp()``.
3276
Georg Brandl116aa622007-08-15 14:28:22 +00003277
3278.. cfunction:: PyObject* PyDate_FromTimestamp(PyObject *args)
3279
3280 Create and return a new ``datetime.date`` object given an argument tuple
3281 suitable for passing to ``datetime.date.fromtimestamp()``.
3282
Georg Brandl116aa622007-08-15 14:28:22 +00003283
3284.. _setobjects:
3285
3286Set Objects
3287-----------
3288
3289.. sectionauthor:: Raymond D. Hettinger <python@rcn.com>
3290
3291
3292.. index::
3293 object: set
3294 object: frozenset
3295
Georg Brandl116aa622007-08-15 14:28:22 +00003296This section details the public API for :class:`set` and :class:`frozenset`
3297objects. Any functionality not listed below is best accessed using the either
3298the abstract object protocol (including :cfunc:`PyObject_CallMethod`,
3299:cfunc:`PyObject_RichCompareBool`, :cfunc:`PyObject_Hash`,
3300:cfunc:`PyObject_Repr`, :cfunc:`PyObject_IsTrue`, :cfunc:`PyObject_Print`, and
3301:cfunc:`PyObject_GetIter`) or the abstract number protocol (including
3302:cfunc:`PyNumber_And`, :cfunc:`PyNumber_Subtract`, :cfunc:`PyNumber_Or`,
3303:cfunc:`PyNumber_Xor`, :cfunc:`PyNumber_InPlaceAnd`,
3304:cfunc:`PyNumber_InPlaceSubtract`, :cfunc:`PyNumber_InPlaceOr`, and
3305:cfunc:`PyNumber_InPlaceXor`).
3306
3307
3308.. ctype:: PySetObject
3309
3310 This subtype of :ctype:`PyObject` is used to hold the internal data for both
3311 :class:`set` and :class:`frozenset` objects. It is like a :ctype:`PyDictObject`
3312 in that it is a fixed size for small sets (much like tuple storage) and will
3313 point to a separate, variable sized block of memory for medium and large sized
3314 sets (much like list storage). None of the fields of this structure should be
3315 considered public and are subject to change. All access should be done through
3316 the documented API rather than by manipulating the values in the structure.
3317
3318
3319.. cvar:: PyTypeObject PySet_Type
3320
3321 This is an instance of :ctype:`PyTypeObject` representing the Python
3322 :class:`set` type.
3323
3324
3325.. cvar:: PyTypeObject PyFrozenSet_Type
3326
3327 This is an instance of :ctype:`PyTypeObject` representing the Python
3328 :class:`frozenset` type.
3329
3330The following type check macros work on pointers to any Python object. Likewise,
3331the constructor functions work with any iterable Python object.
3332
3333
3334.. cfunction:: int PyAnySet_Check(PyObject *p)
3335
3336 Return true if *p* is a :class:`set` object, a :class:`frozenset` object, or an
3337 instance of a subtype.
3338
3339
3340.. cfunction:: int PyAnySet_CheckExact(PyObject *p)
3341
3342 Return true if *p* is a :class:`set` object or a :class:`frozenset` object but
3343 not an instance of a subtype.
3344
3345
3346.. cfunction:: int PyFrozenSet_CheckExact(PyObject *p)
3347
3348 Return true if *p* is a :class:`frozenset` object but not an instance of a
3349 subtype.
3350
3351
3352.. cfunction:: PyObject* PySet_New(PyObject *iterable)
3353
3354 Return a new :class:`set` containing objects returned by the *iterable*. The
3355 *iterable* may be *NULL* to create a new empty set. Return the new set on
3356 success or *NULL* on failure. Raise :exc:`TypeError` if *iterable* is not
3357 actually iterable. The constructor is also useful for copying a set
3358 (``c=set(s)``).
3359
3360
3361.. cfunction:: PyObject* PyFrozenSet_New(PyObject *iterable)
3362
3363 Return a new :class:`frozenset` containing objects returned by the *iterable*.
3364 The *iterable* may be *NULL* to create a new empty frozenset. Return the new
3365 set on success or *NULL* on failure. Raise :exc:`TypeError` if *iterable* is
3366 not actually iterable.
3367
3368The following functions and macros are available for instances of :class:`set`
3369or :class:`frozenset` or instances of their subtypes.
3370
3371
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003372.. cfunction:: Py_ssize_t PySet_Size(PyObject *anyset)
Georg Brandl116aa622007-08-15 14:28:22 +00003373
3374 .. index:: builtin: len
3375
3376 Return the length of a :class:`set` or :class:`frozenset` object. Equivalent to
3377 ``len(anyset)``. Raises a :exc:`PyExc_SystemError` if *anyset* is not a
3378 :class:`set`, :class:`frozenset`, or an instance of a subtype.
3379
3380
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003381.. cfunction:: Py_ssize_t PySet_GET_SIZE(PyObject *anyset)
Georg Brandl116aa622007-08-15 14:28:22 +00003382
3383 Macro form of :cfunc:`PySet_Size` without error checking.
3384
3385
3386.. cfunction:: int PySet_Contains(PyObject *anyset, PyObject *key)
3387
3388 Return 1 if found, 0 if not found, and -1 if an error is encountered. Unlike
3389 the Python :meth:`__contains__` method, this function does not automatically
3390 convert unhashable sets into temporary frozensets. Raise a :exc:`TypeError` if
3391 the *key* is unhashable. Raise :exc:`PyExc_SystemError` if *anyset* is not a
3392 :class:`set`, :class:`frozenset`, or an instance of a subtype.
3393
3394The following functions are available for instances of :class:`set` or its
3395subtypes but not for instances of :class:`frozenset` or its subtypes.
3396
3397
3398.. cfunction:: int PySet_Add(PyObject *set, PyObject *key)
3399
3400 Add *key* to a :class:`set` instance. Does not apply to :class:`frozenset`
3401 instances. Return 0 on success or -1 on failure. Raise a :exc:`TypeError` if
3402 the *key* is unhashable. Raise a :exc:`MemoryError` if there is no room to grow.
3403 Raise a :exc:`SystemError` if *set* is an not an instance of :class:`set` or its
3404 subtype.
3405
3406
3407.. cfunction:: int PySet_Discard(PyObject *set, PyObject *key)
3408
3409 Return 1 if found and removed, 0 if not found (no action taken), and -1 if an
3410 error is encountered. Does not raise :exc:`KeyError` for missing keys. Raise a
3411 :exc:`TypeError` if the *key* is unhashable. Unlike the Python :meth:`discard`
3412 method, this function does not automatically convert unhashable sets into
3413 temporary frozensets. Raise :exc:`PyExc_SystemError` if *set* is an not an
3414 instance of :class:`set` or its subtype.
3415
3416
3417.. cfunction:: PyObject* PySet_Pop(PyObject *set)
3418
3419 Return a new reference to an arbitrary object in the *set*, and removes the
3420 object from the *set*. Return *NULL* on failure. Raise :exc:`KeyError` if the
3421 set is empty. Raise a :exc:`SystemError` if *set* is an not an instance of
3422 :class:`set` or its subtype.
3423
3424
3425.. cfunction:: int PySet_Clear(PyObject *set)
3426
3427 Empty an existing set of all elements.
3428