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