1 /* Abstract Object Interface (many thanks to Jim Fulton) */
5 #include "structmember.h" /* we need the offsetof() macro from there */
6 #include "longintrepr.h"
8 #define NEW_STYLE_NUMBER(o) PyType_HasFeature((o)->ob_type, \
12 /* Shorthands to return certain errors */
15 type_error(const char *msg
, PyObject
*obj
)
17 PyErr_Format(PyExc_TypeError
, msg
, obj
->ob_type
->tp_name
);
24 if (!PyErr_Occurred())
25 PyErr_SetString(PyExc_SystemError
,
26 "null argument to internal routine");
30 /* Operations on any object */
33 PyObject_Cmp(PyObject
*o1
, PyObject
*o2
, int *result
)
37 if (o1
== NULL
|| o2
== NULL
) {
41 r
= PyObject_Compare(o1
, o2
);
49 PyObject_Type(PyObject
*o
)
55 v
= (PyObject
*)o
->ob_type
;
61 PyObject_Size(PyObject
*o
)
70 m
= o
->ob_type
->tp_as_sequence
;
71 if (m
&& m
->sq_length
)
72 return m
->sq_length(o
);
74 return PyMapping_Size(o
);
77 #undef PyObject_Length
79 PyObject_Length(PyObject
*o
)
81 return PyObject_Size(o
);
83 #define PyObject_Length PyObject_Size
86 /* The length hint function returns a non-negative value from o.__len__()
87 or o.__length_hint__(). If those methods aren't found or return a negative
88 value, then the defaultvalue is returned. This function never fails.
89 Accordingly, it will mask exceptions raised in either method.
93 _PyObject_LengthHint(PyObject
*o
, Py_ssize_t defaultvalue
)
95 static PyObject
*hintstrobj
= NULL
;
100 rv
= PyObject_Size(o
);
103 if (PyErr_Occurred())
106 /* cache a hashed version of the attribute string */
107 if (hintstrobj
== NULL
) {
108 hintstrobj
= PyString_InternFromString("__length_hint__");
109 if (hintstrobj
== NULL
)
113 /* try o.__length_hint__() */
114 ro
= PyObject_CallMethodObjArgs(o
, hintstrobj
, NULL
);
117 rv
= PyInt_AsLong(ro
);
123 if (PyErr_Occurred())
129 PyObject_GetItem(PyObject
*o
, PyObject
*key
)
133 if (o
== NULL
|| key
== NULL
)
136 m
= o
->ob_type
->tp_as_mapping
;
137 if (m
&& m
->mp_subscript
)
138 return m
->mp_subscript(o
, key
);
140 if (o
->ob_type
->tp_as_sequence
) {
141 if (PyIndex_Check(key
)) {
142 Py_ssize_t key_value
;
143 key_value
= PyNumber_AsSsize_t(key
, PyExc_IndexError
);
144 if (key_value
== -1 && PyErr_Occurred())
146 return PySequence_GetItem(o
, key_value
);
148 else if (o
->ob_type
->tp_as_sequence
->sq_item
)
149 return type_error("sequence index must "
150 "be integer, not '%.200s'", key
);
153 return type_error("'%.200s' object is unsubscriptable", o
);
157 PyObject_SetItem(PyObject
*o
, PyObject
*key
, PyObject
*value
)
161 if (o
== NULL
|| key
== NULL
|| value
== NULL
) {
165 m
= o
->ob_type
->tp_as_mapping
;
166 if (m
&& m
->mp_ass_subscript
)
167 return m
->mp_ass_subscript(o
, key
, value
);
169 if (o
->ob_type
->tp_as_sequence
) {
170 if (PyIndex_Check(key
)) {
171 Py_ssize_t key_value
;
172 key_value
= PyNumber_AsSsize_t(key
, PyExc_IndexError
);
173 if (key_value
== -1 && PyErr_Occurred())
175 return PySequence_SetItem(o
, key_value
, value
);
177 else if (o
->ob_type
->tp_as_sequence
->sq_ass_item
) {
178 type_error("sequence index must be "
179 "integer, not '%.200s'", key
);
184 type_error("'%.200s' object does not support item assignment", o
);
189 PyObject_DelItem(PyObject
*o
, PyObject
*key
)
193 if (o
== NULL
|| key
== NULL
) {
197 m
= o
->ob_type
->tp_as_mapping
;
198 if (m
&& m
->mp_ass_subscript
)
199 return m
->mp_ass_subscript(o
, key
, (PyObject
*)NULL
);
201 if (o
->ob_type
->tp_as_sequence
) {
202 if (PyIndex_Check(key
)) {
203 Py_ssize_t key_value
;
204 key_value
= PyNumber_AsSsize_t(key
, PyExc_IndexError
);
205 if (key_value
== -1 && PyErr_Occurred())
207 return PySequence_DelItem(o
, key_value
);
209 else if (o
->ob_type
->tp_as_sequence
->sq_ass_item
) {
210 type_error("sequence index must be "
211 "integer, not '%.200s'", key
);
216 type_error("'%.200s' object does not support item deletion", o
);
221 PyObject_DelItemString(PyObject
*o
, char *key
)
226 if (o
== NULL
|| key
== NULL
) {
230 okey
= PyString_FromString(key
);
233 ret
= PyObject_DelItem(o
, okey
);
239 PyObject_AsCharBuffer(PyObject
*obj
,
241 Py_ssize_t
*buffer_len
)
247 if (obj
== NULL
|| buffer
== NULL
|| buffer_len
== NULL
) {
251 pb
= obj
->ob_type
->tp_as_buffer
;
253 pb
->bf_getcharbuffer
== NULL
||
254 pb
->bf_getsegcount
== NULL
) {
255 PyErr_SetString(PyExc_TypeError
,
256 "expected a character buffer object");
259 if ((*pb
->bf_getsegcount
)(obj
,NULL
) != 1) {
260 PyErr_SetString(PyExc_TypeError
,
261 "expected a single-segment buffer object");
264 len
= (*pb
->bf_getcharbuffer
)(obj
, 0, &pp
);
273 PyObject_CheckReadBuffer(PyObject
*obj
)
275 PyBufferProcs
*pb
= obj
->ob_type
->tp_as_buffer
;
278 pb
->bf_getreadbuffer
== NULL
||
279 pb
->bf_getsegcount
== NULL
||
280 (*pb
->bf_getsegcount
)(obj
, NULL
) != 1)
285 int PyObject_AsReadBuffer(PyObject
*obj
,
287 Py_ssize_t
*buffer_len
)
293 if (obj
== NULL
|| buffer
== NULL
|| buffer_len
== NULL
) {
297 pb
= obj
->ob_type
->tp_as_buffer
;
299 pb
->bf_getreadbuffer
== NULL
||
300 pb
->bf_getsegcount
== NULL
) {
301 PyErr_SetString(PyExc_TypeError
,
302 "expected a readable buffer object");
305 if ((*pb
->bf_getsegcount
)(obj
, NULL
) != 1) {
306 PyErr_SetString(PyExc_TypeError
,
307 "expected a single-segment buffer object");
310 len
= (*pb
->bf_getreadbuffer
)(obj
, 0, &pp
);
318 int PyObject_AsWriteBuffer(PyObject
*obj
,
320 Py_ssize_t
*buffer_len
)
326 if (obj
== NULL
|| buffer
== NULL
|| buffer_len
== NULL
) {
330 pb
= obj
->ob_type
->tp_as_buffer
;
332 pb
->bf_getwritebuffer
== NULL
||
333 pb
->bf_getsegcount
== NULL
) {
334 PyErr_SetString(PyExc_TypeError
,
335 "expected a writeable buffer object");
338 if ((*pb
->bf_getsegcount
)(obj
, NULL
) != 1) {
339 PyErr_SetString(PyExc_TypeError
,
340 "expected a single-segment buffer object");
343 len
= (*pb
->bf_getwritebuffer
)(obj
,0,&pp
);
351 /* Buffer C-API for Python 3.0 */
354 PyObject_GetBuffer(PyObject
*obj
, Py_buffer
*view
, int flags
)
356 if (!PyObject_CheckBuffer(obj
)) {
357 PyErr_Format(PyExc_TypeError
,
358 "'%100s' does not have the buffer interface",
359 Py_TYPE(obj
)->tp_name
);
362 return (*(obj
->ob_type
->tp_as_buffer
->bf_getbuffer
))(obj
, view
, flags
);
366 PyObject_ReleaseBuffer(PyObject
*obj
, Py_buffer
*view
)
368 if (obj
->ob_type
->tp_as_buffer
!= NULL
&&
369 obj
->ob_type
->tp_as_buffer
->bf_releasebuffer
!= NULL
) {
370 (*(obj
->ob_type
->tp_as_buffer
->bf_releasebuffer
))(obj
, view
);
376 _IsFortranContiguous(Py_buffer
*view
)
381 if (view
->ndim
== 0) return 1;
382 if (view
->strides
== NULL
) return (view
->ndim
== 1);
385 if (view
->ndim
== 1) return (view
->shape
[0] == 1 ||
386 sd
== view
->strides
[0]);
387 for (i
=0; i
<view
->ndim
; i
++) {
388 dim
= view
->shape
[i
];
389 if (dim
== 0) return 1;
390 if (view
->strides
[i
] != sd
) return 0;
397 _IsCContiguous(Py_buffer
*view
)
402 if (view
->ndim
== 0) return 1;
403 if (view
->strides
== NULL
) return 1;
406 if (view
->ndim
== 1) return (view
->shape
[0] == 1 ||
407 sd
== view
->strides
[0]);
408 for (i
=view
->ndim
-1; i
>=0; i
--) {
409 dim
= view
->shape
[i
];
410 if (dim
== 0) return 1;
411 if (view
->strides
[i
] != sd
) return 0;
418 PyBuffer_IsContiguous(Py_buffer
*view
, char fort
)
421 if (view
->suboffsets
!= NULL
) return 0;
424 return _IsCContiguous(view
);
425 else if (fort
== 'F')
426 return _IsFortranContiguous(view
);
427 else if (fort
== 'A')
428 return (_IsCContiguous(view
) || _IsFortranContiguous(view
));
434 PyBuffer_GetPointer(Py_buffer
*view
, Py_ssize_t
*indices
)
438 pointer
= (char *)view
->buf
;
439 for (i
= 0; i
< view
->ndim
; i
++) {
440 pointer
+= view
->strides
[i
]*indices
[i
];
441 if ((view
->suboffsets
!= NULL
) && (view
->suboffsets
[i
] >= 0)) {
442 pointer
= *((char**)pointer
) + view
->suboffsets
[i
];
445 return (void*)pointer
;
450 _add_one_to_index_F(int nd
, Py_ssize_t
*index
, Py_ssize_t
*shape
)
454 for (k
=0; k
<nd
; k
++) {
455 if (index
[k
] < shape
[k
]-1) {
466 _add_one_to_index_C(int nd
, Py_ssize_t
*index
, Py_ssize_t
*shape
)
470 for (k
=nd
-1; k
>=0; k
--) {
471 if (index
[k
] < shape
[k
]-1) {
481 /* view is not checked for consistency in either of these. It is
482 assumed that the size of the buffer is view->len in
483 view->len / view->itemsize elements.
487 PyBuffer_ToContiguous(void *buf
, Py_buffer
*view
, Py_ssize_t len
, char fort
)
490 void (*addone
)(int, Py_ssize_t
*, Py_ssize_t
*);
491 Py_ssize_t
*indices
, elements
;
494 if (len
> view
->len
) {
498 if (PyBuffer_IsContiguous(view
, fort
)) {
499 /* simplest copy is all that is needed */
500 memcpy(buf
, view
->buf
, len
);
504 /* Otherwise a more elaborate scheme is needed */
506 /* XXX(nnorwitz): need to check for overflow! */
507 indices
= (Py_ssize_t
*)PyMem_Malloc(sizeof(Py_ssize_t
)*(view
->ndim
));
508 if (indices
== NULL
) {
512 for (k
=0; k
<view
->ndim
;k
++) {
517 addone
= _add_one_to_index_F
;
520 addone
= _add_one_to_index_C
;
523 /* XXX : This is not going to be the fastest code in the world
524 several optimizations are possible.
526 elements
= len
/ view
->itemsize
;
528 addone(view
->ndim
, indices
, view
->shape
);
529 ptr
= PyBuffer_GetPointer(view
, indices
);
530 memcpy(dest
, ptr
, view
->itemsize
);
531 dest
+= view
->itemsize
;
538 PyBuffer_FromContiguous(Py_buffer
*view
, void *buf
, Py_ssize_t len
, char fort
)
541 void (*addone
)(int, Py_ssize_t
*, Py_ssize_t
*);
542 Py_ssize_t
*indices
, elements
;
545 if (len
> view
->len
) {
549 if (PyBuffer_IsContiguous(view
, fort
)) {
550 /* simplest copy is all that is needed */
551 memcpy(view
->buf
, buf
, len
);
555 /* Otherwise a more elaborate scheme is needed */
557 /* XXX(nnorwitz): need to check for overflow! */
558 indices
= (Py_ssize_t
*)PyMem_Malloc(sizeof(Py_ssize_t
)*(view
->ndim
));
559 if (indices
== NULL
) {
563 for (k
=0; k
<view
->ndim
;k
++) {
568 addone
= _add_one_to_index_F
;
571 addone
= _add_one_to_index_C
;
574 /* XXX : This is not going to be the fastest code in the world
575 several optimizations are possible.
577 elements
= len
/ view
->itemsize
;
579 addone(view
->ndim
, indices
, view
->shape
);
580 ptr
= PyBuffer_GetPointer(view
, indices
);
581 memcpy(ptr
, src
, view
->itemsize
);
582 src
+= view
->itemsize
;
589 int PyObject_CopyData(PyObject
*dest
, PyObject
*src
)
591 Py_buffer view_dest
, view_src
;
593 Py_ssize_t
*indices
, elements
;
596 if (!PyObject_CheckBuffer(dest
) ||
597 !PyObject_CheckBuffer(src
)) {
598 PyErr_SetString(PyExc_TypeError
,
599 "both destination and source must have the "\
604 if (PyObject_GetBuffer(dest
, &view_dest
, PyBUF_FULL
) != 0) return -1;
605 if (PyObject_GetBuffer(src
, &view_src
, PyBUF_FULL_RO
) != 0) {
606 PyObject_ReleaseBuffer(dest
, &view_dest
);
610 if (view_dest
.len
< view_src
.len
) {
611 PyErr_SetString(PyExc_BufferError
,
612 "destination is too small to receive data from source");
613 PyObject_ReleaseBuffer(dest
, &view_dest
);
614 PyObject_ReleaseBuffer(src
, &view_src
);
618 if ((PyBuffer_IsContiguous(&view_dest
, 'C') &&
619 PyBuffer_IsContiguous(&view_src
, 'C')) ||
620 (PyBuffer_IsContiguous(&view_dest
, 'F') &&
621 PyBuffer_IsContiguous(&view_src
, 'F'))) {
622 /* simplest copy is all that is needed */
623 memcpy(view_dest
.buf
, view_src
.buf
, view_src
.len
);
624 PyObject_ReleaseBuffer(dest
, &view_dest
);
625 PyObject_ReleaseBuffer(src
, &view_src
);
629 /* Otherwise a more elaborate copy scheme is needed */
631 /* XXX(nnorwitz): need to check for overflow! */
632 indices
= (Py_ssize_t
*)PyMem_Malloc(sizeof(Py_ssize_t
)*view_src
.ndim
);
633 if (indices
== NULL
) {
635 PyObject_ReleaseBuffer(dest
, &view_dest
);
636 PyObject_ReleaseBuffer(src
, &view_src
);
639 for (k
=0; k
<view_src
.ndim
;k
++) {
643 for (k
=0; k
<view_src
.ndim
; k
++) {
644 /* XXX(nnorwitz): can this overflow? */
645 elements
*= view_src
.shape
[k
];
648 _add_one_to_index_C(view_src
.ndim
, indices
, view_src
.shape
);
649 dptr
= PyBuffer_GetPointer(&view_dest
, indices
);
650 sptr
= PyBuffer_GetPointer(&view_src
, indices
);
651 memcpy(dptr
, sptr
, view_src
.itemsize
);
654 PyObject_ReleaseBuffer(dest
, &view_dest
);
655 PyObject_ReleaseBuffer(src
, &view_src
);
660 PyBuffer_FillContiguousStrides(int nd
, Py_ssize_t
*shape
,
661 Py_ssize_t
*strides
, int itemsize
,
669 for (k
=0; k
<nd
; k
++) {
675 for (k
=nd
-1; k
>=0; k
--) {
684 PyBuffer_FillInfo(Py_buffer
*view
, void *buf
, Py_ssize_t len
,
685 int readonly
, int flags
)
687 if (view
== NULL
) return 0;
688 if (((flags
& PyBUF_LOCK
) == PyBUF_LOCK
) &&
690 PyErr_SetString(PyExc_BufferError
,
691 "Cannot lock this object.");
694 if (((flags
& PyBUF_WRITABLE
) == PyBUF_WRITABLE
) &&
696 PyErr_SetString(PyExc_BufferError
,
697 "Object is not writable.");
703 view
->readonly
= readonly
;
706 if ((flags
& PyBUF_FORMAT
) == PyBUF_FORMAT
)
710 if ((flags
& PyBUF_ND
) == PyBUF_ND
)
711 view
->shape
= &(view
->len
);
712 view
->strides
= NULL
;
713 if ((flags
& PyBUF_STRIDES
) == PyBUF_STRIDES
)
714 view
->strides
= &(view
->itemsize
);
715 view
->suboffsets
= NULL
;
716 view
->internal
= NULL
;
721 PyObject_Format(PyObject
* obj
, PyObject
*format_spec
)
723 static PyObject
* str__format__
= NULL
;
724 PyObject
*empty
= NULL
;
725 PyObject
*result
= NULL
;
727 int result_is_unicode
;
729 /* Initialize cached value */
730 if (str__format__
== NULL
) {
731 /* Initialize static variable needed by _PyType_Lookup */
732 str__format__
= PyString_InternFromString("__format__");
733 if (str__format__
== NULL
)
737 /* If no format_spec is provided, use an empty string */
738 if (format_spec
== NULL
) {
739 empty
= PyString_FromStringAndSize(NULL
, 0);
743 /* Check the format_spec type, and make sure it's str or unicode */
744 if (PyUnicode_Check(format_spec
))
746 else if (PyString_Check(format_spec
))
749 PyErr_Format(PyExc_TypeError
,
750 "format expects arg 2 to be string "
751 "or unicode, not %.100s", Py_TYPE(format_spec
)->tp_name
);
755 /* Make sure the type is initialized. float gets initialized late */
756 if (Py_TYPE(obj
)->tp_dict
== NULL
)
757 if (PyType_Ready(Py_TYPE(obj
)) < 0)
760 /* Check for a __format__ method and call it. */
761 if (PyInstance_Check(obj
)) {
762 /* We're an instance of a classic class */
763 PyObject
*bound_method
= PyObject_GetAttr(obj
,
765 if (bound_method
!= NULL
) {
766 result
= PyObject_CallFunctionObjArgs(bound_method
,
769 Py_DECREF(bound_method
);
771 PyObject
*self_as_str
;
772 PyObject
*format_method
;
775 /* Per the PEP, convert to str (or unicode,
776 depending on the type of the format
777 specifier). For new-style classes, this
778 logic is done by object.__format__(). */
780 self_as_str
= PyObject_Unicode(obj
);
782 self_as_str
= PyObject_Str(obj
);
783 if (self_as_str
== NULL
)
786 /* Then call str.__format__ on that result */
787 format_method
= PyObject_GetAttr(self_as_str
,
789 if (format_method
== NULL
) {
790 Py_DECREF(self_as_str
);
793 result
= PyObject_CallFunctionObjArgs(format_method
,
796 Py_DECREF(self_as_str
);
797 Py_DECREF(format_method
);
802 /* Not an instance of a classic class, use the code
805 /* Find the (unbound!) __format__ method (a borrowed
807 PyObject
*method
= _PyType_Lookup(Py_TYPE(obj
),
809 if (method
== NULL
) {
810 PyErr_Format(PyExc_TypeError
,
811 "Type %.100s doesn't define __format__",
812 Py_TYPE(obj
)->tp_name
);
815 /* And call it, binding it to the value */
816 result
= PyObject_CallFunctionObjArgs(method
, obj
,
823 /* Check the result type, and make sure it's str or unicode */
824 if (PyUnicode_Check(result
))
825 result_is_unicode
= 1;
826 else if (PyString_Check(result
))
827 result_is_unicode
= 0;
829 PyErr_Format(PyExc_TypeError
,
830 "%.100s.__format__ must return string or "
831 "unicode, not %.100s", Py_TYPE(obj
)->tp_name
,
832 Py_TYPE(result
)->tp_name
);
838 /* Convert to unicode, if needed. Required if spec is unicode
840 if (spec_is_unicode
&& !result_is_unicode
) {
841 PyObject
*tmp
= PyObject_Unicode(result
);
842 /* This logic works whether or not tmp is NULL */
852 /* Operations on numbers */
855 PyNumber_Check(PyObject
*o
)
857 return o
&& o
->ob_type
->tp_as_number
&&
858 (o
->ob_type
->tp_as_number
->nb_int
||
859 o
->ob_type
->tp_as_number
->nb_float
);
862 /* Binary operators */
864 /* New style number protocol support */
866 #define NB_SLOT(x) offsetof(PyNumberMethods, x)
867 #define NB_BINOP(nb_methods, slot) \
868 (*(binaryfunc*)(& ((char*)nb_methods)[slot]))
869 #define NB_TERNOP(nb_methods, slot) \
870 (*(ternaryfunc*)(& ((char*)nb_methods)[slot]))
873 Calling scheme used for binary operations:
876 -------------------------------------------------------------------
877 new new w.op(v,w)[*], v.op(v,w), w.op(v,w)
878 new old v.op(v,w), coerce(v,w), v.op(v,w)
879 old new w.op(v,w), coerce(v,w), v.op(v,w)
880 old old coerce(v,w), v.op(v,w)
882 [*] only when v->ob_type != w->ob_type && w->ob_type is a subclass of
887 * new == new style number
888 * old == old style number
889 * Action indicates the order in which operations are tried until either
890 a valid result is produced or an error occurs.
895 binary_op1(PyObject
*v
, PyObject
*w
, const int op_slot
)
898 binaryfunc slotv
= NULL
;
899 binaryfunc slotw
= NULL
;
901 if (v
->ob_type
->tp_as_number
!= NULL
&& NEW_STYLE_NUMBER(v
))
902 slotv
= NB_BINOP(v
->ob_type
->tp_as_number
, op_slot
);
903 if (w
->ob_type
!= v
->ob_type
&&
904 w
->ob_type
->tp_as_number
!= NULL
&& NEW_STYLE_NUMBER(w
)) {
905 slotw
= NB_BINOP(w
->ob_type
->tp_as_number
, op_slot
);
910 if (slotw
&& PyType_IsSubtype(w
->ob_type
, v
->ob_type
)) {
912 if (x
!= Py_NotImplemented
)
914 Py_DECREF(x
); /* can't do it */
918 if (x
!= Py_NotImplemented
)
920 Py_DECREF(x
); /* can't do it */
924 if (x
!= Py_NotImplemented
)
926 Py_DECREF(x
); /* can't do it */
928 if (!NEW_STYLE_NUMBER(v
) || !NEW_STYLE_NUMBER(w
)) {
929 int err
= PyNumber_CoerceEx(&v
, &w
);
934 PyNumberMethods
*mv
= v
->ob_type
->tp_as_number
;
937 slot
= NB_BINOP(mv
, op_slot
);
945 /* CoerceEx incremented the reference counts */
950 Py_INCREF(Py_NotImplemented
);
951 return Py_NotImplemented
;
955 binop_type_error(PyObject
*v
, PyObject
*w
, const char *op_name
)
957 PyErr_Format(PyExc_TypeError
,
958 "unsupported operand type(s) for %.100s: "
959 "'%.100s' and '%.100s'",
962 w
->ob_type
->tp_name
);
967 binary_op(PyObject
*v
, PyObject
*w
, const int op_slot
, const char *op_name
)
969 PyObject
*result
= binary_op1(v
, w
, op_slot
);
970 if (result
== Py_NotImplemented
) {
972 return binop_type_error(v
, w
, op_name
);
979 Calling scheme used for ternary operations:
981 *** In some cases, w.op is called before v.op; see binary_op1. ***
984 -------------------------------------------------------------------
985 new new new v.op(v,w,z), w.op(v,w,z), z.op(v,w,z)
986 new old new v.op(v,w,z), z.op(v,w,z), coerce(v,w,z), v.op(v,w,z)
987 old new new w.op(v,w,z), z.op(v,w,z), coerce(v,w,z), v.op(v,w,z)
988 old old new z.op(v,w,z), coerce(v,w,z), v.op(v,w,z)
989 new new old v.op(v,w,z), w.op(v,w,z), coerce(v,w,z), v.op(v,w,z)
990 new old old v.op(v,w,z), coerce(v,w,z), v.op(v,w,z)
991 old new old w.op(v,w,z), coerce(v,w,z), v.op(v,w,z)
992 old old old coerce(v,w,z), v.op(v,w,z)
996 * new == new style number
997 * old == old style number
998 * Action indicates the order in which operations are tried until either
999 a valid result is produced or an error occurs.
1000 * coerce(v,w,z) actually does: coerce(v,w), coerce(v,z), coerce(w,z) and
1001 only if z != Py_None; if z == Py_None, then it is treated as absent
1002 variable and only coerce(v,w) is tried.
1007 ternary_op(PyObject
*v
,
1011 const char *op_name
)
1013 PyNumberMethods
*mv
, *mw
, *mz
;
1015 ternaryfunc slotv
= NULL
;
1016 ternaryfunc slotw
= NULL
;
1017 ternaryfunc slotz
= NULL
;
1019 mv
= v
->ob_type
->tp_as_number
;
1020 mw
= w
->ob_type
->tp_as_number
;
1021 if (mv
!= NULL
&& NEW_STYLE_NUMBER(v
))
1022 slotv
= NB_TERNOP(mv
, op_slot
);
1023 if (w
->ob_type
!= v
->ob_type
&&
1024 mw
!= NULL
&& NEW_STYLE_NUMBER(w
)) {
1025 slotw
= NB_TERNOP(mw
, op_slot
);
1030 if (slotw
&& PyType_IsSubtype(w
->ob_type
, v
->ob_type
)) {
1032 if (x
!= Py_NotImplemented
)
1034 Py_DECREF(x
); /* can't do it */
1038 if (x
!= Py_NotImplemented
)
1040 Py_DECREF(x
); /* can't do it */
1044 if (x
!= Py_NotImplemented
)
1046 Py_DECREF(x
); /* can't do it */
1048 mz
= z
->ob_type
->tp_as_number
;
1049 if (mz
!= NULL
&& NEW_STYLE_NUMBER(z
)) {
1050 slotz
= NB_TERNOP(mz
, op_slot
);
1051 if (slotz
== slotv
|| slotz
== slotw
)
1055 if (x
!= Py_NotImplemented
)
1057 Py_DECREF(x
); /* can't do it */
1061 if (!NEW_STYLE_NUMBER(v
) || !NEW_STYLE_NUMBER(w
) ||
1062 (z
!= Py_None
&& !NEW_STYLE_NUMBER(z
))) {
1063 /* we have an old style operand, coerce */
1064 PyObject
*v1
, *z1
, *w2
, *z2
;
1067 c
= PyNumber_Coerce(&v
, &w
);
1071 /* Special case: if the third argument is None, it is
1072 treated as absent argument and not coerced. */
1074 if (v
->ob_type
->tp_as_number
) {
1075 slotz
= NB_TERNOP(v
->ob_type
->tp_as_number
,
1088 c
= PyNumber_Coerce(&v1
, &z1
);
1093 c
= PyNumber_Coerce(&w2
, &z2
);
1097 if (v1
->ob_type
->tp_as_number
!= NULL
) {
1098 slotv
= NB_TERNOP(v1
->ob_type
->tp_as_number
,
1101 x
= slotv(v1
, w2
, z2
);
1124 "unsupported operand type(s) for ** or pow(): "
1125 "'%.100s' and '%.100s'",
1126 v
->ob_type
->tp_name
,
1127 w
->ob_type
->tp_name
);
1131 "unsupported operand type(s) for pow(): "
1132 "'%.100s', '%.100s', '%.100s'",
1133 v
->ob_type
->tp_name
,
1134 w
->ob_type
->tp_name
,
1135 z
->ob_type
->tp_name
);
1139 #define BINARY_FUNC(func, op, op_name) \
1141 func(PyObject *v, PyObject *w) { \
1142 return binary_op(v, w, NB_SLOT(op), op_name); \
1145 BINARY_FUNC(PyNumber_Or
, nb_or
, "|")
1146 BINARY_FUNC(PyNumber_Xor
, nb_xor
, "^")
1147 BINARY_FUNC(PyNumber_And
, nb_and
, "&")
1148 BINARY_FUNC(PyNumber_Lshift
, nb_lshift
, "<<")
1149 BINARY_FUNC(PyNumber_Rshift
, nb_rshift
, ">>")
1150 BINARY_FUNC(PyNumber_Subtract
, nb_subtract
, "-")
1151 BINARY_FUNC(PyNumber_Divide
, nb_divide
, "/")
1152 BINARY_FUNC(PyNumber_Divmod
, nb_divmod
, "divmod()")
1155 PyNumber_Add(PyObject
*v
, PyObject
*w
)
1157 PyObject
*result
= binary_op1(v
, w
, NB_SLOT(nb_add
));
1158 if (result
== Py_NotImplemented
) {
1159 PySequenceMethods
*m
= v
->ob_type
->tp_as_sequence
;
1161 if (m
&& m
->sq_concat
) {
1162 return (*m
->sq_concat
)(v
, w
);
1164 result
= binop_type_error(v
, w
, "+");
1170 sequence_repeat(ssizeargfunc repeatfunc
, PyObject
*seq
, PyObject
*n
)
1173 if (PyIndex_Check(n
)) {
1174 count
= PyNumber_AsSsize_t(n
, PyExc_OverflowError
);
1175 if (count
== -1 && PyErr_Occurred())
1179 return type_error("can't multiply sequence by "
1180 "non-int of type '%.200s'", n
);
1182 return (*repeatfunc
)(seq
, count
);
1186 PyNumber_Multiply(PyObject
*v
, PyObject
*w
)
1188 PyObject
*result
= binary_op1(v
, w
, NB_SLOT(nb_multiply
));
1189 if (result
== Py_NotImplemented
) {
1190 PySequenceMethods
*mv
= v
->ob_type
->tp_as_sequence
;
1191 PySequenceMethods
*mw
= w
->ob_type
->tp_as_sequence
;
1193 if (mv
&& mv
->sq_repeat
) {
1194 return sequence_repeat(mv
->sq_repeat
, v
, w
);
1196 else if (mw
&& mw
->sq_repeat
) {
1197 return sequence_repeat(mw
->sq_repeat
, w
, v
);
1199 result
= binop_type_error(v
, w
, "*");
1205 PyNumber_FloorDivide(PyObject
*v
, PyObject
*w
)
1207 /* XXX tp_flags test */
1208 return binary_op(v
, w
, NB_SLOT(nb_floor_divide
), "//");
1212 PyNumber_TrueDivide(PyObject
*v
, PyObject
*w
)
1214 /* XXX tp_flags test */
1215 return binary_op(v
, w
, NB_SLOT(nb_true_divide
), "/");
1219 PyNumber_Remainder(PyObject
*v
, PyObject
*w
)
1221 return binary_op(v
, w
, NB_SLOT(nb_remainder
), "%");
1225 PyNumber_Power(PyObject
*v
, PyObject
*w
, PyObject
*z
)
1227 return ternary_op(v
, w
, z
, NB_SLOT(nb_power
), "** or pow()");
1230 /* Binary in-place operators */
1232 /* The in-place operators are defined to fall back to the 'normal',
1233 non in-place operations, if the in-place methods are not in place.
1235 - If the left hand object has the appropriate struct members, and
1236 they are filled, call the appropriate function and return the
1237 result. No coercion is done on the arguments; the left-hand object
1238 is the one the operation is performed on, and it's up to the
1239 function to deal with the right-hand object.
1241 - Otherwise, in-place modification is not supported. Handle it exactly as
1242 a non in-place operation of the same kind.
1246 #define HASINPLACE(t) \
1247 PyType_HasFeature((t)->ob_type, Py_TPFLAGS_HAVE_INPLACEOPS)
1250 binary_iop1(PyObject
*v
, PyObject
*w
, const int iop_slot
, const int op_slot
)
1252 PyNumberMethods
*mv
= v
->ob_type
->tp_as_number
;
1253 if (mv
!= NULL
&& HASINPLACE(v
)) {
1254 binaryfunc slot
= NB_BINOP(mv
, iop_slot
);
1256 PyObject
*x
= (slot
)(v
, w
);
1257 if (x
!= Py_NotImplemented
) {
1263 return binary_op1(v
, w
, op_slot
);
1267 binary_iop(PyObject
*v
, PyObject
*w
, const int iop_slot
, const int op_slot
,
1268 const char *op_name
)
1270 PyObject
*result
= binary_iop1(v
, w
, iop_slot
, op_slot
);
1271 if (result
== Py_NotImplemented
) {
1273 return binop_type_error(v
, w
, op_name
);
1278 #define INPLACE_BINOP(func, iop, op, op_name) \
1280 func(PyObject *v, PyObject *w) { \
1281 return binary_iop(v, w, NB_SLOT(iop), NB_SLOT(op), op_name); \
1284 INPLACE_BINOP(PyNumber_InPlaceOr
, nb_inplace_or
, nb_or
, "|=")
1285 INPLACE_BINOP(PyNumber_InPlaceXor
, nb_inplace_xor
, nb_xor
, "^=")
1286 INPLACE_BINOP(PyNumber_InPlaceAnd
, nb_inplace_and
, nb_and
, "&=")
1287 INPLACE_BINOP(PyNumber_InPlaceLshift
, nb_inplace_lshift
, nb_lshift
, "<<=")
1288 INPLACE_BINOP(PyNumber_InPlaceRshift
, nb_inplace_rshift
, nb_rshift
, ">>=")
1289 INPLACE_BINOP(PyNumber_InPlaceSubtract
, nb_inplace_subtract
, nb_subtract
, "-=")
1290 INPLACE_BINOP(PyNumber_InPlaceDivide
, nb_inplace_divide
, nb_divide
, "/=")
1293 PyNumber_InPlaceFloorDivide(PyObject
*v
, PyObject
*w
)
1295 /* XXX tp_flags test */
1296 return binary_iop(v
, w
, NB_SLOT(nb_inplace_floor_divide
),
1297 NB_SLOT(nb_floor_divide
), "//=");
1301 PyNumber_InPlaceTrueDivide(PyObject
*v
, PyObject
*w
)
1303 /* XXX tp_flags test */
1304 return binary_iop(v
, w
, NB_SLOT(nb_inplace_true_divide
),
1305 NB_SLOT(nb_true_divide
), "/=");
1309 PyNumber_InPlaceAdd(PyObject
*v
, PyObject
*w
)
1311 PyObject
*result
= binary_iop1(v
, w
, NB_SLOT(nb_inplace_add
),
1313 if (result
== Py_NotImplemented
) {
1314 PySequenceMethods
*m
= v
->ob_type
->tp_as_sequence
;
1317 binaryfunc f
= NULL
;
1319 f
= m
->sq_inplace_concat
;
1325 result
= binop_type_error(v
, w
, "+=");
1331 PyNumber_InPlaceMultiply(PyObject
*v
, PyObject
*w
)
1333 PyObject
*result
= binary_iop1(v
, w
, NB_SLOT(nb_inplace_multiply
),
1334 NB_SLOT(nb_multiply
));
1335 if (result
== Py_NotImplemented
) {
1336 ssizeargfunc f
= NULL
;
1337 PySequenceMethods
*mv
= v
->ob_type
->tp_as_sequence
;
1338 PySequenceMethods
*mw
= w
->ob_type
->tp_as_sequence
;
1342 f
= mv
->sq_inplace_repeat
;
1346 return sequence_repeat(f
, v
, w
);
1348 else if (mw
!= NULL
) {
1349 /* Note that the right hand operand should not be
1350 * mutated in this case so sq_inplace_repeat is not
1353 return sequence_repeat(mw
->sq_repeat
, w
, v
);
1355 result
= binop_type_error(v
, w
, "*=");
1361 PyNumber_InPlaceRemainder(PyObject
*v
, PyObject
*w
)
1363 return binary_iop(v
, w
, NB_SLOT(nb_inplace_remainder
),
1364 NB_SLOT(nb_remainder
), "%=");
1368 PyNumber_InPlacePower(PyObject
*v
, PyObject
*w
, PyObject
*z
)
1370 if (HASINPLACE(v
) && v
->ob_type
->tp_as_number
&&
1371 v
->ob_type
->tp_as_number
->nb_inplace_power
!= NULL
) {
1372 return ternary_op(v
, w
, z
, NB_SLOT(nb_inplace_power
), "**=");
1375 return ternary_op(v
, w
, z
, NB_SLOT(nb_power
), "**=");
1380 /* Unary operators and functions */
1383 PyNumber_Negative(PyObject
*o
)
1388 return null_error();
1389 m
= o
->ob_type
->tp_as_number
;
1390 if (m
&& m
->nb_negative
)
1391 return (*m
->nb_negative
)(o
);
1393 return type_error("bad operand type for unary -: '%.200s'", o
);
1397 PyNumber_Positive(PyObject
*o
)
1402 return null_error();
1403 m
= o
->ob_type
->tp_as_number
;
1404 if (m
&& m
->nb_positive
)
1405 return (*m
->nb_positive
)(o
);
1407 return type_error("bad operand type for unary +: '%.200s'", o
);
1411 PyNumber_Invert(PyObject
*o
)
1416 return null_error();
1417 m
= o
->ob_type
->tp_as_number
;
1418 if (m
&& m
->nb_invert
)
1419 return (*m
->nb_invert
)(o
);
1421 return type_error("bad operand type for unary ~: '%.200s'", o
);
1425 PyNumber_Absolute(PyObject
*o
)
1430 return null_error();
1431 m
= o
->ob_type
->tp_as_number
;
1432 if (m
&& m
->nb_absolute
)
1433 return m
->nb_absolute(o
);
1435 return type_error("bad operand type for abs(): '%.200s'", o
);
1438 /* Add a check for embedded NULL-bytes in the argument. */
1440 int_from_string(const char *s
, Py_ssize_t len
)
1445 x
= PyInt_FromString((char*)s
, &end
, 10);
1448 if (end
!= s
+ len
) {
1449 PyErr_SetString(PyExc_ValueError
,
1450 "null byte in argument for int()");
1457 /* Return a Python Int or Long from the object item
1458 Raise TypeError if the result is not an int-or-long
1459 or if the object cannot be interpreted as an index.
1462 PyNumber_Index(PyObject
*item
)
1464 PyObject
*result
= NULL
;
1466 return null_error();
1467 if (PyInt_Check(item
) || PyLong_Check(item
)) {
1471 if (PyIndex_Check(item
)) {
1472 result
= item
->ob_type
->tp_as_number
->nb_index(item
);
1474 !PyInt_Check(result
) && !PyLong_Check(result
)) {
1475 PyErr_Format(PyExc_TypeError
,
1476 "__index__ returned non-(int,long) " \
1478 result
->ob_type
->tp_name
);
1484 PyErr_Format(PyExc_TypeError
,
1485 "'%.200s' object cannot be interpreted "
1486 "as an index", item
->ob_type
->tp_name
);
1491 /* Return an error on Overflow only if err is not NULL*/
1494 PyNumber_AsSsize_t(PyObject
*item
, PyObject
*err
)
1498 PyObject
*value
= PyNumber_Index(item
);
1502 /* We're done if PyInt_AsSsize_t() returns without error. */
1503 result
= PyInt_AsSsize_t(value
);
1504 if (result
!= -1 || !(runerr
= PyErr_Occurred()))
1507 /* Error handling code -- only manage OverflowError differently */
1508 if (!PyErr_GivenExceptionMatches(runerr
, PyExc_OverflowError
))
1512 /* If no error-handling desired then the default clipping
1516 assert(PyLong_Check(value
));
1517 /* Whether or not it is less than or equal to
1518 zero is determined by the sign of ob_size
1520 if (_PyLong_Sign(value
) < 0)
1521 result
= PY_SSIZE_T_MIN
;
1523 result
= PY_SSIZE_T_MAX
;
1526 /* Otherwise replace the error with caller's error object. */
1528 "cannot fit '%.200s' into an index-sized integer",
1529 item
->ob_type
->tp_name
);
1539 _PyNumber_ConvertIntegralToInt(PyObject
*integral
, const char* error_format
)
1541 const char *type_name
;
1542 static PyObject
*int_name
= NULL
;
1543 if (int_name
== NULL
) {
1544 int_name
= PyString_InternFromString("__int__");
1545 if (int_name
== NULL
)
1549 if (integral
&& (!PyInt_Check(integral
) &&
1550 !PyLong_Check(integral
))) {
1551 /* Don't go through tp_as_number->nb_int to avoid
1552 hitting the classic class fallback to __trunc__. */
1553 PyObject
*int_func
= PyObject_GetAttr(integral
, int_name
);
1554 if (int_func
== NULL
) {
1555 PyErr_Clear(); /* Raise a different error. */
1556 goto non_integral_error
;
1558 Py_DECREF(integral
);
1559 integral
= PyEval_CallObject(int_func
, NULL
);
1560 Py_DECREF(int_func
);
1561 if (integral
&& (!PyInt_Check(integral
) &&
1562 !PyLong_Check(integral
))) {
1563 goto non_integral_error
;
1569 if (PyInstance_Check(integral
)) {
1570 type_name
= PyString_AS_STRING(((PyInstanceObject
*)integral
)
1571 ->in_class
->cl_name
);
1574 type_name
= integral
->ob_type
->tp_name
;
1576 PyErr_Format(PyExc_TypeError
, error_format
, type_name
);
1577 Py_DECREF(integral
);
1583 PyNumber_Int(PyObject
*o
)
1586 static PyObject
*trunc_name
= NULL
;
1587 PyObject
*trunc_func
;
1589 Py_ssize_t buffer_len
;
1591 if (trunc_name
== NULL
) {
1592 trunc_name
= PyString_InternFromString("__trunc__");
1593 if (trunc_name
== NULL
)
1598 return null_error();
1599 if (PyInt_CheckExact(o
)) {
1603 m
= o
->ob_type
->tp_as_number
;
1604 if (m
&& m
->nb_int
) { /* This should include subclasses of int */
1605 /* Classic classes always take this branch. */
1606 PyObject
*res
= m
->nb_int(o
);
1607 if (res
&& (!PyInt_Check(res
) && !PyLong_Check(res
))) {
1608 PyErr_Format(PyExc_TypeError
,
1609 "__int__ returned non-int (type %.200s)",
1610 res
->ob_type
->tp_name
);
1616 if (PyInt_Check(o
)) { /* A int subclass without nb_int */
1617 PyIntObject
*io
= (PyIntObject
*)o
;
1618 return PyInt_FromLong(io
->ob_ival
);
1620 trunc_func
= PyObject_GetAttr(o
, trunc_name
);
1622 PyObject
*truncated
= PyEval_CallObject(trunc_func
, NULL
);
1623 Py_DECREF(trunc_func
);
1624 /* __trunc__ is specified to return an Integral type, but
1625 int() needs to return an int. */
1626 return _PyNumber_ConvertIntegralToInt(
1628 "__trunc__ returned non-Integral (type %.200s)");
1630 PyErr_Clear(); /* It's not an error if o.__trunc__ doesn't exist. */
1632 if (PyString_Check(o
))
1633 return int_from_string(PyString_AS_STRING(o
),
1634 PyString_GET_SIZE(o
));
1635 #ifdef Py_USING_UNICODE
1636 if (PyUnicode_Check(o
))
1637 return PyInt_FromUnicode(PyUnicode_AS_UNICODE(o
),
1638 PyUnicode_GET_SIZE(o
),
1641 if (!PyObject_AsCharBuffer(o
, &buffer
, &buffer_len
))
1642 return int_from_string((char*)buffer
, buffer_len
);
1644 return type_error("int() argument must be a string or a "
1645 "number, not '%.200s'", o
);
1648 /* Add a check for embedded NULL-bytes in the argument. */
1650 long_from_string(const char *s
, Py_ssize_t len
)
1655 x
= PyLong_FromString((char*)s
, &end
, 10);
1658 if (end
!= s
+ len
) {
1659 PyErr_SetString(PyExc_ValueError
,
1660 "null byte in argument for long()");
1668 PyNumber_Long(PyObject
*o
)
1671 static PyObject
*trunc_name
= NULL
;
1672 PyObject
*trunc_func
;
1674 Py_ssize_t buffer_len
;
1676 if (trunc_name
== NULL
) {
1677 trunc_name
= PyString_InternFromString("__trunc__");
1678 if (trunc_name
== NULL
)
1683 return null_error();
1684 m
= o
->ob_type
->tp_as_number
;
1685 if (m
&& m
->nb_long
) { /* This should include subclasses of long */
1686 /* Classic classes always take this branch. */
1687 PyObject
*res
= m
->nb_long(o
);
1688 if (res
&& (!PyInt_Check(res
) && !PyLong_Check(res
))) {
1689 PyErr_Format(PyExc_TypeError
,
1690 "__long__ returned non-long (type %.200s)",
1691 res
->ob_type
->tp_name
);
1697 if (PyLong_Check(o
)) /* A long subclass without nb_long */
1698 return _PyLong_Copy((PyLongObject
*)o
);
1699 trunc_func
= PyObject_GetAttr(o
, trunc_name
);
1701 PyObject
*truncated
= PyEval_CallObject(trunc_func
, NULL
);
1702 PyObject
*int_instance
;
1703 Py_DECREF(trunc_func
);
1704 /* __trunc__ is specified to return an Integral type,
1705 but long() needs to return a long. */
1706 int_instance
= _PyNumber_ConvertIntegralToInt(
1708 "__trunc__ returned non-Integral (type %.200s)");
1709 if (int_instance
&& PyInt_Check(int_instance
)) {
1710 /* Make sure that long() returns a long instance. */
1711 long value
= PyInt_AS_LONG(int_instance
);
1712 Py_DECREF(int_instance
);
1713 return PyLong_FromLong(value
);
1715 return int_instance
;
1717 PyErr_Clear(); /* It's not an error if o.__trunc__ doesn't exist. */
1719 if (PyString_Check(o
))
1720 /* need to do extra error checking that PyLong_FromString()
1721 * doesn't do. In particular long('9.5') must raise an
1722 * exception, not truncate the float.
1724 return long_from_string(PyString_AS_STRING(o
),
1725 PyString_GET_SIZE(o
));
1726 #ifdef Py_USING_UNICODE
1727 if (PyUnicode_Check(o
))
1728 /* The above check is done in PyLong_FromUnicode(). */
1729 return PyLong_FromUnicode(PyUnicode_AS_UNICODE(o
),
1730 PyUnicode_GET_SIZE(o
),
1733 if (!PyObject_AsCharBuffer(o
, &buffer
, &buffer_len
))
1734 return long_from_string(buffer
, buffer_len
);
1736 return type_error("long() argument must be a string or a "
1737 "number, not '%.200s'", o
);
1741 PyNumber_Float(PyObject
*o
)
1746 return null_error();
1747 m
= o
->ob_type
->tp_as_number
;
1748 if (m
&& m
->nb_float
) { /* This should include subclasses of float */
1749 PyObject
*res
= m
->nb_float(o
);
1750 if (res
&& !PyFloat_Check(res
)) {
1751 PyErr_Format(PyExc_TypeError
,
1752 "__float__ returned non-float (type %.200s)",
1753 res
->ob_type
->tp_name
);
1759 if (PyFloat_Check(o
)) { /* A float subclass with nb_float == NULL */
1760 PyFloatObject
*po
= (PyFloatObject
*)o
;
1761 return PyFloat_FromDouble(po
->ob_fval
);
1763 return PyFloat_FromString(o
, NULL
);
1767 PyNumber_ToBase(PyObject
*n
, int base
)
1769 PyObject
*res
= NULL
;
1770 PyObject
*index
= PyNumber_Index(n
);
1774 if (PyLong_Check(index
))
1775 res
= _PyLong_Format(index
, base
, 0, 1);
1776 else if (PyInt_Check(index
))
1777 res
= _PyInt_Format((PyIntObject
*)index
, base
, 1);
1779 /* It should not be possible to get here, as
1780 PyNumber_Index already has a check for the same
1782 PyErr_SetString(PyExc_ValueError
, "PyNumber_ToBase: index not "
1789 /* Operations on sequences */
1792 PySequence_Check(PyObject
*s
)
1794 if (s
&& PyInstance_Check(s
))
1795 return PyObject_HasAttrString(s
, "__getitem__");
1796 if (PyObject_IsInstance(s
, (PyObject
*)&PyDict_Type
))
1798 return s
!= NULL
&& s
->ob_type
->tp_as_sequence
&&
1799 s
->ob_type
->tp_as_sequence
->sq_item
!= NULL
;
1803 PySequence_Size(PyObject
*s
)
1805 PySequenceMethods
*m
;
1812 m
= s
->ob_type
->tp_as_sequence
;
1813 if (m
&& m
->sq_length
)
1814 return m
->sq_length(s
);
1816 type_error("object of type '%.200s' has no len()", s
);
1820 #undef PySequence_Length
1822 PySequence_Length(PyObject
*s
)
1824 return PySequence_Size(s
);
1826 #define PySequence_Length PySequence_Size
1829 PySequence_Concat(PyObject
*s
, PyObject
*o
)
1831 PySequenceMethods
*m
;
1833 if (s
== NULL
|| o
== NULL
)
1834 return null_error();
1836 m
= s
->ob_type
->tp_as_sequence
;
1837 if (m
&& m
->sq_concat
)
1838 return m
->sq_concat(s
, o
);
1840 /* Instances of user classes defining an __add__() method only
1841 have an nb_add slot, not an sq_concat slot. So we fall back
1842 to nb_add if both arguments appear to be sequences. */
1843 if (PySequence_Check(s
) && PySequence_Check(o
)) {
1844 PyObject
*result
= binary_op1(s
, o
, NB_SLOT(nb_add
));
1845 if (result
!= Py_NotImplemented
)
1849 return type_error("'%.200s' object can't be concatenated", s
);
1853 PySequence_Repeat(PyObject
*o
, Py_ssize_t count
)
1855 PySequenceMethods
*m
;
1858 return null_error();
1860 m
= o
->ob_type
->tp_as_sequence
;
1861 if (m
&& m
->sq_repeat
)
1862 return m
->sq_repeat(o
, count
);
1864 /* Instances of user classes defining a __mul__() method only
1865 have an nb_multiply slot, not an sq_repeat slot. so we fall back
1866 to nb_multiply if o appears to be a sequence. */
1867 if (PySequence_Check(o
)) {
1868 PyObject
*n
, *result
;
1869 n
= PyInt_FromSsize_t(count
);
1872 result
= binary_op1(o
, n
, NB_SLOT(nb_multiply
));
1874 if (result
!= Py_NotImplemented
)
1878 return type_error("'%.200s' object can't be repeated", o
);
1882 PySequence_InPlaceConcat(PyObject
*s
, PyObject
*o
)
1884 PySequenceMethods
*m
;
1886 if (s
== NULL
|| o
== NULL
)
1887 return null_error();
1889 m
= s
->ob_type
->tp_as_sequence
;
1890 if (m
&& HASINPLACE(s
) && m
->sq_inplace_concat
)
1891 return m
->sq_inplace_concat(s
, o
);
1892 if (m
&& m
->sq_concat
)
1893 return m
->sq_concat(s
, o
);
1895 if (PySequence_Check(s
) && PySequence_Check(o
)) {
1896 PyObject
*result
= binary_iop1(s
, o
, NB_SLOT(nb_inplace_add
),
1898 if (result
!= Py_NotImplemented
)
1902 return type_error("'%.200s' object can't be concatenated", s
);
1906 PySequence_InPlaceRepeat(PyObject
*o
, Py_ssize_t count
)
1908 PySequenceMethods
*m
;
1911 return null_error();
1913 m
= o
->ob_type
->tp_as_sequence
;
1914 if (m
&& HASINPLACE(o
) && m
->sq_inplace_repeat
)
1915 return m
->sq_inplace_repeat(o
, count
);
1916 if (m
&& m
->sq_repeat
)
1917 return m
->sq_repeat(o
, count
);
1919 if (PySequence_Check(o
)) {
1920 PyObject
*n
, *result
;
1921 n
= PyInt_FromSsize_t(count
);
1924 result
= binary_iop1(o
, n
, NB_SLOT(nb_inplace_multiply
),
1925 NB_SLOT(nb_multiply
));
1927 if (result
!= Py_NotImplemented
)
1931 return type_error("'%.200s' object can't be repeated", o
);
1935 PySequence_GetItem(PyObject
*s
, Py_ssize_t i
)
1937 PySequenceMethods
*m
;
1940 return null_error();
1942 m
= s
->ob_type
->tp_as_sequence
;
1943 if (m
&& m
->sq_item
) {
1946 Py_ssize_t l
= (*m
->sq_length
)(s
);
1952 return m
->sq_item(s
, i
);
1955 return type_error("'%.200s' object is unindexable", s
);
1959 PySequence_GetSlice(PyObject
*s
, Py_ssize_t i1
, Py_ssize_t i2
)
1961 PySequenceMethods
*m
;
1962 PyMappingMethods
*mp
;
1964 if (!s
) return null_error();
1966 m
= s
->ob_type
->tp_as_sequence
;
1967 if (m
&& m
->sq_slice
) {
1968 if (i1
< 0 || i2
< 0) {
1970 Py_ssize_t l
= (*m
->sq_length
)(s
);
1979 return m
->sq_slice(s
, i1
, i2
);
1980 } else if ((mp
= s
->ob_type
->tp_as_mapping
) && mp
->mp_subscript
) {
1982 PyObject
*slice
= _PySlice_FromIndices(i1
, i2
);
1985 res
= mp
->mp_subscript(s
, slice
);
1990 return type_error("'%.200s' object is unsliceable", s
);
1994 PySequence_SetItem(PyObject
*s
, Py_ssize_t i
, PyObject
*o
)
1996 PySequenceMethods
*m
;
2003 m
= s
->ob_type
->tp_as_sequence
;
2004 if (m
&& m
->sq_ass_item
) {
2007 Py_ssize_t l
= (*m
->sq_length
)(s
);
2013 return m
->sq_ass_item(s
, i
, o
);
2016 type_error("'%.200s' object does not support item assignment", s
);
2021 PySequence_DelItem(PyObject
*s
, Py_ssize_t i
)
2023 PySequenceMethods
*m
;
2030 m
= s
->ob_type
->tp_as_sequence
;
2031 if (m
&& m
->sq_ass_item
) {
2034 Py_ssize_t l
= (*m
->sq_length
)(s
);
2040 return m
->sq_ass_item(s
, i
, (PyObject
*)NULL
);
2043 type_error("'%.200s' object doesn't support item deletion", s
);
2048 PySequence_SetSlice(PyObject
*s
, Py_ssize_t i1
, Py_ssize_t i2
, PyObject
*o
)
2050 PySequenceMethods
*m
;
2051 PyMappingMethods
*mp
;
2058 m
= s
->ob_type
->tp_as_sequence
;
2059 if (m
&& m
->sq_ass_slice
) {
2060 if (i1
< 0 || i2
< 0) {
2062 Py_ssize_t l
= (*m
->sq_length
)(s
);
2071 return m
->sq_ass_slice(s
, i1
, i2
, o
);
2072 } else if ((mp
= s
->ob_type
->tp_as_mapping
) && mp
->mp_ass_subscript
) {
2074 PyObject
*slice
= _PySlice_FromIndices(i1
, i2
);
2077 res
= mp
->mp_ass_subscript(s
, slice
, o
);
2082 type_error("'%.200s' object doesn't support slice assignment", s
);
2087 PySequence_DelSlice(PyObject
*s
, Py_ssize_t i1
, Py_ssize_t i2
)
2089 PySequenceMethods
*m
;
2096 m
= s
->ob_type
->tp_as_sequence
;
2097 if (m
&& m
->sq_ass_slice
) {
2098 if (i1
< 0 || i2
< 0) {
2100 Py_ssize_t l
= (*m
->sq_length
)(s
);
2109 return m
->sq_ass_slice(s
, i1
, i2
, (PyObject
*)NULL
);
2111 type_error("'%.200s' object doesn't support slice deletion", s
);
2116 PySequence_Tuple(PyObject
*v
)
2118 PyObject
*it
; /* iter(v) */
2119 Py_ssize_t n
; /* guess for result tuple size */
2124 return null_error();
2126 /* Special-case the common tuple and list cases, for efficiency. */
2127 if (PyTuple_CheckExact(v
)) {
2128 /* Note that we can't know whether it's safe to return
2129 a tuple *subclass* instance as-is, hence the restriction
2130 to exact tuples here. In contrast, lists always make
2131 a copy, so there's no need for exactness below. */
2135 if (PyList_Check(v
))
2136 return PyList_AsTuple(v
);
2139 it
= PyObject_GetIter(v
);
2143 /* Guess result size and allocate space. */
2144 n
= _PyObject_LengthHint(v
, 10);
2145 result
= PyTuple_New(n
);
2149 /* Fill the tuple. */
2150 for (j
= 0; ; ++j
) {
2151 PyObject
*item
= PyIter_Next(it
);
2153 if (PyErr_Occurred())
2158 Py_ssize_t oldn
= n
;
2159 /* The over-allocation strategy can grow a bit faster
2160 than for lists because unlike lists the
2161 over-allocation isn't permanent -- we reclaim
2162 the excess before the end of this routine.
2163 So, grow by ten and then add 25%.
2168 /* Check for overflow */
2173 if (_PyTuple_Resize(&result
, n
) != 0) {
2178 PyTuple_SET_ITEM(result
, j
, item
);
2181 /* Cut tuple back if guess was too large. */
2183 _PyTuple_Resize(&result
, j
) != 0)
2196 PySequence_List(PyObject
*v
)
2198 PyObject
*result
; /* result list */
2199 PyObject
*rv
; /* return value from PyList_Extend */
2202 return null_error();
2204 result
= PyList_New(0);
2208 rv
= _PyList_Extend((PyListObject
*)result
, v
);
2218 PySequence_Fast(PyObject
*v
, const char *m
)
2223 return null_error();
2225 if (PyList_CheckExact(v
) || PyTuple_CheckExact(v
)) {
2230 it
= PyObject_GetIter(v
);
2232 if (PyErr_ExceptionMatches(PyExc_TypeError
))
2233 PyErr_SetString(PyExc_TypeError
, m
);
2237 v
= PySequence_List(it
);
2243 /* Iterate over seq. Result depends on the operation:
2244 PY_ITERSEARCH_COUNT: -1 if error, else # of times obj appears in seq.
2245 PY_ITERSEARCH_INDEX: 0-based index of first occurence of obj in seq;
2246 set ValueError and return -1 if none found; also return -1 on error.
2247 Py_ITERSEARCH_CONTAINS: return 1 if obj in seq, else 0; -1 on error.
2250 _PySequence_IterSearch(PyObject
*seq
, PyObject
*obj
, int operation
)
2253 int wrapped
; /* for PY_ITERSEARCH_INDEX, true iff n wrapped around */
2254 PyObject
*it
; /* iter(seq) */
2256 if (seq
== NULL
|| obj
== NULL
) {
2261 it
= PyObject_GetIter(seq
);
2263 type_error("argument of type '%.200s' is not iterable", seq
);
2270 PyObject
*item
= PyIter_Next(it
);
2272 if (PyErr_Occurred())
2277 cmp
= PyObject_RichCompareBool(obj
, item
, Py_EQ
);
2282 switch (operation
) {
2283 case PY_ITERSEARCH_COUNT
:
2284 if (n
== PY_SSIZE_T_MAX
) {
2285 PyErr_SetString(PyExc_OverflowError
,
2286 "count exceeds C integer size");
2292 case PY_ITERSEARCH_INDEX
:
2294 PyErr_SetString(PyExc_OverflowError
,
2295 "index exceeds C integer size");
2300 case PY_ITERSEARCH_CONTAINS
:
2305 assert(!"unknown operation");
2309 if (operation
== PY_ITERSEARCH_INDEX
) {
2310 if (n
== PY_SSIZE_T_MAX
)
2316 if (operation
!= PY_ITERSEARCH_INDEX
)
2319 PyErr_SetString(PyExc_ValueError
,
2320 "sequence.index(x): x not in sequence");
2321 /* fall into failure code */
2331 /* Return # of times o appears in s. */
2333 PySequence_Count(PyObject
*s
, PyObject
*o
)
2335 return _PySequence_IterSearch(s
, o
, PY_ITERSEARCH_COUNT
);
2338 /* Return -1 if error; 1 if ob in seq; 0 if ob not in seq.
2339 * Use sq_contains if possible, else defer to _PySequence_IterSearch().
2342 PySequence_Contains(PyObject
*seq
, PyObject
*ob
)
2345 if (PyType_HasFeature(seq
->ob_type
, Py_TPFLAGS_HAVE_SEQUENCE_IN
)) {
2346 PySequenceMethods
*sqm
= seq
->ob_type
->tp_as_sequence
;
2347 if (sqm
!= NULL
&& sqm
->sq_contains
!= NULL
)
2348 return (*sqm
->sq_contains
)(seq
, ob
);
2350 result
= _PySequence_IterSearch(seq
, ob
, PY_ITERSEARCH_CONTAINS
);
2351 return Py_SAFE_DOWNCAST(result
, Py_ssize_t
, int);
2354 /* Backwards compatibility */
2355 #undef PySequence_In
2357 PySequence_In(PyObject
*w
, PyObject
*v
)
2359 return PySequence_Contains(w
, v
);
2363 PySequence_Index(PyObject
*s
, PyObject
*o
)
2365 return _PySequence_IterSearch(s
, o
, PY_ITERSEARCH_INDEX
);
2368 /* Operations on mappings */
2371 PyMapping_Check(PyObject
*o
)
2373 if (o
&& PyInstance_Check(o
))
2374 return PyObject_HasAttrString(o
, "__getitem__");
2376 return o
&& o
->ob_type
->tp_as_mapping
&&
2377 o
->ob_type
->tp_as_mapping
->mp_subscript
&&
2378 !(o
->ob_type
->tp_as_sequence
&&
2379 o
->ob_type
->tp_as_sequence
->sq_slice
);
2383 PyMapping_Size(PyObject
*o
)
2385 PyMappingMethods
*m
;
2392 m
= o
->ob_type
->tp_as_mapping
;
2393 if (m
&& m
->mp_length
)
2394 return m
->mp_length(o
);
2396 type_error("object of type '%.200s' has no len()", o
);
2400 #undef PyMapping_Length
2402 PyMapping_Length(PyObject
*o
)
2404 return PyMapping_Size(o
);
2406 #define PyMapping_Length PyMapping_Size
2409 PyMapping_GetItemString(PyObject
*o
, char *key
)
2414 return null_error();
2416 okey
= PyString_FromString(key
);
2419 r
= PyObject_GetItem(o
, okey
);
2425 PyMapping_SetItemString(PyObject
*o
, char *key
, PyObject
*value
)
2435 okey
= PyString_FromString(key
);
2438 r
= PyObject_SetItem(o
, okey
, value
);
2444 PyMapping_HasKeyString(PyObject
*o
, char *key
)
2448 v
= PyMapping_GetItemString(o
, key
);
2458 PyMapping_HasKey(PyObject
*o
, PyObject
*key
)
2462 v
= PyObject_GetItem(o
, key
);
2471 /* Operations on callable objects */
2473 /* XXX PyCallable_Check() is in object.c */
2476 PyObject_CallObject(PyObject
*o
, PyObject
*a
)
2478 return PyEval_CallObjectWithKeywords(o
, a
, NULL
);
2482 PyObject_Call(PyObject
*func
, PyObject
*arg
, PyObject
*kw
)
2486 if ((call
= func
->ob_type
->tp_call
) != NULL
) {
2488 if (Py_EnterRecursiveCall(" while calling a Python object"))
2490 result
= (*call
)(func
, arg
, kw
);
2491 Py_LeaveRecursiveCall();
2492 if (result
== NULL
&& !PyErr_Occurred())
2495 "NULL result without error in PyObject_Call");
2498 PyErr_Format(PyExc_TypeError
, "'%.200s' object is not callable",
2499 func
->ob_type
->tp_name
);
2504 call_function_tail(PyObject
*callable
, PyObject
*args
)
2511 if (!PyTuple_Check(args
)) {
2519 PyTuple_SET_ITEM(a
, 0, args
);
2522 retval
= PyObject_Call(callable
, args
, NULL
);
2530 PyObject_CallFunction(PyObject
*callable
, char *format
, ...)
2535 if (callable
== NULL
)
2536 return null_error();
2538 if (format
&& *format
) {
2539 va_start(va
, format
);
2540 args
= Py_VaBuildValue(format
, va
);
2544 args
= PyTuple_New(0);
2546 return call_function_tail(callable
, args
);
2550 _PyObject_CallFunction_SizeT(PyObject
*callable
, char *format
, ...)
2555 if (callable
== NULL
)
2556 return null_error();
2558 if (format
&& *format
) {
2559 va_start(va
, format
);
2560 args
= _Py_VaBuildValue_SizeT(format
, va
);
2564 args
= PyTuple_New(0);
2566 return call_function_tail(callable
, args
);
2570 PyObject_CallMethod(PyObject
*o
, char *name
, char *format
, ...)
2574 PyObject
*func
= NULL
;
2575 PyObject
*retval
= NULL
;
2577 if (o
== NULL
|| name
== NULL
)
2578 return null_error();
2580 func
= PyObject_GetAttrString(o
, name
);
2582 PyErr_SetString(PyExc_AttributeError
, name
);
2586 if (!PyCallable_Check(func
)) {
2587 type_error("attribute of type '%.200s' is not callable", func
);
2591 if (format
&& *format
) {
2592 va_start(va
, format
);
2593 args
= Py_VaBuildValue(format
, va
);
2597 args
= PyTuple_New(0);
2599 retval
= call_function_tail(func
, args
);
2602 /* args gets consumed in call_function_tail */
2609 _PyObject_CallMethod_SizeT(PyObject
*o
, char *name
, char *format
, ...)
2613 PyObject
*func
= NULL
;
2614 PyObject
*retval
= NULL
;
2616 if (o
== NULL
|| name
== NULL
)
2617 return null_error();
2619 func
= PyObject_GetAttrString(o
, name
);
2621 PyErr_SetString(PyExc_AttributeError
, name
);
2625 if (!PyCallable_Check(func
)) {
2626 type_error("attribute of type '%.200s' is not callable", func
);
2630 if (format
&& *format
) {
2631 va_start(va
, format
);
2632 args
= _Py_VaBuildValue_SizeT(format
, va
);
2636 args
= PyTuple_New(0);
2638 retval
= call_function_tail(func
, args
);
2641 /* args gets consumed in call_function_tail */
2649 objargs_mktuple(va_list va
)
2653 PyObject
*result
, *tmp
;
2655 #ifdef VA_LIST_IS_ARRAY
2656 memcpy(countva
, va
, sizeof(va_list));
2659 __va_copy(countva
, va
);
2665 while (((PyObject
*)va_arg(countva
, PyObject
*)) != NULL
)
2667 result
= PyTuple_New(n
);
2668 if (result
!= NULL
&& n
> 0) {
2669 for (i
= 0; i
< n
; ++i
) {
2670 tmp
= (PyObject
*)va_arg(va
, PyObject
*);
2671 PyTuple_SET_ITEM(result
, i
, tmp
);
2679 PyObject_CallMethodObjArgs(PyObject
*callable
, PyObject
*name
, ...)
2681 PyObject
*args
, *tmp
;
2684 if (callable
== NULL
|| name
== NULL
)
2685 return null_error();
2687 callable
= PyObject_GetAttr(callable
, name
);
2688 if (callable
== NULL
)
2691 /* count the args */
2692 va_start(vargs
, name
);
2693 args
= objargs_mktuple(vargs
);
2696 Py_DECREF(callable
);
2699 tmp
= PyObject_Call(callable
, args
, NULL
);
2701 Py_DECREF(callable
);
2707 PyObject_CallFunctionObjArgs(PyObject
*callable
, ...)
2709 PyObject
*args
, *tmp
;
2712 if (callable
== NULL
)
2713 return null_error();
2715 /* count the args */
2716 va_start(vargs
, callable
);
2717 args
= objargs_mktuple(vargs
);
2721 tmp
= PyObject_Call(callable
, args
, NULL
);
2728 /* isinstance(), issubclass() */
2730 /* abstract_get_bases() has logically 4 return states, with a sort of 0th
2731 * state that will almost never happen.
2733 * 0. creating the __bases__ static string could get a MemoryError
2734 * 1. getattr(cls, '__bases__') could raise an AttributeError
2735 * 2. getattr(cls, '__bases__') could raise some other exception
2736 * 3. getattr(cls, '__bases__') could return a tuple
2737 * 4. getattr(cls, '__bases__') could return something other than a tuple
2739 * Only state #3 is a non-error state and only it returns a non-NULL object
2740 * (it returns the retrieved tuple).
2742 * Any raised AttributeErrors are masked by clearing the exception and
2743 * returning NULL. If an object other than a tuple comes out of __bases__,
2744 * then again, the return value is NULL. So yes, these two situations
2745 * produce exactly the same results: NULL is returned and no error is set.
2747 * If some exception other than AttributeError is raised, then NULL is also
2748 * returned, but the exception is not cleared. That's because we want the
2749 * exception to be propagated along.
2751 * Callers are expected to test for PyErr_Occurred() when the return value
2752 * is NULL to decide whether a valid exception should be propagated or not.
2753 * When there's no exception to propagate, it's customary for the caller to
2757 abstract_get_bases(PyObject
*cls
)
2759 static PyObject
*__bases__
= NULL
;
2762 if (__bases__
== NULL
) {
2763 __bases__
= PyString_InternFromString("__bases__");
2764 if (__bases__
== NULL
)
2767 bases
= PyObject_GetAttr(cls
, __bases__
);
2768 if (bases
== NULL
) {
2769 if (PyErr_ExceptionMatches(PyExc_AttributeError
))
2773 if (!PyTuple_Check(bases
)) {
2782 abstract_issubclass(PyObject
*derived
, PyObject
*cls
)
2792 if (PyTuple_Check(cls
)) {
2793 /* Not a general sequence -- that opens up the road to
2794 recursion and stack overflow. */
2795 n
= PyTuple_GET_SIZE(cls
);
2796 for (i
= 0; i
< n
; i
++) {
2797 if (derived
== PyTuple_GET_ITEM(cls
, i
))
2801 bases
= abstract_get_bases(derived
);
2802 if (bases
== NULL
) {
2803 if (PyErr_Occurred())
2807 n
= PyTuple_GET_SIZE(bases
);
2808 for (i
= 0; i
< n
; i
++) {
2809 r
= abstract_issubclass(PyTuple_GET_ITEM(bases
, i
), cls
);
2820 check_class(PyObject
*cls
, const char *error
)
2822 PyObject
*bases
= abstract_get_bases(cls
);
2823 if (bases
== NULL
) {
2824 /* Do not mask errors. */
2825 if (!PyErr_Occurred())
2826 PyErr_SetString(PyExc_TypeError
, error
);
2834 recursive_isinstance(PyObject
*inst
, PyObject
*cls
, int recursion_depth
)
2837 static PyObject
*__class__
= NULL
;
2840 if (__class__
== NULL
) {
2841 __class__
= PyString_InternFromString("__class__");
2842 if (__class__
== NULL
)
2846 if (PyClass_Check(cls
) && PyInstance_Check(inst
)) {
2848 (PyObject
*)((PyInstanceObject
*)inst
)->in_class
;
2849 retval
= PyClass_IsSubclass(inclass
, cls
);
2851 else if (PyType_Check(cls
)) {
2852 retval
= PyObject_TypeCheck(inst
, (PyTypeObject
*)cls
);
2854 PyObject
*c
= PyObject_GetAttr(inst
, __class__
);
2859 if (c
!= (PyObject
*)(inst
->ob_type
) &&
2861 retval
= PyType_IsSubtype(
2863 (PyTypeObject
*)cls
);
2868 else if (PyTuple_Check(cls
)) {
2871 if (!recursion_depth
) {
2872 PyErr_SetString(PyExc_RuntimeError
,
2873 "nest level of tuple too deep");
2877 n
= PyTuple_GET_SIZE(cls
);
2878 for (i
= 0; i
< n
; i
++) {
2879 retval
= recursive_isinstance(
2881 PyTuple_GET_ITEM(cls
, i
),
2888 if (!check_class(cls
,
2889 "isinstance() arg 2 must be a class, type,"
2890 " or tuple of classes and types"))
2892 icls
= PyObject_GetAttr(inst
, __class__
);
2898 retval
= abstract_issubclass(icls
, cls
);
2907 PyObject_IsInstance(PyObject
*inst
, PyObject
*cls
)
2909 static PyObject
*name
= NULL
;
2912 /* Quick test for an exact match */
2913 if (Py_TYPE(inst
) == (PyTypeObject
*)cls
)
2917 name
= PyString_InternFromString("__instancecheck__");
2921 checker
= PyObject_GetAttr(cls
, name
);
2922 if (checker
== NULL
&& PyErr_Occurred())
2924 if (checker
!= NULL
) {
2927 if (Py_EnterRecursiveCall(" in __instancecheck__")) {
2931 res
= PyObject_CallFunctionObjArgs(checker
, inst
, NULL
);
2932 Py_LeaveRecursiveCall();
2935 ok
= PyObject_IsTrue(res
);
2940 return recursive_isinstance(inst
, cls
, Py_GetRecursionLimit());
2944 recursive_issubclass(PyObject
*derived
, PyObject
*cls
, int recursion_depth
)
2948 if (!PyClass_Check(derived
) || !PyClass_Check(cls
)) {
2949 if (!check_class(derived
,
2950 "issubclass() arg 1 must be a class"))
2953 if (PyTuple_Check(cls
)) {
2955 Py_ssize_t n
= PyTuple_GET_SIZE(cls
);
2957 if (!recursion_depth
) {
2958 PyErr_SetString(PyExc_RuntimeError
,
2959 "nest level of tuple too deep");
2962 for (i
= 0; i
< n
; ++i
) {
2963 retval
= recursive_issubclass(
2965 PyTuple_GET_ITEM(cls
, i
),
2968 /* either found it, or got an error */
2975 if (!check_class(cls
,
2976 "issubclass() arg 2 must be a class"
2977 " or tuple of classes"))
2981 retval
= abstract_issubclass(derived
, cls
);
2985 if (!(retval
= (derived
== cls
)))
2986 retval
= PyClass_IsSubclass(derived
, cls
);
2993 PyObject_IsSubclass(PyObject
*derived
, PyObject
*cls
)
2995 static PyObject
*name
= NULL
;
2996 PyObject
*t
, *v
, *tb
;
2998 PyErr_Fetch(&t
, &v
, &tb
);
3001 name
= PyString_InternFromString("__subclasscheck__");
3005 checker
= PyObject_GetAttr(cls
, name
);
3006 PyErr_Restore(t
, v
, tb
);
3007 if (checker
!= NULL
) {
3010 if (Py_EnterRecursiveCall(" in __subclasscheck__"))
3012 res
= PyObject_CallFunctionObjArgs(checker
, derived
, NULL
);
3013 Py_LeaveRecursiveCall();
3016 ok
= PyObject_IsTrue(res
);
3021 return recursive_issubclass(derived
, cls
, Py_GetRecursionLimit());
3026 PyObject_GetIter(PyObject
*o
)
3028 PyTypeObject
*t
= o
->ob_type
;
3029 getiterfunc f
= NULL
;
3030 if (PyType_HasFeature(t
, Py_TPFLAGS_HAVE_ITER
))
3033 if (PySequence_Check(o
))
3034 return PySeqIter_New(o
);
3035 return type_error("'%.200s' object is not iterable", o
);
3038 PyObject
*res
= (*f
)(o
);
3039 if (res
!= NULL
&& !PyIter_Check(res
)) {
3040 PyErr_Format(PyExc_TypeError
,
3041 "iter() returned non-iterator "
3043 res
->ob_type
->tp_name
);
3051 /* Return next item.
3052 * If an error occurs, return NULL. PyErr_Occurred() will be true.
3053 * If the iteration terminates normally, return NULL and clear the
3054 * PyExc_StopIteration exception (if it was set). PyErr_Occurred()
3056 * Else return the next object. PyErr_Occurred() will be false.
3059 PyIter_Next(PyObject
*iter
)
3062 assert(PyIter_Check(iter
));
3063 result
= (*iter
->ob_type
->tp_iternext
)(iter
);
3064 if (result
== NULL
&&
3066 PyErr_ExceptionMatches(PyExc_StopIteration
))