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. If one of the calls fails,
89 this function returns -1.
93 _PyObject_LengthHint(PyObject
*o
, Py_ssize_t defaultvalue
)
95 static PyObject
*hintstrobj
= NULL
;
96 PyObject
*ro
, *hintmeth
;
100 rv
= PyObject_Size(o
);
103 if (PyErr_Occurred()) {
104 if (!PyErr_ExceptionMatches(PyExc_TypeError
) &&
105 !PyErr_ExceptionMatches(PyExc_AttributeError
))
110 if (PyInstance_Check(o
))
112 /* try o.__length_hint__() */
113 hintmeth
= _PyObject_LookupSpecial(o
, "__length_hint__", &hintstrobj
);
114 if (hintmeth
== NULL
) {
115 if (PyErr_Occurred())
120 ro
= PyObject_CallFunctionObjArgs(hintmeth
, NULL
);
123 if (!PyErr_ExceptionMatches(PyExc_TypeError
) &&
124 !PyErr_ExceptionMatches(PyExc_AttributeError
))
129 rv
= PyLong_Check(ro
) ? PyLong_AsSsize_t(ro
) : defaultvalue
;
135 PyObject_GetItem(PyObject
*o
, PyObject
*key
)
139 if (o
== NULL
|| key
== NULL
)
142 m
= o
->ob_type
->tp_as_mapping
;
143 if (m
&& m
->mp_subscript
)
144 return m
->mp_subscript(o
, key
);
146 if (o
->ob_type
->tp_as_sequence
) {
147 if (PyIndex_Check(key
)) {
148 Py_ssize_t key_value
;
149 key_value
= PyNumber_AsSsize_t(key
, PyExc_IndexError
);
150 if (key_value
== -1 && PyErr_Occurred())
152 return PySequence_GetItem(o
, key_value
);
154 else if (o
->ob_type
->tp_as_sequence
->sq_item
)
155 return type_error("sequence index must "
156 "be integer, not '%.200s'", key
);
159 return type_error("'%.200s' object is not subscriptable", o
);
163 PyObject_SetItem(PyObject
*o
, PyObject
*key
, PyObject
*value
)
167 if (o
== NULL
|| key
== NULL
|| value
== NULL
) {
171 m
= o
->ob_type
->tp_as_mapping
;
172 if (m
&& m
->mp_ass_subscript
)
173 return m
->mp_ass_subscript(o
, key
, value
);
175 if (o
->ob_type
->tp_as_sequence
) {
176 if (PyIndex_Check(key
)) {
177 Py_ssize_t key_value
;
178 key_value
= PyNumber_AsSsize_t(key
, PyExc_IndexError
);
179 if (key_value
== -1 && PyErr_Occurred())
181 return PySequence_SetItem(o
, key_value
, value
);
183 else if (o
->ob_type
->tp_as_sequence
->sq_ass_item
) {
184 type_error("sequence index must be "
185 "integer, not '%.200s'", key
);
190 type_error("'%.200s' object does not support item assignment", o
);
195 PyObject_DelItem(PyObject
*o
, PyObject
*key
)
199 if (o
== NULL
|| key
== NULL
) {
203 m
= o
->ob_type
->tp_as_mapping
;
204 if (m
&& m
->mp_ass_subscript
)
205 return m
->mp_ass_subscript(o
, key
, (PyObject
*)NULL
);
207 if (o
->ob_type
->tp_as_sequence
) {
208 if (PyIndex_Check(key
)) {
209 Py_ssize_t key_value
;
210 key_value
= PyNumber_AsSsize_t(key
, PyExc_IndexError
);
211 if (key_value
== -1 && PyErr_Occurred())
213 return PySequence_DelItem(o
, key_value
);
215 else if (o
->ob_type
->tp_as_sequence
->sq_ass_item
) {
216 type_error("sequence index must be "
217 "integer, not '%.200s'", key
);
222 type_error("'%.200s' object does not support item deletion", o
);
227 PyObject_DelItemString(PyObject
*o
, char *key
)
232 if (o
== NULL
|| key
== NULL
) {
236 okey
= PyString_FromString(key
);
239 ret
= PyObject_DelItem(o
, okey
);
245 PyObject_AsCharBuffer(PyObject
*obj
,
247 Py_ssize_t
*buffer_len
)
253 if (obj
== NULL
|| buffer
== NULL
|| buffer_len
== NULL
) {
257 pb
= obj
->ob_type
->tp_as_buffer
;
259 pb
->bf_getcharbuffer
== NULL
||
260 pb
->bf_getsegcount
== NULL
) {
261 PyErr_SetString(PyExc_TypeError
,
262 "expected a character buffer object");
265 if ((*pb
->bf_getsegcount
)(obj
,NULL
) != 1) {
266 PyErr_SetString(PyExc_TypeError
,
267 "expected a single-segment buffer object");
270 len
= (*pb
->bf_getcharbuffer
)(obj
, 0, &pp
);
279 PyObject_CheckReadBuffer(PyObject
*obj
)
281 PyBufferProcs
*pb
= obj
->ob_type
->tp_as_buffer
;
284 pb
->bf_getreadbuffer
== NULL
||
285 pb
->bf_getsegcount
== NULL
||
286 (*pb
->bf_getsegcount
)(obj
, NULL
) != 1)
291 int PyObject_AsReadBuffer(PyObject
*obj
,
293 Py_ssize_t
*buffer_len
)
299 if (obj
== NULL
|| buffer
== NULL
|| buffer_len
== NULL
) {
303 pb
= obj
->ob_type
->tp_as_buffer
;
305 pb
->bf_getreadbuffer
== NULL
||
306 pb
->bf_getsegcount
== NULL
) {
307 PyErr_SetString(PyExc_TypeError
,
308 "expected a readable buffer object");
311 if ((*pb
->bf_getsegcount
)(obj
, NULL
) != 1) {
312 PyErr_SetString(PyExc_TypeError
,
313 "expected a single-segment buffer object");
316 len
= (*pb
->bf_getreadbuffer
)(obj
, 0, &pp
);
324 int PyObject_AsWriteBuffer(PyObject
*obj
,
326 Py_ssize_t
*buffer_len
)
332 if (obj
== NULL
|| buffer
== NULL
|| buffer_len
== NULL
) {
336 pb
= obj
->ob_type
->tp_as_buffer
;
338 pb
->bf_getwritebuffer
== NULL
||
339 pb
->bf_getsegcount
== NULL
) {
340 PyErr_SetString(PyExc_TypeError
,
341 "expected a writeable buffer object");
344 if ((*pb
->bf_getsegcount
)(obj
, NULL
) != 1) {
345 PyErr_SetString(PyExc_TypeError
,
346 "expected a single-segment buffer object");
349 len
= (*pb
->bf_getwritebuffer
)(obj
,0,&pp
);
357 /* Buffer C-API for Python 3.0 */
360 PyObject_GetBuffer(PyObject
*obj
, Py_buffer
*view
, int flags
)
362 if (!PyObject_CheckBuffer(obj
)) {
363 PyErr_Format(PyExc_TypeError
,
364 "'%100s' does not have the buffer interface",
365 Py_TYPE(obj
)->tp_name
);
368 return (*(obj
->ob_type
->tp_as_buffer
->bf_getbuffer
))(obj
, view
, flags
);
372 _IsFortranContiguous(Py_buffer
*view
)
377 if (view
->ndim
== 0) return 1;
378 if (view
->strides
== NULL
) return (view
->ndim
== 1);
381 if (view
->ndim
== 1) return (view
->shape
[0] == 1 ||
382 sd
== view
->strides
[0]);
383 for (i
=0; i
<view
->ndim
; i
++) {
384 dim
= view
->shape
[i
];
385 if (dim
== 0) return 1;
386 if (view
->strides
[i
] != sd
) return 0;
393 _IsCContiguous(Py_buffer
*view
)
398 if (view
->ndim
== 0) return 1;
399 if (view
->strides
== NULL
) return 1;
402 if (view
->ndim
== 1) return (view
->shape
[0] == 1 ||
403 sd
== view
->strides
[0]);
404 for (i
=view
->ndim
-1; i
>=0; i
--) {
405 dim
= view
->shape
[i
];
406 if (dim
== 0) return 1;
407 if (view
->strides
[i
] != sd
) return 0;
414 PyBuffer_IsContiguous(Py_buffer
*view
, char fort
)
417 if (view
->suboffsets
!= NULL
) return 0;
420 return _IsCContiguous(view
);
421 else if (fort
== 'F')
422 return _IsFortranContiguous(view
);
423 else if (fort
== 'A')
424 return (_IsCContiguous(view
) || _IsFortranContiguous(view
));
430 PyBuffer_GetPointer(Py_buffer
*view
, Py_ssize_t
*indices
)
434 pointer
= (char *)view
->buf
;
435 for (i
= 0; i
< view
->ndim
; i
++) {
436 pointer
+= view
->strides
[i
]*indices
[i
];
437 if ((view
->suboffsets
!= NULL
) && (view
->suboffsets
[i
] >= 0)) {
438 pointer
= *((char**)pointer
) + view
->suboffsets
[i
];
441 return (void*)pointer
;
446 _add_one_to_index_F(int nd
, Py_ssize_t
*index
, Py_ssize_t
*shape
)
450 for (k
=0; k
<nd
; k
++) {
451 if (index
[k
] < shape
[k
]-1) {
462 _add_one_to_index_C(int nd
, Py_ssize_t
*index
, Py_ssize_t
*shape
)
466 for (k
=nd
-1; k
>=0; k
--) {
467 if (index
[k
] < shape
[k
]-1) {
477 /* view is not checked for consistency in either of these. It is
478 assumed that the size of the buffer is view->len in
479 view->len / view->itemsize elements.
483 PyBuffer_ToContiguous(void *buf
, Py_buffer
*view
, Py_ssize_t len
, char fort
)
486 void (*addone
)(int, Py_ssize_t
*, Py_ssize_t
*);
487 Py_ssize_t
*indices
, elements
;
490 if (len
> view
->len
) {
494 if (PyBuffer_IsContiguous(view
, fort
)) {
495 /* simplest copy is all that is needed */
496 memcpy(buf
, view
->buf
, len
);
500 /* Otherwise a more elaborate scheme is needed */
502 /* XXX(nnorwitz): need to check for overflow! */
503 indices
= (Py_ssize_t
*)PyMem_Malloc(sizeof(Py_ssize_t
)*(view
->ndim
));
504 if (indices
== NULL
) {
508 for (k
=0; k
<view
->ndim
;k
++) {
513 addone
= _add_one_to_index_F
;
516 addone
= _add_one_to_index_C
;
519 /* XXX : This is not going to be the fastest code in the world
520 several optimizations are possible.
522 elements
= len
/ view
->itemsize
;
524 addone(view
->ndim
, indices
, view
->shape
);
525 ptr
= PyBuffer_GetPointer(view
, indices
);
526 memcpy(dest
, ptr
, view
->itemsize
);
527 dest
+= view
->itemsize
;
534 PyBuffer_FromContiguous(Py_buffer
*view
, void *buf
, Py_ssize_t len
, char fort
)
537 void (*addone
)(int, Py_ssize_t
*, Py_ssize_t
*);
538 Py_ssize_t
*indices
, elements
;
541 if (len
> view
->len
) {
545 if (PyBuffer_IsContiguous(view
, fort
)) {
546 /* simplest copy is all that is needed */
547 memcpy(view
->buf
, buf
, len
);
551 /* Otherwise a more elaborate scheme is needed */
553 /* XXX(nnorwitz): need to check for overflow! */
554 indices
= (Py_ssize_t
*)PyMem_Malloc(sizeof(Py_ssize_t
)*(view
->ndim
));
555 if (indices
== NULL
) {
559 for (k
=0; k
<view
->ndim
;k
++) {
564 addone
= _add_one_to_index_F
;
567 addone
= _add_one_to_index_C
;
570 /* XXX : This is not going to be the fastest code in the world
571 several optimizations are possible.
573 elements
= len
/ view
->itemsize
;
575 addone(view
->ndim
, indices
, view
->shape
);
576 ptr
= PyBuffer_GetPointer(view
, indices
);
577 memcpy(ptr
, src
, view
->itemsize
);
578 src
+= view
->itemsize
;
585 int PyObject_CopyData(PyObject
*dest
, PyObject
*src
)
587 Py_buffer view_dest
, view_src
;
589 Py_ssize_t
*indices
, elements
;
592 if (!PyObject_CheckBuffer(dest
) ||
593 !PyObject_CheckBuffer(src
)) {
594 PyErr_SetString(PyExc_TypeError
,
595 "both destination and source must have the "\
600 if (PyObject_GetBuffer(dest
, &view_dest
, PyBUF_FULL
) != 0) return -1;
601 if (PyObject_GetBuffer(src
, &view_src
, PyBUF_FULL_RO
) != 0) {
602 PyBuffer_Release(&view_dest
);
606 if (view_dest
.len
< view_src
.len
) {
607 PyErr_SetString(PyExc_BufferError
,
608 "destination is too small to receive data from source");
609 PyBuffer_Release(&view_dest
);
610 PyBuffer_Release(&view_src
);
614 if ((PyBuffer_IsContiguous(&view_dest
, 'C') &&
615 PyBuffer_IsContiguous(&view_src
, 'C')) ||
616 (PyBuffer_IsContiguous(&view_dest
, 'F') &&
617 PyBuffer_IsContiguous(&view_src
, 'F'))) {
618 /* simplest copy is all that is needed */
619 memcpy(view_dest
.buf
, view_src
.buf
, view_src
.len
);
620 PyBuffer_Release(&view_dest
);
621 PyBuffer_Release(&view_src
);
625 /* Otherwise a more elaborate copy scheme is needed */
627 /* XXX(nnorwitz): need to check for overflow! */
628 indices
= (Py_ssize_t
*)PyMem_Malloc(sizeof(Py_ssize_t
)*view_src
.ndim
);
629 if (indices
== NULL
) {
631 PyBuffer_Release(&view_dest
);
632 PyBuffer_Release(&view_src
);
635 for (k
=0; k
<view_src
.ndim
;k
++) {
639 for (k
=0; k
<view_src
.ndim
; k
++) {
640 /* XXX(nnorwitz): can this overflow? */
641 elements
*= view_src
.shape
[k
];
644 _add_one_to_index_C(view_src
.ndim
, indices
, view_src
.shape
);
645 dptr
= PyBuffer_GetPointer(&view_dest
, indices
);
646 sptr
= PyBuffer_GetPointer(&view_src
, indices
);
647 memcpy(dptr
, sptr
, view_src
.itemsize
);
650 PyBuffer_Release(&view_dest
);
651 PyBuffer_Release(&view_src
);
656 PyBuffer_FillContiguousStrides(int nd
, Py_ssize_t
*shape
,
657 Py_ssize_t
*strides
, int itemsize
,
665 for (k
=0; k
<nd
; k
++) {
671 for (k
=nd
-1; k
>=0; k
--) {
680 PyBuffer_FillInfo(Py_buffer
*view
, PyObject
*obj
, void *buf
, Py_ssize_t len
,
681 int readonly
, int flags
)
683 if (view
== NULL
) return 0;
684 if (((flags
& PyBUF_WRITABLE
) == PyBUF_WRITABLE
) &&
686 PyErr_SetString(PyExc_BufferError
,
687 "Object is not writable.");
696 view
->readonly
= readonly
;
699 if ((flags
& PyBUF_FORMAT
) == PyBUF_FORMAT
)
703 if ((flags
& PyBUF_ND
) == PyBUF_ND
)
704 view
->shape
= &(view
->len
);
705 view
->strides
= NULL
;
706 if ((flags
& PyBUF_STRIDES
) == PyBUF_STRIDES
)
707 view
->strides
= &(view
->itemsize
);
708 view
->suboffsets
= NULL
;
709 view
->internal
= NULL
;
714 PyBuffer_Release(Py_buffer
*view
)
716 PyObject
*obj
= view
->obj
;
717 if (obj
&& Py_TYPE(obj
)->tp_as_buffer
&& Py_TYPE(obj
)->tp_as_buffer
->bf_releasebuffer
)
718 Py_TYPE(obj
)->tp_as_buffer
->bf_releasebuffer(obj
, view
);
724 PyObject_Format(PyObject
* obj
, PyObject
*format_spec
)
726 PyObject
*empty
= NULL
;
727 PyObject
*result
= NULL
;
728 #ifdef Py_USING_UNICODE
730 int result_is_unicode
;
733 /* If no format_spec is provided, use an empty string */
734 if (format_spec
== NULL
) {
735 empty
= PyString_FromStringAndSize(NULL
, 0);
739 /* Check the format_spec type, and make sure it's str or unicode */
740 #ifdef Py_USING_UNICODE
741 if (PyUnicode_Check(format_spec
))
743 else if (PyString_Check(format_spec
))
747 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 /* Check for a __format__ method and call it. */
756 if (PyInstance_Check(obj
)) {
757 /* We're an instance of a classic class */
758 PyObject
*bound_method
= PyObject_GetAttrString(obj
, "__format__");
759 if (bound_method
!= NULL
) {
760 result
= PyObject_CallFunctionObjArgs(bound_method
,
763 Py_DECREF(bound_method
);
765 PyObject
*self_as_str
= NULL
;
766 PyObject
*format_method
= NULL
;
767 Py_ssize_t format_len
;
770 /* Per the PEP, convert to str (or unicode,
771 depending on the type of the format
772 specifier). For new-style classes, this
773 logic is done by object.__format__(). */
774 #ifdef Py_USING_UNICODE
775 if (spec_is_unicode
) {
776 format_len
= PyUnicode_GET_SIZE(format_spec
);
777 self_as_str
= PyObject_Unicode(obj
);
781 format_len
= PyString_GET_SIZE(format_spec
);
782 self_as_str
= PyObject_Str(obj
);
784 if (self_as_str
== NULL
)
787 if (format_len
> 0) {
788 /* See the almost identical code in
789 typeobject.c for new-style
792 PyExc_PendingDeprecationWarning
,
793 "object.__format__ with a non-empty "
794 "format string is deprecated", 1)
798 /* Eventually this will become an
800 PyErr_Format(PyExc_TypeError,
801 "non-empty format string passed to "
802 "object.__format__");
807 /* Then call str.__format__ on that result */
808 format_method
= PyObject_GetAttrString(self_as_str
, "__format__");
809 if (format_method
== NULL
) {
812 result
= PyObject_CallFunctionObjArgs(format_method
,
816 Py_XDECREF(self_as_str
);
817 Py_XDECREF(format_method
);
822 /* Not an instance of a classic class, use the code
824 static PyObject
*format_cache
= NULL
;
826 /* Find the (unbound!) __format__ method (a borrowed
828 PyObject
*method
= _PyObject_LookupSpecial(obj
, "__format__",
830 if (method
== NULL
) {
831 if (!PyErr_Occurred())
832 PyErr_Format(PyExc_TypeError
,
833 "Type %.100s doesn't define __format__",
834 Py_TYPE(obj
)->tp_name
);
838 result
= PyObject_CallFunctionObjArgs(method
, format_spec
, NULL
);
845 /* Check the result type, and make sure it's str or unicode */
846 #ifdef Py_USING_UNICODE
847 if (PyUnicode_Check(result
))
848 result_is_unicode
= 1;
849 else if (PyString_Check(result
))
850 result_is_unicode
= 0;
853 if (!PyString_Check(result
)) {
855 PyErr_Format(PyExc_TypeError
,
856 "%.100s.__format__ must return string or "
857 "unicode, not %.100s", Py_TYPE(obj
)->tp_name
,
858 Py_TYPE(result
)->tp_name
);
864 /* Convert to unicode, if needed. Required if spec is unicode
866 #ifdef Py_USING_UNICODE
867 if (spec_is_unicode
&& !result_is_unicode
) {
868 PyObject
*tmp
= PyObject_Unicode(result
);
869 /* This logic works whether or not tmp is NULL */
880 /* Operations on numbers */
883 PyNumber_Check(PyObject
*o
)
885 return o
&& o
->ob_type
->tp_as_number
&&
886 (o
->ob_type
->tp_as_number
->nb_int
||
887 o
->ob_type
->tp_as_number
->nb_float
);
890 /* Binary operators */
892 /* New style number protocol support */
894 #define NB_SLOT(x) offsetof(PyNumberMethods, x)
895 #define NB_BINOP(nb_methods, slot) \
896 (*(binaryfunc*)(& ((char*)nb_methods)[slot]))
897 #define NB_TERNOP(nb_methods, slot) \
898 (*(ternaryfunc*)(& ((char*)nb_methods)[slot]))
901 Calling scheme used for binary operations:
904 -------------------------------------------------------------------
905 new new w.op(v,w)[*], v.op(v,w), w.op(v,w)
906 new old v.op(v,w), coerce(v,w), v.op(v,w)
907 old new w.op(v,w), coerce(v,w), v.op(v,w)
908 old old coerce(v,w), v.op(v,w)
910 [*] only when v->ob_type != w->ob_type && w->ob_type is a subclass of
915 * new == new style number
916 * old == old style number
917 * Action indicates the order in which operations are tried until either
918 a valid result is produced or an error occurs.
923 binary_op1(PyObject
*v
, PyObject
*w
, const int op_slot
)
926 binaryfunc slotv
= NULL
;
927 binaryfunc slotw
= NULL
;
929 if (v
->ob_type
->tp_as_number
!= NULL
&& NEW_STYLE_NUMBER(v
))
930 slotv
= NB_BINOP(v
->ob_type
->tp_as_number
, op_slot
);
931 if (w
->ob_type
!= v
->ob_type
&&
932 w
->ob_type
->tp_as_number
!= NULL
&& NEW_STYLE_NUMBER(w
)) {
933 slotw
= NB_BINOP(w
->ob_type
->tp_as_number
, op_slot
);
938 if (slotw
&& PyType_IsSubtype(w
->ob_type
, v
->ob_type
)) {
940 if (x
!= Py_NotImplemented
)
942 Py_DECREF(x
); /* can't do it */
946 if (x
!= Py_NotImplemented
)
948 Py_DECREF(x
); /* can't do it */
952 if (x
!= Py_NotImplemented
)
954 Py_DECREF(x
); /* can't do it */
956 if (!NEW_STYLE_NUMBER(v
) || !NEW_STYLE_NUMBER(w
)) {
957 int err
= PyNumber_CoerceEx(&v
, &w
);
962 PyNumberMethods
*mv
= v
->ob_type
->tp_as_number
;
965 slot
= NB_BINOP(mv
, op_slot
);
973 /* CoerceEx incremented the reference counts */
978 Py_INCREF(Py_NotImplemented
);
979 return Py_NotImplemented
;
983 binop_type_error(PyObject
*v
, PyObject
*w
, const char *op_name
)
985 PyErr_Format(PyExc_TypeError
,
986 "unsupported operand type(s) for %.100s: "
987 "'%.100s' and '%.100s'",
990 w
->ob_type
->tp_name
);
995 binary_op(PyObject
*v
, PyObject
*w
, const int op_slot
, const char *op_name
)
997 PyObject
*result
= binary_op1(v
, w
, op_slot
);
998 if (result
== Py_NotImplemented
) {
1000 return binop_type_error(v
, w
, op_name
);
1007 Calling scheme used for ternary operations:
1009 *** In some cases, w.op is called before v.op; see binary_op1. ***
1012 -------------------------------------------------------------------
1013 new new new v.op(v,w,z), w.op(v,w,z), z.op(v,w,z)
1014 new old new v.op(v,w,z), z.op(v,w,z), coerce(v,w,z), v.op(v,w,z)
1015 old new new w.op(v,w,z), z.op(v,w,z), coerce(v,w,z), v.op(v,w,z)
1016 old old new z.op(v,w,z), coerce(v,w,z), v.op(v,w,z)
1017 new new old v.op(v,w,z), w.op(v,w,z), coerce(v,w,z), v.op(v,w,z)
1018 new old old v.op(v,w,z), coerce(v,w,z), v.op(v,w,z)
1019 old new old w.op(v,w,z), coerce(v,w,z), v.op(v,w,z)
1020 old old old coerce(v,w,z), v.op(v,w,z)
1024 * new == new style number
1025 * old == old style number
1026 * Action indicates the order in which operations are tried until either
1027 a valid result is produced or an error occurs.
1028 * coerce(v,w,z) actually does: coerce(v,w), coerce(v,z), coerce(w,z) and
1029 only if z != Py_None; if z == Py_None, then it is treated as absent
1030 variable and only coerce(v,w) is tried.
1035 ternary_op(PyObject
*v
,
1039 const char *op_name
)
1041 PyNumberMethods
*mv
, *mw
, *mz
;
1043 ternaryfunc slotv
= NULL
;
1044 ternaryfunc slotw
= NULL
;
1045 ternaryfunc slotz
= NULL
;
1047 mv
= v
->ob_type
->tp_as_number
;
1048 mw
= w
->ob_type
->tp_as_number
;
1049 if (mv
!= NULL
&& NEW_STYLE_NUMBER(v
))
1050 slotv
= NB_TERNOP(mv
, op_slot
);
1051 if (w
->ob_type
!= v
->ob_type
&&
1052 mw
!= NULL
&& NEW_STYLE_NUMBER(w
)) {
1053 slotw
= NB_TERNOP(mw
, op_slot
);
1058 if (slotw
&& PyType_IsSubtype(w
->ob_type
, v
->ob_type
)) {
1060 if (x
!= Py_NotImplemented
)
1062 Py_DECREF(x
); /* can't do it */
1066 if (x
!= Py_NotImplemented
)
1068 Py_DECREF(x
); /* can't do it */
1072 if (x
!= Py_NotImplemented
)
1074 Py_DECREF(x
); /* can't do it */
1076 mz
= z
->ob_type
->tp_as_number
;
1077 if (mz
!= NULL
&& NEW_STYLE_NUMBER(z
)) {
1078 slotz
= NB_TERNOP(mz
, op_slot
);
1079 if (slotz
== slotv
|| slotz
== slotw
)
1083 if (x
!= Py_NotImplemented
)
1085 Py_DECREF(x
); /* can't do it */
1089 if (!NEW_STYLE_NUMBER(v
) || !NEW_STYLE_NUMBER(w
) ||
1090 (z
!= Py_None
&& !NEW_STYLE_NUMBER(z
))) {
1091 /* we have an old style operand, coerce */
1092 PyObject
*v1
, *z1
, *w2
, *z2
;
1095 c
= PyNumber_Coerce(&v
, &w
);
1099 /* Special case: if the third argument is None, it is
1100 treated as absent argument and not coerced. */
1102 if (v
->ob_type
->tp_as_number
) {
1103 slotz
= NB_TERNOP(v
->ob_type
->tp_as_number
,
1116 c
= PyNumber_Coerce(&v1
, &z1
);
1121 c
= PyNumber_Coerce(&w2
, &z2
);
1125 if (v1
->ob_type
->tp_as_number
!= NULL
) {
1126 slotv
= NB_TERNOP(v1
->ob_type
->tp_as_number
,
1129 x
= slotv(v1
, w2
, z2
);
1152 "unsupported operand type(s) for ** or pow(): "
1153 "'%.100s' and '%.100s'",
1154 v
->ob_type
->tp_name
,
1155 w
->ob_type
->tp_name
);
1159 "unsupported operand type(s) for pow(): "
1160 "'%.100s', '%.100s', '%.100s'",
1161 v
->ob_type
->tp_name
,
1162 w
->ob_type
->tp_name
,
1163 z
->ob_type
->tp_name
);
1167 #define BINARY_FUNC(func, op, op_name) \
1169 func(PyObject *v, PyObject *w) { \
1170 return binary_op(v, w, NB_SLOT(op), op_name); \
1173 BINARY_FUNC(PyNumber_Or
, nb_or
, "|")
1174 BINARY_FUNC(PyNumber_Xor
, nb_xor
, "^")
1175 BINARY_FUNC(PyNumber_And
, nb_and
, "&")
1176 BINARY_FUNC(PyNumber_Lshift
, nb_lshift
, "<<")
1177 BINARY_FUNC(PyNumber_Rshift
, nb_rshift
, ">>")
1178 BINARY_FUNC(PyNumber_Subtract
, nb_subtract
, "-")
1179 BINARY_FUNC(PyNumber_Divide
, nb_divide
, "/")
1180 BINARY_FUNC(PyNumber_Divmod
, nb_divmod
, "divmod()")
1183 PyNumber_Add(PyObject
*v
, PyObject
*w
)
1185 PyObject
*result
= binary_op1(v
, w
, NB_SLOT(nb_add
));
1186 if (result
== Py_NotImplemented
) {
1187 PySequenceMethods
*m
= v
->ob_type
->tp_as_sequence
;
1189 if (m
&& m
->sq_concat
) {
1190 return (*m
->sq_concat
)(v
, w
);
1192 result
= binop_type_error(v
, w
, "+");
1198 sequence_repeat(ssizeargfunc repeatfunc
, PyObject
*seq
, PyObject
*n
)
1201 if (PyIndex_Check(n
)) {
1202 count
= PyNumber_AsSsize_t(n
, PyExc_OverflowError
);
1203 if (count
== -1 && PyErr_Occurred())
1207 return type_error("can't multiply sequence by "
1208 "non-int of type '%.200s'", n
);
1210 return (*repeatfunc
)(seq
, count
);
1214 PyNumber_Multiply(PyObject
*v
, PyObject
*w
)
1216 PyObject
*result
= binary_op1(v
, w
, NB_SLOT(nb_multiply
));
1217 if (result
== Py_NotImplemented
) {
1218 PySequenceMethods
*mv
= v
->ob_type
->tp_as_sequence
;
1219 PySequenceMethods
*mw
= w
->ob_type
->tp_as_sequence
;
1221 if (mv
&& mv
->sq_repeat
) {
1222 return sequence_repeat(mv
->sq_repeat
, v
, w
);
1224 else if (mw
&& mw
->sq_repeat
) {
1225 return sequence_repeat(mw
->sq_repeat
, w
, v
);
1227 result
= binop_type_error(v
, w
, "*");
1233 PyNumber_FloorDivide(PyObject
*v
, PyObject
*w
)
1235 /* XXX tp_flags test */
1236 return binary_op(v
, w
, NB_SLOT(nb_floor_divide
), "//");
1240 PyNumber_TrueDivide(PyObject
*v
, PyObject
*w
)
1242 /* XXX tp_flags test */
1243 return binary_op(v
, w
, NB_SLOT(nb_true_divide
), "/");
1247 PyNumber_Remainder(PyObject
*v
, PyObject
*w
)
1249 return binary_op(v
, w
, NB_SLOT(nb_remainder
), "%");
1253 PyNumber_Power(PyObject
*v
, PyObject
*w
, PyObject
*z
)
1255 return ternary_op(v
, w
, z
, NB_SLOT(nb_power
), "** or pow()");
1258 /* Binary in-place operators */
1260 /* The in-place operators are defined to fall back to the 'normal',
1261 non in-place operations, if the in-place methods are not in place.
1263 - If the left hand object has the appropriate struct members, and
1264 they are filled, call the appropriate function and return the
1265 result. No coercion is done on the arguments; the left-hand object
1266 is the one the operation is performed on, and it's up to the
1267 function to deal with the right-hand object.
1269 - Otherwise, in-place modification is not supported. Handle it exactly as
1270 a non in-place operation of the same kind.
1274 #define HASINPLACE(t) \
1275 PyType_HasFeature((t)->ob_type, Py_TPFLAGS_HAVE_INPLACEOPS)
1278 binary_iop1(PyObject
*v
, PyObject
*w
, const int iop_slot
, const int op_slot
)
1280 PyNumberMethods
*mv
= v
->ob_type
->tp_as_number
;
1281 if (mv
!= NULL
&& HASINPLACE(v
)) {
1282 binaryfunc slot
= NB_BINOP(mv
, iop_slot
);
1284 PyObject
*x
= (slot
)(v
, w
);
1285 if (x
!= Py_NotImplemented
) {
1291 return binary_op1(v
, w
, op_slot
);
1295 binary_iop(PyObject
*v
, PyObject
*w
, const int iop_slot
, const int op_slot
,
1296 const char *op_name
)
1298 PyObject
*result
= binary_iop1(v
, w
, iop_slot
, op_slot
);
1299 if (result
== Py_NotImplemented
) {
1301 return binop_type_error(v
, w
, op_name
);
1306 #define INPLACE_BINOP(func, iop, op, op_name) \
1308 func(PyObject *v, PyObject *w) { \
1309 return binary_iop(v, w, NB_SLOT(iop), NB_SLOT(op), op_name); \
1312 INPLACE_BINOP(PyNumber_InPlaceOr
, nb_inplace_or
, nb_or
, "|=")
1313 INPLACE_BINOP(PyNumber_InPlaceXor
, nb_inplace_xor
, nb_xor
, "^=")
1314 INPLACE_BINOP(PyNumber_InPlaceAnd
, nb_inplace_and
, nb_and
, "&=")
1315 INPLACE_BINOP(PyNumber_InPlaceLshift
, nb_inplace_lshift
, nb_lshift
, "<<=")
1316 INPLACE_BINOP(PyNumber_InPlaceRshift
, nb_inplace_rshift
, nb_rshift
, ">>=")
1317 INPLACE_BINOP(PyNumber_InPlaceSubtract
, nb_inplace_subtract
, nb_subtract
, "-=")
1318 INPLACE_BINOP(PyNumber_InPlaceDivide
, nb_inplace_divide
, nb_divide
, "/=")
1321 PyNumber_InPlaceFloorDivide(PyObject
*v
, PyObject
*w
)
1323 /* XXX tp_flags test */
1324 return binary_iop(v
, w
, NB_SLOT(nb_inplace_floor_divide
),
1325 NB_SLOT(nb_floor_divide
), "//=");
1329 PyNumber_InPlaceTrueDivide(PyObject
*v
, PyObject
*w
)
1331 /* XXX tp_flags test */
1332 return binary_iop(v
, w
, NB_SLOT(nb_inplace_true_divide
),
1333 NB_SLOT(nb_true_divide
), "/=");
1337 PyNumber_InPlaceAdd(PyObject
*v
, PyObject
*w
)
1339 PyObject
*result
= binary_iop1(v
, w
, NB_SLOT(nb_inplace_add
),
1341 if (result
== Py_NotImplemented
) {
1342 PySequenceMethods
*m
= v
->ob_type
->tp_as_sequence
;
1345 binaryfunc f
= NULL
;
1347 f
= m
->sq_inplace_concat
;
1353 result
= binop_type_error(v
, w
, "+=");
1359 PyNumber_InPlaceMultiply(PyObject
*v
, PyObject
*w
)
1361 PyObject
*result
= binary_iop1(v
, w
, NB_SLOT(nb_inplace_multiply
),
1362 NB_SLOT(nb_multiply
));
1363 if (result
== Py_NotImplemented
) {
1364 ssizeargfunc f
= NULL
;
1365 PySequenceMethods
*mv
= v
->ob_type
->tp_as_sequence
;
1366 PySequenceMethods
*mw
= w
->ob_type
->tp_as_sequence
;
1370 f
= mv
->sq_inplace_repeat
;
1374 return sequence_repeat(f
, v
, w
);
1376 else if (mw
!= NULL
) {
1377 /* Note that the right hand operand should not be
1378 * mutated in this case so sq_inplace_repeat is not
1381 return sequence_repeat(mw
->sq_repeat
, w
, v
);
1383 result
= binop_type_error(v
, w
, "*=");
1389 PyNumber_InPlaceRemainder(PyObject
*v
, PyObject
*w
)
1391 return binary_iop(v
, w
, NB_SLOT(nb_inplace_remainder
),
1392 NB_SLOT(nb_remainder
), "%=");
1396 PyNumber_InPlacePower(PyObject
*v
, PyObject
*w
, PyObject
*z
)
1398 if (HASINPLACE(v
) && v
->ob_type
->tp_as_number
&&
1399 v
->ob_type
->tp_as_number
->nb_inplace_power
!= NULL
) {
1400 return ternary_op(v
, w
, z
, NB_SLOT(nb_inplace_power
), "**=");
1403 return ternary_op(v
, w
, z
, NB_SLOT(nb_power
), "**=");
1408 /* Unary operators and functions */
1411 PyNumber_Negative(PyObject
*o
)
1416 return null_error();
1417 m
= o
->ob_type
->tp_as_number
;
1418 if (m
&& m
->nb_negative
)
1419 return (*m
->nb_negative
)(o
);
1421 return type_error("bad operand type for unary -: '%.200s'", o
);
1425 PyNumber_Positive(PyObject
*o
)
1430 return null_error();
1431 m
= o
->ob_type
->tp_as_number
;
1432 if (m
&& m
->nb_positive
)
1433 return (*m
->nb_positive
)(o
);
1435 return type_error("bad operand type for unary +: '%.200s'", o
);
1439 PyNumber_Invert(PyObject
*o
)
1444 return null_error();
1445 m
= o
->ob_type
->tp_as_number
;
1446 if (m
&& m
->nb_invert
)
1447 return (*m
->nb_invert
)(o
);
1449 return type_error("bad operand type for unary ~: '%.200s'", o
);
1453 PyNumber_Absolute(PyObject
*o
)
1458 return null_error();
1459 m
= o
->ob_type
->tp_as_number
;
1460 if (m
&& m
->nb_absolute
)
1461 return m
->nb_absolute(o
);
1463 return type_error("bad operand type for abs(): '%.200s'", o
);
1466 /* Add a check for embedded NULL-bytes in the argument. */
1468 int_from_string(const char *s
, Py_ssize_t len
)
1473 x
= PyInt_FromString((char*)s
, &end
, 10);
1476 if (end
!= s
+ len
) {
1477 PyErr_SetString(PyExc_ValueError
,
1478 "null byte in argument for int()");
1485 /* Return a Python Int or Long from the object item
1486 Raise TypeError if the result is not an int-or-long
1487 or if the object cannot be interpreted as an index.
1490 PyNumber_Index(PyObject
*item
)
1492 PyObject
*result
= NULL
;
1494 return null_error();
1495 if (PyInt_Check(item
) || PyLong_Check(item
)) {
1499 if (PyIndex_Check(item
)) {
1500 result
= item
->ob_type
->tp_as_number
->nb_index(item
);
1502 !PyInt_Check(result
) && !PyLong_Check(result
)) {
1503 PyErr_Format(PyExc_TypeError
,
1504 "__index__ returned non-(int,long) " \
1506 result
->ob_type
->tp_name
);
1512 PyErr_Format(PyExc_TypeError
,
1513 "'%.200s' object cannot be interpreted "
1514 "as an index", item
->ob_type
->tp_name
);
1519 /* Return an error on Overflow only if err is not NULL*/
1522 PyNumber_AsSsize_t(PyObject
*item
, PyObject
*err
)
1526 PyObject
*value
= PyNumber_Index(item
);
1530 /* We're done if PyInt_AsSsize_t() returns without error. */
1531 result
= PyInt_AsSsize_t(value
);
1532 if (result
!= -1 || !(runerr
= PyErr_Occurred()))
1535 /* Error handling code -- only manage OverflowError differently */
1536 if (!PyErr_GivenExceptionMatches(runerr
, PyExc_OverflowError
))
1540 /* If no error-handling desired then the default clipping
1544 assert(PyLong_Check(value
));
1545 /* Whether or not it is less than or equal to
1546 zero is determined by the sign of ob_size
1548 if (_PyLong_Sign(value
) < 0)
1549 result
= PY_SSIZE_T_MIN
;
1551 result
= PY_SSIZE_T_MAX
;
1554 /* Otherwise replace the error with caller's error object. */
1556 "cannot fit '%.200s' into an index-sized integer",
1557 item
->ob_type
->tp_name
);
1567 _PyNumber_ConvertIntegralToInt(PyObject
*integral
, const char* error_format
)
1569 const char *type_name
;
1570 static PyObject
*int_name
= NULL
;
1571 if (int_name
== NULL
) {
1572 int_name
= PyString_InternFromString("__int__");
1573 if (int_name
== NULL
)
1577 if (integral
&& (!PyInt_Check(integral
) &&
1578 !PyLong_Check(integral
))) {
1579 /* Don't go through tp_as_number->nb_int to avoid
1580 hitting the classic class fallback to __trunc__. */
1581 PyObject
*int_func
= PyObject_GetAttr(integral
, int_name
);
1582 if (int_func
== NULL
) {
1583 PyErr_Clear(); /* Raise a different error. */
1584 goto non_integral_error
;
1586 Py_DECREF(integral
);
1587 integral
= PyEval_CallObject(int_func
, NULL
);
1588 Py_DECREF(int_func
);
1589 if (integral
&& (!PyInt_Check(integral
) &&
1590 !PyLong_Check(integral
))) {
1591 goto non_integral_error
;
1597 if (PyInstance_Check(integral
)) {
1598 type_name
= PyString_AS_STRING(((PyInstanceObject
*)integral
)
1599 ->in_class
->cl_name
);
1602 type_name
= integral
->ob_type
->tp_name
;
1604 PyErr_Format(PyExc_TypeError
, error_format
, type_name
);
1605 Py_DECREF(integral
);
1611 PyNumber_Int(PyObject
*o
)
1614 static PyObject
*trunc_name
= NULL
;
1615 PyObject
*trunc_func
;
1617 Py_ssize_t buffer_len
;
1619 if (trunc_name
== NULL
) {
1620 trunc_name
= PyString_InternFromString("__trunc__");
1621 if (trunc_name
== NULL
)
1626 return null_error();
1627 if (PyInt_CheckExact(o
)) {
1631 m
= o
->ob_type
->tp_as_number
;
1632 if (m
&& m
->nb_int
) { /* This should include subclasses of int */
1633 /* Classic classes always take this branch. */
1634 PyObject
*res
= m
->nb_int(o
);
1635 if (res
&& (!PyInt_Check(res
) && !PyLong_Check(res
))) {
1636 PyErr_Format(PyExc_TypeError
,
1637 "__int__ returned non-int (type %.200s)",
1638 res
->ob_type
->tp_name
);
1644 if (PyInt_Check(o
)) { /* A int subclass without nb_int */
1645 PyIntObject
*io
= (PyIntObject
*)o
;
1646 return PyInt_FromLong(io
->ob_ival
);
1648 trunc_func
= PyObject_GetAttr(o
, trunc_name
);
1650 PyObject
*truncated
= PyEval_CallObject(trunc_func
, NULL
);
1651 Py_DECREF(trunc_func
);
1652 /* __trunc__ is specified to return an Integral type, but
1653 int() needs to return an int. */
1654 return _PyNumber_ConvertIntegralToInt(
1656 "__trunc__ returned non-Integral (type %.200s)");
1658 PyErr_Clear(); /* It's not an error if o.__trunc__ doesn't exist. */
1660 if (PyString_Check(o
))
1661 return int_from_string(PyString_AS_STRING(o
),
1662 PyString_GET_SIZE(o
));
1663 #ifdef Py_USING_UNICODE
1664 if (PyUnicode_Check(o
))
1665 return PyInt_FromUnicode(PyUnicode_AS_UNICODE(o
),
1666 PyUnicode_GET_SIZE(o
),
1669 if (!PyObject_AsCharBuffer(o
, &buffer
, &buffer_len
))
1670 return int_from_string((char*)buffer
, buffer_len
);
1672 return type_error("int() argument must be a string or a "
1673 "number, not '%.200s'", o
);
1676 /* Add a check for embedded NULL-bytes in the argument. */
1678 long_from_string(const char *s
, Py_ssize_t len
)
1683 x
= PyLong_FromString((char*)s
, &end
, 10);
1686 if (end
!= s
+ len
) {
1687 PyErr_SetString(PyExc_ValueError
,
1688 "null byte in argument for long()");
1696 PyNumber_Long(PyObject
*o
)
1699 static PyObject
*trunc_name
= NULL
;
1700 PyObject
*trunc_func
;
1702 Py_ssize_t buffer_len
;
1704 if (trunc_name
== NULL
) {
1705 trunc_name
= PyString_InternFromString("__trunc__");
1706 if (trunc_name
== NULL
)
1711 return null_error();
1712 m
= o
->ob_type
->tp_as_number
;
1713 if (m
&& m
->nb_long
) { /* This should include subclasses of long */
1714 /* Classic classes always take this branch. */
1715 PyObject
*res
= m
->nb_long(o
);
1716 if (res
&& (!PyInt_Check(res
) && !PyLong_Check(res
))) {
1717 PyErr_Format(PyExc_TypeError
,
1718 "__long__ returned non-long (type %.200s)",
1719 res
->ob_type
->tp_name
);
1725 if (PyLong_Check(o
)) /* A long subclass without nb_long */
1726 return _PyLong_Copy((PyLongObject
*)o
);
1727 trunc_func
= PyObject_GetAttr(o
, trunc_name
);
1729 PyObject
*truncated
= PyEval_CallObject(trunc_func
, NULL
);
1730 PyObject
*int_instance
;
1731 Py_DECREF(trunc_func
);
1732 /* __trunc__ is specified to return an Integral type,
1733 but long() needs to return a long. */
1734 int_instance
= _PyNumber_ConvertIntegralToInt(
1736 "__trunc__ returned non-Integral (type %.200s)");
1737 if (int_instance
&& PyInt_Check(int_instance
)) {
1738 /* Make sure that long() returns a long instance. */
1739 long value
= PyInt_AS_LONG(int_instance
);
1740 Py_DECREF(int_instance
);
1741 return PyLong_FromLong(value
);
1743 return int_instance
;
1745 PyErr_Clear(); /* It's not an error if o.__trunc__ doesn't exist. */
1747 if (PyString_Check(o
))
1748 /* need to do extra error checking that PyLong_FromString()
1749 * doesn't do. In particular long('9.5') must raise an
1750 * exception, not truncate the float.
1752 return long_from_string(PyString_AS_STRING(o
),
1753 PyString_GET_SIZE(o
));
1754 #ifdef Py_USING_UNICODE
1755 if (PyUnicode_Check(o
))
1756 /* The above check is done in PyLong_FromUnicode(). */
1757 return PyLong_FromUnicode(PyUnicode_AS_UNICODE(o
),
1758 PyUnicode_GET_SIZE(o
),
1761 if (!PyObject_AsCharBuffer(o
, &buffer
, &buffer_len
))
1762 return long_from_string(buffer
, buffer_len
);
1764 return type_error("long() argument must be a string or a "
1765 "number, not '%.200s'", o
);
1769 PyNumber_Float(PyObject
*o
)
1774 return null_error();
1775 m
= o
->ob_type
->tp_as_number
;
1776 if (m
&& m
->nb_float
) { /* This should include subclasses of float */
1777 PyObject
*res
= m
->nb_float(o
);
1778 if (res
&& !PyFloat_Check(res
)) {
1779 PyErr_Format(PyExc_TypeError
,
1780 "__float__ returned non-float (type %.200s)",
1781 res
->ob_type
->tp_name
);
1787 if (PyFloat_Check(o
)) { /* A float subclass with nb_float == NULL */
1788 PyFloatObject
*po
= (PyFloatObject
*)o
;
1789 return PyFloat_FromDouble(po
->ob_fval
);
1791 return PyFloat_FromString(o
, NULL
);
1795 PyNumber_ToBase(PyObject
*n
, int base
)
1797 PyObject
*res
= NULL
;
1798 PyObject
*index
= PyNumber_Index(n
);
1802 if (PyLong_Check(index
))
1803 res
= _PyLong_Format(index
, base
, 0, 1);
1804 else if (PyInt_Check(index
))
1805 res
= _PyInt_Format((PyIntObject
*)index
, base
, 1);
1807 /* It should not be possible to get here, as
1808 PyNumber_Index already has a check for the same
1810 PyErr_SetString(PyExc_ValueError
, "PyNumber_ToBase: index not "
1817 /* Operations on sequences */
1820 PySequence_Check(PyObject
*s
)
1824 if (PyInstance_Check(s
))
1825 return PyObject_HasAttrString(s
, "__getitem__");
1826 if (PyDict_Check(s
))
1828 return s
->ob_type
->tp_as_sequence
&&
1829 s
->ob_type
->tp_as_sequence
->sq_item
!= NULL
;
1833 PySequence_Size(PyObject
*s
)
1835 PySequenceMethods
*m
;
1842 m
= s
->ob_type
->tp_as_sequence
;
1843 if (m
&& m
->sq_length
)
1844 return m
->sq_length(s
);
1846 type_error("object of type '%.200s' has no len()", s
);
1850 #undef PySequence_Length
1852 PySequence_Length(PyObject
*s
)
1854 return PySequence_Size(s
);
1856 #define PySequence_Length PySequence_Size
1859 PySequence_Concat(PyObject
*s
, PyObject
*o
)
1861 PySequenceMethods
*m
;
1863 if (s
== NULL
|| o
== NULL
)
1864 return null_error();
1866 m
= s
->ob_type
->tp_as_sequence
;
1867 if (m
&& m
->sq_concat
)
1868 return m
->sq_concat(s
, o
);
1870 /* Instances of user classes defining an __add__() method only
1871 have an nb_add slot, not an sq_concat slot. So we fall back
1872 to nb_add if both arguments appear to be sequences. */
1873 if (PySequence_Check(s
) && PySequence_Check(o
)) {
1874 PyObject
*result
= binary_op1(s
, o
, NB_SLOT(nb_add
));
1875 if (result
!= Py_NotImplemented
)
1879 return type_error("'%.200s' object can't be concatenated", s
);
1883 PySequence_Repeat(PyObject
*o
, Py_ssize_t count
)
1885 PySequenceMethods
*m
;
1888 return null_error();
1890 m
= o
->ob_type
->tp_as_sequence
;
1891 if (m
&& m
->sq_repeat
)
1892 return m
->sq_repeat(o
, count
);
1894 /* Instances of user classes defining a __mul__() method only
1895 have an nb_multiply slot, not an sq_repeat slot. so we fall back
1896 to nb_multiply if o appears to be a sequence. */
1897 if (PySequence_Check(o
)) {
1898 PyObject
*n
, *result
;
1899 n
= PyInt_FromSsize_t(count
);
1902 result
= binary_op1(o
, n
, NB_SLOT(nb_multiply
));
1904 if (result
!= Py_NotImplemented
)
1908 return type_error("'%.200s' object can't be repeated", o
);
1912 PySequence_InPlaceConcat(PyObject
*s
, PyObject
*o
)
1914 PySequenceMethods
*m
;
1916 if (s
== NULL
|| o
== NULL
)
1917 return null_error();
1919 m
= s
->ob_type
->tp_as_sequence
;
1920 if (m
&& HASINPLACE(s
) && m
->sq_inplace_concat
)
1921 return m
->sq_inplace_concat(s
, o
);
1922 if (m
&& m
->sq_concat
)
1923 return m
->sq_concat(s
, o
);
1925 if (PySequence_Check(s
) && PySequence_Check(o
)) {
1926 PyObject
*result
= binary_iop1(s
, o
, NB_SLOT(nb_inplace_add
),
1928 if (result
!= Py_NotImplemented
)
1932 return type_error("'%.200s' object can't be concatenated", s
);
1936 PySequence_InPlaceRepeat(PyObject
*o
, Py_ssize_t count
)
1938 PySequenceMethods
*m
;
1941 return null_error();
1943 m
= o
->ob_type
->tp_as_sequence
;
1944 if (m
&& HASINPLACE(o
) && m
->sq_inplace_repeat
)
1945 return m
->sq_inplace_repeat(o
, count
);
1946 if (m
&& m
->sq_repeat
)
1947 return m
->sq_repeat(o
, count
);
1949 if (PySequence_Check(o
)) {
1950 PyObject
*n
, *result
;
1951 n
= PyInt_FromSsize_t(count
);
1954 result
= binary_iop1(o
, n
, NB_SLOT(nb_inplace_multiply
),
1955 NB_SLOT(nb_multiply
));
1957 if (result
!= Py_NotImplemented
)
1961 return type_error("'%.200s' object can't be repeated", o
);
1965 PySequence_GetItem(PyObject
*s
, Py_ssize_t i
)
1967 PySequenceMethods
*m
;
1970 return null_error();
1972 m
= s
->ob_type
->tp_as_sequence
;
1973 if (m
&& m
->sq_item
) {
1976 Py_ssize_t l
= (*m
->sq_length
)(s
);
1982 return m
->sq_item(s
, i
);
1985 return type_error("'%.200s' object does not support indexing", s
);
1989 PySequence_GetSlice(PyObject
*s
, Py_ssize_t i1
, Py_ssize_t i2
)
1991 PySequenceMethods
*m
;
1992 PyMappingMethods
*mp
;
1994 if (!s
) return null_error();
1996 m
= s
->ob_type
->tp_as_sequence
;
1997 if (m
&& m
->sq_slice
) {
1998 if (i1
< 0 || i2
< 0) {
2000 Py_ssize_t l
= (*m
->sq_length
)(s
);
2009 return m
->sq_slice(s
, i1
, i2
);
2010 } else if ((mp
= s
->ob_type
->tp_as_mapping
) && mp
->mp_subscript
) {
2012 PyObject
*slice
= _PySlice_FromIndices(i1
, i2
);
2015 res
= mp
->mp_subscript(s
, slice
);
2020 return type_error("'%.200s' object is unsliceable", s
);
2024 PySequence_SetItem(PyObject
*s
, Py_ssize_t i
, PyObject
*o
)
2026 PySequenceMethods
*m
;
2033 m
= s
->ob_type
->tp_as_sequence
;
2034 if (m
&& m
->sq_ass_item
) {
2037 Py_ssize_t l
= (*m
->sq_length
)(s
);
2043 return m
->sq_ass_item(s
, i
, o
);
2046 type_error("'%.200s' object does not support item assignment", s
);
2051 PySequence_DelItem(PyObject
*s
, Py_ssize_t i
)
2053 PySequenceMethods
*m
;
2060 m
= s
->ob_type
->tp_as_sequence
;
2061 if (m
&& m
->sq_ass_item
) {
2064 Py_ssize_t l
= (*m
->sq_length
)(s
);
2070 return m
->sq_ass_item(s
, i
, (PyObject
*)NULL
);
2073 type_error("'%.200s' object doesn't support item deletion", s
);
2078 PySequence_SetSlice(PyObject
*s
, Py_ssize_t i1
, Py_ssize_t i2
, PyObject
*o
)
2080 PySequenceMethods
*m
;
2081 PyMappingMethods
*mp
;
2088 m
= s
->ob_type
->tp_as_sequence
;
2089 if (m
&& m
->sq_ass_slice
) {
2090 if (i1
< 0 || i2
< 0) {
2092 Py_ssize_t l
= (*m
->sq_length
)(s
);
2101 return m
->sq_ass_slice(s
, i1
, i2
, o
);
2102 } else if ((mp
= s
->ob_type
->tp_as_mapping
) && mp
->mp_ass_subscript
) {
2104 PyObject
*slice
= _PySlice_FromIndices(i1
, i2
);
2107 res
= mp
->mp_ass_subscript(s
, slice
, o
);
2112 type_error("'%.200s' object doesn't support slice assignment", s
);
2117 PySequence_DelSlice(PyObject
*s
, Py_ssize_t i1
, Py_ssize_t i2
)
2119 PySequenceMethods
*m
;
2126 m
= s
->ob_type
->tp_as_sequence
;
2127 if (m
&& m
->sq_ass_slice
) {
2128 if (i1
< 0 || i2
< 0) {
2130 Py_ssize_t l
= (*m
->sq_length
)(s
);
2139 return m
->sq_ass_slice(s
, i1
, i2
, (PyObject
*)NULL
);
2141 type_error("'%.200s' object doesn't support slice deletion", s
);
2146 PySequence_Tuple(PyObject
*v
)
2148 PyObject
*it
; /* iter(v) */
2149 Py_ssize_t n
; /* guess for result tuple size */
2150 PyObject
*result
= NULL
;
2154 return null_error();
2156 /* Special-case the common tuple and list cases, for efficiency. */
2157 if (PyTuple_CheckExact(v
)) {
2158 /* Note that we can't know whether it's safe to return
2159 a tuple *subclass* instance as-is, hence the restriction
2160 to exact tuples here. In contrast, lists always make
2161 a copy, so there's no need for exactness below. */
2165 if (PyList_Check(v
))
2166 return PyList_AsTuple(v
);
2169 it
= PyObject_GetIter(v
);
2173 /* Guess result size and allocate space. */
2174 n
= _PyObject_LengthHint(v
, 10);
2177 result
= PyTuple_New(n
);
2181 /* Fill the tuple. */
2182 for (j
= 0; ; ++j
) {
2183 PyObject
*item
= PyIter_Next(it
);
2185 if (PyErr_Occurred())
2190 Py_ssize_t oldn
= n
;
2191 /* The over-allocation strategy can grow a bit faster
2192 than for lists because unlike lists the
2193 over-allocation isn't permanent -- we reclaim
2194 the excess before the end of this routine.
2195 So, grow by ten and then add 25%.
2200 /* Check for overflow */
2205 if (_PyTuple_Resize(&result
, n
) != 0) {
2210 PyTuple_SET_ITEM(result
, j
, item
);
2213 /* Cut tuple back if guess was too large. */
2215 _PyTuple_Resize(&result
, j
) != 0)
2228 PySequence_List(PyObject
*v
)
2230 PyObject
*result
; /* result list */
2231 PyObject
*rv
; /* return value from PyList_Extend */
2234 return null_error();
2236 result
= PyList_New(0);
2240 rv
= _PyList_Extend((PyListObject
*)result
, v
);
2250 PySequence_Fast(PyObject
*v
, const char *m
)
2255 return null_error();
2257 if (PyList_CheckExact(v
) || PyTuple_CheckExact(v
)) {
2262 it
= PyObject_GetIter(v
);
2264 if (PyErr_ExceptionMatches(PyExc_TypeError
))
2265 PyErr_SetString(PyExc_TypeError
, m
);
2269 v
= PySequence_List(it
);
2275 /* Iterate over seq. Result depends on the operation:
2276 PY_ITERSEARCH_COUNT: -1 if error, else # of times obj appears in seq.
2277 PY_ITERSEARCH_INDEX: 0-based index of first occurrence of obj in seq;
2278 set ValueError and return -1 if none found; also return -1 on error.
2279 Py_ITERSEARCH_CONTAINS: return 1 if obj in seq, else 0; -1 on error.
2282 _PySequence_IterSearch(PyObject
*seq
, PyObject
*obj
, int operation
)
2285 int wrapped
; /* for PY_ITERSEARCH_INDEX, true iff n wrapped around */
2286 PyObject
*it
; /* iter(seq) */
2288 if (seq
== NULL
|| obj
== NULL
) {
2293 it
= PyObject_GetIter(seq
);
2295 type_error("argument of type '%.200s' is not iterable", seq
);
2302 PyObject
*item
= PyIter_Next(it
);
2304 if (PyErr_Occurred())
2309 cmp
= PyObject_RichCompareBool(obj
, item
, Py_EQ
);
2314 switch (operation
) {
2315 case PY_ITERSEARCH_COUNT
:
2316 if (n
== PY_SSIZE_T_MAX
) {
2317 PyErr_SetString(PyExc_OverflowError
,
2318 "count exceeds C integer size");
2324 case PY_ITERSEARCH_INDEX
:
2326 PyErr_SetString(PyExc_OverflowError
,
2327 "index exceeds C integer size");
2332 case PY_ITERSEARCH_CONTAINS
:
2337 assert(!"unknown operation");
2341 if (operation
== PY_ITERSEARCH_INDEX
) {
2342 if (n
== PY_SSIZE_T_MAX
)
2348 if (operation
!= PY_ITERSEARCH_INDEX
)
2351 PyErr_SetString(PyExc_ValueError
,
2352 "sequence.index(x): x not in sequence");
2353 /* fall into failure code */
2363 /* Return # of times o appears in s. */
2365 PySequence_Count(PyObject
*s
, PyObject
*o
)
2367 return _PySequence_IterSearch(s
, o
, PY_ITERSEARCH_COUNT
);
2370 /* Return -1 if error; 1 if ob in seq; 0 if ob not in seq.
2371 * Use sq_contains if possible, else defer to _PySequence_IterSearch().
2374 PySequence_Contains(PyObject
*seq
, PyObject
*ob
)
2377 if (PyType_HasFeature(seq
->ob_type
, Py_TPFLAGS_HAVE_SEQUENCE_IN
)) {
2378 PySequenceMethods
*sqm
= seq
->ob_type
->tp_as_sequence
;
2379 if (sqm
!= NULL
&& sqm
->sq_contains
!= NULL
)
2380 return (*sqm
->sq_contains
)(seq
, ob
);
2382 result
= _PySequence_IterSearch(seq
, ob
, PY_ITERSEARCH_CONTAINS
);
2383 return Py_SAFE_DOWNCAST(result
, Py_ssize_t
, int);
2386 /* Backwards compatibility */
2387 #undef PySequence_In
2389 PySequence_In(PyObject
*w
, PyObject
*v
)
2391 return PySequence_Contains(w
, v
);
2395 PySequence_Index(PyObject
*s
, PyObject
*o
)
2397 return _PySequence_IterSearch(s
, o
, PY_ITERSEARCH_INDEX
);
2400 /* Operations on mappings */
2403 PyMapping_Check(PyObject
*o
)
2405 if (o
&& PyInstance_Check(o
))
2406 return PyObject_HasAttrString(o
, "__getitem__");
2408 return o
&& o
->ob_type
->tp_as_mapping
&&
2409 o
->ob_type
->tp_as_mapping
->mp_subscript
&&
2410 !(o
->ob_type
->tp_as_sequence
&&
2411 o
->ob_type
->tp_as_sequence
->sq_slice
);
2415 PyMapping_Size(PyObject
*o
)
2417 PyMappingMethods
*m
;
2424 m
= o
->ob_type
->tp_as_mapping
;
2425 if (m
&& m
->mp_length
)
2426 return m
->mp_length(o
);
2428 type_error("object of type '%.200s' has no len()", o
);
2432 #undef PyMapping_Length
2434 PyMapping_Length(PyObject
*o
)
2436 return PyMapping_Size(o
);
2438 #define PyMapping_Length PyMapping_Size
2441 PyMapping_GetItemString(PyObject
*o
, char *key
)
2446 return null_error();
2448 okey
= PyString_FromString(key
);
2451 r
= PyObject_GetItem(o
, okey
);
2457 PyMapping_SetItemString(PyObject
*o
, char *key
, PyObject
*value
)
2467 okey
= PyString_FromString(key
);
2470 r
= PyObject_SetItem(o
, okey
, value
);
2476 PyMapping_HasKeyString(PyObject
*o
, char *key
)
2480 v
= PyMapping_GetItemString(o
, key
);
2490 PyMapping_HasKey(PyObject
*o
, PyObject
*key
)
2494 v
= PyObject_GetItem(o
, key
);
2503 /* Operations on callable objects */
2505 /* XXX PyCallable_Check() is in object.c */
2508 PyObject_CallObject(PyObject
*o
, PyObject
*a
)
2510 return PyEval_CallObjectWithKeywords(o
, a
, NULL
);
2514 PyObject_Call(PyObject
*func
, PyObject
*arg
, PyObject
*kw
)
2518 if ((call
= func
->ob_type
->tp_call
) != NULL
) {
2520 if (Py_EnterRecursiveCall(" while calling a Python object"))
2522 result
= (*call
)(func
, arg
, kw
);
2523 Py_LeaveRecursiveCall();
2524 if (result
== NULL
&& !PyErr_Occurred())
2527 "NULL result without error in PyObject_Call");
2530 PyErr_Format(PyExc_TypeError
, "'%.200s' object is not callable",
2531 func
->ob_type
->tp_name
);
2536 call_function_tail(PyObject
*callable
, PyObject
*args
)
2543 if (!PyTuple_Check(args
)) {
2551 PyTuple_SET_ITEM(a
, 0, args
);
2554 retval
= PyObject_Call(callable
, args
, NULL
);
2562 PyObject_CallFunction(PyObject
*callable
, char *format
, ...)
2567 if (callable
== NULL
)
2568 return null_error();
2570 if (format
&& *format
) {
2571 va_start(va
, format
);
2572 args
= Py_VaBuildValue(format
, va
);
2576 args
= PyTuple_New(0);
2578 return call_function_tail(callable
, args
);
2582 _PyObject_CallFunction_SizeT(PyObject
*callable
, char *format
, ...)
2587 if (callable
== NULL
)
2588 return null_error();
2590 if (format
&& *format
) {
2591 va_start(va
, format
);
2592 args
= _Py_VaBuildValue_SizeT(format
, va
);
2596 args
= PyTuple_New(0);
2598 return call_function_tail(callable
, args
);
2602 PyObject_CallMethod(PyObject
*o
, char *name
, char *format
, ...)
2606 PyObject
*func
= NULL
;
2607 PyObject
*retval
= NULL
;
2609 if (o
== NULL
|| name
== NULL
)
2610 return null_error();
2612 func
= PyObject_GetAttrString(o
, name
);
2614 PyErr_SetString(PyExc_AttributeError
, name
);
2618 if (!PyCallable_Check(func
)) {
2619 type_error("attribute of type '%.200s' is not callable", func
);
2623 if (format
&& *format
) {
2624 va_start(va
, format
);
2625 args
= Py_VaBuildValue(format
, va
);
2629 args
= PyTuple_New(0);
2631 retval
= call_function_tail(func
, args
);
2634 /* args gets consumed in call_function_tail */
2641 _PyObject_CallMethod_SizeT(PyObject
*o
, char *name
, char *format
, ...)
2645 PyObject
*func
= NULL
;
2646 PyObject
*retval
= NULL
;
2648 if (o
== NULL
|| name
== NULL
)
2649 return null_error();
2651 func
= PyObject_GetAttrString(o
, name
);
2653 PyErr_SetString(PyExc_AttributeError
, name
);
2657 if (!PyCallable_Check(func
)) {
2658 type_error("attribute of type '%.200s' is not callable", func
);
2662 if (format
&& *format
) {
2663 va_start(va
, format
);
2664 args
= _Py_VaBuildValue_SizeT(format
, va
);
2668 args
= PyTuple_New(0);
2670 retval
= call_function_tail(func
, args
);
2673 /* args gets consumed in call_function_tail */
2681 objargs_mktuple(va_list va
)
2685 PyObject
*result
, *tmp
;
2687 #ifdef VA_LIST_IS_ARRAY
2688 memcpy(countva
, va
, sizeof(va_list));
2691 __va_copy(countva
, va
);
2697 while (((PyObject
*)va_arg(countva
, PyObject
*)) != NULL
)
2699 result
= PyTuple_New(n
);
2700 if (result
!= NULL
&& n
> 0) {
2701 for (i
= 0; i
< n
; ++i
) {
2702 tmp
= (PyObject
*)va_arg(va
, PyObject
*);
2703 PyTuple_SET_ITEM(result
, i
, tmp
);
2711 PyObject_CallMethodObjArgs(PyObject
*callable
, PyObject
*name
, ...)
2713 PyObject
*args
, *tmp
;
2716 if (callable
== NULL
|| name
== NULL
)
2717 return null_error();
2719 callable
= PyObject_GetAttr(callable
, name
);
2720 if (callable
== NULL
)
2723 /* count the args */
2724 va_start(vargs
, name
);
2725 args
= objargs_mktuple(vargs
);
2728 Py_DECREF(callable
);
2731 tmp
= PyObject_Call(callable
, args
, NULL
);
2733 Py_DECREF(callable
);
2739 PyObject_CallFunctionObjArgs(PyObject
*callable
, ...)
2741 PyObject
*args
, *tmp
;
2744 if (callable
== NULL
)
2745 return null_error();
2747 /* count the args */
2748 va_start(vargs
, callable
);
2749 args
= objargs_mktuple(vargs
);
2753 tmp
= PyObject_Call(callable
, args
, NULL
);
2760 /* isinstance(), issubclass() */
2762 /* abstract_get_bases() has logically 4 return states, with a sort of 0th
2763 * state that will almost never happen.
2765 * 0. creating the __bases__ static string could get a MemoryError
2766 * 1. getattr(cls, '__bases__') could raise an AttributeError
2767 * 2. getattr(cls, '__bases__') could raise some other exception
2768 * 3. getattr(cls, '__bases__') could return a tuple
2769 * 4. getattr(cls, '__bases__') could return something other than a tuple
2771 * Only state #3 is a non-error state and only it returns a non-NULL object
2772 * (it returns the retrieved tuple).
2774 * Any raised AttributeErrors are masked by clearing the exception and
2775 * returning NULL. If an object other than a tuple comes out of __bases__,
2776 * then again, the return value is NULL. So yes, these two situations
2777 * produce exactly the same results: NULL is returned and no error is set.
2779 * If some exception other than AttributeError is raised, then NULL is also
2780 * returned, but the exception is not cleared. That's because we want the
2781 * exception to be propagated along.
2783 * Callers are expected to test for PyErr_Occurred() when the return value
2784 * is NULL to decide whether a valid exception should be propagated or not.
2785 * When there's no exception to propagate, it's customary for the caller to
2789 abstract_get_bases(PyObject
*cls
)
2791 static PyObject
*__bases__
= NULL
;
2794 if (__bases__
== NULL
) {
2795 __bases__
= PyString_InternFromString("__bases__");
2796 if (__bases__
== NULL
)
2799 bases
= PyObject_GetAttr(cls
, __bases__
);
2800 if (bases
== NULL
) {
2801 if (PyErr_ExceptionMatches(PyExc_AttributeError
))
2805 if (!PyTuple_Check(bases
)) {
2814 abstract_issubclass(PyObject
*derived
, PyObject
*cls
)
2816 PyObject
*bases
= NULL
;
2823 bases
= abstract_get_bases(derived
);
2824 if (bases
== NULL
) {
2825 if (PyErr_Occurred())
2829 n
= PyTuple_GET_SIZE(bases
);
2834 /* Avoid recursivity in the single inheritance case */
2836 derived
= PyTuple_GET_ITEM(bases
, 0);
2840 for (i
= 0; i
< n
; i
++) {
2841 r
= abstract_issubclass(PyTuple_GET_ITEM(bases
, i
), cls
);
2851 check_class(PyObject
*cls
, const char *error
)
2853 PyObject
*bases
= abstract_get_bases(cls
);
2854 if (bases
== NULL
) {
2855 /* Do not mask errors. */
2856 if (!PyErr_Occurred())
2857 PyErr_SetString(PyExc_TypeError
, error
);
2865 recursive_isinstance(PyObject
*inst
, PyObject
*cls
)
2868 static PyObject
*__class__
= NULL
;
2871 if (__class__
== NULL
) {
2872 __class__
= PyString_InternFromString("__class__");
2873 if (__class__
== NULL
)
2877 if (PyClass_Check(cls
) && PyInstance_Check(inst
)) {
2879 (PyObject
*)((PyInstanceObject
*)inst
)->in_class
;
2880 retval
= PyClass_IsSubclass(inclass
, cls
);
2882 else if (PyType_Check(cls
)) {
2883 retval
= PyObject_TypeCheck(inst
, (PyTypeObject
*)cls
);
2885 PyObject
*c
= PyObject_GetAttr(inst
, __class__
);
2890 if (c
!= (PyObject
*)(inst
->ob_type
) &&
2892 retval
= PyType_IsSubtype(
2894 (PyTypeObject
*)cls
);
2900 if (!check_class(cls
,
2901 "isinstance() arg 2 must be a class, type,"
2902 " or tuple of classes and types"))
2904 icls
= PyObject_GetAttr(inst
, __class__
);
2910 retval
= abstract_issubclass(icls
, cls
);
2919 PyObject_IsInstance(PyObject
*inst
, PyObject
*cls
)
2921 static PyObject
*name
= NULL
;
2923 /* Quick test for an exact match */
2924 if (Py_TYPE(inst
) == (PyTypeObject
*)cls
)
2927 if (PyTuple_Check(cls
)) {
2932 if (Py_EnterRecursiveCall(" in __instancecheck__"))
2934 n
= PyTuple_GET_SIZE(cls
);
2935 for (i
= 0; i
< n
; ++i
) {
2936 PyObject
*item
= PyTuple_GET_ITEM(cls
, i
);
2937 r
= PyObject_IsInstance(inst
, item
);
2939 /* either found it, or got an error */
2942 Py_LeaveRecursiveCall();
2946 if (!(PyClass_Check(cls
) || PyInstance_Check(cls
))) {
2948 checker
= _PyObject_LookupSpecial(cls
, "__instancecheck__", &name
);
2949 if (checker
!= NULL
) {
2952 if (Py_EnterRecursiveCall(" in __instancecheck__")) {
2956 res
= PyObject_CallFunctionObjArgs(checker
, inst
, NULL
);
2957 Py_LeaveRecursiveCall();
2960 ok
= PyObject_IsTrue(res
);
2965 else if (PyErr_Occurred())
2968 return recursive_isinstance(inst
, cls
);
2972 recursive_issubclass(PyObject
*derived
, PyObject
*cls
)
2976 if (PyType_Check(cls
) && PyType_Check(derived
)) {
2977 /* Fast path (non-recursive) */
2978 return PyType_IsSubtype(
2979 (PyTypeObject
*)derived
, (PyTypeObject
*)cls
);
2981 if (!PyClass_Check(derived
) || !PyClass_Check(cls
)) {
2982 if (!check_class(derived
,
2983 "issubclass() arg 1 must be a class"))
2986 if (!check_class(cls
,
2987 "issubclass() arg 2 must be a class"
2988 " or tuple of classes"))
2990 retval
= abstract_issubclass(derived
, cls
);
2994 if (!(retval
= (derived
== cls
)))
2995 retval
= PyClass_IsSubclass(derived
, cls
);
3002 PyObject_IsSubclass(PyObject
*derived
, PyObject
*cls
)
3004 static PyObject
*name
= NULL
;
3006 if (PyTuple_Check(cls
)) {
3011 if (Py_EnterRecursiveCall(" in __subclasscheck__"))
3013 n
= PyTuple_GET_SIZE(cls
);
3014 for (i
= 0; i
< n
; ++i
) {
3015 PyObject
*item
= PyTuple_GET_ITEM(cls
, i
);
3016 r
= PyObject_IsSubclass(derived
, item
);
3018 /* either found it, or got an error */
3021 Py_LeaveRecursiveCall();
3024 if (!(PyClass_Check(cls
) || PyInstance_Check(cls
))) {
3026 checker
= _PyObject_LookupSpecial(cls
, "__subclasscheck__", &name
);
3027 if (checker
!= NULL
) {
3030 if (Py_EnterRecursiveCall(" in __subclasscheck__")) {
3034 res
= PyObject_CallFunctionObjArgs(checker
, derived
, NULL
);
3035 Py_LeaveRecursiveCall();
3038 ok
= PyObject_IsTrue(res
);
3043 else if (PyErr_Occurred()) {
3047 return recursive_issubclass(derived
, cls
);
3051 _PyObject_RealIsInstance(PyObject
*inst
, PyObject
*cls
)
3053 return recursive_isinstance(inst
, cls
);
3057 _PyObject_RealIsSubclass(PyObject
*derived
, PyObject
*cls
)
3059 return recursive_issubclass(derived
, cls
);
3064 PyObject_GetIter(PyObject
*o
)
3066 PyTypeObject
*t
= o
->ob_type
;
3067 getiterfunc f
= NULL
;
3068 if (PyType_HasFeature(t
, Py_TPFLAGS_HAVE_ITER
))
3071 if (PySequence_Check(o
))
3072 return PySeqIter_New(o
);
3073 return type_error("'%.200s' object is not iterable", o
);
3076 PyObject
*res
= (*f
)(o
);
3077 if (res
!= NULL
&& !PyIter_Check(res
)) {
3078 PyErr_Format(PyExc_TypeError
,
3079 "iter() returned non-iterator "
3081 res
->ob_type
->tp_name
);
3089 /* Return next item.
3090 * If an error occurs, return NULL. PyErr_Occurred() will be true.
3091 * If the iteration terminates normally, return NULL and clear the
3092 * PyExc_StopIteration exception (if it was set). PyErr_Occurred()
3094 * Else return the next object. PyErr_Occurred() will be false.
3097 PyIter_Next(PyObject
*iter
)
3100 result
= (*iter
->ob_type
->tp_iternext
)(iter
);
3101 if (result
== NULL
&&
3103 PyErr_ExceptionMatches(PyExc_StopIteration
))