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