blob: 2bc11fad08dc05b8a062e2d4f56a8d343100c789 [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
1304These are the UTF-16 codec APIs:
1305
1306.. % --- UTF-16 Codecs ------------------------------------------------------ */
1307
1308
1309.. cfunction:: PyObject* PyUnicode_DecodeUTF16(const char *s, Py_ssize_t size, const char *errors, int *byteorder)
1310
1311 Decode *length* bytes from a UTF-16 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 two 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.
1326
1327 If *byteorder* is *NULL*, the codec starts in native order mode.
1328
1329 Return *NULL* if an exception was raised by the codec.
1330
1331
1332.. cfunction:: PyObject* PyUnicode_DecodeUTF16Stateful(const char *s, Py_ssize_t size, const char *errors, int *byteorder, Py_ssize_t *consumed)
1333
1334 If *consumed* is *NULL*, behave like :cfunc:`PyUnicode_DecodeUTF16`. If
1335 *consumed* is not *NULL*, :cfunc:`PyUnicode_DecodeUTF16Stateful` will not treat
1336 trailing incomplete UTF-16 byte sequences (such as an odd number of bytes or a
1337 split surrogate pair) as an error. Those bytes will not be decoded and the
1338 number of bytes that have been decoded will be stored in *consumed*.
1339
1340 .. versionadded:: 2.4
1341
1342
1343.. cfunction:: PyObject* PyUnicode_EncodeUTF16(const Py_UNICODE *s, Py_ssize_t size, const char *errors, int byteorder)
1344
1345 Return a Python string object holding the UTF-16 encoded value of the Unicode
1346 data in *s*. If *byteorder* is not ``0``, output is written according to the
1347 following byte order::
1348
1349 byteorder == -1: little endian
1350 byteorder == 0: native byte order (writes a BOM mark)
1351 byteorder == 1: big endian
1352
1353 If byteorder is ``0``, the output string will always start with the Unicode BOM
1354 mark (U+FEFF). In the other two modes, no BOM mark is prepended.
1355
1356 If *Py_UNICODE_WIDE* is defined, a single :ctype:`Py_UNICODE` value may get
1357 represented as a surrogate pair. If it is not defined, each :ctype:`Py_UNICODE`
1358 values is interpreted as an UCS-2 character.
1359
1360 Return *NULL* if an exception was raised by the codec.
1361
1362
1363.. cfunction:: PyObject* PyUnicode_AsUTF16String(PyObject *unicode)
1364
1365 Return a Python string using the UTF-16 encoding in native byte order. The
1366 string always starts with a BOM mark. Error handling is "strict". Return
1367 *NULL* if an exception was raised by the codec.
1368
1369These are the "Unicode Escape" codec APIs:
1370
1371.. % --- Unicode-Escape Codecs ----------------------------------------------
1372
1373
1374.. cfunction:: PyObject* PyUnicode_DecodeUnicodeEscape(const char *s, Py_ssize_t size, const char *errors)
1375
1376 Create a Unicode object by decoding *size* bytes of the Unicode-Escape encoded
1377 string *s*. Return *NULL* if an exception was raised by the codec.
1378
1379
1380.. cfunction:: PyObject* PyUnicode_EncodeUnicodeEscape(const Py_UNICODE *s, Py_ssize_t size)
1381
1382 Encode the :ctype:`Py_UNICODE` buffer of the given size using Unicode-Escape and
1383 return a Python string object. Return *NULL* if an exception was raised by the
1384 codec.
1385
1386
1387.. cfunction:: PyObject* PyUnicode_AsUnicodeEscapeString(PyObject *unicode)
1388
1389 Encode a Unicode objects using Unicode-Escape and return the result as Python
1390 string object. Error handling is "strict". Return *NULL* if an exception was
1391 raised by the codec.
1392
1393These are the "Raw Unicode Escape" codec APIs:
1394
1395.. % --- Raw-Unicode-Escape Codecs ------------------------------------------
1396
1397
1398.. cfunction:: PyObject* PyUnicode_DecodeRawUnicodeEscape(const char *s, Py_ssize_t size, const char *errors)
1399
1400 Create a Unicode object by decoding *size* bytes of the Raw-Unicode-Escape
1401 encoded string *s*. Return *NULL* if an exception was raised by the codec.
1402
1403
1404.. cfunction:: PyObject* PyUnicode_EncodeRawUnicodeEscape(const Py_UNICODE *s, Py_ssize_t size, const char *errors)
1405
1406 Encode the :ctype:`Py_UNICODE` buffer of the given size using Raw-Unicode-Escape
1407 and return a Python string object. Return *NULL* if an exception was raised by
1408 the codec.
1409
1410
1411.. cfunction:: PyObject* PyUnicode_AsRawUnicodeEscapeString(PyObject *unicode)
1412
1413 Encode a Unicode objects using Raw-Unicode-Escape and return the result as
1414 Python string object. Error handling is "strict". Return *NULL* if an exception
1415 was raised by the codec.
1416
1417These are the Latin-1 codec APIs: Latin-1 corresponds to the first 256 Unicode
1418ordinals and only these are accepted by the codecs during encoding.
1419
1420.. % --- Latin-1 Codecs -----------------------------------------------------
1421
1422
1423.. cfunction:: PyObject* PyUnicode_DecodeLatin1(const char *s, Py_ssize_t size, const char *errors)
1424
1425 Create a Unicode object by decoding *size* bytes of the Latin-1 encoded string
1426 *s*. Return *NULL* if an exception was raised by the codec.
1427
1428
1429.. cfunction:: PyObject* PyUnicode_EncodeLatin1(const Py_UNICODE *s, Py_ssize_t size, const char *errors)
1430
1431 Encode the :ctype:`Py_UNICODE` buffer of the given size using Latin-1 and return
1432 a Python string object. Return *NULL* if an exception was raised by the codec.
1433
1434
1435.. cfunction:: PyObject* PyUnicode_AsLatin1String(PyObject *unicode)
1436
1437 Encode a Unicode objects using Latin-1 and return the result as Python string
1438 object. Error handling is "strict". Return *NULL* if an exception was raised
1439 by the codec.
1440
1441These are the ASCII codec APIs. Only 7-bit ASCII data is accepted. All other
1442codes generate errors.
1443
1444.. % --- ASCII Codecs -------------------------------------------------------
1445
1446
1447.. cfunction:: PyObject* PyUnicode_DecodeASCII(const char *s, Py_ssize_t size, const char *errors)
1448
1449 Create a Unicode object by decoding *size* bytes of the ASCII encoded string
1450 *s*. Return *NULL* if an exception was raised by the codec.
1451
1452
1453.. cfunction:: PyObject* PyUnicode_EncodeASCII(const Py_UNICODE *s, Py_ssize_t size, const char *errors)
1454
1455 Encode the :ctype:`Py_UNICODE` buffer of the given size using ASCII and return a
1456 Python string object. Return *NULL* if an exception was raised by the codec.
1457
1458
1459.. cfunction:: PyObject* PyUnicode_AsASCIIString(PyObject *unicode)
1460
1461 Encode a Unicode objects using ASCII and return the result as Python string
1462 object. Error handling is "strict". Return *NULL* if an exception was raised
1463 by the codec.
1464
1465These are the mapping codec APIs:
1466
1467.. % --- Character Map Codecs -----------------------------------------------
1468
1469This codec is special in that it can be used to implement many different codecs
1470(and this is in fact what was done to obtain most of the standard codecs
1471included in the :mod:`encodings` package). The codec uses mapping to encode and
1472decode characters.
1473
1474Decoding mappings must map single string characters to single Unicode
1475characters, integers (which are then interpreted as Unicode ordinals) or None
1476(meaning "undefined mapping" and causing an error).
1477
1478Encoding mappings must map single Unicode characters to single string
1479characters, integers (which are then interpreted as Latin-1 ordinals) or None
1480(meaning "undefined mapping" and causing an error).
1481
1482The mapping objects provided must only support the __getitem__ mapping
1483interface.
1484
1485If a character lookup fails with a LookupError, the character is copied as-is
1486meaning that its ordinal value will be interpreted as Unicode or Latin-1 ordinal
1487resp. Because of this, mappings only need to contain those mappings which map
1488characters to different code points.
1489
1490
1491.. cfunction:: PyObject* PyUnicode_DecodeCharmap(const char *s, Py_ssize_t size, PyObject *mapping, const char *errors)
1492
1493 Create a Unicode object by decoding *size* bytes of the encoded string *s* using
1494 the given *mapping* object. Return *NULL* if an exception was raised by the
1495 codec. If *mapping* is *NULL* latin-1 decoding will be done. Else it can be a
1496 dictionary mapping byte or a unicode string, which is treated as a lookup table.
1497 Byte values greater that the length of the string and U+FFFE "characters" are
1498 treated as "undefined mapping".
1499
1500 .. versionchanged:: 2.4
1501 Allowed unicode string as mapping argument.
1502
1503
1504.. cfunction:: PyObject* PyUnicode_EncodeCharmap(const Py_UNICODE *s, Py_ssize_t size, PyObject *mapping, const char *errors)
1505
1506 Encode the :ctype:`Py_UNICODE` buffer of the given size using the given
1507 *mapping* object and return a Python string object. Return *NULL* if an
1508 exception was raised by the codec.
1509
1510
1511.. cfunction:: PyObject* PyUnicode_AsCharmapString(PyObject *unicode, PyObject *mapping)
1512
1513 Encode a Unicode objects using the given *mapping* object and return the result
1514 as Python string object. Error handling is "strict". Return *NULL* if an
1515 exception was raised by the codec.
1516
1517The following codec API is special in that maps Unicode to Unicode.
1518
1519
1520.. cfunction:: PyObject* PyUnicode_TranslateCharmap(const Py_UNICODE *s, Py_ssize_t size, PyObject *table, const char *errors)
1521
1522 Translate a :ctype:`Py_UNICODE` buffer of the given length by applying a
1523 character mapping *table* to it and return the resulting Unicode object. Return
1524 *NULL* when an exception was raised by the codec.
1525
1526 The *mapping* table must map Unicode ordinal integers to Unicode ordinal
1527 integers or None (causing deletion of the character).
1528
1529 Mapping tables need only provide the :meth:`__getitem__` interface; dictionaries
1530 and sequences work well. Unmapped character ordinals (ones which cause a
1531 :exc:`LookupError`) are left untouched and are copied as-is.
1532
1533These are the MBCS codec APIs. They are currently only available on Windows and
1534use the Win32 MBCS converters to implement the conversions. Note that MBCS (or
1535DBCS) is a class of encodings, not just one. The target encoding is defined by
1536the user settings on the machine running the codec.
1537
1538.. % --- MBCS codecs for Windows --------------------------------------------
1539
1540
1541.. cfunction:: PyObject* PyUnicode_DecodeMBCS(const char *s, Py_ssize_t size, const char *errors)
1542
1543 Create a Unicode object by decoding *size* bytes of the MBCS encoded string *s*.
1544 Return *NULL* if an exception was raised by the codec.
1545
1546
1547.. cfunction:: PyObject* PyUnicode_DecodeMBCSStateful(const char *s, int size, const char *errors, int *consumed)
1548
1549 If *consumed* is *NULL*, behave like :cfunc:`PyUnicode_DecodeMBCS`. If
1550 *consumed* is not *NULL*, :cfunc:`PyUnicode_DecodeMBCSStateful` will not decode
1551 trailing lead byte and the number of bytes that have been decoded will be stored
1552 in *consumed*.
1553
1554 .. versionadded:: 2.5
1555
1556
1557.. cfunction:: PyObject* PyUnicode_EncodeMBCS(const Py_UNICODE *s, Py_ssize_t size, const char *errors)
1558
1559 Encode the :ctype:`Py_UNICODE` buffer of the given size using MBCS and return a
1560 Python string object. Return *NULL* if an exception was raised by the codec.
1561
1562
1563.. cfunction:: PyObject* PyUnicode_AsMBCSString(PyObject *unicode)
1564
1565 Encode a Unicode objects using MBCS and return the result as Python string
1566 object. Error handling is "strict". Return *NULL* if an exception was raised
1567 by the codec.
1568
1569.. % --- Methods & Slots ----------------------------------------------------
1570
1571
1572.. _unicodemethodsandslots:
1573
1574Methods and Slot Functions
1575^^^^^^^^^^^^^^^^^^^^^^^^^^
1576
1577The following APIs are capable of handling Unicode objects and strings on input
1578(we refer to them as strings in the descriptions) and return Unicode objects or
1579integers as appropriate.
1580
1581They all return *NULL* or ``-1`` if an exception occurs.
1582
1583
1584.. cfunction:: PyObject* PyUnicode_Concat(PyObject *left, PyObject *right)
1585
1586 Concat two strings giving a new Unicode string.
1587
1588
1589.. cfunction:: PyObject* PyUnicode_Split(PyObject *s, PyObject *sep, Py_ssize_t maxsplit)
1590
1591 Split a string giving a list of Unicode strings. If sep is *NULL*, splitting
1592 will be done at all whitespace substrings. Otherwise, splits occur at the given
1593 separator. At most *maxsplit* splits will be done. If negative, no limit is
1594 set. Separators are not included in the resulting list.
1595
1596
1597.. cfunction:: PyObject* PyUnicode_Splitlines(PyObject *s, int keepend)
1598
1599 Split a Unicode string at line breaks, returning a list of Unicode strings.
1600 CRLF is considered to be one line break. If *keepend* is 0, the Line break
1601 characters are not included in the resulting strings.
1602
1603
1604.. cfunction:: PyObject* PyUnicode_Translate(PyObject *str, PyObject *table, const char *errors)
1605
1606 Translate a string by applying a character mapping table to it and return the
1607 resulting Unicode object.
1608
1609 The mapping table must map Unicode ordinal integers to Unicode ordinal integers
1610 or None (causing deletion of the character).
1611
1612 Mapping tables need only provide the :meth:`__getitem__` interface; dictionaries
1613 and sequences work well. Unmapped character ordinals (ones which cause a
1614 :exc:`LookupError`) are left untouched and are copied as-is.
1615
1616 *errors* has the usual meaning for codecs. It may be *NULL* which indicates to
1617 use the default error handling.
1618
1619
1620.. cfunction:: PyObject* PyUnicode_Join(PyObject *separator, PyObject *seq)
1621
1622 Join a sequence of strings using the given separator and return the resulting
1623 Unicode string.
1624
1625
1626.. cfunction:: int PyUnicode_Tailmatch(PyObject *str, PyObject *substr, Py_ssize_t start, Py_ssize_t end, int direction)
1627
1628 Return 1 if *substr* matches *str*[*start*:*end*] at the given tail end
1629 (*direction* == -1 means to do a prefix match, *direction* == 1 a suffix match),
1630 0 otherwise. Return ``-1`` if an error occurred.
1631
1632
1633.. cfunction:: Py_ssize_t PyUnicode_Find(PyObject *str, PyObject *substr, Py_ssize_t start, Py_ssize_t end, int direction)
1634
1635 Return the first position of *substr* in *str*[*start*:*end*] using the given
1636 *direction* (*direction* == 1 means to do a forward search, *direction* == -1 a
1637 backward search). The return value is the index of the first match; a value of
1638 ``-1`` indicates that no match was found, and ``-2`` indicates that an error
1639 occurred and an exception has been set.
1640
1641
1642.. cfunction:: Py_ssize_t PyUnicode_Count(PyObject *str, PyObject *substr, Py_ssize_t start, Py_ssize_t end)
1643
1644 Return the number of non-overlapping occurrences of *substr* in
1645 ``str[start:end]``. Return ``-1`` if an error occurred.
1646
1647
1648.. cfunction:: PyObject* PyUnicode_Replace(PyObject *str, PyObject *substr, PyObject *replstr, Py_ssize_t maxcount)
1649
1650 Replace at most *maxcount* occurrences of *substr* in *str* with *replstr* and
1651 return the resulting Unicode object. *maxcount* == -1 means replace all
1652 occurrences.
1653
1654
1655.. cfunction:: int PyUnicode_Compare(PyObject *left, PyObject *right)
1656
1657 Compare two strings and return -1, 0, 1 for less than, equal, and greater than,
1658 respectively.
1659
1660
1661.. cfunction:: int PyUnicode_RichCompare(PyObject *left, PyObject *right, int op)
1662
1663 Rich compare two unicode strings and return one of the following:
1664
1665 * ``NULL`` in case an exception was raised
1666 * :const:`Py_True` or :const:`Py_False` for successful comparisons
1667 * :const:`Py_NotImplemented` in case the type combination is unknown
1668
1669 Note that :const:`Py_EQ` and :const:`Py_NE` comparisons can cause a
1670 :exc:`UnicodeWarning` in case the conversion of the arguments to Unicode fails
1671 with a :exc:`UnicodeDecodeError`.
1672
1673 Possible values for *op* are :const:`Py_GT`, :const:`Py_GE`, :const:`Py_EQ`,
1674 :const:`Py_NE`, :const:`Py_LT`, and :const:`Py_LE`.
1675
1676
1677.. cfunction:: PyObject* PyUnicode_Format(PyObject *format, PyObject *args)
1678
1679 Return a new string object from *format* and *args*; this is analogous to
1680 ``format % args``. The *args* argument must be a tuple.
1681
1682
1683.. cfunction:: int PyUnicode_Contains(PyObject *container, PyObject *element)
1684
1685 Check whether *element* is contained in *container* and return true or false
1686 accordingly.
1687
1688 *element* has to coerce to a one element Unicode string. ``-1`` is returned if
1689 there was an error.
1690
1691
1692.. _bufferobjects:
1693
1694Buffer Objects
1695--------------
1696
1697.. sectionauthor:: Greg Stein <gstein@lyra.org>
1698
1699
1700.. index::
1701 object: buffer
1702 single: buffer interface
1703
1704Python objects implemented in C can export a group of functions called the
1705"buffer interface." These functions can be used by an object to expose its data
1706in a raw, byte-oriented format. Clients of the object can use the buffer
1707interface to access the object data directly, without needing to copy it first.
1708
1709Two examples of objects that support the buffer interface are strings and
1710arrays. The string object exposes the character contents in the buffer
1711interface's byte-oriented form. An array can also expose its contents, but it
1712should be noted that array elements may be multi-byte values.
1713
1714An example user of the buffer interface is the file object's :meth:`write`
1715method. Any object that can export a series of bytes through the buffer
1716interface can be written to a file. There are a number of format codes to
1717:cfunc:`PyArg_ParseTuple` that operate against an object's buffer interface,
1718returning data from the target object.
1719
1720.. index:: single: PyBufferProcs
1721
1722More information on the buffer interface is provided in the section
1723:ref:`buffer-structs`, under the description for :ctype:`PyBufferProcs`.
1724
1725A "buffer object" is defined in the :file:`bufferobject.h` header (included by
1726:file:`Python.h`). These objects look very similar to string objects at the
1727Python programming level: they support slicing, indexing, concatenation, and
1728some other standard string operations. However, their data can come from one of
1729two sources: from a block of memory, or from another object which exports the
1730buffer interface.
1731
1732Buffer objects are useful as a way to expose the data from another object's
1733buffer interface to the Python programmer. They can also be used as a zero-copy
1734slicing mechanism. Using their ability to reference a block of memory, it is
1735possible to expose any data to the Python programmer quite easily. The memory
1736could be a large, constant array in a C extension, it could be a raw block of
1737memory for manipulation before passing to an operating system library, or it
1738could be used to pass around structured data in its native, in-memory format.
1739
1740
1741.. ctype:: PyBufferObject
1742
1743 This subtype of :ctype:`PyObject` represents a buffer object.
1744
1745
1746.. cvar:: PyTypeObject PyBuffer_Type
1747
1748 .. index:: single: BufferType (in module types)
1749
1750 The instance of :ctype:`PyTypeObject` which represents the Python buffer type;
1751 it is the same object as ``buffer`` and ``types.BufferType`` in the Python
1752 layer. .
1753
1754
1755.. cvar:: int Py_END_OF_BUFFER
1756
1757 This constant may be passed as the *size* parameter to
1758 :cfunc:`PyBuffer_FromObject` or :cfunc:`PyBuffer_FromReadWriteObject`. It
1759 indicates that the new :ctype:`PyBufferObject` should refer to *base* object
1760 from the specified *offset* to the end of its exported buffer. Using this
1761 enables the caller to avoid querying the *base* object for its length.
1762
1763
1764.. cfunction:: int PyBuffer_Check(PyObject *p)
1765
1766 Return true if the argument has type :cdata:`PyBuffer_Type`.
1767
1768
1769.. cfunction:: PyObject* PyBuffer_FromObject(PyObject *base, Py_ssize_t offset, Py_ssize_t size)
1770
1771 Return a new read-only buffer object. This raises :exc:`TypeError` if *base*
1772 doesn't support the read-only buffer protocol or doesn't provide exactly one
1773 buffer segment, or it raises :exc:`ValueError` if *offset* is less than zero.
1774 The buffer will hold a reference to the *base* object, and the buffer's contents
1775 will refer to the *base* object's buffer interface, starting as position
1776 *offset* and extending for *size* bytes. If *size* is :const:`Py_END_OF_BUFFER`,
1777 then the new buffer's contents extend to the length of the *base* object's
1778 exported buffer data.
1779
1780
1781.. cfunction:: PyObject* PyBuffer_FromReadWriteObject(PyObject *base, Py_ssize_t offset, Py_ssize_t size)
1782
1783 Return a new writable buffer object. Parameters and exceptions are similar to
1784 those for :cfunc:`PyBuffer_FromObject`. If the *base* object does not export
1785 the writeable buffer protocol, then :exc:`TypeError` is raised.
1786
1787
1788.. cfunction:: PyObject* PyBuffer_FromMemory(void *ptr, Py_ssize_t size)
1789
1790 Return a new read-only buffer object that reads from a specified location in
1791 memory, with a specified size. The caller is responsible for ensuring that the
1792 memory buffer, passed in as *ptr*, is not deallocated while the returned buffer
1793 object exists. Raises :exc:`ValueError` if *size* is less than zero. Note that
1794 :const:`Py_END_OF_BUFFER` may *not* be passed for the *size* parameter;
1795 :exc:`ValueError` will be raised in that case.
1796
1797
1798.. cfunction:: PyObject* PyBuffer_FromReadWriteMemory(void *ptr, Py_ssize_t size)
1799
1800 Similar to :cfunc:`PyBuffer_FromMemory`, but the returned buffer is writable.
1801
1802
1803.. cfunction:: PyObject* PyBuffer_New(Py_ssize_t size)
1804
1805 Return a new writable buffer object that maintains its own memory buffer of
1806 *size* bytes. :exc:`ValueError` is returned if *size* is not zero or positive.
1807 Note that the memory buffer (as returned by :cfunc:`PyObject_AsWriteBuffer`) is
1808 not specifically aligned.
1809
1810
1811.. _tupleobjects:
1812
1813Tuple Objects
1814-------------
1815
1816.. index:: object: tuple
1817
1818
1819.. ctype:: PyTupleObject
1820
1821 This subtype of :ctype:`PyObject` represents a Python tuple object.
1822
1823
1824.. cvar:: PyTypeObject PyTuple_Type
1825
1826 .. index:: single: TupleType (in module types)
1827
1828 This instance of :ctype:`PyTypeObject` represents the Python tuple type; it is
1829 the same object as ``tuple`` and ``types.TupleType`` in the Python layer..
1830
1831
1832.. cfunction:: int PyTuple_Check(PyObject *p)
1833
1834 Return true if *p* is a tuple object or an instance of a subtype of the tuple
1835 type.
1836
1837 .. versionchanged:: 2.2
1838 Allowed subtypes to be accepted.
1839
1840
1841.. cfunction:: int PyTuple_CheckExact(PyObject *p)
1842
1843 Return true if *p* is a tuple object, but not an instance of a subtype of the
1844 tuple type.
1845
1846 .. versionadded:: 2.2
1847
1848
1849.. cfunction:: PyObject* PyTuple_New(Py_ssize_t len)
1850
1851 Return a new tuple object of size *len*, or *NULL* on failure.
1852
1853
1854.. cfunction:: PyObject* PyTuple_Pack(Py_ssize_t n, ...)
1855
1856 Return a new tuple object of size *n*, or *NULL* on failure. The tuple values
1857 are initialized to the subsequent *n* C arguments pointing to Python objects.
1858 ``PyTuple_Pack(2, a, b)`` is equivalent to ``Py_BuildValue("(OO)", a, b)``.
1859
1860 .. versionadded:: 2.4
1861
1862
1863.. cfunction:: int PyTuple_Size(PyObject *p)
1864
1865 Take a pointer to a tuple object, and return the size of that tuple.
1866
1867
1868.. cfunction:: int PyTuple_GET_SIZE(PyObject *p)
1869
1870 Return the size of the tuple *p*, which must be non-*NULL* and point to a tuple;
1871 no error checking is performed.
1872
1873
1874.. cfunction:: PyObject* PyTuple_GetItem(PyObject *p, Py_ssize_t pos)
1875
1876 Return the object at position *pos* in the tuple pointed to by *p*. If *pos* is
1877 out of bounds, return *NULL* and sets an :exc:`IndexError` exception.
1878
1879
1880.. cfunction:: PyObject* PyTuple_GET_ITEM(PyObject *p, Py_ssize_t pos)
1881
1882 Like :cfunc:`PyTuple_GetItem`, but does no checking of its arguments.
1883
1884
1885.. cfunction:: PyObject* PyTuple_GetSlice(PyObject *p, Py_ssize_t low, Py_ssize_t high)
1886
1887 Take a slice of the tuple pointed to by *p* from *low* to *high* and return it
1888 as a new tuple.
1889
1890
1891.. cfunction:: int PyTuple_SetItem(PyObject *p, Py_ssize_t pos, PyObject *o)
1892
1893 Insert a reference to object *o* at position *pos* of the tuple pointed to by
1894 *p*. Return ``0`` on success.
1895
1896 .. note::
1897
1898 This function "steals" a reference to *o*.
1899
1900
1901.. cfunction:: void PyTuple_SET_ITEM(PyObject *p, Py_ssize_t pos, PyObject *o)
1902
1903 Like :cfunc:`PyTuple_SetItem`, but does no error checking, and should *only* be
1904 used to fill in brand new tuples.
1905
1906 .. note::
1907
1908 This function "steals" a reference to *o*.
1909
1910
1911.. cfunction:: int _PyTuple_Resize(PyObject **p, Py_ssize_t newsize)
1912
1913 Can be used to resize a tuple. *newsize* will be the new length of the tuple.
1914 Because tuples are *supposed* to be immutable, this should only be used if there
1915 is only one reference to the object. Do *not* use this if the tuple may already
1916 be known to some other part of the code. The tuple will always grow or shrink
1917 at the end. Think of this as destroying the old tuple and creating a new one,
1918 only more efficiently. Returns ``0`` on success. Client code should never
1919 assume that the resulting value of ``*p`` will be the same as before calling
1920 this function. If the object referenced by ``*p`` is replaced, the original
1921 ``*p`` is destroyed. On failure, returns ``-1`` and sets ``*p`` to *NULL*, and
1922 raises :exc:`MemoryError` or :exc:`SystemError`.
1923
1924 .. versionchanged:: 2.2
1925 Removed unused third parameter, *last_is_sticky*.
1926
1927
1928.. _listobjects:
1929
1930List Objects
1931------------
1932
1933.. index:: object: list
1934
1935
1936.. ctype:: PyListObject
1937
1938 This subtype of :ctype:`PyObject` represents a Python list object.
1939
1940
1941.. cvar:: PyTypeObject PyList_Type
1942
1943 .. index:: single: ListType (in module types)
1944
1945 This instance of :ctype:`PyTypeObject` represents the Python list type. This is
1946 the same object as ``list`` and ``types.ListType`` in the Python layer.
1947
1948
1949.. cfunction:: int PyList_Check(PyObject *p)
1950
1951 Return true if *p* is a list object or an instance of a subtype of the list
1952 type.
1953
1954 .. versionchanged:: 2.2
1955 Allowed subtypes to be accepted.
1956
1957
1958.. cfunction:: int PyList_CheckExact(PyObject *p)
1959
1960 Return true if *p* is a list object, but not an instance of a subtype of the
1961 list type.
1962
1963 .. versionadded:: 2.2
1964
1965
1966.. cfunction:: PyObject* PyList_New(Py_ssize_t len)
1967
1968 Return a new list of length *len* on success, or *NULL* on failure.
1969
1970 .. note::
1971
1972 If *length* is greater than zero, the returned list object's items are set to
1973 ``NULL``. Thus you cannot use abstract API functions such as
1974 :cfunc:`PySequence_SetItem` or expose the object to Python code before setting
1975 all items to a real object with :cfunc:`PyList_SetItem`.
1976
1977
1978.. cfunction:: Py_ssize_t PyList_Size(PyObject *list)
1979
1980 .. index:: builtin: len
1981
1982 Return the length of the list object in *list*; this is equivalent to
1983 ``len(list)`` on a list object.
1984
1985
1986.. cfunction:: Py_ssize_t PyList_GET_SIZE(PyObject *list)
1987
1988 Macro form of :cfunc:`PyList_Size` without error checking.
1989
1990
1991.. cfunction:: PyObject* PyList_GetItem(PyObject *list, Py_ssize_t index)
1992
1993 Return the object at position *pos* in the list pointed to by *p*. The position
1994 must be positive, indexing from the end of the list is not supported. If *pos*
1995 is out of bounds, return *NULL* and set an :exc:`IndexError` exception.
1996
1997
1998.. cfunction:: PyObject* PyList_GET_ITEM(PyObject *list, Py_ssize_t i)
1999
2000 Macro form of :cfunc:`PyList_GetItem` without error checking.
2001
2002
2003.. cfunction:: int PyList_SetItem(PyObject *list, Py_ssize_t index, PyObject *item)
2004
2005 Set the item at index *index* in list to *item*. Return ``0`` on success or
2006 ``-1`` on failure.
2007
2008 .. note::
2009
2010 This function "steals" a reference to *item* and discards a reference to an item
2011 already in the list at the affected position.
2012
2013
2014.. cfunction:: void PyList_SET_ITEM(PyObject *list, Py_ssize_t i, PyObject *o)
2015
2016 Macro form of :cfunc:`PyList_SetItem` without error checking. This is normally
2017 only used to fill in new lists where there is no previous content.
2018
2019 .. note::
2020
2021 This function "steals" a reference to *item*, and, unlike
2022 :cfunc:`PyList_SetItem`, does *not* discard a reference to any item that it
2023 being replaced; any reference in *list* at position *i* will be leaked.
2024
2025
2026.. cfunction:: int PyList_Insert(PyObject *list, Py_ssize_t index, PyObject *item)
2027
2028 Insert the item *item* into list *list* in front of index *index*. Return ``0``
2029 if successful; return ``-1`` and set an exception if unsuccessful. Analogous to
2030 ``list.insert(index, item)``.
2031
2032
2033.. cfunction:: int PyList_Append(PyObject *list, PyObject *item)
2034
2035 Append the object *item* at the end of list *list*. Return ``0`` if successful;
2036 return ``-1`` and set an exception if unsuccessful. Analogous to
2037 ``list.append(item)``.
2038
2039
2040.. cfunction:: PyObject* PyList_GetSlice(PyObject *list, Py_ssize_t low, Py_ssize_t high)
2041
2042 Return a list of the objects in *list* containing the objects *between* *low*
2043 and *high*. Return *NULL* and set an exception if unsuccessful. Analogous to
2044 ``list[low:high]``.
2045
2046
2047.. cfunction:: int PyList_SetSlice(PyObject *list, Py_ssize_t low, Py_ssize_t high, PyObject *itemlist)
2048
2049 Set the slice of *list* between *low* and *high* to the contents of *itemlist*.
2050 Analogous to ``list[low:high] = itemlist``. The *itemlist* may be *NULL*,
2051 indicating the assignment of an empty list (slice deletion). Return ``0`` on
2052 success, ``-1`` on failure.
2053
2054
2055.. cfunction:: int PyList_Sort(PyObject *list)
2056
2057 Sort the items of *list* in place. Return ``0`` on success, ``-1`` on failure.
2058 This is equivalent to ``list.sort()``.
2059
2060
2061.. cfunction:: int PyList_Reverse(PyObject *list)
2062
2063 Reverse the items of *list* in place. Return ``0`` on success, ``-1`` on
2064 failure. This is the equivalent of ``list.reverse()``.
2065
2066
2067.. cfunction:: PyObject* PyList_AsTuple(PyObject *list)
2068
2069 .. index:: builtin: tuple
2070
2071 Return a new tuple object containing the contents of *list*; equivalent to
2072 ``tuple(list)``.
2073
2074
2075.. _mapobjects:
2076
2077Mapping Objects
2078===============
2079
2080.. index:: object: mapping
2081
2082
2083.. _dictobjects:
2084
2085Dictionary Objects
2086------------------
2087
2088.. index:: object: dictionary
2089
2090
2091.. ctype:: PyDictObject
2092
2093 This subtype of :ctype:`PyObject` represents a Python dictionary object.
2094
2095
2096.. cvar:: PyTypeObject PyDict_Type
2097
2098 .. index::
2099 single: DictType (in module types)
2100 single: DictionaryType (in module types)
2101
2102 This instance of :ctype:`PyTypeObject` represents the Python dictionary type.
2103 This is exposed to Python programs as ``dict`` and ``types.DictType``.
2104
2105
2106.. cfunction:: int PyDict_Check(PyObject *p)
2107
2108 Return true if *p* is a dict object or an instance of a subtype of the dict
2109 type.
2110
2111 .. versionchanged:: 2.2
2112 Allowed subtypes to be accepted.
2113
2114
2115.. cfunction:: int PyDict_CheckExact(PyObject *p)
2116
2117 Return true if *p* is a dict object, but not an instance of a subtype of the
2118 dict type.
2119
2120 .. versionadded:: 2.4
2121
2122
2123.. cfunction:: PyObject* PyDict_New()
2124
2125 Return a new empty dictionary, or *NULL* on failure.
2126
2127
2128.. cfunction:: PyObject* PyDictProxy_New(PyObject *dict)
2129
2130 Return a proxy object for a mapping which enforces read-only behavior. This is
2131 normally used to create a proxy to prevent modification of the dictionary for
2132 non-dynamic class types.
2133
2134 .. versionadded:: 2.2
2135
2136
2137.. cfunction:: void PyDict_Clear(PyObject *p)
2138
2139 Empty an existing dictionary of all key-value pairs.
2140
2141
2142.. cfunction:: int PyDict_Contains(PyObject *p, PyObject *key)
2143
2144 Determine if dictionary *p* contains *key*. If an item in *p* is matches *key*,
2145 return ``1``, otherwise return ``0``. On error, return ``-1``. This is
2146 equivalent to the Python expression ``key in p``.
2147
2148 .. versionadded:: 2.4
2149
2150
2151.. cfunction:: PyObject* PyDict_Copy(PyObject *p)
2152
2153 Return a new dictionary that contains the same key-value pairs as *p*.
2154
2155 .. versionadded:: 1.6
2156
2157
2158.. cfunction:: int PyDict_SetItem(PyObject *p, PyObject *key, PyObject *val)
2159
2160 Insert *value* into the dictionary *p* with a key of *key*. *key* must be
2161 hashable; if it isn't, :exc:`TypeError` will be raised. Return ``0`` on success
2162 or ``-1`` on failure.
2163
2164
2165.. cfunction:: int PyDict_SetItemString(PyObject *p, const char *key, PyObject *val)
2166
2167 .. index:: single: PyString_FromString()
2168
2169 Insert *value* into the dictionary *p* using *key* as a key. *key* should be a
2170 :ctype:`char\*`. The key object is created using ``PyString_FromString(key)``.
2171 Return ``0`` on success or ``-1`` on failure.
2172
2173
2174.. cfunction:: int PyDict_DelItem(PyObject *p, PyObject *key)
2175
2176 Remove the entry in dictionary *p* with key *key*. *key* must be hashable; if it
2177 isn't, :exc:`TypeError` is raised. Return ``0`` on success or ``-1`` on
2178 failure.
2179
2180
2181.. cfunction:: int PyDict_DelItemString(PyObject *p, char *key)
2182
2183 Remove the entry in dictionary *p* which has a key specified by the string
2184 *key*. Return ``0`` on success or ``-1`` on failure.
2185
2186
2187.. cfunction:: PyObject* PyDict_GetItem(PyObject *p, PyObject *key)
2188
2189 Return the object from dictionary *p* which has a key *key*. Return *NULL* if
2190 the key *key* is not present, but *without* setting an exception.
2191
2192
2193.. cfunction:: PyObject* PyDict_GetItemString(PyObject *p, const char *key)
2194
2195 This is the same as :cfunc:`PyDict_GetItem`, but *key* is specified as a
2196 :ctype:`char\*`, rather than a :ctype:`PyObject\*`.
2197
2198
2199.. cfunction:: PyObject* PyDict_Items(PyObject *p)
2200
2201 Return a :ctype:`PyListObject` containing all the items from the dictionary, as
2202 in the dictionary method :meth:`dict.items`.
2203
2204
2205.. cfunction:: PyObject* PyDict_Keys(PyObject *p)
2206
2207 Return a :ctype:`PyListObject` containing all the keys from the dictionary, as
2208 in the dictionary method :meth:`dict.keys`.
2209
2210
2211.. cfunction:: PyObject* PyDict_Values(PyObject *p)
2212
2213 Return a :ctype:`PyListObject` containing all the values from the dictionary
2214 *p*, as in the dictionary method :meth:`dict.values`.
2215
2216
2217.. cfunction:: Py_ssize_t PyDict_Size(PyObject *p)
2218
2219 .. index:: builtin: len
2220
2221 Return the number of items in the dictionary. This is equivalent to ``len(p)``
2222 on a dictionary.
2223
2224
2225.. cfunction:: int PyDict_Next(PyObject *p, Py_ssize_t *ppos, PyObject **pkey, PyObject **pvalue)
2226
2227 Iterate over all key-value pairs in the dictionary *p*. The :ctype:`int`
2228 referred to by *ppos* must be initialized to ``0`` prior to the first call to
2229 this function to start the iteration; the function returns true for each pair in
2230 the dictionary, and false once all pairs have been reported. The parameters
2231 *pkey* and *pvalue* should either point to :ctype:`PyObject\*` variables that
2232 will be filled in with each key and value, respectively, or may be *NULL*. Any
2233 references returned through them are borrowed. *ppos* should not be altered
2234 during iteration. Its value represents offsets within the internal dictionary
2235 structure, and since the structure is sparse, the offsets are not consecutive.
2236
2237 For example::
2238
2239 PyObject *key, *value;
2240 Py_ssize_t pos = 0;
2241
2242 while (PyDict_Next(self->dict, &pos, &key, &value)) {
2243 /* do something interesting with the values... */
2244 ...
2245 }
2246
2247 The dictionary *p* should not be mutated during iteration. It is safe (since
2248 Python 2.1) to modify the values of the keys as you iterate over the dictionary,
2249 but only so long as the set of keys does not change. For example::
2250
2251 PyObject *key, *value;
2252 Py_ssize_t pos = 0;
2253
2254 while (PyDict_Next(self->dict, &pos, &key, &value)) {
2255 int i = PyInt_AS_LONG(value) + 1;
2256 PyObject *o = PyInt_FromLong(i);
2257 if (o == NULL)
2258 return -1;
2259 if (PyDict_SetItem(self->dict, key, o) < 0) {
2260 Py_DECREF(o);
2261 return -1;
2262 }
2263 Py_DECREF(o);
2264 }
2265
2266
2267.. cfunction:: int PyDict_Merge(PyObject *a, PyObject *b, int override)
2268
2269 Iterate over mapping object *b* adding key-value pairs to dictionary *a*. *b*
2270 may be a dictionary, or any object supporting :func:`PyMapping_Keys` and
2271 :func:`PyObject_GetItem`. If *override* is true, existing pairs in *a* will be
2272 replaced if a matching key is found in *b*, otherwise pairs will only be added
2273 if there is not a matching key in *a*. Return ``0`` on success or ``-1`` if an
2274 exception was raised.
2275
2276 .. versionadded:: 2.2
2277
2278
2279.. cfunction:: int PyDict_Update(PyObject *a, PyObject *b)
2280
2281 This is the same as ``PyDict_Merge(a, b, 1)`` in C, or ``a.update(b)`` in
2282 Python. Return ``0`` on success or ``-1`` if an exception was raised.
2283
2284 .. versionadded:: 2.2
2285
2286
2287.. cfunction:: int PyDict_MergeFromSeq2(PyObject *a, PyObject *seq2, int override)
2288
2289 Update or merge into dictionary *a*, from the key-value pairs in *seq2*. *seq2*
2290 must be an iterable object producing iterable objects of length 2, viewed as
2291 key-value pairs. In case of duplicate keys, the last wins if *override* is
2292 true, else the first wins. Return ``0`` on success or ``-1`` if an exception was
2293 raised. Equivalent Python (except for the return value)::
2294
2295 def PyDict_MergeFromSeq2(a, seq2, override):
2296 for key, value in seq2:
2297 if override or key not in a:
2298 a[key] = value
2299
2300 .. versionadded:: 2.2
2301
2302
2303.. _otherobjects:
2304
2305Other Objects
2306=============
2307
2308
2309.. _classobjects:
2310
2311Class Objects
2312-------------
2313
2314.. index:: object: class
2315
2316Note that the class objects described here represent old-style classes, which
2317will go away in Python 3. When creating new types for extension modules, you
2318will want to work with type objects (section :ref:`typeobjects`).
2319
2320
2321.. ctype:: PyClassObject
2322
2323 The C structure of the objects used to describe built-in classes.
2324
2325
2326.. cvar:: PyObject* PyClass_Type
2327
2328 .. index:: single: ClassType (in module types)
2329
2330 This is the type object for class objects; it is the same object as
2331 ``types.ClassType`` in the Python layer.
2332
2333
2334.. cfunction:: int PyClass_Check(PyObject *o)
2335
2336 Return true if the object *o* is a class object, including instances of types
2337 derived from the standard class object. Return false in all other cases.
2338
2339
2340.. cfunction:: int PyClass_IsSubclass(PyObject *klass, PyObject *base)
2341
2342 Return true if *klass* is a subclass of *base*. Return false in all other cases.
2343
2344
2345.. _fileobjects:
2346
2347File Objects
2348------------
2349
2350.. index:: object: file
2351
2352Python's built-in file objects are implemented entirely on the :ctype:`FILE\*`
2353support from the C standard library. This is an implementation detail and may
2354change in future releases of Python.
2355
2356
2357.. ctype:: PyFileObject
2358
2359 This subtype of :ctype:`PyObject` represents a Python file object.
2360
2361
2362.. cvar:: PyTypeObject PyFile_Type
2363
2364 .. index:: single: FileType (in module types)
2365
2366 This instance of :ctype:`PyTypeObject` represents the Python file type. This is
2367 exposed to Python programs as ``file`` and ``types.FileType``.
2368
2369
2370.. cfunction:: int PyFile_Check(PyObject *p)
2371
2372 Return true if its argument is a :ctype:`PyFileObject` or a subtype of
2373 :ctype:`PyFileObject`.
2374
2375 .. versionchanged:: 2.2
2376 Allowed subtypes to be accepted.
2377
2378
2379.. cfunction:: int PyFile_CheckExact(PyObject *p)
2380
2381 Return true if its argument is a :ctype:`PyFileObject`, but not a subtype of
2382 :ctype:`PyFileObject`.
2383
2384 .. versionadded:: 2.2
2385
2386
2387.. cfunction:: PyObject* PyFile_FromString(char *filename, char *mode)
2388
2389 .. index:: single: fopen()
2390
2391 On success, return a new file object that is opened on the file given by
2392 *filename*, with a file mode given by *mode*, where *mode* has the same
2393 semantics as the standard C routine :cfunc:`fopen`. On failure, return *NULL*.
2394
2395
2396.. cfunction:: PyObject* PyFile_FromFile(FILE *fp, char *name, char *mode, int (*close)(FILE*))
2397
2398 Create a new :ctype:`PyFileObject` from the already-open standard C file
2399 pointer, *fp*. The function *close* will be called when the file should be
2400 closed. Return *NULL* on failure.
2401
2402
2403.. cfunction:: FILE* PyFile_AsFile(PyObject *p)
2404
2405 Return the file object associated with *p* as a :ctype:`FILE\*`.
2406
2407
2408.. cfunction:: PyObject* PyFile_GetLine(PyObject *p, int n)
2409
2410 .. index:: single: EOFError (built-in exception)
2411
2412 Equivalent to ``p.readline([n])``, this function reads one line from the
2413 object *p*. *p* may be a file object or any object with a :meth:`readline`
2414 method. If *n* is ``0``, exactly one line is read, regardless of the length of
2415 the line. If *n* is greater than ``0``, no more than *n* bytes will be read
2416 from the file; a partial line can be returned. In both cases, an empty string
2417 is returned if the end of the file is reached immediately. If *n* is less than
2418 ``0``, however, one line is read regardless of length, but :exc:`EOFError` is
2419 raised if the end of the file is reached immediately.
2420
2421
2422.. cfunction:: PyObject* PyFile_Name(PyObject *p)
2423
2424 Return the name of the file specified by *p* as a string object.
2425
2426
2427.. cfunction:: void PyFile_SetBufSize(PyFileObject *p, int n)
2428
2429 .. index:: single: setvbuf()
2430
2431 Available on systems with :cfunc:`setvbuf` only. This should only be called
2432 immediately after file object creation.
2433
2434
2435.. cfunction:: int PyFile_Encoding(PyFileObject *p, char *enc)
2436
2437 Set the file's encoding for Unicode output to *enc*. Return 1 on success and 0
2438 on failure.
2439
2440 .. versionadded:: 2.3
2441
2442
2443.. cfunction:: int PyFile_SoftSpace(PyObject *p, int newflag)
2444
2445 .. index:: single: softspace (file attribute)
2446
2447 This function exists for internal use by the interpreter. Set the
2448 :attr:`softspace` attribute of *p* to *newflag* and return the previous value.
2449 *p* does not have to be a file object for this function to work properly; any
2450 object is supported (thought its only interesting if the :attr:`softspace`
2451 attribute can be set). This function clears any errors, and will return ``0``
2452 as the previous value if the attribute either does not exist or if there were
2453 errors in retrieving it. There is no way to detect errors from this function,
2454 but doing so should not be needed.
2455
2456
2457.. cfunction:: int PyFile_WriteObject(PyObject *obj, PyObject *p, int flags)
2458
2459 .. index:: single: Py_PRINT_RAW
2460
2461 Write object *obj* to file object *p*. The only supported flag for *flags* is
2462 :const:`Py_PRINT_RAW`; if given, the :func:`str` of the object is written
2463 instead of the :func:`repr`. Return ``0`` on success or ``-1`` on failure; the
2464 appropriate exception will be set.
2465
2466
2467.. cfunction:: int PyFile_WriteString(const char *s, PyObject *p)
2468
2469 Write string *s* to file object *p*. Return ``0`` on success or ``-1`` on
2470 failure; the appropriate exception will be set.
2471
2472
2473.. _instanceobjects:
2474
2475Instance Objects
2476----------------
2477
2478.. index:: object: instance
2479
2480There are very few functions specific to instance objects.
2481
2482
2483.. cvar:: PyTypeObject PyInstance_Type
2484
2485 Type object for class instances.
2486
2487
2488.. cfunction:: int PyInstance_Check(PyObject *obj)
2489
2490 Return true if *obj* is an instance.
2491
2492
2493.. cfunction:: PyObject* PyInstance_New(PyObject *class, PyObject *arg, PyObject *kw)
2494
2495 Create a new instance of a specific class. The parameters *arg* and *kw* are
2496 used as the positional and keyword parameters to the object's constructor.
2497
2498
2499.. cfunction:: PyObject* PyInstance_NewRaw(PyObject *class, PyObject *dict)
2500
2501 Create a new instance of a specific class without calling its constructor.
2502 *class* is the class of new object. The *dict* parameter will be used as the
2503 object's :attr:`__dict__`; if *NULL*, a new dictionary will be created for the
2504 instance.
2505
2506
2507.. _function-objects:
2508
2509Function Objects
2510----------------
2511
2512.. index:: object: function
2513
2514There are a few functions specific to Python functions.
2515
2516
2517.. ctype:: PyFunctionObject
2518
2519 The C structure used for functions.
2520
2521
2522.. cvar:: PyTypeObject PyFunction_Type
2523
2524 .. index:: single: MethodType (in module types)
2525
2526 This is an instance of :ctype:`PyTypeObject` and represents the Python function
2527 type. It is exposed to Python programmers as ``types.FunctionType``.
2528
2529
2530.. cfunction:: int PyFunction_Check(PyObject *o)
2531
2532 Return true if *o* is a function object (has type :cdata:`PyFunction_Type`).
2533 The parameter must not be *NULL*.
2534
2535
2536.. cfunction:: PyObject* PyFunction_New(PyObject *code, PyObject *globals)
2537
2538 Return a new function object associated with the code object *code*. *globals*
2539 must be a dictionary with the global variables accessible to the function.
2540
2541 The function's docstring, name and *__module__* are retrieved from the code
2542 object, the argument defaults and closure are set to *NULL*.
2543
2544
2545.. cfunction:: PyObject* PyFunction_GetCode(PyObject *op)
2546
2547 Return the code object associated with the function object *op*.
2548
2549
2550.. cfunction:: PyObject* PyFunction_GetGlobals(PyObject *op)
2551
2552 Return the globals dictionary associated with the function object *op*.
2553
2554
2555.. cfunction:: PyObject* PyFunction_GetModule(PyObject *op)
2556
2557 Return the *__module__* attribute of the function object *op*. This is normally
2558 a string containing the module name, but can be set to any other object by
2559 Python code.
2560
2561
2562.. cfunction:: PyObject* PyFunction_GetDefaults(PyObject *op)
2563
2564 Return the argument default values of the function object *op*. This can be a
2565 tuple of arguments or *NULL*.
2566
2567
2568.. cfunction:: int PyFunction_SetDefaults(PyObject *op, PyObject *defaults)
2569
2570 Set the argument default values for the function object *op*. *defaults* must be
2571 *Py_None* or a tuple.
2572
2573 Raises :exc:`SystemError` and returns ``-1`` on failure.
2574
2575
2576.. cfunction:: PyObject* PyFunction_GetClosure(PyObject *op)
2577
2578 Return the closure associated with the function object *op*. This can be *NULL*
2579 or a tuple of cell objects.
2580
2581
2582.. cfunction:: int PyFunction_SetClosure(PyObject *op, PyObject *closure)
2583
2584 Set the closure associated with the function object *op*. *closure* must be
2585 *Py_None* or a tuple of cell objects.
2586
2587 Raises :exc:`SystemError` and returns ``-1`` on failure.
2588
2589
2590.. _method-objects:
2591
2592Method Objects
2593--------------
2594
2595.. index:: object: method
2596
2597There are some useful functions that are useful for working with method objects.
2598
2599
2600.. cvar:: PyTypeObject PyMethod_Type
2601
2602 .. index:: single: MethodType (in module types)
2603
2604 This instance of :ctype:`PyTypeObject` represents the Python method type. This
2605 is exposed to Python programs as ``types.MethodType``.
2606
2607
2608.. cfunction:: int PyMethod_Check(PyObject *o)
2609
2610 Return true if *o* is a method object (has type :cdata:`PyMethod_Type`). The
2611 parameter must not be *NULL*.
2612
2613
2614.. cfunction:: PyObject* PyMethod_New(PyObject *func, PyObject *self, PyObject *class)
2615
2616 Return a new method object, with *func* being any callable object; this is the
2617 function that will be called when the method is called. If this method should
2618 be bound to an instance, *self* should be the instance and *class* should be the
2619 class of *self*, otherwise *self* should be *NULL* and *class* should be the
2620 class which provides the unbound method..
2621
2622
2623.. cfunction:: PyObject* PyMethod_Class(PyObject *meth)
2624
2625 Return the class object from which the method *meth* was created; if this was
2626 created from an instance, it will be the class of the instance.
2627
2628
2629.. cfunction:: PyObject* PyMethod_GET_CLASS(PyObject *meth)
2630
2631 Macro version of :cfunc:`PyMethod_Class` which avoids error checking.
2632
2633
2634.. cfunction:: PyObject* PyMethod_Function(PyObject *meth)
2635
2636 Return the function object associated with the method *meth*.
2637
2638
2639.. cfunction:: PyObject* PyMethod_GET_FUNCTION(PyObject *meth)
2640
2641 Macro version of :cfunc:`PyMethod_Function` which avoids error checking.
2642
2643
2644.. cfunction:: PyObject* PyMethod_Self(PyObject *meth)
2645
2646 Return the instance associated with the method *meth* if it is bound, otherwise
2647 return *NULL*.
2648
2649
2650.. cfunction:: PyObject* PyMethod_GET_SELF(PyObject *meth)
2651
2652 Macro version of :cfunc:`PyMethod_Self` which avoids error checking.
2653
2654
2655.. _moduleobjects:
2656
2657Module Objects
2658--------------
2659
2660.. index:: object: module
2661
2662There are only a few functions special to module objects.
2663
2664
2665.. cvar:: PyTypeObject PyModule_Type
2666
2667 .. index:: single: ModuleType (in module types)
2668
2669 This instance of :ctype:`PyTypeObject` represents the Python module type. This
2670 is exposed to Python programs as ``types.ModuleType``.
2671
2672
2673.. cfunction:: int PyModule_Check(PyObject *p)
2674
2675 Return true if *p* is a module object, or a subtype of a module object.
2676
2677 .. versionchanged:: 2.2
2678 Allowed subtypes to be accepted.
2679
2680
2681.. cfunction:: int PyModule_CheckExact(PyObject *p)
2682
2683 Return true if *p* is a module object, but not a subtype of
2684 :cdata:`PyModule_Type`.
2685
2686 .. versionadded:: 2.2
2687
2688
2689.. cfunction:: PyObject* PyModule_New(const char *name)
2690
2691 .. index::
2692 single: __name__ (module attribute)
2693 single: __doc__ (module attribute)
2694 single: __file__ (module attribute)
2695
2696 Return a new module object with the :attr:`__name__` attribute set to *name*.
2697 Only the module's :attr:`__doc__` and :attr:`__name__` attributes are filled in;
2698 the caller is responsible for providing a :attr:`__file__` attribute.
2699
2700
2701.. cfunction:: PyObject* PyModule_GetDict(PyObject *module)
2702
2703 .. index:: single: __dict__ (module attribute)
2704
2705 Return the dictionary object that implements *module*'s namespace; this object
2706 is the same as the :attr:`__dict__` attribute of the module object. This
2707 function never fails. It is recommended extensions use other
2708 :cfunc:`PyModule_\*` and :cfunc:`PyObject_\*` functions rather than directly
2709 manipulate a module's :attr:`__dict__`.
2710
2711
2712.. cfunction:: char* PyModule_GetName(PyObject *module)
2713
2714 .. index::
2715 single: __name__ (module attribute)
2716 single: SystemError (built-in exception)
2717
2718 Return *module*'s :attr:`__name__` value. If the module does not provide one,
2719 or if it is not a string, :exc:`SystemError` is raised and *NULL* is returned.
2720
2721
2722.. cfunction:: char* PyModule_GetFilename(PyObject *module)
2723
2724 .. index::
2725 single: __file__ (module attribute)
2726 single: SystemError (built-in exception)
2727
2728 Return the name of the file from which *module* was loaded using *module*'s
2729 :attr:`__file__` attribute. If this is not defined, or if it is not a string,
2730 raise :exc:`SystemError` and return *NULL*.
2731
2732
2733.. cfunction:: int PyModule_AddObject(PyObject *module, const char *name, PyObject *value)
2734
2735 Add an object to *module* as *name*. This is a convenience function which can
2736 be used from the module's initialization function. This steals a reference to
2737 *value*. Return ``-1`` on error, ``0`` on success.
2738
2739 .. versionadded:: 2.0
2740
2741
2742.. cfunction:: int PyModule_AddIntConstant(PyObject *module, const char *name, long value)
2743
2744 Add an integer constant to *module* as *name*. This convenience function can be
2745 used from the module's initialization function. Return ``-1`` on error, ``0`` on
2746 success.
2747
2748 .. versionadded:: 2.0
2749
2750
2751.. cfunction:: int PyModule_AddStringConstant(PyObject *module, const char *name, const char *value)
2752
2753 Add a string constant to *module* as *name*. This convenience function can be
2754 used from the module's initialization function. The string *value* must be
2755 null-terminated. Return ``-1`` on error, ``0`` on success.
2756
2757 .. versionadded:: 2.0
2758
2759
2760.. _iterator-objects:
2761
2762Iterator Objects
2763----------------
2764
2765Python provides two general-purpose iterator objects. The first, a sequence
2766iterator, works with an arbitrary sequence supporting the :meth:`__getitem__`
2767method. The second works with a callable object and a sentinel value, calling
2768the callable for each item in the sequence, and ending the iteration when the
2769sentinel value is returned.
2770
2771
2772.. cvar:: PyTypeObject PySeqIter_Type
2773
2774 Type object for iterator objects returned by :cfunc:`PySeqIter_New` and the
2775 one-argument form of the :func:`iter` built-in function for built-in sequence
2776 types.
2777
2778 .. versionadded:: 2.2
2779
2780
2781.. cfunction:: int PySeqIter_Check(op)
2782
2783 Return true if the type of *op* is :cdata:`PySeqIter_Type`.
2784
2785 .. versionadded:: 2.2
2786
2787
2788.. cfunction:: PyObject* PySeqIter_New(PyObject *seq)
2789
2790 Return an iterator that works with a general sequence object, *seq*. The
2791 iteration ends when the sequence raises :exc:`IndexError` for the subscripting
2792 operation.
2793
2794 .. versionadded:: 2.2
2795
2796
2797.. cvar:: PyTypeObject PyCallIter_Type
2798
2799 Type object for iterator objects returned by :cfunc:`PyCallIter_New` and the
2800 two-argument form of the :func:`iter` built-in function.
2801
2802 .. versionadded:: 2.2
2803
2804
2805.. cfunction:: int PyCallIter_Check(op)
2806
2807 Return true if the type of *op* is :cdata:`PyCallIter_Type`.
2808
2809 .. versionadded:: 2.2
2810
2811
2812.. cfunction:: PyObject* PyCallIter_New(PyObject *callable, PyObject *sentinel)
2813
2814 Return a new iterator. The first parameter, *callable*, can be any Python
2815 callable object that can be called with no parameters; each call to it should
2816 return the next item in the iteration. When *callable* returns a value equal to
2817 *sentinel*, the iteration will be terminated.
2818
2819 .. versionadded:: 2.2
2820
2821
2822.. _descriptor-objects:
2823
2824Descriptor Objects
2825------------------
2826
2827"Descriptors" are objects that describe some attribute of an object. They are
2828found in the dictionary of type objects.
2829
2830
2831.. cvar:: PyTypeObject PyProperty_Type
2832
2833 The type object for the built-in descriptor types.
2834
2835 .. versionadded:: 2.2
2836
2837
2838.. cfunction:: PyObject* PyDescr_NewGetSet(PyTypeObject *type, struct PyGetSetDef *getset)
2839
2840 .. versionadded:: 2.2
2841
2842
2843.. cfunction:: PyObject* PyDescr_NewMember(PyTypeObject *type, struct PyMemberDef *meth)
2844
2845 .. versionadded:: 2.2
2846
2847
2848.. cfunction:: PyObject* PyDescr_NewMethod(PyTypeObject *type, struct PyMethodDef *meth)
2849
2850 .. versionadded:: 2.2
2851
2852
2853.. cfunction:: PyObject* PyDescr_NewWrapper(PyTypeObject *type, struct wrapperbase *wrapper, void *wrapped)
2854
2855 .. versionadded:: 2.2
2856
2857
2858.. cfunction:: PyObject* PyDescr_NewClassMethod(PyTypeObject *type, PyMethodDef *method)
2859
2860 .. versionadded:: 2.3
2861
2862
2863.. cfunction:: int PyDescr_IsData(PyObject *descr)
2864
2865 Return true if the descriptor objects *descr* describes a data attribute, or
2866 false if it describes a method. *descr* must be a descriptor object; there is
2867 no error checking.
2868
2869 .. versionadded:: 2.2
2870
2871
2872.. cfunction:: PyObject* PyWrapper_New(PyObject *, PyObject *)
2873
2874 .. versionadded:: 2.2
2875
2876
2877.. _slice-objects:
2878
2879Slice Objects
2880-------------
2881
2882
2883.. cvar:: PyTypeObject PySlice_Type
2884
2885 .. index:: single: SliceType (in module types)
2886
2887 The type object for slice objects. This is the same as ``slice`` and
2888 ``types.SliceType``.
2889
2890
2891.. cfunction:: int PySlice_Check(PyObject *ob)
2892
2893 Return true if *ob* is a slice object; *ob* must not be *NULL*.
2894
2895
2896.. cfunction:: PyObject* PySlice_New(PyObject *start, PyObject *stop, PyObject *step)
2897
2898 Return a new slice object with the given values. The *start*, *stop*, and
2899 *step* parameters are used as the values of the slice object attributes of the
2900 same names. Any of the values may be *NULL*, in which case the ``None`` will be
2901 used for the corresponding attribute. Return *NULL* if the new object could not
2902 be allocated.
2903
2904
2905.. cfunction:: int PySlice_GetIndices(PySliceObject *slice, Py_ssize_t length, Py_ssize_t *start, Py_ssize_t *stop, Py_ssize_t *step)
2906
2907 Retrieve the start, stop and step indices from the slice object *slice*,
2908 assuming a sequence of length *length*. Treats indices greater than *length* as
2909 errors.
2910
2911 Returns 0 on success and -1 on error with no exception set (unless one of the
2912 indices was not :const:`None` and failed to be converted to an integer, in which
2913 case -1 is returned with an exception set).
2914
2915 You probably do not want to use this function. If you want to use slice objects
2916 in versions of Python prior to 2.3, you would probably do well to incorporate
2917 the source of :cfunc:`PySlice_GetIndicesEx`, suitably renamed, in the source of
2918 your extension.
2919
2920
2921.. 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)
2922
2923 Usable replacement for :cfunc:`PySlice_GetIndices`. Retrieve the start, stop,
2924 and step indices from the slice object *slice* assuming a sequence of length
2925 *length*, and store the length of the slice in *slicelength*. Out of bounds
2926 indices are clipped in a manner consistent with the handling of normal slices.
2927
2928 Returns 0 on success and -1 on error with exception set.
2929
2930 .. versionadded:: 2.3
2931
2932
2933.. _weakrefobjects:
2934
2935Weak Reference Objects
2936----------------------
2937
2938Python supports *weak references* as first-class objects. There are two
2939specific object types which directly implement weak references. The first is a
2940simple reference object, and the second acts as a proxy for the original object
2941as much as it can.
2942
2943
2944.. cfunction:: int PyWeakref_Check(ob)
2945
2946 Return true if *ob* is either a reference or proxy object.
2947
2948 .. versionadded:: 2.2
2949
2950
2951.. cfunction:: int PyWeakref_CheckRef(ob)
2952
2953 Return true if *ob* is a reference object.
2954
2955 .. versionadded:: 2.2
2956
2957
2958.. cfunction:: int PyWeakref_CheckProxy(ob)
2959
2960 Return true if *ob* is a proxy object.
2961
2962 .. versionadded:: 2.2
2963
2964
2965.. cfunction:: PyObject* PyWeakref_NewRef(PyObject *ob, PyObject *callback)
2966
2967 Return a weak reference object for the object *ob*. This will always return
2968 a new reference, but is not guaranteed to create a new object; an existing
2969 reference object may be returned. The second parameter, *callback*, can be a
2970 callable object that receives notification when *ob* is garbage collected; it
2971 should accept a single parameter, which will be the weak reference object
2972 itself. *callback* may also be ``None`` or *NULL*. If *ob* is not a
2973 weakly-referencable object, or if *callback* is not callable, ``None``, or
2974 *NULL*, this will return *NULL* and raise :exc:`TypeError`.
2975
2976 .. versionadded:: 2.2
2977
2978
2979.. cfunction:: PyObject* PyWeakref_NewProxy(PyObject *ob, PyObject *callback)
2980
2981 Return a weak reference proxy object for the object *ob*. This will always
2982 return a new reference, but is not guaranteed to create a new object; an
2983 existing proxy object may be returned. The second parameter, *callback*, can
2984 be a callable object that receives notification when *ob* is garbage
2985 collected; it should accept a single parameter, which will be the weak
2986 reference object itself. *callback* may also be ``None`` or *NULL*. If *ob*
2987 is not a weakly-referencable object, or if *callback* is not callable,
2988 ``None``, or *NULL*, this will return *NULL* and raise :exc:`TypeError`.
2989
2990 .. versionadded:: 2.2
2991
2992
2993.. cfunction:: PyObject* PyWeakref_GetObject(PyObject *ref)
2994
2995 Return the referenced object from a weak reference, *ref*. If the referent is
2996 no longer live, returns ``None``.
2997
2998 .. versionadded:: 2.2
2999
3000
3001.. cfunction:: PyObject* PyWeakref_GET_OBJECT(PyObject *ref)
3002
3003 Similar to :cfunc:`PyWeakref_GetObject`, but implemented as a macro that does no
3004 error checking.
3005
3006 .. versionadded:: 2.2
3007
3008
3009.. _cobjects:
3010
3011CObjects
3012--------
3013
3014.. index:: object: CObject
3015
3016Refer to *Extending and Embedding the Python Interpreter*, section 1.12,
3017"Providing a C API for an Extension Module," for more information on using these
3018objects.
3019
3020
3021.. ctype:: PyCObject
3022
3023 This subtype of :ctype:`PyObject` represents an opaque value, useful for C
3024 extension modules who need to pass an opaque value (as a :ctype:`void\*`
3025 pointer) through Python code to other C code. It is often used to make a C
3026 function pointer defined in one module available to other modules, so the
3027 regular import mechanism can be used to access C APIs defined in dynamically
3028 loaded modules.
3029
3030
3031.. cfunction:: int PyCObject_Check(PyObject *p)
3032
3033 Return true if its argument is a :ctype:`PyCObject`.
3034
3035
3036.. cfunction:: PyObject* PyCObject_FromVoidPtr(void* cobj, void (*destr)(void *))
3037
3038 Create a :ctype:`PyCObject` from the ``void *`` *cobj*. The *destr* function
3039 will be called when the object is reclaimed, unless it is *NULL*.
3040
3041
3042.. cfunction:: PyObject* PyCObject_FromVoidPtrAndDesc(void* cobj, void* desc, void (*destr)(void *, void *))
3043
3044 Create a :ctype:`PyCObject` from the :ctype:`void \*` *cobj*. The *destr*
3045 function will be called when the object is reclaimed. The *desc* argument can
3046 be used to pass extra callback data for the destructor function.
3047
3048
3049.. cfunction:: void* PyCObject_AsVoidPtr(PyObject* self)
3050
3051 Return the object :ctype:`void \*` that the :ctype:`PyCObject` *self* was
3052 created with.
3053
3054
3055.. cfunction:: void* PyCObject_GetDesc(PyObject* self)
3056
3057 Return the description :ctype:`void \*` that the :ctype:`PyCObject` *self* was
3058 created with.
3059
3060
3061.. cfunction:: int PyCObject_SetVoidPtr(PyObject* self, void* cobj)
3062
3063 Set the void pointer inside *self* to *cobj*. The :ctype:`PyCObject` must not
3064 have an associated destructor. Return true on success, false on failure.
3065
3066
3067.. _cell-objects:
3068
3069Cell Objects
3070------------
3071
3072"Cell" objects are used to implement variables referenced by multiple scopes.
3073For each such variable, a cell object is created to store the value; the local
3074variables of each stack frame that references the value contains a reference to
3075the cells from outer scopes which also use that variable. When the value is
3076accessed, the value contained in the cell is used instead of the cell object
3077itself. This de-referencing of the cell object requires support from the
3078generated byte-code; these are not automatically de-referenced when accessed.
3079Cell objects are not likely to be useful elsewhere.
3080
3081
3082.. ctype:: PyCellObject
3083
3084 The C structure used for cell objects.
3085
3086
3087.. cvar:: PyTypeObject PyCell_Type
3088
3089 The type object corresponding to cell objects.
3090
3091
3092.. cfunction:: int PyCell_Check(ob)
3093
3094 Return true if *ob* is a cell object; *ob* must not be *NULL*.
3095
3096
3097.. cfunction:: PyObject* PyCell_New(PyObject *ob)
3098
3099 Create and return a new cell object containing the value *ob*. The parameter may
3100 be *NULL*.
3101
3102
3103.. cfunction:: PyObject* PyCell_Get(PyObject *cell)
3104
3105 Return the contents of the cell *cell*.
3106
3107
3108.. cfunction:: PyObject* PyCell_GET(PyObject *cell)
3109
3110 Return the contents of the cell *cell*, but without checking that *cell* is
3111 non-*NULL* and a cell object.
3112
3113
3114.. cfunction:: int PyCell_Set(PyObject *cell, PyObject *value)
3115
3116 Set the contents of the cell object *cell* to *value*. This releases the
3117 reference to any current content of the cell. *value* may be *NULL*. *cell*
3118 must be non-*NULL*; if it is not a cell object, ``-1`` will be returned. On
3119 success, ``0`` will be returned.
3120
3121
3122.. cfunction:: void PyCell_SET(PyObject *cell, PyObject *value)
3123
3124 Sets the value of the cell object *cell* to *value*. No reference counts are
3125 adjusted, and no checks are made for safety; *cell* must be non-*NULL* and must
3126 be a cell object.
3127
3128
3129.. _gen-objects:
3130
3131Generator Objects
3132-----------------
3133
3134Generator objects are what Python uses to implement generator iterators. They
3135are normally created by iterating over a function that yields values, rather
3136than explicitly calling :cfunc:`PyGen_New`.
3137
3138
3139.. ctype:: PyGenObject
3140
3141 The C structure used for generator objects.
3142
3143
3144.. cvar:: PyTypeObject PyGen_Type
3145
3146 The type object corresponding to generator objects
3147
3148
3149.. cfunction:: int PyGen_Check(ob)
3150
3151 Return true if *ob* is a generator object; *ob* must not be *NULL*.
3152
3153
3154.. cfunction:: int PyGen_CheckExact(ob)
3155
3156 Return true if *ob*'s type is *PyGen_Type* is a generator object; *ob* must not
3157 be *NULL*.
3158
3159
3160.. cfunction:: PyObject* PyGen_New(PyFrameObject *frame)
3161
3162 Create and return a new generator object based on the *frame* object. A
3163 reference to *frame* is stolen by this function. The parameter must not be
3164 *NULL*.
3165
3166
3167.. _datetimeobjects:
3168
3169DateTime Objects
3170----------------
3171
3172Various date and time objects are supplied by the :mod:`datetime` module.
3173Before using any of these functions, the header file :file:`datetime.h` must be
3174included in your source (note that this is not included by :file:`Python.h`),
3175and the macro :cfunc:`PyDateTime_IMPORT` must be invoked. The macro puts a
3176pointer to a C structure into a static variable, ``PyDateTimeAPI``, that is
3177used by the following macros.
3178
3179Type-check macros:
3180
3181
3182.. cfunction:: int PyDate_Check(PyObject *ob)
3183
3184 Return true if *ob* is of type :cdata:`PyDateTime_DateType` or a subtype of
3185 :cdata:`PyDateTime_DateType`. *ob* must not be *NULL*.
3186
3187 .. versionadded:: 2.4
3188
3189
3190.. cfunction:: int PyDate_CheckExact(PyObject *ob)
3191
3192 Return true if *ob* is of type :cdata:`PyDateTime_DateType`. *ob* must not be
3193 *NULL*.
3194
3195 .. versionadded:: 2.4
3196
3197
3198.. cfunction:: int PyDateTime_Check(PyObject *ob)
3199
3200 Return true if *ob* is of type :cdata:`PyDateTime_DateTimeType` or a subtype of
3201 :cdata:`PyDateTime_DateTimeType`. *ob* must not be *NULL*.
3202
3203 .. versionadded:: 2.4
3204
3205
3206.. cfunction:: int PyDateTime_CheckExact(PyObject *ob)
3207
3208 Return true if *ob* is of type :cdata:`PyDateTime_DateTimeType`. *ob* must not
3209 be *NULL*.
3210
3211 .. versionadded:: 2.4
3212
3213
3214.. cfunction:: int PyTime_Check(PyObject *ob)
3215
3216 Return true if *ob* is of type :cdata:`PyDateTime_TimeType` or a subtype of
3217 :cdata:`PyDateTime_TimeType`. *ob* must not be *NULL*.
3218
3219 .. versionadded:: 2.4
3220
3221
3222.. cfunction:: int PyTime_CheckExact(PyObject *ob)
3223
3224 Return true if *ob* is of type :cdata:`PyDateTime_TimeType`. *ob* must not be
3225 *NULL*.
3226
3227 .. versionadded:: 2.4
3228
3229
3230.. cfunction:: int PyDelta_Check(PyObject *ob)
3231
3232 Return true if *ob* is of type :cdata:`PyDateTime_DeltaType` or a subtype of
3233 :cdata:`PyDateTime_DeltaType`. *ob* must not be *NULL*.
3234
3235 .. versionadded:: 2.4
3236
3237
3238.. cfunction:: int PyDelta_CheckExact(PyObject *ob)
3239
3240 Return true if *ob* is of type :cdata:`PyDateTime_DeltaType`. *ob* must not be
3241 *NULL*.
3242
3243 .. versionadded:: 2.4
3244
3245
3246.. cfunction:: int PyTZInfo_Check(PyObject *ob)
3247
3248 Return true if *ob* is of type :cdata:`PyDateTime_TZInfoType` or a subtype of
3249 :cdata:`PyDateTime_TZInfoType`. *ob* must not be *NULL*.
3250
3251 .. versionadded:: 2.4
3252
3253
3254.. cfunction:: int PyTZInfo_CheckExact(PyObject *ob)
3255
3256 Return true if *ob* is of type :cdata:`PyDateTime_TZInfoType`. *ob* must not be
3257 *NULL*.
3258
3259 .. versionadded:: 2.4
3260
3261Macros to create objects:
3262
3263
3264.. cfunction:: PyObject* PyDate_FromDate(int year, int month, int day)
3265
3266 Return a ``datetime.date`` object with the specified year, month and day.
3267
3268 .. versionadded:: 2.4
3269
3270
3271.. cfunction:: PyObject* PyDateTime_FromDateAndTime(int year, int month, int day, int hour, int minute, int second, int usecond)
3272
3273 Return a ``datetime.datetime`` object with the specified year, month, day, hour,
3274 minute, second and microsecond.
3275
3276 .. versionadded:: 2.4
3277
3278
3279.. cfunction:: PyObject* PyTime_FromTime(int hour, int minute, int second, int usecond)
3280
3281 Return a ``datetime.time`` object with the specified hour, minute, second and
3282 microsecond.
3283
3284 .. versionadded:: 2.4
3285
3286
3287.. cfunction:: PyObject* PyDelta_FromDSU(int days, int seconds, int useconds)
3288
3289 Return a ``datetime.timedelta`` object representing the given number of days,
3290 seconds and microseconds. Normalization is performed so that the resulting
3291 number of microseconds and seconds lie in the ranges documented for
3292 ``datetime.timedelta`` objects.
3293
3294 .. versionadded:: 2.4
3295
3296Macros to extract fields from date objects. The argument must be an instance of
3297:cdata:`PyDateTime_Date`, including subclasses (such as
3298:cdata:`PyDateTime_DateTime`). The argument must not be *NULL*, and the type is
3299not checked:
3300
3301
3302.. cfunction:: int PyDateTime_GET_YEAR(PyDateTime_Date *o)
3303
3304 Return the year, as a positive int.
3305
3306 .. versionadded:: 2.4
3307
3308
3309.. cfunction:: int PyDateTime_GET_MONTH(PyDateTime_Date *o)
3310
3311 Return the month, as an int from 1 through 12.
3312
3313 .. versionadded:: 2.4
3314
3315
3316.. cfunction:: int PyDateTime_GET_DAY(PyDateTime_Date *o)
3317
3318 Return the day, as an int from 1 through 31.
3319
3320 .. versionadded:: 2.4
3321
3322Macros to extract fields from datetime objects. The argument must be an
3323instance of :cdata:`PyDateTime_DateTime`, including subclasses. The argument
3324must not be *NULL*, and the type is not checked:
3325
3326
3327.. cfunction:: int PyDateTime_DATE_GET_HOUR(PyDateTime_DateTime *o)
3328
3329 Return the hour, as an int from 0 through 23.
3330
3331 .. versionadded:: 2.4
3332
3333
3334.. cfunction:: int PyDateTime_DATE_GET_MINUTE(PyDateTime_DateTime *o)
3335
3336 Return the minute, as an int from 0 through 59.
3337
3338 .. versionadded:: 2.4
3339
3340
3341.. cfunction:: int PyDateTime_DATE_GET_SECOND(PyDateTime_DateTime *o)
3342
3343 Return the second, as an int from 0 through 59.
3344
3345 .. versionadded:: 2.4
3346
3347
3348.. cfunction:: int PyDateTime_DATE_GET_MICROSECOND(PyDateTime_DateTime *o)
3349
3350 Return the microsecond, as an int from 0 through 999999.
3351
3352 .. versionadded:: 2.4
3353
3354Macros to extract fields from time objects. The argument must be an instance of
3355:cdata:`PyDateTime_Time`, including subclasses. The argument must not be *NULL*,
3356and the type is not checked:
3357
3358
3359.. cfunction:: int PyDateTime_TIME_GET_HOUR(PyDateTime_Time *o)
3360
3361 Return the hour, as an int from 0 through 23.
3362
3363 .. versionadded:: 2.4
3364
3365
3366.. cfunction:: int PyDateTime_TIME_GET_MINUTE(PyDateTime_Time *o)
3367
3368 Return the minute, as an int from 0 through 59.
3369
3370 .. versionadded:: 2.4
3371
3372
3373.. cfunction:: int PyDateTime_TIME_GET_SECOND(PyDateTime_Time *o)
3374
3375 Return the second, as an int from 0 through 59.
3376
3377 .. versionadded:: 2.4
3378
3379
3380.. cfunction:: int PyDateTime_TIME_GET_MICROSECOND(PyDateTime_Time *o)
3381
3382 Return the microsecond, as an int from 0 through 999999.
3383
3384 .. versionadded:: 2.4
3385
3386Macros for the convenience of modules implementing the DB API:
3387
3388
3389.. cfunction:: PyObject* PyDateTime_FromTimestamp(PyObject *args)
3390
3391 Create and return a new ``datetime.datetime`` object given an argument tuple
3392 suitable for passing to ``datetime.datetime.fromtimestamp()``.
3393
3394 .. versionadded:: 2.4
3395
3396
3397.. cfunction:: PyObject* PyDate_FromTimestamp(PyObject *args)
3398
3399 Create and return a new ``datetime.date`` object given an argument tuple
3400 suitable for passing to ``datetime.date.fromtimestamp()``.
3401
3402 .. versionadded:: 2.4
3403
3404
3405.. _setobjects:
3406
3407Set Objects
3408-----------
3409
3410.. sectionauthor:: Raymond D. Hettinger <python@rcn.com>
3411
3412
3413.. index::
3414 object: set
3415 object: frozenset
3416
3417.. versionadded:: 2.5
3418
3419This section details the public API for :class:`set` and :class:`frozenset`
3420objects. Any functionality not listed below is best accessed using the either
3421the abstract object protocol (including :cfunc:`PyObject_CallMethod`,
3422:cfunc:`PyObject_RichCompareBool`, :cfunc:`PyObject_Hash`,
3423:cfunc:`PyObject_Repr`, :cfunc:`PyObject_IsTrue`, :cfunc:`PyObject_Print`, and
3424:cfunc:`PyObject_GetIter`) or the abstract number protocol (including
3425:cfunc:`PyNumber_And`, :cfunc:`PyNumber_Subtract`, :cfunc:`PyNumber_Or`,
3426:cfunc:`PyNumber_Xor`, :cfunc:`PyNumber_InPlaceAnd`,
3427:cfunc:`PyNumber_InPlaceSubtract`, :cfunc:`PyNumber_InPlaceOr`, and
3428:cfunc:`PyNumber_InPlaceXor`).
3429
3430
3431.. ctype:: PySetObject
3432
3433 This subtype of :ctype:`PyObject` is used to hold the internal data for both
3434 :class:`set` and :class:`frozenset` objects. It is like a :ctype:`PyDictObject`
3435 in that it is a fixed size for small sets (much like tuple storage) and will
3436 point to a separate, variable sized block of memory for medium and large sized
3437 sets (much like list storage). None of the fields of this structure should be
3438 considered public and are subject to change. All access should be done through
3439 the documented API rather than by manipulating the values in the structure.
3440
3441
3442.. cvar:: PyTypeObject PySet_Type
3443
3444 This is an instance of :ctype:`PyTypeObject` representing the Python
3445 :class:`set` type.
3446
3447
3448.. cvar:: PyTypeObject PyFrozenSet_Type
3449
3450 This is an instance of :ctype:`PyTypeObject` representing the Python
3451 :class:`frozenset` type.
3452
3453The following type check macros work on pointers to any Python object. Likewise,
3454the constructor functions work with any iterable Python object.
3455
3456
3457.. cfunction:: int PyAnySet_Check(PyObject *p)
3458
3459 Return true if *p* is a :class:`set` object, a :class:`frozenset` object, or an
3460 instance of a subtype.
3461
3462
3463.. cfunction:: int PyAnySet_CheckExact(PyObject *p)
3464
3465 Return true if *p* is a :class:`set` object or a :class:`frozenset` object but
3466 not an instance of a subtype.
3467
3468
3469.. cfunction:: int PyFrozenSet_CheckExact(PyObject *p)
3470
3471 Return true if *p* is a :class:`frozenset` object but not an instance of a
3472 subtype.
3473
3474
3475.. cfunction:: PyObject* PySet_New(PyObject *iterable)
3476
3477 Return a new :class:`set` containing objects returned by the *iterable*. The
3478 *iterable* may be *NULL* to create a new empty set. Return the new set on
3479 success or *NULL* on failure. Raise :exc:`TypeError` if *iterable* is not
3480 actually iterable. The constructor is also useful for copying a set
3481 (``c=set(s)``).
3482
3483
3484.. cfunction:: PyObject* PyFrozenSet_New(PyObject *iterable)
3485
3486 Return a new :class:`frozenset` containing objects returned by the *iterable*.
3487 The *iterable* may be *NULL* to create a new empty frozenset. Return the new
3488 set on success or *NULL* on failure. Raise :exc:`TypeError` if *iterable* is
3489 not actually iterable.
3490
3491The following functions and macros are available for instances of :class:`set`
3492or :class:`frozenset` or instances of their subtypes.
3493
3494
3495.. cfunction:: int PySet_Size(PyObject *anyset)
3496
3497 .. index:: builtin: len
3498
3499 Return the length of a :class:`set` or :class:`frozenset` object. Equivalent to
3500 ``len(anyset)``. Raises a :exc:`PyExc_SystemError` if *anyset* is not a
3501 :class:`set`, :class:`frozenset`, or an instance of a subtype.
3502
3503
3504.. cfunction:: int PySet_GET_SIZE(PyObject *anyset)
3505
3506 Macro form of :cfunc:`PySet_Size` without error checking.
3507
3508
3509.. cfunction:: int PySet_Contains(PyObject *anyset, PyObject *key)
3510
3511 Return 1 if found, 0 if not found, and -1 if an error is encountered. Unlike
3512 the Python :meth:`__contains__` method, this function does not automatically
3513 convert unhashable sets into temporary frozensets. Raise a :exc:`TypeError` if
3514 the *key* is unhashable. Raise :exc:`PyExc_SystemError` if *anyset* is not a
3515 :class:`set`, :class:`frozenset`, or an instance of a subtype.
3516
3517The following functions are available for instances of :class:`set` or its
3518subtypes but not for instances of :class:`frozenset` or its subtypes.
3519
3520
3521.. cfunction:: int PySet_Add(PyObject *set, PyObject *key)
3522
3523 Add *key* to a :class:`set` instance. Does not apply to :class:`frozenset`
3524 instances. Return 0 on success or -1 on failure. Raise a :exc:`TypeError` if
3525 the *key* is unhashable. Raise a :exc:`MemoryError` if there is no room to grow.
3526 Raise a :exc:`SystemError` if *set* is an not an instance of :class:`set` or its
3527 subtype.
3528
3529
3530.. cfunction:: int PySet_Discard(PyObject *set, PyObject *key)
3531
3532 Return 1 if found and removed, 0 if not found (no action taken), and -1 if an
3533 error is encountered. Does not raise :exc:`KeyError` for missing keys. Raise a
3534 :exc:`TypeError` if the *key* is unhashable. Unlike the Python :meth:`discard`
3535 method, this function does not automatically convert unhashable sets into
3536 temporary frozensets. Raise :exc:`PyExc_SystemError` if *set* is an not an
3537 instance of :class:`set` or its subtype.
3538
3539
3540.. cfunction:: PyObject* PySet_Pop(PyObject *set)
3541
3542 Return a new reference to an arbitrary object in the *set*, and removes the
3543 object from the *set*. Return *NULL* on failure. Raise :exc:`KeyError` if the
3544 set is empty. Raise a :exc:`SystemError` if *set* is an not an instance of
3545 :class:`set` or its subtype.
3546
3547
3548.. cfunction:: int PySet_Clear(PyObject *set)
3549
3550 Empty an existing set of all elements.
3551