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_WRITABLE
) == PyBUF_WRITABLE
) &&
690 PyErr_SetString(PyExc_BufferError
,
691 "Object is not writable.");
697 view
->readonly
= readonly
;
700 if ((flags
& PyBUF_FORMAT
) == PyBUF_FORMAT
)
704 if ((flags
& PyBUF_ND
) == PyBUF_ND
)
705 view
->shape
= &(view
->len
);
706 view
->strides
= NULL
;
707 if ((flags
& PyBUF_STRIDES
) == PyBUF_STRIDES
)
708 view
->strides
= &(view
->itemsize
);
709 view
->suboffsets
= NULL
;
710 view
->internal
= NULL
;
715 PyObject_Format(PyObject
* obj
, PyObject
*format_spec
)
717 static PyObject
* str__format__
= NULL
;
718 PyObject
*empty
= NULL
;
719 PyObject
*result
= NULL
;
721 int result_is_unicode
;
723 /* Initialize cached value */
724 if (str__format__
== NULL
) {
725 /* Initialize static variable needed by _PyType_Lookup */
726 str__format__
= PyString_InternFromString("__format__");
727 if (str__format__
== NULL
)
731 /* If no format_spec is provided, use an empty string */
732 if (format_spec
== NULL
) {
733 empty
= PyString_FromStringAndSize(NULL
, 0);
737 /* Check the format_spec type, and make sure it's str or unicode */
738 if (PyUnicode_Check(format_spec
))
740 else if (PyString_Check(format_spec
))
743 PyErr_Format(PyExc_TypeError
,
744 "format expects arg 2 to be string "
745 "or unicode, not %.100s", Py_TYPE(format_spec
)->tp_name
);
749 /* Make sure the type is initialized. float gets initialized late */
750 if (Py_TYPE(obj
)->tp_dict
== NULL
)
751 if (PyType_Ready(Py_TYPE(obj
)) < 0)
754 /* Check for a __format__ method and call it. */
755 if (PyInstance_Check(obj
)) {
756 /* We're an instance of a classic class */
757 PyObject
*bound_method
= PyObject_GetAttr(obj
,
759 if (bound_method
!= NULL
) {
760 result
= PyObject_CallFunctionObjArgs(bound_method
,
763 Py_DECREF(bound_method
);
765 PyObject
*self_as_str
;
766 PyObject
*format_method
;
769 /* Per the PEP, convert to str (or unicode,
770 depending on the type of the format
771 specifier). For new-style classes, this
772 logic is done by object.__format__(). */
774 self_as_str
= PyObject_Unicode(obj
);
776 self_as_str
= PyObject_Str(obj
);
777 if (self_as_str
== NULL
)
780 /* Then call str.__format__ on that result */
781 format_method
= PyObject_GetAttr(self_as_str
,
783 if (format_method
== NULL
) {
784 Py_DECREF(self_as_str
);
787 result
= PyObject_CallFunctionObjArgs(format_method
,
790 Py_DECREF(self_as_str
);
791 Py_DECREF(format_method
);
796 /* Not an instance of a classic class, use the code
799 /* Find the (unbound!) __format__ method (a borrowed
801 PyObject
*method
= _PyType_Lookup(Py_TYPE(obj
),
803 if (method
== NULL
) {
804 PyErr_Format(PyExc_TypeError
,
805 "Type %.100s doesn't define __format__",
806 Py_TYPE(obj
)->tp_name
);
809 /* And call it, binding it to the value */
810 result
= PyObject_CallFunctionObjArgs(method
, obj
,
817 /* Check the result type, and make sure it's str or unicode */
818 if (PyUnicode_Check(result
))
819 result_is_unicode
= 1;
820 else if (PyString_Check(result
))
821 result_is_unicode
= 0;
823 PyErr_Format(PyExc_TypeError
,
824 "%.100s.__format__ must return string or "
825 "unicode, not %.100s", Py_TYPE(obj
)->tp_name
,
826 Py_TYPE(result
)->tp_name
);
832 /* Convert to unicode, if needed. Required if spec is unicode
834 if (spec_is_unicode
&& !result_is_unicode
) {
835 PyObject
*tmp
= PyObject_Unicode(result
);
836 /* This logic works whether or not tmp is NULL */
846 /* Operations on numbers */
849 PyNumber_Check(PyObject
*o
)
851 return o
&& o
->ob_type
->tp_as_number
&&
852 (o
->ob_type
->tp_as_number
->nb_int
||
853 o
->ob_type
->tp_as_number
->nb_float
);
856 /* Binary operators */
858 /* New style number protocol support */
860 #define NB_SLOT(x) offsetof(PyNumberMethods, x)
861 #define NB_BINOP(nb_methods, slot) \
862 (*(binaryfunc*)(& ((char*)nb_methods)[slot]))
863 #define NB_TERNOP(nb_methods, slot) \
864 (*(ternaryfunc*)(& ((char*)nb_methods)[slot]))
867 Calling scheme used for binary operations:
870 -------------------------------------------------------------------
871 new new w.op(v,w)[*], v.op(v,w), w.op(v,w)
872 new old v.op(v,w), coerce(v,w), v.op(v,w)
873 old new w.op(v,w), coerce(v,w), v.op(v,w)
874 old old coerce(v,w), v.op(v,w)
876 [*] only when v->ob_type != w->ob_type && w->ob_type is a subclass of
881 * new == new style number
882 * old == old style number
883 * Action indicates the order in which operations are tried until either
884 a valid result is produced or an error occurs.
889 binary_op1(PyObject
*v
, PyObject
*w
, const int op_slot
)
892 binaryfunc slotv
= NULL
;
893 binaryfunc slotw
= NULL
;
895 if (v
->ob_type
->tp_as_number
!= NULL
&& NEW_STYLE_NUMBER(v
))
896 slotv
= NB_BINOP(v
->ob_type
->tp_as_number
, op_slot
);
897 if (w
->ob_type
!= v
->ob_type
&&
898 w
->ob_type
->tp_as_number
!= NULL
&& NEW_STYLE_NUMBER(w
)) {
899 slotw
= NB_BINOP(w
->ob_type
->tp_as_number
, op_slot
);
904 if (slotw
&& PyType_IsSubtype(w
->ob_type
, v
->ob_type
)) {
906 if (x
!= Py_NotImplemented
)
908 Py_DECREF(x
); /* can't do it */
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 */
922 if (!NEW_STYLE_NUMBER(v
) || !NEW_STYLE_NUMBER(w
)) {
923 int err
= PyNumber_CoerceEx(&v
, &w
);
928 PyNumberMethods
*mv
= v
->ob_type
->tp_as_number
;
931 slot
= NB_BINOP(mv
, op_slot
);
939 /* CoerceEx incremented the reference counts */
944 Py_INCREF(Py_NotImplemented
);
945 return Py_NotImplemented
;
949 binop_type_error(PyObject
*v
, PyObject
*w
, const char *op_name
)
951 PyErr_Format(PyExc_TypeError
,
952 "unsupported operand type(s) for %.100s: "
953 "'%.100s' and '%.100s'",
956 w
->ob_type
->tp_name
);
961 binary_op(PyObject
*v
, PyObject
*w
, const int op_slot
, const char *op_name
)
963 PyObject
*result
= binary_op1(v
, w
, op_slot
);
964 if (result
== Py_NotImplemented
) {
966 return binop_type_error(v
, w
, op_name
);
973 Calling scheme used for ternary operations:
975 *** In some cases, w.op is called before v.op; see binary_op1. ***
978 -------------------------------------------------------------------
979 new new new v.op(v,w,z), w.op(v,w,z), z.op(v,w,z)
980 new old new v.op(v,w,z), z.op(v,w,z), coerce(v,w,z), v.op(v,w,z)
981 old new new w.op(v,w,z), z.op(v,w,z), coerce(v,w,z), v.op(v,w,z)
982 old old new z.op(v,w,z), coerce(v,w,z), v.op(v,w,z)
983 new new old v.op(v,w,z), w.op(v,w,z), coerce(v,w,z), v.op(v,w,z)
984 new old old v.op(v,w,z), coerce(v,w,z), v.op(v,w,z)
985 old new old w.op(v,w,z), coerce(v,w,z), v.op(v,w,z)
986 old old old coerce(v,w,z), v.op(v,w,z)
990 * new == new style number
991 * old == old style number
992 * Action indicates the order in which operations are tried until either
993 a valid result is produced or an error occurs.
994 * coerce(v,w,z) actually does: coerce(v,w), coerce(v,z), coerce(w,z) and
995 only if z != Py_None; if z == Py_None, then it is treated as absent
996 variable and only coerce(v,w) is tried.
1001 ternary_op(PyObject
*v
,
1005 const char *op_name
)
1007 PyNumberMethods
*mv
, *mw
, *mz
;
1009 ternaryfunc slotv
= NULL
;
1010 ternaryfunc slotw
= NULL
;
1011 ternaryfunc slotz
= NULL
;
1013 mv
= v
->ob_type
->tp_as_number
;
1014 mw
= w
->ob_type
->tp_as_number
;
1015 if (mv
!= NULL
&& NEW_STYLE_NUMBER(v
))
1016 slotv
= NB_TERNOP(mv
, op_slot
);
1017 if (w
->ob_type
!= v
->ob_type
&&
1018 mw
!= NULL
&& NEW_STYLE_NUMBER(w
)) {
1019 slotw
= NB_TERNOP(mw
, op_slot
);
1024 if (slotw
&& PyType_IsSubtype(w
->ob_type
, v
->ob_type
)) {
1026 if (x
!= Py_NotImplemented
)
1028 Py_DECREF(x
); /* can't do it */
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 */
1042 mz
= z
->ob_type
->tp_as_number
;
1043 if (mz
!= NULL
&& NEW_STYLE_NUMBER(z
)) {
1044 slotz
= NB_TERNOP(mz
, op_slot
);
1045 if (slotz
== slotv
|| slotz
== slotw
)
1049 if (x
!= Py_NotImplemented
)
1051 Py_DECREF(x
); /* can't do it */
1055 if (!NEW_STYLE_NUMBER(v
) || !NEW_STYLE_NUMBER(w
) ||
1056 (z
!= Py_None
&& !NEW_STYLE_NUMBER(z
))) {
1057 /* we have an old style operand, coerce */
1058 PyObject
*v1
, *z1
, *w2
, *z2
;
1061 c
= PyNumber_Coerce(&v
, &w
);
1065 /* Special case: if the third argument is None, it is
1066 treated as absent argument and not coerced. */
1068 if (v
->ob_type
->tp_as_number
) {
1069 slotz
= NB_TERNOP(v
->ob_type
->tp_as_number
,
1082 c
= PyNumber_Coerce(&v1
, &z1
);
1087 c
= PyNumber_Coerce(&w2
, &z2
);
1091 if (v1
->ob_type
->tp_as_number
!= NULL
) {
1092 slotv
= NB_TERNOP(v1
->ob_type
->tp_as_number
,
1095 x
= slotv(v1
, w2
, z2
);
1118 "unsupported operand type(s) for ** or pow(): "
1119 "'%.100s' and '%.100s'",
1120 v
->ob_type
->tp_name
,
1121 w
->ob_type
->tp_name
);
1125 "unsupported operand type(s) for pow(): "
1126 "'%.100s', '%.100s', '%.100s'",
1127 v
->ob_type
->tp_name
,
1128 w
->ob_type
->tp_name
,
1129 z
->ob_type
->tp_name
);
1133 #define BINARY_FUNC(func, op, op_name) \
1135 func(PyObject *v, PyObject *w) { \
1136 return binary_op(v, w, NB_SLOT(op), op_name); \
1139 BINARY_FUNC(PyNumber_Or
, nb_or
, "|")
1140 BINARY_FUNC(PyNumber_Xor
, nb_xor
, "^")
1141 BINARY_FUNC(PyNumber_And
, nb_and
, "&")
1142 BINARY_FUNC(PyNumber_Lshift
, nb_lshift
, "<<")
1143 BINARY_FUNC(PyNumber_Rshift
, nb_rshift
, ">>")
1144 BINARY_FUNC(PyNumber_Subtract
, nb_subtract
, "-")
1145 BINARY_FUNC(PyNumber_Divide
, nb_divide
, "/")
1146 BINARY_FUNC(PyNumber_Divmod
, nb_divmod
, "divmod()")
1149 PyNumber_Add(PyObject
*v
, PyObject
*w
)
1151 PyObject
*result
= binary_op1(v
, w
, NB_SLOT(nb_add
));
1152 if (result
== Py_NotImplemented
) {
1153 PySequenceMethods
*m
= v
->ob_type
->tp_as_sequence
;
1155 if (m
&& m
->sq_concat
) {
1156 return (*m
->sq_concat
)(v
, w
);
1158 result
= binop_type_error(v
, w
, "+");
1164 sequence_repeat(ssizeargfunc repeatfunc
, PyObject
*seq
, PyObject
*n
)
1167 if (PyIndex_Check(n
)) {
1168 count
= PyNumber_AsSsize_t(n
, PyExc_OverflowError
);
1169 if (count
== -1 && PyErr_Occurred())
1173 return type_error("can't multiply sequence by "
1174 "non-int of type '%.200s'", n
);
1176 return (*repeatfunc
)(seq
, count
);
1180 PyNumber_Multiply(PyObject
*v
, PyObject
*w
)
1182 PyObject
*result
= binary_op1(v
, w
, NB_SLOT(nb_multiply
));
1183 if (result
== Py_NotImplemented
) {
1184 PySequenceMethods
*mv
= v
->ob_type
->tp_as_sequence
;
1185 PySequenceMethods
*mw
= w
->ob_type
->tp_as_sequence
;
1187 if (mv
&& mv
->sq_repeat
) {
1188 return sequence_repeat(mv
->sq_repeat
, v
, w
);
1190 else if (mw
&& mw
->sq_repeat
) {
1191 return sequence_repeat(mw
->sq_repeat
, w
, v
);
1193 result
= binop_type_error(v
, w
, "*");
1199 PyNumber_FloorDivide(PyObject
*v
, PyObject
*w
)
1201 /* XXX tp_flags test */
1202 return binary_op(v
, w
, NB_SLOT(nb_floor_divide
), "//");
1206 PyNumber_TrueDivide(PyObject
*v
, PyObject
*w
)
1208 /* XXX tp_flags test */
1209 return binary_op(v
, w
, NB_SLOT(nb_true_divide
), "/");
1213 PyNumber_Remainder(PyObject
*v
, PyObject
*w
)
1215 return binary_op(v
, w
, NB_SLOT(nb_remainder
), "%");
1219 PyNumber_Power(PyObject
*v
, PyObject
*w
, PyObject
*z
)
1221 return ternary_op(v
, w
, z
, NB_SLOT(nb_power
), "** or pow()");
1224 /* Binary in-place operators */
1226 /* The in-place operators are defined to fall back to the 'normal',
1227 non in-place operations, if the in-place methods are not in place.
1229 - If the left hand object has the appropriate struct members, and
1230 they are filled, call the appropriate function and return the
1231 result. No coercion is done on the arguments; the left-hand object
1232 is the one the operation is performed on, and it's up to the
1233 function to deal with the right-hand object.
1235 - Otherwise, in-place modification is not supported. Handle it exactly as
1236 a non in-place operation of the same kind.
1240 #define HASINPLACE(t) \
1241 PyType_HasFeature((t)->ob_type, Py_TPFLAGS_HAVE_INPLACEOPS)
1244 binary_iop1(PyObject
*v
, PyObject
*w
, const int iop_slot
, const int op_slot
)
1246 PyNumberMethods
*mv
= v
->ob_type
->tp_as_number
;
1247 if (mv
!= NULL
&& HASINPLACE(v
)) {
1248 binaryfunc slot
= NB_BINOP(mv
, iop_slot
);
1250 PyObject
*x
= (slot
)(v
, w
);
1251 if (x
!= Py_NotImplemented
) {
1257 return binary_op1(v
, w
, op_slot
);
1261 binary_iop(PyObject
*v
, PyObject
*w
, const int iop_slot
, const int op_slot
,
1262 const char *op_name
)
1264 PyObject
*result
= binary_iop1(v
, w
, iop_slot
, op_slot
);
1265 if (result
== Py_NotImplemented
) {
1267 return binop_type_error(v
, w
, op_name
);
1272 #define INPLACE_BINOP(func, iop, op, op_name) \
1274 func(PyObject *v, PyObject *w) { \
1275 return binary_iop(v, w, NB_SLOT(iop), NB_SLOT(op), op_name); \
1278 INPLACE_BINOP(PyNumber_InPlaceOr
, nb_inplace_or
, nb_or
, "|=")
1279 INPLACE_BINOP(PyNumber_InPlaceXor
, nb_inplace_xor
, nb_xor
, "^=")
1280 INPLACE_BINOP(PyNumber_InPlaceAnd
, nb_inplace_and
, nb_and
, "&=")
1281 INPLACE_BINOP(PyNumber_InPlaceLshift
, nb_inplace_lshift
, nb_lshift
, "<<=")
1282 INPLACE_BINOP(PyNumber_InPlaceRshift
, nb_inplace_rshift
, nb_rshift
, ">>=")
1283 INPLACE_BINOP(PyNumber_InPlaceSubtract
, nb_inplace_subtract
, nb_subtract
, "-=")
1284 INPLACE_BINOP(PyNumber_InPlaceDivide
, nb_inplace_divide
, nb_divide
, "/=")
1287 PyNumber_InPlaceFloorDivide(PyObject
*v
, PyObject
*w
)
1289 /* XXX tp_flags test */
1290 return binary_iop(v
, w
, NB_SLOT(nb_inplace_floor_divide
),
1291 NB_SLOT(nb_floor_divide
), "//=");
1295 PyNumber_InPlaceTrueDivide(PyObject
*v
, PyObject
*w
)
1297 /* XXX tp_flags test */
1298 return binary_iop(v
, w
, NB_SLOT(nb_inplace_true_divide
),
1299 NB_SLOT(nb_true_divide
), "/=");
1303 PyNumber_InPlaceAdd(PyObject
*v
, PyObject
*w
)
1305 PyObject
*result
= binary_iop1(v
, w
, NB_SLOT(nb_inplace_add
),
1307 if (result
== Py_NotImplemented
) {
1308 PySequenceMethods
*m
= v
->ob_type
->tp_as_sequence
;
1311 binaryfunc f
= NULL
;
1313 f
= m
->sq_inplace_concat
;
1319 result
= binop_type_error(v
, w
, "+=");
1325 PyNumber_InPlaceMultiply(PyObject
*v
, PyObject
*w
)
1327 PyObject
*result
= binary_iop1(v
, w
, NB_SLOT(nb_inplace_multiply
),
1328 NB_SLOT(nb_multiply
));
1329 if (result
== Py_NotImplemented
) {
1330 ssizeargfunc f
= NULL
;
1331 PySequenceMethods
*mv
= v
->ob_type
->tp_as_sequence
;
1332 PySequenceMethods
*mw
= w
->ob_type
->tp_as_sequence
;
1336 f
= mv
->sq_inplace_repeat
;
1340 return sequence_repeat(f
, v
, w
);
1342 else if (mw
!= NULL
) {
1343 /* Note that the right hand operand should not be
1344 * mutated in this case so sq_inplace_repeat is not
1347 return sequence_repeat(mw
->sq_repeat
, w
, v
);
1349 result
= binop_type_error(v
, w
, "*=");
1355 PyNumber_InPlaceRemainder(PyObject
*v
, PyObject
*w
)
1357 return binary_iop(v
, w
, NB_SLOT(nb_inplace_remainder
),
1358 NB_SLOT(nb_remainder
), "%=");
1362 PyNumber_InPlacePower(PyObject
*v
, PyObject
*w
, PyObject
*z
)
1364 if (HASINPLACE(v
) && v
->ob_type
->tp_as_number
&&
1365 v
->ob_type
->tp_as_number
->nb_inplace_power
!= NULL
) {
1366 return ternary_op(v
, w
, z
, NB_SLOT(nb_inplace_power
), "**=");
1369 return ternary_op(v
, w
, z
, NB_SLOT(nb_power
), "**=");
1374 /* Unary operators and functions */
1377 PyNumber_Negative(PyObject
*o
)
1382 return null_error();
1383 m
= o
->ob_type
->tp_as_number
;
1384 if (m
&& m
->nb_negative
)
1385 return (*m
->nb_negative
)(o
);
1387 return type_error("bad operand type for unary -: '%.200s'", o
);
1391 PyNumber_Positive(PyObject
*o
)
1396 return null_error();
1397 m
= o
->ob_type
->tp_as_number
;
1398 if (m
&& m
->nb_positive
)
1399 return (*m
->nb_positive
)(o
);
1401 return type_error("bad operand type for unary +: '%.200s'", o
);
1405 PyNumber_Invert(PyObject
*o
)
1410 return null_error();
1411 m
= o
->ob_type
->tp_as_number
;
1412 if (m
&& m
->nb_invert
)
1413 return (*m
->nb_invert
)(o
);
1415 return type_error("bad operand type for unary ~: '%.200s'", o
);
1419 PyNumber_Absolute(PyObject
*o
)
1424 return null_error();
1425 m
= o
->ob_type
->tp_as_number
;
1426 if (m
&& m
->nb_absolute
)
1427 return m
->nb_absolute(o
);
1429 return type_error("bad operand type for abs(): '%.200s'", o
);
1432 /* Add a check for embedded NULL-bytes in the argument. */
1434 int_from_string(const char *s
, Py_ssize_t len
)
1439 x
= PyInt_FromString((char*)s
, &end
, 10);
1442 if (end
!= s
+ len
) {
1443 PyErr_SetString(PyExc_ValueError
,
1444 "null byte in argument for int()");
1451 /* Return a Python Int or Long from the object item
1452 Raise TypeError if the result is not an int-or-long
1453 or if the object cannot be interpreted as an index.
1456 PyNumber_Index(PyObject
*item
)
1458 PyObject
*result
= NULL
;
1460 return null_error();
1461 if (PyInt_Check(item
) || PyLong_Check(item
)) {
1465 if (PyIndex_Check(item
)) {
1466 result
= item
->ob_type
->tp_as_number
->nb_index(item
);
1468 !PyInt_Check(result
) && !PyLong_Check(result
)) {
1469 PyErr_Format(PyExc_TypeError
,
1470 "__index__ returned non-(int,long) " \
1472 result
->ob_type
->tp_name
);
1478 PyErr_Format(PyExc_TypeError
,
1479 "'%.200s' object cannot be interpreted "
1480 "as an index", item
->ob_type
->tp_name
);
1485 /* Return an error on Overflow only if err is not NULL*/
1488 PyNumber_AsSsize_t(PyObject
*item
, PyObject
*err
)
1492 PyObject
*value
= PyNumber_Index(item
);
1496 /* We're done if PyInt_AsSsize_t() returns without error. */
1497 result
= PyInt_AsSsize_t(value
);
1498 if (result
!= -1 || !(runerr
= PyErr_Occurred()))
1501 /* Error handling code -- only manage OverflowError differently */
1502 if (!PyErr_GivenExceptionMatches(runerr
, PyExc_OverflowError
))
1506 /* If no error-handling desired then the default clipping
1510 assert(PyLong_Check(value
));
1511 /* Whether or not it is less than or equal to
1512 zero is determined by the sign of ob_size
1514 if (_PyLong_Sign(value
) < 0)
1515 result
= PY_SSIZE_T_MIN
;
1517 result
= PY_SSIZE_T_MAX
;
1520 /* Otherwise replace the error with caller's error object. */
1522 "cannot fit '%.200s' into an index-sized integer",
1523 item
->ob_type
->tp_name
);
1533 _PyNumber_ConvertIntegralToInt(PyObject
*integral
, const char* error_format
)
1535 const char *type_name
;
1536 static PyObject
*int_name
= NULL
;
1537 if (int_name
== NULL
) {
1538 int_name
= PyString_InternFromString("__int__");
1539 if (int_name
== NULL
)
1543 if (integral
&& (!PyInt_Check(integral
) &&
1544 !PyLong_Check(integral
))) {
1545 /* Don't go through tp_as_number->nb_int to avoid
1546 hitting the classic class fallback to __trunc__. */
1547 PyObject
*int_func
= PyObject_GetAttr(integral
, int_name
);
1548 if (int_func
== NULL
) {
1549 PyErr_Clear(); /* Raise a different error. */
1550 goto non_integral_error
;
1552 Py_DECREF(integral
);
1553 integral
= PyEval_CallObject(int_func
, NULL
);
1554 Py_DECREF(int_func
);
1555 if (integral
&& (!PyInt_Check(integral
) &&
1556 !PyLong_Check(integral
))) {
1557 goto non_integral_error
;
1563 if (PyInstance_Check(integral
)) {
1564 type_name
= PyString_AS_STRING(((PyInstanceObject
*)integral
)
1565 ->in_class
->cl_name
);
1568 type_name
= integral
->ob_type
->tp_name
;
1570 PyErr_Format(PyExc_TypeError
, error_format
, type_name
);
1571 Py_DECREF(integral
);
1577 PyNumber_Int(PyObject
*o
)
1580 static PyObject
*trunc_name
= NULL
;
1581 PyObject
*trunc_func
;
1583 Py_ssize_t buffer_len
;
1585 if (trunc_name
== NULL
) {
1586 trunc_name
= PyString_InternFromString("__trunc__");
1587 if (trunc_name
== NULL
)
1592 return null_error();
1593 if (PyInt_CheckExact(o
)) {
1597 m
= o
->ob_type
->tp_as_number
;
1598 if (m
&& m
->nb_int
) { /* This should include subclasses of int */
1599 /* Classic classes always take this branch. */
1600 PyObject
*res
= m
->nb_int(o
);
1601 if (res
&& (!PyInt_Check(res
) && !PyLong_Check(res
))) {
1602 PyErr_Format(PyExc_TypeError
,
1603 "__int__ returned non-int (type %.200s)",
1604 res
->ob_type
->tp_name
);
1610 if (PyInt_Check(o
)) { /* A int subclass without nb_int */
1611 PyIntObject
*io
= (PyIntObject
*)o
;
1612 return PyInt_FromLong(io
->ob_ival
);
1614 trunc_func
= PyObject_GetAttr(o
, trunc_name
);
1616 PyObject
*truncated
= PyEval_CallObject(trunc_func
, NULL
);
1617 Py_DECREF(trunc_func
);
1618 /* __trunc__ is specified to return an Integral type, but
1619 int() needs to return an int. */
1620 return _PyNumber_ConvertIntegralToInt(
1622 "__trunc__ returned non-Integral (type %.200s)");
1624 PyErr_Clear(); /* It's not an error if o.__trunc__ doesn't exist. */
1626 if (PyString_Check(o
))
1627 return int_from_string(PyString_AS_STRING(o
),
1628 PyString_GET_SIZE(o
));
1629 #ifdef Py_USING_UNICODE
1630 if (PyUnicode_Check(o
))
1631 return PyInt_FromUnicode(PyUnicode_AS_UNICODE(o
),
1632 PyUnicode_GET_SIZE(o
),
1635 if (!PyObject_AsCharBuffer(o
, &buffer
, &buffer_len
))
1636 return int_from_string((char*)buffer
, buffer_len
);
1638 return type_error("int() argument must be a string or a "
1639 "number, not '%.200s'", o
);
1642 /* Add a check for embedded NULL-bytes in the argument. */
1644 long_from_string(const char *s
, Py_ssize_t len
)
1649 x
= PyLong_FromString((char*)s
, &end
, 10);
1652 if (end
!= s
+ len
) {
1653 PyErr_SetString(PyExc_ValueError
,
1654 "null byte in argument for long()");
1662 PyNumber_Long(PyObject
*o
)
1665 static PyObject
*trunc_name
= NULL
;
1666 PyObject
*trunc_func
;
1668 Py_ssize_t buffer_len
;
1670 if (trunc_name
== NULL
) {
1671 trunc_name
= PyString_InternFromString("__trunc__");
1672 if (trunc_name
== NULL
)
1677 return null_error();
1678 m
= o
->ob_type
->tp_as_number
;
1679 if (m
&& m
->nb_long
) { /* This should include subclasses of long */
1680 /* Classic classes always take this branch. */
1681 PyObject
*res
= m
->nb_long(o
);
1682 if (res
&& (!PyInt_Check(res
) && !PyLong_Check(res
))) {
1683 PyErr_Format(PyExc_TypeError
,
1684 "__long__ returned non-long (type %.200s)",
1685 res
->ob_type
->tp_name
);
1691 if (PyLong_Check(o
)) /* A long subclass without nb_long */
1692 return _PyLong_Copy((PyLongObject
*)o
);
1693 trunc_func
= PyObject_GetAttr(o
, trunc_name
);
1695 PyObject
*truncated
= PyEval_CallObject(trunc_func
, NULL
);
1696 PyObject
*int_instance
;
1697 Py_DECREF(trunc_func
);
1698 /* __trunc__ is specified to return an Integral type,
1699 but long() needs to return a long. */
1700 int_instance
= _PyNumber_ConvertIntegralToInt(
1702 "__trunc__ returned non-Integral (type %.200s)");
1703 if (int_instance
&& PyInt_Check(int_instance
)) {
1704 /* Make sure that long() returns a long instance. */
1705 long value
= PyInt_AS_LONG(int_instance
);
1706 Py_DECREF(int_instance
);
1707 return PyLong_FromLong(value
);
1709 return int_instance
;
1711 PyErr_Clear(); /* It's not an error if o.__trunc__ doesn't exist. */
1713 if (PyString_Check(o
))
1714 /* need to do extra error checking that PyLong_FromString()
1715 * doesn't do. In particular long('9.5') must raise an
1716 * exception, not truncate the float.
1718 return long_from_string(PyString_AS_STRING(o
),
1719 PyString_GET_SIZE(o
));
1720 #ifdef Py_USING_UNICODE
1721 if (PyUnicode_Check(o
))
1722 /* The above check is done in PyLong_FromUnicode(). */
1723 return PyLong_FromUnicode(PyUnicode_AS_UNICODE(o
),
1724 PyUnicode_GET_SIZE(o
),
1727 if (!PyObject_AsCharBuffer(o
, &buffer
, &buffer_len
))
1728 return long_from_string(buffer
, buffer_len
);
1730 return type_error("long() argument must be a string or a "
1731 "number, not '%.200s'", o
);
1735 PyNumber_Float(PyObject
*o
)
1740 return null_error();
1741 m
= o
->ob_type
->tp_as_number
;
1742 if (m
&& m
->nb_float
) { /* This should include subclasses of float */
1743 PyObject
*res
= m
->nb_float(o
);
1744 if (res
&& !PyFloat_Check(res
)) {
1745 PyErr_Format(PyExc_TypeError
,
1746 "__float__ returned non-float (type %.200s)",
1747 res
->ob_type
->tp_name
);
1753 if (PyFloat_Check(o
)) { /* A float subclass with nb_float == NULL */
1754 PyFloatObject
*po
= (PyFloatObject
*)o
;
1755 return PyFloat_FromDouble(po
->ob_fval
);
1757 return PyFloat_FromString(o
, NULL
);
1761 PyNumber_ToBase(PyObject
*n
, int base
)
1763 PyObject
*res
= NULL
;
1764 PyObject
*index
= PyNumber_Index(n
);
1768 if (PyLong_Check(index
))
1769 res
= _PyLong_Format(index
, base
, 0, 1);
1770 else if (PyInt_Check(index
))
1771 res
= _PyInt_Format((PyIntObject
*)index
, base
, 1);
1773 /* It should not be possible to get here, as
1774 PyNumber_Index already has a check for the same
1776 PyErr_SetString(PyExc_ValueError
, "PyNumber_ToBase: index not "
1783 /* Operations on sequences */
1786 PySequence_Check(PyObject
*s
)
1788 if (s
&& PyInstance_Check(s
))
1789 return PyObject_HasAttrString(s
, "__getitem__");
1790 if (PyObject_IsInstance(s
, (PyObject
*)&PyDict_Type
))
1792 return s
!= NULL
&& s
->ob_type
->tp_as_sequence
&&
1793 s
->ob_type
->tp_as_sequence
->sq_item
!= NULL
;
1797 PySequence_Size(PyObject
*s
)
1799 PySequenceMethods
*m
;
1806 m
= s
->ob_type
->tp_as_sequence
;
1807 if (m
&& m
->sq_length
)
1808 return m
->sq_length(s
);
1810 type_error("object of type '%.200s' has no len()", s
);
1814 #undef PySequence_Length
1816 PySequence_Length(PyObject
*s
)
1818 return PySequence_Size(s
);
1820 #define PySequence_Length PySequence_Size
1823 PySequence_Concat(PyObject
*s
, PyObject
*o
)
1825 PySequenceMethods
*m
;
1827 if (s
== NULL
|| o
== NULL
)
1828 return null_error();
1830 m
= s
->ob_type
->tp_as_sequence
;
1831 if (m
&& m
->sq_concat
)
1832 return m
->sq_concat(s
, o
);
1834 /* Instances of user classes defining an __add__() method only
1835 have an nb_add slot, not an sq_concat slot. So we fall back
1836 to nb_add if both arguments appear to be sequences. */
1837 if (PySequence_Check(s
) && PySequence_Check(o
)) {
1838 PyObject
*result
= binary_op1(s
, o
, NB_SLOT(nb_add
));
1839 if (result
!= Py_NotImplemented
)
1843 return type_error("'%.200s' object can't be concatenated", s
);
1847 PySequence_Repeat(PyObject
*o
, Py_ssize_t count
)
1849 PySequenceMethods
*m
;
1852 return null_error();
1854 m
= o
->ob_type
->tp_as_sequence
;
1855 if (m
&& m
->sq_repeat
)
1856 return m
->sq_repeat(o
, count
);
1858 /* Instances of user classes defining a __mul__() method only
1859 have an nb_multiply slot, not an sq_repeat slot. so we fall back
1860 to nb_multiply if o appears to be a sequence. */
1861 if (PySequence_Check(o
)) {
1862 PyObject
*n
, *result
;
1863 n
= PyInt_FromSsize_t(count
);
1866 result
= binary_op1(o
, n
, NB_SLOT(nb_multiply
));
1868 if (result
!= Py_NotImplemented
)
1872 return type_error("'%.200s' object can't be repeated", o
);
1876 PySequence_InPlaceConcat(PyObject
*s
, PyObject
*o
)
1878 PySequenceMethods
*m
;
1880 if (s
== NULL
|| o
== NULL
)
1881 return null_error();
1883 m
= s
->ob_type
->tp_as_sequence
;
1884 if (m
&& HASINPLACE(s
) && m
->sq_inplace_concat
)
1885 return m
->sq_inplace_concat(s
, o
);
1886 if (m
&& m
->sq_concat
)
1887 return m
->sq_concat(s
, o
);
1889 if (PySequence_Check(s
) && PySequence_Check(o
)) {
1890 PyObject
*result
= binary_iop1(s
, o
, NB_SLOT(nb_inplace_add
),
1892 if (result
!= Py_NotImplemented
)
1896 return type_error("'%.200s' object can't be concatenated", s
);
1900 PySequence_InPlaceRepeat(PyObject
*o
, Py_ssize_t count
)
1902 PySequenceMethods
*m
;
1905 return null_error();
1907 m
= o
->ob_type
->tp_as_sequence
;
1908 if (m
&& HASINPLACE(o
) && m
->sq_inplace_repeat
)
1909 return m
->sq_inplace_repeat(o
, count
);
1910 if (m
&& m
->sq_repeat
)
1911 return m
->sq_repeat(o
, count
);
1913 if (PySequence_Check(o
)) {
1914 PyObject
*n
, *result
;
1915 n
= PyInt_FromSsize_t(count
);
1918 result
= binary_iop1(o
, n
, NB_SLOT(nb_inplace_multiply
),
1919 NB_SLOT(nb_multiply
));
1921 if (result
!= Py_NotImplemented
)
1925 return type_error("'%.200s' object can't be repeated", o
);
1929 PySequence_GetItem(PyObject
*s
, Py_ssize_t i
)
1931 PySequenceMethods
*m
;
1934 return null_error();
1936 m
= s
->ob_type
->tp_as_sequence
;
1937 if (m
&& m
->sq_item
) {
1940 Py_ssize_t l
= (*m
->sq_length
)(s
);
1946 return m
->sq_item(s
, i
);
1949 return type_error("'%.200s' object does not support indexing", s
);
1953 PySequence_GetSlice(PyObject
*s
, Py_ssize_t i1
, Py_ssize_t i2
)
1955 PySequenceMethods
*m
;
1956 PyMappingMethods
*mp
;
1958 if (!s
) return null_error();
1960 m
= s
->ob_type
->tp_as_sequence
;
1961 if (m
&& m
->sq_slice
) {
1962 if (i1
< 0 || i2
< 0) {
1964 Py_ssize_t l
= (*m
->sq_length
)(s
);
1973 return m
->sq_slice(s
, i1
, i2
);
1974 } else if ((mp
= s
->ob_type
->tp_as_mapping
) && mp
->mp_subscript
) {
1976 PyObject
*slice
= _PySlice_FromIndices(i1
, i2
);
1979 res
= mp
->mp_subscript(s
, slice
);
1984 return type_error("'%.200s' object is unsliceable", s
);
1988 PySequence_SetItem(PyObject
*s
, Py_ssize_t i
, PyObject
*o
)
1990 PySequenceMethods
*m
;
1997 m
= s
->ob_type
->tp_as_sequence
;
1998 if (m
&& m
->sq_ass_item
) {
2001 Py_ssize_t l
= (*m
->sq_length
)(s
);
2007 return m
->sq_ass_item(s
, i
, o
);
2010 type_error("'%.200s' object does not support item assignment", s
);
2015 PySequence_DelItem(PyObject
*s
, Py_ssize_t i
)
2017 PySequenceMethods
*m
;
2024 m
= s
->ob_type
->tp_as_sequence
;
2025 if (m
&& m
->sq_ass_item
) {
2028 Py_ssize_t l
= (*m
->sq_length
)(s
);
2034 return m
->sq_ass_item(s
, i
, (PyObject
*)NULL
);
2037 type_error("'%.200s' object doesn't support item deletion", s
);
2042 PySequence_SetSlice(PyObject
*s
, Py_ssize_t i1
, Py_ssize_t i2
, PyObject
*o
)
2044 PySequenceMethods
*m
;
2045 PyMappingMethods
*mp
;
2052 m
= s
->ob_type
->tp_as_sequence
;
2053 if (m
&& m
->sq_ass_slice
) {
2054 if (i1
< 0 || i2
< 0) {
2056 Py_ssize_t l
= (*m
->sq_length
)(s
);
2065 return m
->sq_ass_slice(s
, i1
, i2
, o
);
2066 } else if ((mp
= s
->ob_type
->tp_as_mapping
) && mp
->mp_ass_subscript
) {
2068 PyObject
*slice
= _PySlice_FromIndices(i1
, i2
);
2071 res
= mp
->mp_ass_subscript(s
, slice
, o
);
2076 type_error("'%.200s' object doesn't support slice assignment", s
);
2081 PySequence_DelSlice(PyObject
*s
, Py_ssize_t i1
, Py_ssize_t i2
)
2083 PySequenceMethods
*m
;
2090 m
= s
->ob_type
->tp_as_sequence
;
2091 if (m
&& m
->sq_ass_slice
) {
2092 if (i1
< 0 || i2
< 0) {
2094 Py_ssize_t l
= (*m
->sq_length
)(s
);
2103 return m
->sq_ass_slice(s
, i1
, i2
, (PyObject
*)NULL
);
2105 type_error("'%.200s' object doesn't support slice deletion", s
);
2110 PySequence_Tuple(PyObject
*v
)
2112 PyObject
*it
; /* iter(v) */
2113 Py_ssize_t n
; /* guess for result tuple size */
2118 return null_error();
2120 /* Special-case the common tuple and list cases, for efficiency. */
2121 if (PyTuple_CheckExact(v
)) {
2122 /* Note that we can't know whether it's safe to return
2123 a tuple *subclass* instance as-is, hence the restriction
2124 to exact tuples here. In contrast, lists always make
2125 a copy, so there's no need for exactness below. */
2129 if (PyList_Check(v
))
2130 return PyList_AsTuple(v
);
2133 it
= PyObject_GetIter(v
);
2137 /* Guess result size and allocate space. */
2138 n
= _PyObject_LengthHint(v
, 10);
2139 result
= PyTuple_New(n
);
2143 /* Fill the tuple. */
2144 for (j
= 0; ; ++j
) {
2145 PyObject
*item
= PyIter_Next(it
);
2147 if (PyErr_Occurred())
2152 Py_ssize_t oldn
= n
;
2153 /* The over-allocation strategy can grow a bit faster
2154 than for lists because unlike lists the
2155 over-allocation isn't permanent -- we reclaim
2156 the excess before the end of this routine.
2157 So, grow by ten and then add 25%.
2162 /* Check for overflow */
2167 if (_PyTuple_Resize(&result
, n
) != 0) {
2172 PyTuple_SET_ITEM(result
, j
, item
);
2175 /* Cut tuple back if guess was too large. */
2177 _PyTuple_Resize(&result
, j
) != 0)
2190 PySequence_List(PyObject
*v
)
2192 PyObject
*result
; /* result list */
2193 PyObject
*rv
; /* return value from PyList_Extend */
2196 return null_error();
2198 result
= PyList_New(0);
2202 rv
= _PyList_Extend((PyListObject
*)result
, v
);
2212 PySequence_Fast(PyObject
*v
, const char *m
)
2217 return null_error();
2219 if (PyList_CheckExact(v
) || PyTuple_CheckExact(v
)) {
2224 it
= PyObject_GetIter(v
);
2226 if (PyErr_ExceptionMatches(PyExc_TypeError
))
2227 PyErr_SetString(PyExc_TypeError
, m
);
2231 v
= PySequence_List(it
);
2237 /* Iterate over seq. Result depends on the operation:
2238 PY_ITERSEARCH_COUNT: -1 if error, else # of times obj appears in seq.
2239 PY_ITERSEARCH_INDEX: 0-based index of first occurence of obj in seq;
2240 set ValueError and return -1 if none found; also return -1 on error.
2241 Py_ITERSEARCH_CONTAINS: return 1 if obj in seq, else 0; -1 on error.
2244 _PySequence_IterSearch(PyObject
*seq
, PyObject
*obj
, int operation
)
2247 int wrapped
; /* for PY_ITERSEARCH_INDEX, true iff n wrapped around */
2248 PyObject
*it
; /* iter(seq) */
2250 if (seq
== NULL
|| obj
== NULL
) {
2255 it
= PyObject_GetIter(seq
);
2257 type_error("argument of type '%.200s' is not iterable", seq
);
2264 PyObject
*item
= PyIter_Next(it
);
2266 if (PyErr_Occurred())
2271 cmp
= PyObject_RichCompareBool(obj
, item
, Py_EQ
);
2276 switch (operation
) {
2277 case PY_ITERSEARCH_COUNT
:
2278 if (n
== PY_SSIZE_T_MAX
) {
2279 PyErr_SetString(PyExc_OverflowError
,
2280 "count exceeds C integer size");
2286 case PY_ITERSEARCH_INDEX
:
2288 PyErr_SetString(PyExc_OverflowError
,
2289 "index exceeds C integer size");
2294 case PY_ITERSEARCH_CONTAINS
:
2299 assert(!"unknown operation");
2303 if (operation
== PY_ITERSEARCH_INDEX
) {
2304 if (n
== PY_SSIZE_T_MAX
)
2310 if (operation
!= PY_ITERSEARCH_INDEX
)
2313 PyErr_SetString(PyExc_ValueError
,
2314 "sequence.index(x): x not in sequence");
2315 /* fall into failure code */
2325 /* Return # of times o appears in s. */
2327 PySequence_Count(PyObject
*s
, PyObject
*o
)
2329 return _PySequence_IterSearch(s
, o
, PY_ITERSEARCH_COUNT
);
2332 /* Return -1 if error; 1 if ob in seq; 0 if ob not in seq.
2333 * Use sq_contains if possible, else defer to _PySequence_IterSearch().
2336 PySequence_Contains(PyObject
*seq
, PyObject
*ob
)
2339 if (PyType_HasFeature(seq
->ob_type
, Py_TPFLAGS_HAVE_SEQUENCE_IN
)) {
2340 PySequenceMethods
*sqm
= seq
->ob_type
->tp_as_sequence
;
2341 if (sqm
!= NULL
&& sqm
->sq_contains
!= NULL
)
2342 return (*sqm
->sq_contains
)(seq
, ob
);
2344 result
= _PySequence_IterSearch(seq
, ob
, PY_ITERSEARCH_CONTAINS
);
2345 return Py_SAFE_DOWNCAST(result
, Py_ssize_t
, int);
2348 /* Backwards compatibility */
2349 #undef PySequence_In
2351 PySequence_In(PyObject
*w
, PyObject
*v
)
2353 return PySequence_Contains(w
, v
);
2357 PySequence_Index(PyObject
*s
, PyObject
*o
)
2359 return _PySequence_IterSearch(s
, o
, PY_ITERSEARCH_INDEX
);
2362 /* Operations on mappings */
2365 PyMapping_Check(PyObject
*o
)
2367 if (o
&& PyInstance_Check(o
))
2368 return PyObject_HasAttrString(o
, "__getitem__");
2370 return o
&& o
->ob_type
->tp_as_mapping
&&
2371 o
->ob_type
->tp_as_mapping
->mp_subscript
&&
2372 !(o
->ob_type
->tp_as_sequence
&&
2373 o
->ob_type
->tp_as_sequence
->sq_slice
);
2377 PyMapping_Size(PyObject
*o
)
2379 PyMappingMethods
*m
;
2386 m
= o
->ob_type
->tp_as_mapping
;
2387 if (m
&& m
->mp_length
)
2388 return m
->mp_length(o
);
2390 type_error("object of type '%.200s' has no len()", o
);
2394 #undef PyMapping_Length
2396 PyMapping_Length(PyObject
*o
)
2398 return PyMapping_Size(o
);
2400 #define PyMapping_Length PyMapping_Size
2403 PyMapping_GetItemString(PyObject
*o
, char *key
)
2408 return null_error();
2410 okey
= PyString_FromString(key
);
2413 r
= PyObject_GetItem(o
, okey
);
2419 PyMapping_SetItemString(PyObject
*o
, char *key
, PyObject
*value
)
2429 okey
= PyString_FromString(key
);
2432 r
= PyObject_SetItem(o
, okey
, value
);
2438 PyMapping_HasKeyString(PyObject
*o
, char *key
)
2442 v
= PyMapping_GetItemString(o
, key
);
2452 PyMapping_HasKey(PyObject
*o
, PyObject
*key
)
2456 v
= PyObject_GetItem(o
, key
);
2465 /* Operations on callable objects */
2467 /* XXX PyCallable_Check() is in object.c */
2470 PyObject_CallObject(PyObject
*o
, PyObject
*a
)
2472 return PyEval_CallObjectWithKeywords(o
, a
, NULL
);
2476 PyObject_Call(PyObject
*func
, PyObject
*arg
, PyObject
*kw
)
2480 if ((call
= func
->ob_type
->tp_call
) != NULL
) {
2482 if (Py_EnterRecursiveCall(" while calling a Python object"))
2484 result
= (*call
)(func
, arg
, kw
);
2485 Py_LeaveRecursiveCall();
2486 if (result
== NULL
&& !PyErr_Occurred())
2489 "NULL result without error in PyObject_Call");
2492 PyErr_Format(PyExc_TypeError
, "'%.200s' object is not callable",
2493 func
->ob_type
->tp_name
);
2498 call_function_tail(PyObject
*callable
, PyObject
*args
)
2505 if (!PyTuple_Check(args
)) {
2513 PyTuple_SET_ITEM(a
, 0, args
);
2516 retval
= PyObject_Call(callable
, args
, NULL
);
2524 PyObject_CallFunction(PyObject
*callable
, char *format
, ...)
2529 if (callable
== NULL
)
2530 return null_error();
2532 if (format
&& *format
) {
2533 va_start(va
, format
);
2534 args
= Py_VaBuildValue(format
, va
);
2538 args
= PyTuple_New(0);
2540 return call_function_tail(callable
, args
);
2544 _PyObject_CallFunction_SizeT(PyObject
*callable
, char *format
, ...)
2549 if (callable
== NULL
)
2550 return null_error();
2552 if (format
&& *format
) {
2553 va_start(va
, format
);
2554 args
= _Py_VaBuildValue_SizeT(format
, va
);
2558 args
= PyTuple_New(0);
2560 return call_function_tail(callable
, args
);
2564 PyObject_CallMethod(PyObject
*o
, char *name
, char *format
, ...)
2568 PyObject
*func
= NULL
;
2569 PyObject
*retval
= NULL
;
2571 if (o
== NULL
|| name
== NULL
)
2572 return null_error();
2574 func
= PyObject_GetAttrString(o
, name
);
2576 PyErr_SetString(PyExc_AttributeError
, name
);
2580 if (!PyCallable_Check(func
)) {
2581 type_error("attribute of type '%.200s' is not callable", func
);
2585 if (format
&& *format
) {
2586 va_start(va
, format
);
2587 args
= Py_VaBuildValue(format
, va
);
2591 args
= PyTuple_New(0);
2593 retval
= call_function_tail(func
, args
);
2596 /* args gets consumed in call_function_tail */
2603 _PyObject_CallMethod_SizeT(PyObject
*o
, char *name
, char *format
, ...)
2607 PyObject
*func
= NULL
;
2608 PyObject
*retval
= NULL
;
2610 if (o
== NULL
|| name
== NULL
)
2611 return null_error();
2613 func
= PyObject_GetAttrString(o
, name
);
2615 PyErr_SetString(PyExc_AttributeError
, name
);
2619 if (!PyCallable_Check(func
)) {
2620 type_error("attribute of type '%.200s' is not callable", func
);
2624 if (format
&& *format
) {
2625 va_start(va
, format
);
2626 args
= _Py_VaBuildValue_SizeT(format
, va
);
2630 args
= PyTuple_New(0);
2632 retval
= call_function_tail(func
, args
);
2635 /* args gets consumed in call_function_tail */
2643 objargs_mktuple(va_list va
)
2647 PyObject
*result
, *tmp
;
2649 #ifdef VA_LIST_IS_ARRAY
2650 memcpy(countva
, va
, sizeof(va_list));
2653 __va_copy(countva
, va
);
2659 while (((PyObject
*)va_arg(countva
, PyObject
*)) != NULL
)
2661 result
= PyTuple_New(n
);
2662 if (result
!= NULL
&& n
> 0) {
2663 for (i
= 0; i
< n
; ++i
) {
2664 tmp
= (PyObject
*)va_arg(va
, PyObject
*);
2665 PyTuple_SET_ITEM(result
, i
, tmp
);
2673 PyObject_CallMethodObjArgs(PyObject
*callable
, PyObject
*name
, ...)
2675 PyObject
*args
, *tmp
;
2678 if (callable
== NULL
|| name
== NULL
)
2679 return null_error();
2681 callable
= PyObject_GetAttr(callable
, name
);
2682 if (callable
== NULL
)
2685 /* count the args */
2686 va_start(vargs
, name
);
2687 args
= objargs_mktuple(vargs
);
2690 Py_DECREF(callable
);
2693 tmp
= PyObject_Call(callable
, args
, NULL
);
2695 Py_DECREF(callable
);
2701 PyObject_CallFunctionObjArgs(PyObject
*callable
, ...)
2703 PyObject
*args
, *tmp
;
2706 if (callable
== NULL
)
2707 return null_error();
2709 /* count the args */
2710 va_start(vargs
, callable
);
2711 args
= objargs_mktuple(vargs
);
2715 tmp
= PyObject_Call(callable
, args
, NULL
);
2722 /* isinstance(), issubclass() */
2724 /* abstract_get_bases() has logically 4 return states, with a sort of 0th
2725 * state that will almost never happen.
2727 * 0. creating the __bases__ static string could get a MemoryError
2728 * 1. getattr(cls, '__bases__') could raise an AttributeError
2729 * 2. getattr(cls, '__bases__') could raise some other exception
2730 * 3. getattr(cls, '__bases__') could return a tuple
2731 * 4. getattr(cls, '__bases__') could return something other than a tuple
2733 * Only state #3 is a non-error state and only it returns a non-NULL object
2734 * (it returns the retrieved tuple).
2736 * Any raised AttributeErrors are masked by clearing the exception and
2737 * returning NULL. If an object other than a tuple comes out of __bases__,
2738 * then again, the return value is NULL. So yes, these two situations
2739 * produce exactly the same results: NULL is returned and no error is set.
2741 * If some exception other than AttributeError is raised, then NULL is also
2742 * returned, but the exception is not cleared. That's because we want the
2743 * exception to be propagated along.
2745 * Callers are expected to test for PyErr_Occurred() when the return value
2746 * is NULL to decide whether a valid exception should be propagated or not.
2747 * When there's no exception to propagate, it's customary for the caller to
2751 abstract_get_bases(PyObject
*cls
)
2753 static PyObject
*__bases__
= NULL
;
2756 if (__bases__
== NULL
) {
2757 __bases__
= PyString_InternFromString("__bases__");
2758 if (__bases__
== NULL
)
2761 bases
= PyObject_GetAttr(cls
, __bases__
);
2762 if (bases
== NULL
) {
2763 if (PyErr_ExceptionMatches(PyExc_AttributeError
))
2767 if (!PyTuple_Check(bases
)) {
2776 abstract_issubclass(PyObject
*derived
, PyObject
*cls
)
2786 if (PyTuple_Check(cls
)) {
2787 /* Not a general sequence -- that opens up the road to
2788 recursion and stack overflow. */
2789 n
= PyTuple_GET_SIZE(cls
);
2790 for (i
= 0; i
< n
; i
++) {
2791 if (derived
== PyTuple_GET_ITEM(cls
, i
))
2795 bases
= abstract_get_bases(derived
);
2796 if (bases
== NULL
) {
2797 if (PyErr_Occurred())
2801 n
= PyTuple_GET_SIZE(bases
);
2802 for (i
= 0; i
< n
; i
++) {
2803 r
= abstract_issubclass(PyTuple_GET_ITEM(bases
, i
), cls
);
2814 check_class(PyObject
*cls
, const char *error
)
2816 PyObject
*bases
= abstract_get_bases(cls
);
2817 if (bases
== NULL
) {
2818 /* Do not mask errors. */
2819 if (!PyErr_Occurred())
2820 PyErr_SetString(PyExc_TypeError
, error
);
2828 recursive_isinstance(PyObject
*inst
, PyObject
*cls
, int recursion_depth
)
2831 static PyObject
*__class__
= NULL
;
2834 if (__class__
== NULL
) {
2835 __class__
= PyString_InternFromString("__class__");
2836 if (__class__
== NULL
)
2840 if (PyClass_Check(cls
) && PyInstance_Check(inst
)) {
2842 (PyObject
*)((PyInstanceObject
*)inst
)->in_class
;
2843 retval
= PyClass_IsSubclass(inclass
, cls
);
2845 else if (PyType_Check(cls
)) {
2846 retval
= PyObject_TypeCheck(inst
, (PyTypeObject
*)cls
);
2848 PyObject
*c
= PyObject_GetAttr(inst
, __class__
);
2853 if (c
!= (PyObject
*)(inst
->ob_type
) &&
2855 retval
= PyType_IsSubtype(
2857 (PyTypeObject
*)cls
);
2862 else if (PyTuple_Check(cls
)) {
2865 if (!recursion_depth
) {
2866 PyErr_SetString(PyExc_RuntimeError
,
2867 "nest level of tuple too deep");
2871 n
= PyTuple_GET_SIZE(cls
);
2872 for (i
= 0; i
< n
; i
++) {
2873 retval
= recursive_isinstance(
2875 PyTuple_GET_ITEM(cls
, i
),
2882 if (!check_class(cls
,
2883 "isinstance() arg 2 must be a class, type,"
2884 " or tuple of classes and types"))
2886 icls
= PyObject_GetAttr(inst
, __class__
);
2892 retval
= abstract_issubclass(icls
, cls
);
2901 PyObject_IsInstance(PyObject
*inst
, PyObject
*cls
)
2903 static PyObject
*name
= NULL
;
2906 /* Quick test for an exact match */
2907 if (Py_TYPE(inst
) == (PyTypeObject
*)cls
)
2911 name
= PyString_InternFromString("__instancecheck__");
2915 checker
= PyObject_GetAttr(cls
, name
);
2916 if (checker
== NULL
&& PyErr_Occurred())
2918 if (checker
!= NULL
) {
2921 if (Py_EnterRecursiveCall(" in __instancecheck__")) {
2925 res
= PyObject_CallFunctionObjArgs(checker
, inst
, NULL
);
2926 Py_LeaveRecursiveCall();
2929 ok
= PyObject_IsTrue(res
);
2934 return recursive_isinstance(inst
, cls
, Py_GetRecursionLimit());
2938 recursive_issubclass(PyObject
*derived
, PyObject
*cls
, int recursion_depth
)
2942 if (!PyClass_Check(derived
) || !PyClass_Check(cls
)) {
2943 if (!check_class(derived
,
2944 "issubclass() arg 1 must be a class"))
2947 if (PyTuple_Check(cls
)) {
2949 Py_ssize_t n
= PyTuple_GET_SIZE(cls
);
2951 if (!recursion_depth
) {
2952 PyErr_SetString(PyExc_RuntimeError
,
2953 "nest level of tuple too deep");
2956 for (i
= 0; i
< n
; ++i
) {
2957 retval
= recursive_issubclass(
2959 PyTuple_GET_ITEM(cls
, i
),
2962 /* either found it, or got an error */
2969 if (!check_class(cls
,
2970 "issubclass() arg 2 must be a class"
2971 " or tuple of classes"))
2975 retval
= abstract_issubclass(derived
, cls
);
2979 if (!(retval
= (derived
== cls
)))
2980 retval
= PyClass_IsSubclass(derived
, cls
);
2987 PyObject_IsSubclass(PyObject
*derived
, PyObject
*cls
)
2989 static PyObject
*name
= NULL
;
2990 PyObject
*t
, *v
, *tb
;
2992 PyErr_Fetch(&t
, &v
, &tb
);
2995 name
= PyString_InternFromString("__subclasscheck__");
2999 checker
= PyObject_GetAttr(cls
, name
);
3000 PyErr_Restore(t
, v
, tb
);
3001 if (checker
!= NULL
) {
3004 if (Py_EnterRecursiveCall(" in __subclasscheck__"))
3006 res
= PyObject_CallFunctionObjArgs(checker
, derived
, NULL
);
3007 Py_LeaveRecursiveCall();
3010 ok
= PyObject_IsTrue(res
);
3015 return recursive_issubclass(derived
, cls
, Py_GetRecursionLimit());
3020 PyObject_GetIter(PyObject
*o
)
3022 PyTypeObject
*t
= o
->ob_type
;
3023 getiterfunc f
= NULL
;
3024 if (PyType_HasFeature(t
, Py_TPFLAGS_HAVE_ITER
))
3027 if (PySequence_Check(o
))
3028 return PySeqIter_New(o
);
3029 return type_error("'%.200s' object is not iterable", o
);
3032 PyObject
*res
= (*f
)(o
);
3033 if (res
!= NULL
&& !PyIter_Check(res
)) {
3034 PyErr_Format(PyExc_TypeError
,
3035 "iter() returned non-iterator "
3037 res
->ob_type
->tp_name
);
3045 /* Return next item.
3046 * If an error occurs, return NULL. PyErr_Occurred() will be true.
3047 * If the iteration terminates normally, return NULL and clear the
3048 * PyExc_StopIteration exception (if it was set). PyErr_Occurred()
3050 * Else return the next object. PyErr_Occurred() will be false.
3053 PyIter_Next(PyObject
*iter
)
3056 assert(PyIter_Check(iter
));
3057 result
= (*iter
->ob_type
->tp_iternext
)(iter
);
3058 if (result
== NULL
&&
3060 PyErr_ExceptionMatches(PyExc_StopIteration
))