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