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 _IsFortranContiguous(Py_buffer
*view
)
371 if (view
->ndim
== 0) return 1;
372 if (view
->strides
== NULL
) return (view
->ndim
== 1);
375 if (view
->ndim
== 1) return (view
->shape
[0] == 1 ||
376 sd
== view
->strides
[0]);
377 for (i
=0; i
<view
->ndim
; i
++) {
378 dim
= view
->shape
[i
];
379 if (dim
== 0) return 1;
380 if (view
->strides
[i
] != sd
) return 0;
387 _IsCContiguous(Py_buffer
*view
)
392 if (view
->ndim
== 0) return 1;
393 if (view
->strides
== NULL
) return 1;
396 if (view
->ndim
== 1) return (view
->shape
[0] == 1 ||
397 sd
== view
->strides
[0]);
398 for (i
=view
->ndim
-1; i
>=0; i
--) {
399 dim
= view
->shape
[i
];
400 if (dim
== 0) return 1;
401 if (view
->strides
[i
] != sd
) return 0;
408 PyBuffer_IsContiguous(Py_buffer
*view
, char fort
)
411 if (view
->suboffsets
!= NULL
) return 0;
414 return _IsCContiguous(view
);
415 else if (fort
== 'F')
416 return _IsFortranContiguous(view
);
417 else if (fort
== 'A')
418 return (_IsCContiguous(view
) || _IsFortranContiguous(view
));
424 PyBuffer_GetPointer(Py_buffer
*view
, Py_ssize_t
*indices
)
428 pointer
= (char *)view
->buf
;
429 for (i
= 0; i
< view
->ndim
; i
++) {
430 pointer
+= view
->strides
[i
]*indices
[i
];
431 if ((view
->suboffsets
!= NULL
) && (view
->suboffsets
[i
] >= 0)) {
432 pointer
= *((char**)pointer
) + view
->suboffsets
[i
];
435 return (void*)pointer
;
440 _add_one_to_index_F(int nd
, Py_ssize_t
*index
, Py_ssize_t
*shape
)
444 for (k
=0; k
<nd
; k
++) {
445 if (index
[k
] < shape
[k
]-1) {
456 _add_one_to_index_C(int nd
, Py_ssize_t
*index
, Py_ssize_t
*shape
)
460 for (k
=nd
-1; k
>=0; k
--) {
461 if (index
[k
] < shape
[k
]-1) {
471 /* view is not checked for consistency in either of these. It is
472 assumed that the size of the buffer is view->len in
473 view->len / view->itemsize elements.
477 PyBuffer_ToContiguous(void *buf
, Py_buffer
*view
, Py_ssize_t len
, char fort
)
480 void (*addone
)(int, Py_ssize_t
*, Py_ssize_t
*);
481 Py_ssize_t
*indices
, elements
;
484 if (len
> view
->len
) {
488 if (PyBuffer_IsContiguous(view
, fort
)) {
489 /* simplest copy is all that is needed */
490 memcpy(buf
, view
->buf
, len
);
494 /* Otherwise a more elaborate scheme is needed */
496 /* XXX(nnorwitz): need to check for overflow! */
497 indices
= (Py_ssize_t
*)PyMem_Malloc(sizeof(Py_ssize_t
)*(view
->ndim
));
498 if (indices
== NULL
) {
502 for (k
=0; k
<view
->ndim
;k
++) {
507 addone
= _add_one_to_index_F
;
510 addone
= _add_one_to_index_C
;
513 /* XXX : This is not going to be the fastest code in the world
514 several optimizations are possible.
516 elements
= len
/ view
->itemsize
;
518 addone(view
->ndim
, indices
, view
->shape
);
519 ptr
= PyBuffer_GetPointer(view
, indices
);
520 memcpy(dest
, ptr
, view
->itemsize
);
521 dest
+= view
->itemsize
;
528 PyBuffer_FromContiguous(Py_buffer
*view
, void *buf
, Py_ssize_t len
, char fort
)
531 void (*addone
)(int, Py_ssize_t
*, Py_ssize_t
*);
532 Py_ssize_t
*indices
, elements
;
535 if (len
> view
->len
) {
539 if (PyBuffer_IsContiguous(view
, fort
)) {
540 /* simplest copy is all that is needed */
541 memcpy(view
->buf
, buf
, len
);
545 /* Otherwise a more elaborate scheme is needed */
547 /* XXX(nnorwitz): need to check for overflow! */
548 indices
= (Py_ssize_t
*)PyMem_Malloc(sizeof(Py_ssize_t
)*(view
->ndim
));
549 if (indices
== NULL
) {
553 for (k
=0; k
<view
->ndim
;k
++) {
558 addone
= _add_one_to_index_F
;
561 addone
= _add_one_to_index_C
;
564 /* XXX : This is not going to be the fastest code in the world
565 several optimizations are possible.
567 elements
= len
/ view
->itemsize
;
569 addone(view
->ndim
, indices
, view
->shape
);
570 ptr
= PyBuffer_GetPointer(view
, indices
);
571 memcpy(ptr
, src
, view
->itemsize
);
572 src
+= view
->itemsize
;
579 int PyObject_CopyData(PyObject
*dest
, PyObject
*src
)
581 Py_buffer view_dest
, view_src
;
583 Py_ssize_t
*indices
, elements
;
586 if (!PyObject_CheckBuffer(dest
) ||
587 !PyObject_CheckBuffer(src
)) {
588 PyErr_SetString(PyExc_TypeError
,
589 "both destination and source must have the "\
594 if (PyObject_GetBuffer(dest
, &view_dest
, PyBUF_FULL
) != 0) return -1;
595 if (PyObject_GetBuffer(src
, &view_src
, PyBUF_FULL_RO
) != 0) {
596 PyBuffer_Release(&view_dest
);
600 if (view_dest
.len
< view_src
.len
) {
601 PyErr_SetString(PyExc_BufferError
,
602 "destination is too small to receive data from source");
603 PyBuffer_Release(&view_dest
);
604 PyBuffer_Release(&view_src
);
608 if ((PyBuffer_IsContiguous(&view_dest
, 'C') &&
609 PyBuffer_IsContiguous(&view_src
, 'C')) ||
610 (PyBuffer_IsContiguous(&view_dest
, 'F') &&
611 PyBuffer_IsContiguous(&view_src
, 'F'))) {
612 /* simplest copy is all that is needed */
613 memcpy(view_dest
.buf
, view_src
.buf
, view_src
.len
);
614 PyBuffer_Release(&view_dest
);
615 PyBuffer_Release(&view_src
);
619 /* Otherwise a more elaborate copy scheme is needed */
621 /* XXX(nnorwitz): need to check for overflow! */
622 indices
= (Py_ssize_t
*)PyMem_Malloc(sizeof(Py_ssize_t
)*view_src
.ndim
);
623 if (indices
== NULL
) {
625 PyBuffer_Release(&view_dest
);
626 PyBuffer_Release(&view_src
);
629 for (k
=0; k
<view_src
.ndim
;k
++) {
633 for (k
=0; k
<view_src
.ndim
; k
++) {
634 /* XXX(nnorwitz): can this overflow? */
635 elements
*= view_src
.shape
[k
];
638 _add_one_to_index_C(view_src
.ndim
, indices
, view_src
.shape
);
639 dptr
= PyBuffer_GetPointer(&view_dest
, indices
);
640 sptr
= PyBuffer_GetPointer(&view_src
, indices
);
641 memcpy(dptr
, sptr
, view_src
.itemsize
);
644 PyBuffer_Release(&view_dest
);
645 PyBuffer_Release(&view_src
);
650 PyBuffer_FillContiguousStrides(int nd
, Py_ssize_t
*shape
,
651 Py_ssize_t
*strides
, int itemsize
,
659 for (k
=0; k
<nd
; k
++) {
665 for (k
=nd
-1; k
>=0; k
--) {
674 PyBuffer_FillInfo(Py_buffer
*view
, PyObject
*obj
, void *buf
, Py_ssize_t len
,
675 int readonly
, int flags
)
677 if (view
== NULL
) return 0;
678 if (((flags
& PyBUF_WRITABLE
) == PyBUF_WRITABLE
) &&
680 PyErr_SetString(PyExc_BufferError
,
681 "Object is not writable.");
690 view
->readonly
= readonly
;
693 if ((flags
& PyBUF_FORMAT
) == PyBUF_FORMAT
)
697 if ((flags
& PyBUF_ND
) == PyBUF_ND
)
698 view
->shape
= &(view
->len
);
699 view
->strides
= NULL
;
700 if ((flags
& PyBUF_STRIDES
) == PyBUF_STRIDES
)
701 view
->strides
= &(view
->itemsize
);
702 view
->suboffsets
= NULL
;
703 view
->internal
= NULL
;
708 PyBuffer_Release(Py_buffer
*view
)
710 PyObject
*obj
= view
->obj
;
711 if (obj
&& Py_TYPE(obj
)->tp_as_buffer
&& Py_TYPE(obj
)->tp_as_buffer
->bf_releasebuffer
)
712 Py_TYPE(obj
)->tp_as_buffer
->bf_releasebuffer(obj
, view
);
718 PyObject_Format(PyObject
* obj
, PyObject
*format_spec
)
720 static PyObject
* str__format__
= NULL
;
721 PyObject
*empty
= NULL
;
722 PyObject
*result
= NULL
;
724 int result_is_unicode
;
726 /* Initialize cached value */
727 if (str__format__
== NULL
) {
728 /* Initialize static variable needed by _PyType_Lookup */
729 str__format__
= PyString_InternFromString("__format__");
730 if (str__format__
== NULL
)
734 /* If no format_spec is provided, use an empty string */
735 if (format_spec
== NULL
) {
736 empty
= PyString_FromStringAndSize(NULL
, 0);
740 /* Check the format_spec type, and make sure it's str or unicode */
741 if (PyUnicode_Check(format_spec
))
743 else if (PyString_Check(format_spec
))
746 PyErr_Format(PyExc_TypeError
,
747 "format expects arg 2 to be string "
748 "or unicode, not %.100s", Py_TYPE(format_spec
)->tp_name
);
752 /* Make sure the type is initialized. float gets initialized late */
753 if (Py_TYPE(obj
)->tp_dict
== NULL
)
754 if (PyType_Ready(Py_TYPE(obj
)) < 0)
757 /* Check for a __format__ method and call it. */
758 if (PyInstance_Check(obj
)) {
759 /* We're an instance of a classic class */
760 PyObject
*bound_method
= PyObject_GetAttr(obj
,
762 if (bound_method
!= NULL
) {
763 result
= PyObject_CallFunctionObjArgs(bound_method
,
766 Py_DECREF(bound_method
);
768 PyObject
*self_as_str
;
769 PyObject
*format_method
;
772 /* Per the PEP, convert to str (or unicode,
773 depending on the type of the format
774 specifier). For new-style classes, this
775 logic is done by object.__format__(). */
777 self_as_str
= PyObject_Unicode(obj
);
779 self_as_str
= PyObject_Str(obj
);
780 if (self_as_str
== NULL
)
783 /* Then call str.__format__ on that result */
784 format_method
= PyObject_GetAttr(self_as_str
,
786 if (format_method
== NULL
) {
787 Py_DECREF(self_as_str
);
790 result
= PyObject_CallFunctionObjArgs(format_method
,
793 Py_DECREF(self_as_str
);
794 Py_DECREF(format_method
);
799 /* Not an instance of a classic class, use the code
802 /* Find the (unbound!) __format__ method (a borrowed
804 PyObject
*method
= _PyType_Lookup(Py_TYPE(obj
),
806 if (method
== NULL
) {
807 PyErr_Format(PyExc_TypeError
,
808 "Type %.100s doesn't define __format__",
809 Py_TYPE(obj
)->tp_name
);
812 /* And call it, binding it to the value */
813 result
= PyObject_CallFunctionObjArgs(method
, obj
,
820 /* Check the result type, and make sure it's str or unicode */
821 if (PyUnicode_Check(result
))
822 result_is_unicode
= 1;
823 else if (PyString_Check(result
))
824 result_is_unicode
= 0;
826 PyErr_Format(PyExc_TypeError
,
827 "%.100s.__format__ must return string or "
828 "unicode, not %.100s", Py_TYPE(obj
)->tp_name
,
829 Py_TYPE(result
)->tp_name
);
835 /* Convert to unicode, if needed. Required if spec is unicode
837 if (spec_is_unicode
&& !result_is_unicode
) {
838 PyObject
*tmp
= PyObject_Unicode(result
);
839 /* This logic works whether or not tmp is NULL */
849 /* Operations on numbers */
852 PyNumber_Check(PyObject
*o
)
854 return o
&& o
->ob_type
->tp_as_number
&&
855 (o
->ob_type
->tp_as_number
->nb_int
||
856 o
->ob_type
->tp_as_number
->nb_float
);
859 /* Binary operators */
861 /* New style number protocol support */
863 #define NB_SLOT(x) offsetof(PyNumberMethods, x)
864 #define NB_BINOP(nb_methods, slot) \
865 (*(binaryfunc*)(& ((char*)nb_methods)[slot]))
866 #define NB_TERNOP(nb_methods, slot) \
867 (*(ternaryfunc*)(& ((char*)nb_methods)[slot]))
870 Calling scheme used for binary operations:
873 -------------------------------------------------------------------
874 new new w.op(v,w)[*], v.op(v,w), w.op(v,w)
875 new old v.op(v,w), coerce(v,w), v.op(v,w)
876 old new w.op(v,w), coerce(v,w), v.op(v,w)
877 old old coerce(v,w), v.op(v,w)
879 [*] only when v->ob_type != w->ob_type && w->ob_type is a subclass of
884 * new == new style number
885 * old == old style number
886 * Action indicates the order in which operations are tried until either
887 a valid result is produced or an error occurs.
892 binary_op1(PyObject
*v
, PyObject
*w
, const int op_slot
)
895 binaryfunc slotv
= NULL
;
896 binaryfunc slotw
= NULL
;
898 if (v
->ob_type
->tp_as_number
!= NULL
&& NEW_STYLE_NUMBER(v
))
899 slotv
= NB_BINOP(v
->ob_type
->tp_as_number
, op_slot
);
900 if (w
->ob_type
!= v
->ob_type
&&
901 w
->ob_type
->tp_as_number
!= NULL
&& NEW_STYLE_NUMBER(w
)) {
902 slotw
= NB_BINOP(w
->ob_type
->tp_as_number
, op_slot
);
907 if (slotw
&& PyType_IsSubtype(w
->ob_type
, v
->ob_type
)) {
909 if (x
!= Py_NotImplemented
)
911 Py_DECREF(x
); /* can't do it */
915 if (x
!= Py_NotImplemented
)
917 Py_DECREF(x
); /* can't do it */
921 if (x
!= Py_NotImplemented
)
923 Py_DECREF(x
); /* can't do it */
925 if (!NEW_STYLE_NUMBER(v
) || !NEW_STYLE_NUMBER(w
)) {
926 int err
= PyNumber_CoerceEx(&v
, &w
);
931 PyNumberMethods
*mv
= v
->ob_type
->tp_as_number
;
934 slot
= NB_BINOP(mv
, op_slot
);
942 /* CoerceEx incremented the reference counts */
947 Py_INCREF(Py_NotImplemented
);
948 return Py_NotImplemented
;
952 binop_type_error(PyObject
*v
, PyObject
*w
, const char *op_name
)
954 PyErr_Format(PyExc_TypeError
,
955 "unsupported operand type(s) for %.100s: "
956 "'%.100s' and '%.100s'",
959 w
->ob_type
->tp_name
);
964 binary_op(PyObject
*v
, PyObject
*w
, const int op_slot
, const char *op_name
)
966 PyObject
*result
= binary_op1(v
, w
, op_slot
);
967 if (result
== Py_NotImplemented
) {
969 return binop_type_error(v
, w
, op_name
);
976 Calling scheme used for ternary operations:
978 *** In some cases, w.op is called before v.op; see binary_op1. ***
981 -------------------------------------------------------------------
982 new new new v.op(v,w,z), w.op(v,w,z), z.op(v,w,z)
983 new old new v.op(v,w,z), z.op(v,w,z), coerce(v,w,z), v.op(v,w,z)
984 old new new w.op(v,w,z), z.op(v,w,z), coerce(v,w,z), v.op(v,w,z)
985 old old new z.op(v,w,z), coerce(v,w,z), v.op(v,w,z)
986 new new old v.op(v,w,z), w.op(v,w,z), coerce(v,w,z), v.op(v,w,z)
987 new old old v.op(v,w,z), coerce(v,w,z), v.op(v,w,z)
988 old new old w.op(v,w,z), coerce(v,w,z), v.op(v,w,z)
989 old old old coerce(v,w,z), v.op(v,w,z)
993 * new == new style number
994 * old == old style number
995 * Action indicates the order in which operations are tried until either
996 a valid result is produced or an error occurs.
997 * coerce(v,w,z) actually does: coerce(v,w), coerce(v,z), coerce(w,z) and
998 only if z != Py_None; if z == Py_None, then it is treated as absent
999 variable and only coerce(v,w) is tried.
1004 ternary_op(PyObject
*v
,
1008 const char *op_name
)
1010 PyNumberMethods
*mv
, *mw
, *mz
;
1012 ternaryfunc slotv
= NULL
;
1013 ternaryfunc slotw
= NULL
;
1014 ternaryfunc slotz
= NULL
;
1016 mv
= v
->ob_type
->tp_as_number
;
1017 mw
= w
->ob_type
->tp_as_number
;
1018 if (mv
!= NULL
&& NEW_STYLE_NUMBER(v
))
1019 slotv
= NB_TERNOP(mv
, op_slot
);
1020 if (w
->ob_type
!= v
->ob_type
&&
1021 mw
!= NULL
&& NEW_STYLE_NUMBER(w
)) {
1022 slotw
= NB_TERNOP(mw
, op_slot
);
1027 if (slotw
&& PyType_IsSubtype(w
->ob_type
, v
->ob_type
)) {
1029 if (x
!= Py_NotImplemented
)
1031 Py_DECREF(x
); /* can't do it */
1035 if (x
!= Py_NotImplemented
)
1037 Py_DECREF(x
); /* can't do it */
1041 if (x
!= Py_NotImplemented
)
1043 Py_DECREF(x
); /* can't do it */
1045 mz
= z
->ob_type
->tp_as_number
;
1046 if (mz
!= NULL
&& NEW_STYLE_NUMBER(z
)) {
1047 slotz
= NB_TERNOP(mz
, op_slot
);
1048 if (slotz
== slotv
|| slotz
== slotw
)
1052 if (x
!= Py_NotImplemented
)
1054 Py_DECREF(x
); /* can't do it */
1058 if (!NEW_STYLE_NUMBER(v
) || !NEW_STYLE_NUMBER(w
) ||
1059 (z
!= Py_None
&& !NEW_STYLE_NUMBER(z
))) {
1060 /* we have an old style operand, coerce */
1061 PyObject
*v1
, *z1
, *w2
, *z2
;
1064 c
= PyNumber_Coerce(&v
, &w
);
1068 /* Special case: if the third argument is None, it is
1069 treated as absent argument and not coerced. */
1071 if (v
->ob_type
->tp_as_number
) {
1072 slotz
= NB_TERNOP(v
->ob_type
->tp_as_number
,
1085 c
= PyNumber_Coerce(&v1
, &z1
);
1090 c
= PyNumber_Coerce(&w2
, &z2
);
1094 if (v1
->ob_type
->tp_as_number
!= NULL
) {
1095 slotv
= NB_TERNOP(v1
->ob_type
->tp_as_number
,
1098 x
= slotv(v1
, w2
, z2
);
1121 "unsupported operand type(s) for ** or pow(): "
1122 "'%.100s' and '%.100s'",
1123 v
->ob_type
->tp_name
,
1124 w
->ob_type
->tp_name
);
1128 "unsupported operand type(s) for pow(): "
1129 "'%.100s', '%.100s', '%.100s'",
1130 v
->ob_type
->tp_name
,
1131 w
->ob_type
->tp_name
,
1132 z
->ob_type
->tp_name
);
1136 #define BINARY_FUNC(func, op, op_name) \
1138 func(PyObject *v, PyObject *w) { \
1139 return binary_op(v, w, NB_SLOT(op), op_name); \
1142 BINARY_FUNC(PyNumber_Or
, nb_or
, "|")
1143 BINARY_FUNC(PyNumber_Xor
, nb_xor
, "^")
1144 BINARY_FUNC(PyNumber_And
, nb_and
, "&")
1145 BINARY_FUNC(PyNumber_Lshift
, nb_lshift
, "<<")
1146 BINARY_FUNC(PyNumber_Rshift
, nb_rshift
, ">>")
1147 BINARY_FUNC(PyNumber_Subtract
, nb_subtract
, "-")
1148 BINARY_FUNC(PyNumber_Divide
, nb_divide
, "/")
1149 BINARY_FUNC(PyNumber_Divmod
, nb_divmod
, "divmod()")
1152 PyNumber_Add(PyObject
*v
, PyObject
*w
)
1154 PyObject
*result
= binary_op1(v
, w
, NB_SLOT(nb_add
));
1155 if (result
== Py_NotImplemented
) {
1156 PySequenceMethods
*m
= v
->ob_type
->tp_as_sequence
;
1158 if (m
&& m
->sq_concat
) {
1159 return (*m
->sq_concat
)(v
, w
);
1161 result
= binop_type_error(v
, w
, "+");
1167 sequence_repeat(ssizeargfunc repeatfunc
, PyObject
*seq
, PyObject
*n
)
1170 if (PyIndex_Check(n
)) {
1171 count
= PyNumber_AsSsize_t(n
, PyExc_OverflowError
);
1172 if (count
== -1 && PyErr_Occurred())
1176 return type_error("can't multiply sequence by "
1177 "non-int of type '%.200s'", n
);
1179 return (*repeatfunc
)(seq
, count
);
1183 PyNumber_Multiply(PyObject
*v
, PyObject
*w
)
1185 PyObject
*result
= binary_op1(v
, w
, NB_SLOT(nb_multiply
));
1186 if (result
== Py_NotImplemented
) {
1187 PySequenceMethods
*mv
= v
->ob_type
->tp_as_sequence
;
1188 PySequenceMethods
*mw
= w
->ob_type
->tp_as_sequence
;
1190 if (mv
&& mv
->sq_repeat
) {
1191 return sequence_repeat(mv
->sq_repeat
, v
, w
);
1193 else if (mw
&& mw
->sq_repeat
) {
1194 return sequence_repeat(mw
->sq_repeat
, w
, v
);
1196 result
= binop_type_error(v
, w
, "*");
1202 PyNumber_FloorDivide(PyObject
*v
, PyObject
*w
)
1204 /* XXX tp_flags test */
1205 return binary_op(v
, w
, NB_SLOT(nb_floor_divide
), "//");
1209 PyNumber_TrueDivide(PyObject
*v
, PyObject
*w
)
1211 /* XXX tp_flags test */
1212 return binary_op(v
, w
, NB_SLOT(nb_true_divide
), "/");
1216 PyNumber_Remainder(PyObject
*v
, PyObject
*w
)
1218 return binary_op(v
, w
, NB_SLOT(nb_remainder
), "%");
1222 PyNumber_Power(PyObject
*v
, PyObject
*w
, PyObject
*z
)
1224 return ternary_op(v
, w
, z
, NB_SLOT(nb_power
), "** or pow()");
1227 /* Binary in-place operators */
1229 /* The in-place operators are defined to fall back to the 'normal',
1230 non in-place operations, if the in-place methods are not in place.
1232 - If the left hand object has the appropriate struct members, and
1233 they are filled, call the appropriate function and return the
1234 result. No coercion is done on the arguments; the left-hand object
1235 is the one the operation is performed on, and it's up to the
1236 function to deal with the right-hand object.
1238 - Otherwise, in-place modification is not supported. Handle it exactly as
1239 a non in-place operation of the same kind.
1243 #define HASINPLACE(t) \
1244 PyType_HasFeature((t)->ob_type, Py_TPFLAGS_HAVE_INPLACEOPS)
1247 binary_iop1(PyObject
*v
, PyObject
*w
, const int iop_slot
, const int op_slot
)
1249 PyNumberMethods
*mv
= v
->ob_type
->tp_as_number
;
1250 if (mv
!= NULL
&& HASINPLACE(v
)) {
1251 binaryfunc slot
= NB_BINOP(mv
, iop_slot
);
1253 PyObject
*x
= (slot
)(v
, w
);
1254 if (x
!= Py_NotImplemented
) {
1260 return binary_op1(v
, w
, op_slot
);
1264 binary_iop(PyObject
*v
, PyObject
*w
, const int iop_slot
, const int op_slot
,
1265 const char *op_name
)
1267 PyObject
*result
= binary_iop1(v
, w
, iop_slot
, op_slot
);
1268 if (result
== Py_NotImplemented
) {
1270 return binop_type_error(v
, w
, op_name
);
1275 #define INPLACE_BINOP(func, iop, op, op_name) \
1277 func(PyObject *v, PyObject *w) { \
1278 return binary_iop(v, w, NB_SLOT(iop), NB_SLOT(op), op_name); \
1281 INPLACE_BINOP(PyNumber_InPlaceOr
, nb_inplace_or
, nb_or
, "|=")
1282 INPLACE_BINOP(PyNumber_InPlaceXor
, nb_inplace_xor
, nb_xor
, "^=")
1283 INPLACE_BINOP(PyNumber_InPlaceAnd
, nb_inplace_and
, nb_and
, "&=")
1284 INPLACE_BINOP(PyNumber_InPlaceLshift
, nb_inplace_lshift
, nb_lshift
, "<<=")
1285 INPLACE_BINOP(PyNumber_InPlaceRshift
, nb_inplace_rshift
, nb_rshift
, ">>=")
1286 INPLACE_BINOP(PyNumber_InPlaceSubtract
, nb_inplace_subtract
, nb_subtract
, "-=")
1287 INPLACE_BINOP(PyNumber_InPlaceDivide
, nb_inplace_divide
, nb_divide
, "/=")
1290 PyNumber_InPlaceFloorDivide(PyObject
*v
, PyObject
*w
)
1292 /* XXX tp_flags test */
1293 return binary_iop(v
, w
, NB_SLOT(nb_inplace_floor_divide
),
1294 NB_SLOT(nb_floor_divide
), "//=");
1298 PyNumber_InPlaceTrueDivide(PyObject
*v
, PyObject
*w
)
1300 /* XXX tp_flags test */
1301 return binary_iop(v
, w
, NB_SLOT(nb_inplace_true_divide
),
1302 NB_SLOT(nb_true_divide
), "/=");
1306 PyNumber_InPlaceAdd(PyObject
*v
, PyObject
*w
)
1308 PyObject
*result
= binary_iop1(v
, w
, NB_SLOT(nb_inplace_add
),
1310 if (result
== Py_NotImplemented
) {
1311 PySequenceMethods
*m
= v
->ob_type
->tp_as_sequence
;
1314 binaryfunc f
= NULL
;
1316 f
= m
->sq_inplace_concat
;
1322 result
= binop_type_error(v
, w
, "+=");
1328 PyNumber_InPlaceMultiply(PyObject
*v
, PyObject
*w
)
1330 PyObject
*result
= binary_iop1(v
, w
, NB_SLOT(nb_inplace_multiply
),
1331 NB_SLOT(nb_multiply
));
1332 if (result
== Py_NotImplemented
) {
1333 ssizeargfunc f
= NULL
;
1334 PySequenceMethods
*mv
= v
->ob_type
->tp_as_sequence
;
1335 PySequenceMethods
*mw
= w
->ob_type
->tp_as_sequence
;
1339 f
= mv
->sq_inplace_repeat
;
1343 return sequence_repeat(f
, v
, w
);
1345 else if (mw
!= NULL
) {
1346 /* Note that the right hand operand should not be
1347 * mutated in this case so sq_inplace_repeat is not
1350 return sequence_repeat(mw
->sq_repeat
, w
, v
);
1352 result
= binop_type_error(v
, w
, "*=");
1358 PyNumber_InPlaceRemainder(PyObject
*v
, PyObject
*w
)
1360 return binary_iop(v
, w
, NB_SLOT(nb_inplace_remainder
),
1361 NB_SLOT(nb_remainder
), "%=");
1365 PyNumber_InPlacePower(PyObject
*v
, PyObject
*w
, PyObject
*z
)
1367 if (HASINPLACE(v
) && v
->ob_type
->tp_as_number
&&
1368 v
->ob_type
->tp_as_number
->nb_inplace_power
!= NULL
) {
1369 return ternary_op(v
, w
, z
, NB_SLOT(nb_inplace_power
), "**=");
1372 return ternary_op(v
, w
, z
, NB_SLOT(nb_power
), "**=");
1377 /* Unary operators and functions */
1380 PyNumber_Negative(PyObject
*o
)
1385 return null_error();
1386 m
= o
->ob_type
->tp_as_number
;
1387 if (m
&& m
->nb_negative
)
1388 return (*m
->nb_negative
)(o
);
1390 return type_error("bad operand type for unary -: '%.200s'", o
);
1394 PyNumber_Positive(PyObject
*o
)
1399 return null_error();
1400 m
= o
->ob_type
->tp_as_number
;
1401 if (m
&& m
->nb_positive
)
1402 return (*m
->nb_positive
)(o
);
1404 return type_error("bad operand type for unary +: '%.200s'", o
);
1408 PyNumber_Invert(PyObject
*o
)
1413 return null_error();
1414 m
= o
->ob_type
->tp_as_number
;
1415 if (m
&& m
->nb_invert
)
1416 return (*m
->nb_invert
)(o
);
1418 return type_error("bad operand type for unary ~: '%.200s'", o
);
1422 PyNumber_Absolute(PyObject
*o
)
1427 return null_error();
1428 m
= o
->ob_type
->tp_as_number
;
1429 if (m
&& m
->nb_absolute
)
1430 return m
->nb_absolute(o
);
1432 return type_error("bad operand type for abs(): '%.200s'", o
);
1435 /* Add a check for embedded NULL-bytes in the argument. */
1437 int_from_string(const char *s
, Py_ssize_t len
)
1442 x
= PyInt_FromString((char*)s
, &end
, 10);
1445 if (end
!= s
+ len
) {
1446 PyErr_SetString(PyExc_ValueError
,
1447 "null byte in argument for int()");
1454 /* Return a Python Int or Long from the object item
1455 Raise TypeError if the result is not an int-or-long
1456 or if the object cannot be interpreted as an index.
1459 PyNumber_Index(PyObject
*item
)
1461 PyObject
*result
= NULL
;
1463 return null_error();
1464 if (PyInt_Check(item
) || PyLong_Check(item
)) {
1468 if (PyIndex_Check(item
)) {
1469 result
= item
->ob_type
->tp_as_number
->nb_index(item
);
1471 !PyInt_Check(result
) && !PyLong_Check(result
)) {
1472 PyErr_Format(PyExc_TypeError
,
1473 "__index__ returned non-(int,long) " \
1475 result
->ob_type
->tp_name
);
1481 PyErr_Format(PyExc_TypeError
,
1482 "'%.200s' object cannot be interpreted "
1483 "as an index", item
->ob_type
->tp_name
);
1488 /* Return an error on Overflow only if err is not NULL*/
1491 PyNumber_AsSsize_t(PyObject
*item
, PyObject
*err
)
1495 PyObject
*value
= PyNumber_Index(item
);
1499 /* We're done if PyInt_AsSsize_t() returns without error. */
1500 result
= PyInt_AsSsize_t(value
);
1501 if (result
!= -1 || !(runerr
= PyErr_Occurred()))
1504 /* Error handling code -- only manage OverflowError differently */
1505 if (!PyErr_GivenExceptionMatches(runerr
, PyExc_OverflowError
))
1509 /* If no error-handling desired then the default clipping
1513 assert(PyLong_Check(value
));
1514 /* Whether or not it is less than or equal to
1515 zero is determined by the sign of ob_size
1517 if (_PyLong_Sign(value
) < 0)
1518 result
= PY_SSIZE_T_MIN
;
1520 result
= PY_SSIZE_T_MAX
;
1523 /* Otherwise replace the error with caller's error object. */
1525 "cannot fit '%.200s' into an index-sized integer",
1526 item
->ob_type
->tp_name
);
1536 _PyNumber_ConvertIntegralToInt(PyObject
*integral
, const char* error_format
)
1538 const char *type_name
;
1539 static PyObject
*int_name
= NULL
;
1540 if (int_name
== NULL
) {
1541 int_name
= PyString_InternFromString("__int__");
1542 if (int_name
== NULL
)
1546 if (integral
&& (!PyInt_Check(integral
) &&
1547 !PyLong_Check(integral
))) {
1548 /* Don't go through tp_as_number->nb_int to avoid
1549 hitting the classic class fallback to __trunc__. */
1550 PyObject
*int_func
= PyObject_GetAttr(integral
, int_name
);
1551 if (int_func
== NULL
) {
1552 PyErr_Clear(); /* Raise a different error. */
1553 goto non_integral_error
;
1555 Py_DECREF(integral
);
1556 integral
= PyEval_CallObject(int_func
, NULL
);
1557 Py_DECREF(int_func
);
1558 if (integral
&& (!PyInt_Check(integral
) &&
1559 !PyLong_Check(integral
))) {
1560 goto non_integral_error
;
1566 if (PyInstance_Check(integral
)) {
1567 type_name
= PyString_AS_STRING(((PyInstanceObject
*)integral
)
1568 ->in_class
->cl_name
);
1571 type_name
= integral
->ob_type
->tp_name
;
1573 PyErr_Format(PyExc_TypeError
, error_format
, type_name
);
1574 Py_DECREF(integral
);
1580 PyNumber_Int(PyObject
*o
)
1583 static PyObject
*trunc_name
= NULL
;
1584 PyObject
*trunc_func
;
1586 Py_ssize_t buffer_len
;
1588 if (trunc_name
== NULL
) {
1589 trunc_name
= PyString_InternFromString("__trunc__");
1590 if (trunc_name
== NULL
)
1595 return null_error();
1596 if (PyInt_CheckExact(o
)) {
1600 m
= o
->ob_type
->tp_as_number
;
1601 if (m
&& m
->nb_int
) { /* This should include subclasses of int */
1602 /* Classic classes always take this branch. */
1603 PyObject
*res
= m
->nb_int(o
);
1604 if (res
&& (!PyInt_Check(res
) && !PyLong_Check(res
))) {
1605 PyErr_Format(PyExc_TypeError
,
1606 "__int__ returned non-int (type %.200s)",
1607 res
->ob_type
->tp_name
);
1613 if (PyInt_Check(o
)) { /* A int subclass without nb_int */
1614 PyIntObject
*io
= (PyIntObject
*)o
;
1615 return PyInt_FromLong(io
->ob_ival
);
1617 trunc_func
= PyObject_GetAttr(o
, trunc_name
);
1619 PyObject
*truncated
= PyEval_CallObject(trunc_func
, NULL
);
1620 Py_DECREF(trunc_func
);
1621 /* __trunc__ is specified to return an Integral type, but
1622 int() needs to return an int. */
1623 return _PyNumber_ConvertIntegralToInt(
1625 "__trunc__ returned non-Integral (type %.200s)");
1627 PyErr_Clear(); /* It's not an error if o.__trunc__ doesn't exist. */
1629 if (PyString_Check(o
))
1630 return int_from_string(PyString_AS_STRING(o
),
1631 PyString_GET_SIZE(o
));
1632 #ifdef Py_USING_UNICODE
1633 if (PyUnicode_Check(o
))
1634 return PyInt_FromUnicode(PyUnicode_AS_UNICODE(o
),
1635 PyUnicode_GET_SIZE(o
),
1638 if (!PyObject_AsCharBuffer(o
, &buffer
, &buffer_len
))
1639 return int_from_string((char*)buffer
, buffer_len
);
1641 return type_error("int() argument must be a string or a "
1642 "number, not '%.200s'", o
);
1645 /* Add a check for embedded NULL-bytes in the argument. */
1647 long_from_string(const char *s
, Py_ssize_t len
)
1652 x
= PyLong_FromString((char*)s
, &end
, 10);
1655 if (end
!= s
+ len
) {
1656 PyErr_SetString(PyExc_ValueError
,
1657 "null byte in argument for long()");
1665 PyNumber_Long(PyObject
*o
)
1668 static PyObject
*trunc_name
= NULL
;
1669 PyObject
*trunc_func
;
1671 Py_ssize_t buffer_len
;
1673 if (trunc_name
== NULL
) {
1674 trunc_name
= PyString_InternFromString("__trunc__");
1675 if (trunc_name
== NULL
)
1680 return null_error();
1681 m
= o
->ob_type
->tp_as_number
;
1682 if (m
&& m
->nb_long
) { /* This should include subclasses of long */
1683 /* Classic classes always take this branch. */
1684 PyObject
*res
= m
->nb_long(o
);
1685 if (res
&& (!PyInt_Check(res
) && !PyLong_Check(res
))) {
1686 PyErr_Format(PyExc_TypeError
,
1687 "__long__ returned non-long (type %.200s)",
1688 res
->ob_type
->tp_name
);
1694 if (PyLong_Check(o
)) /* A long subclass without nb_long */
1695 return _PyLong_Copy((PyLongObject
*)o
);
1696 trunc_func
= PyObject_GetAttr(o
, trunc_name
);
1698 PyObject
*truncated
= PyEval_CallObject(trunc_func
, NULL
);
1699 PyObject
*int_instance
;
1700 Py_DECREF(trunc_func
);
1701 /* __trunc__ is specified to return an Integral type,
1702 but long() needs to return a long. */
1703 int_instance
= _PyNumber_ConvertIntegralToInt(
1705 "__trunc__ returned non-Integral (type %.200s)");
1706 if (int_instance
&& PyInt_Check(int_instance
)) {
1707 /* Make sure that long() returns a long instance. */
1708 long value
= PyInt_AS_LONG(int_instance
);
1709 Py_DECREF(int_instance
);
1710 return PyLong_FromLong(value
);
1712 return int_instance
;
1714 PyErr_Clear(); /* It's not an error if o.__trunc__ doesn't exist. */
1716 if (PyString_Check(o
))
1717 /* need to do extra error checking that PyLong_FromString()
1718 * doesn't do. In particular long('9.5') must raise an
1719 * exception, not truncate the float.
1721 return long_from_string(PyString_AS_STRING(o
),
1722 PyString_GET_SIZE(o
));
1723 #ifdef Py_USING_UNICODE
1724 if (PyUnicode_Check(o
))
1725 /* The above check is done in PyLong_FromUnicode(). */
1726 return PyLong_FromUnicode(PyUnicode_AS_UNICODE(o
),
1727 PyUnicode_GET_SIZE(o
),
1730 if (!PyObject_AsCharBuffer(o
, &buffer
, &buffer_len
))
1731 return long_from_string(buffer
, buffer_len
);
1733 return type_error("long() argument must be a string or a "
1734 "number, not '%.200s'", o
);
1738 PyNumber_Float(PyObject
*o
)
1743 return null_error();
1744 m
= o
->ob_type
->tp_as_number
;
1745 if (m
&& m
->nb_float
) { /* This should include subclasses of float */
1746 PyObject
*res
= m
->nb_float(o
);
1747 if (res
&& !PyFloat_Check(res
)) {
1748 PyErr_Format(PyExc_TypeError
,
1749 "__float__ returned non-float (type %.200s)",
1750 res
->ob_type
->tp_name
);
1756 if (PyFloat_Check(o
)) { /* A float subclass with nb_float == NULL */
1757 PyFloatObject
*po
= (PyFloatObject
*)o
;
1758 return PyFloat_FromDouble(po
->ob_fval
);
1760 return PyFloat_FromString(o
, NULL
);
1764 PyNumber_ToBase(PyObject
*n
, int base
)
1766 PyObject
*res
= NULL
;
1767 PyObject
*index
= PyNumber_Index(n
);
1771 if (PyLong_Check(index
))
1772 res
= _PyLong_Format(index
, base
, 0, 1);
1773 else if (PyInt_Check(index
))
1774 res
= _PyInt_Format((PyIntObject
*)index
, base
, 1);
1776 /* It should not be possible to get here, as
1777 PyNumber_Index already has a check for the same
1779 PyErr_SetString(PyExc_ValueError
, "PyNumber_ToBase: index not "
1786 /* Operations on sequences */
1789 PySequence_Check(PyObject
*s
)
1791 if (s
&& PyInstance_Check(s
))
1792 return PyObject_HasAttrString(s
, "__getitem__");
1793 if (PyObject_IsInstance(s
, (PyObject
*)&PyDict_Type
))
1795 return s
!= NULL
&& s
->ob_type
->tp_as_sequence
&&
1796 s
->ob_type
->tp_as_sequence
->sq_item
!= NULL
;
1800 PySequence_Size(PyObject
*s
)
1802 PySequenceMethods
*m
;
1809 m
= s
->ob_type
->tp_as_sequence
;
1810 if (m
&& m
->sq_length
)
1811 return m
->sq_length(s
);
1813 type_error("object of type '%.200s' has no len()", s
);
1817 #undef PySequence_Length
1819 PySequence_Length(PyObject
*s
)
1821 return PySequence_Size(s
);
1823 #define PySequence_Length PySequence_Size
1826 PySequence_Concat(PyObject
*s
, PyObject
*o
)
1828 PySequenceMethods
*m
;
1830 if (s
== NULL
|| o
== NULL
)
1831 return null_error();
1833 m
= s
->ob_type
->tp_as_sequence
;
1834 if (m
&& m
->sq_concat
)
1835 return m
->sq_concat(s
, o
);
1837 /* Instances of user classes defining an __add__() method only
1838 have an nb_add slot, not an sq_concat slot. So we fall back
1839 to nb_add if both arguments appear to be sequences. */
1840 if (PySequence_Check(s
) && PySequence_Check(o
)) {
1841 PyObject
*result
= binary_op1(s
, o
, NB_SLOT(nb_add
));
1842 if (result
!= Py_NotImplemented
)
1846 return type_error("'%.200s' object can't be concatenated", s
);
1850 PySequence_Repeat(PyObject
*o
, Py_ssize_t count
)
1852 PySequenceMethods
*m
;
1855 return null_error();
1857 m
= o
->ob_type
->tp_as_sequence
;
1858 if (m
&& m
->sq_repeat
)
1859 return m
->sq_repeat(o
, count
);
1861 /* Instances of user classes defining a __mul__() method only
1862 have an nb_multiply slot, not an sq_repeat slot. so we fall back
1863 to nb_multiply if o appears to be a sequence. */
1864 if (PySequence_Check(o
)) {
1865 PyObject
*n
, *result
;
1866 n
= PyInt_FromSsize_t(count
);
1869 result
= binary_op1(o
, n
, NB_SLOT(nb_multiply
));
1871 if (result
!= Py_NotImplemented
)
1875 return type_error("'%.200s' object can't be repeated", o
);
1879 PySequence_InPlaceConcat(PyObject
*s
, PyObject
*o
)
1881 PySequenceMethods
*m
;
1883 if (s
== NULL
|| o
== NULL
)
1884 return null_error();
1886 m
= s
->ob_type
->tp_as_sequence
;
1887 if (m
&& HASINPLACE(s
) && m
->sq_inplace_concat
)
1888 return m
->sq_inplace_concat(s
, o
);
1889 if (m
&& m
->sq_concat
)
1890 return m
->sq_concat(s
, o
);
1892 if (PySequence_Check(s
) && PySequence_Check(o
)) {
1893 PyObject
*result
= binary_iop1(s
, o
, NB_SLOT(nb_inplace_add
),
1895 if (result
!= Py_NotImplemented
)
1899 return type_error("'%.200s' object can't be concatenated", s
);
1903 PySequence_InPlaceRepeat(PyObject
*o
, Py_ssize_t count
)
1905 PySequenceMethods
*m
;
1908 return null_error();
1910 m
= o
->ob_type
->tp_as_sequence
;
1911 if (m
&& HASINPLACE(o
) && m
->sq_inplace_repeat
)
1912 return m
->sq_inplace_repeat(o
, count
);
1913 if (m
&& m
->sq_repeat
)
1914 return m
->sq_repeat(o
, count
);
1916 if (PySequence_Check(o
)) {
1917 PyObject
*n
, *result
;
1918 n
= PyInt_FromSsize_t(count
);
1921 result
= binary_iop1(o
, n
, NB_SLOT(nb_inplace_multiply
),
1922 NB_SLOT(nb_multiply
));
1924 if (result
!= Py_NotImplemented
)
1928 return type_error("'%.200s' object can't be repeated", o
);
1932 PySequence_GetItem(PyObject
*s
, Py_ssize_t i
)
1934 PySequenceMethods
*m
;
1937 return null_error();
1939 m
= s
->ob_type
->tp_as_sequence
;
1940 if (m
&& m
->sq_item
) {
1943 Py_ssize_t l
= (*m
->sq_length
)(s
);
1949 return m
->sq_item(s
, i
);
1952 return type_error("'%.200s' object does not support indexing", s
);
1956 PySequence_GetSlice(PyObject
*s
, Py_ssize_t i1
, Py_ssize_t i2
)
1958 PySequenceMethods
*m
;
1959 PyMappingMethods
*mp
;
1961 if (!s
) return null_error();
1963 m
= s
->ob_type
->tp_as_sequence
;
1964 if (m
&& m
->sq_slice
) {
1965 if (i1
< 0 || i2
< 0) {
1967 Py_ssize_t l
= (*m
->sq_length
)(s
);
1976 return m
->sq_slice(s
, i1
, i2
);
1977 } else if ((mp
= s
->ob_type
->tp_as_mapping
) && mp
->mp_subscript
) {
1979 PyObject
*slice
= _PySlice_FromIndices(i1
, i2
);
1982 res
= mp
->mp_subscript(s
, slice
);
1987 return type_error("'%.200s' object is unsliceable", s
);
1991 PySequence_SetItem(PyObject
*s
, Py_ssize_t i
, PyObject
*o
)
1993 PySequenceMethods
*m
;
2000 m
= s
->ob_type
->tp_as_sequence
;
2001 if (m
&& m
->sq_ass_item
) {
2004 Py_ssize_t l
= (*m
->sq_length
)(s
);
2010 return m
->sq_ass_item(s
, i
, o
);
2013 type_error("'%.200s' object does not support item assignment", s
);
2018 PySequence_DelItem(PyObject
*s
, Py_ssize_t i
)
2020 PySequenceMethods
*m
;
2027 m
= s
->ob_type
->tp_as_sequence
;
2028 if (m
&& m
->sq_ass_item
) {
2031 Py_ssize_t l
= (*m
->sq_length
)(s
);
2037 return m
->sq_ass_item(s
, i
, (PyObject
*)NULL
);
2040 type_error("'%.200s' object doesn't support item deletion", s
);
2045 PySequence_SetSlice(PyObject
*s
, Py_ssize_t i1
, Py_ssize_t i2
, PyObject
*o
)
2047 PySequenceMethods
*m
;
2048 PyMappingMethods
*mp
;
2055 m
= s
->ob_type
->tp_as_sequence
;
2056 if (m
&& m
->sq_ass_slice
) {
2057 if (i1
< 0 || i2
< 0) {
2059 Py_ssize_t l
= (*m
->sq_length
)(s
);
2068 return m
->sq_ass_slice(s
, i1
, i2
, o
);
2069 } else if ((mp
= s
->ob_type
->tp_as_mapping
) && mp
->mp_ass_subscript
) {
2071 PyObject
*slice
= _PySlice_FromIndices(i1
, i2
);
2074 res
= mp
->mp_ass_subscript(s
, slice
, o
);
2079 type_error("'%.200s' object doesn't support slice assignment", s
);
2084 PySequence_DelSlice(PyObject
*s
, Py_ssize_t i1
, Py_ssize_t i2
)
2086 PySequenceMethods
*m
;
2093 m
= s
->ob_type
->tp_as_sequence
;
2094 if (m
&& m
->sq_ass_slice
) {
2095 if (i1
< 0 || i2
< 0) {
2097 Py_ssize_t l
= (*m
->sq_length
)(s
);
2106 return m
->sq_ass_slice(s
, i1
, i2
, (PyObject
*)NULL
);
2108 type_error("'%.200s' object doesn't support slice deletion", s
);
2113 PySequence_Tuple(PyObject
*v
)
2115 PyObject
*it
; /* iter(v) */
2116 Py_ssize_t n
; /* guess for result tuple size */
2121 return null_error();
2123 /* Special-case the common tuple and list cases, for efficiency. */
2124 if (PyTuple_CheckExact(v
)) {
2125 /* Note that we can't know whether it's safe to return
2126 a tuple *subclass* instance as-is, hence the restriction
2127 to exact tuples here. In contrast, lists always make
2128 a copy, so there's no need for exactness below. */
2132 if (PyList_Check(v
))
2133 return PyList_AsTuple(v
);
2136 it
= PyObject_GetIter(v
);
2140 /* Guess result size and allocate space. */
2141 n
= _PyObject_LengthHint(v
, 10);
2142 result
= PyTuple_New(n
);
2146 /* Fill the tuple. */
2147 for (j
= 0; ; ++j
) {
2148 PyObject
*item
= PyIter_Next(it
);
2150 if (PyErr_Occurred())
2155 Py_ssize_t oldn
= n
;
2156 /* The over-allocation strategy can grow a bit faster
2157 than for lists because unlike lists the
2158 over-allocation isn't permanent -- we reclaim
2159 the excess before the end of this routine.
2160 So, grow by ten and then add 25%.
2165 /* Check for overflow */
2170 if (_PyTuple_Resize(&result
, n
) != 0) {
2175 PyTuple_SET_ITEM(result
, j
, item
);
2178 /* Cut tuple back if guess was too large. */
2180 _PyTuple_Resize(&result
, j
) != 0)
2193 PySequence_List(PyObject
*v
)
2195 PyObject
*result
; /* result list */
2196 PyObject
*rv
; /* return value from PyList_Extend */
2199 return null_error();
2201 result
= PyList_New(0);
2205 rv
= _PyList_Extend((PyListObject
*)result
, v
);
2215 PySequence_Fast(PyObject
*v
, const char *m
)
2220 return null_error();
2222 if (PyList_CheckExact(v
) || PyTuple_CheckExact(v
)) {
2227 it
= PyObject_GetIter(v
);
2229 if (PyErr_ExceptionMatches(PyExc_TypeError
))
2230 PyErr_SetString(PyExc_TypeError
, m
);
2234 v
= PySequence_List(it
);
2240 /* Iterate over seq. Result depends on the operation:
2241 PY_ITERSEARCH_COUNT: -1 if error, else # of times obj appears in seq.
2242 PY_ITERSEARCH_INDEX: 0-based index of first occurence of obj in seq;
2243 set ValueError and return -1 if none found; also return -1 on error.
2244 Py_ITERSEARCH_CONTAINS: return 1 if obj in seq, else 0; -1 on error.
2247 _PySequence_IterSearch(PyObject
*seq
, PyObject
*obj
, int operation
)
2250 int wrapped
; /* for PY_ITERSEARCH_INDEX, true iff n wrapped around */
2251 PyObject
*it
; /* iter(seq) */
2253 if (seq
== NULL
|| obj
== NULL
) {
2258 it
= PyObject_GetIter(seq
);
2260 type_error("argument of type '%.200s' is not iterable", seq
);
2267 PyObject
*item
= PyIter_Next(it
);
2269 if (PyErr_Occurred())
2274 cmp
= PyObject_RichCompareBool(obj
, item
, Py_EQ
);
2279 switch (operation
) {
2280 case PY_ITERSEARCH_COUNT
:
2281 if (n
== PY_SSIZE_T_MAX
) {
2282 PyErr_SetString(PyExc_OverflowError
,
2283 "count exceeds C integer size");
2289 case PY_ITERSEARCH_INDEX
:
2291 PyErr_SetString(PyExc_OverflowError
,
2292 "index exceeds C integer size");
2297 case PY_ITERSEARCH_CONTAINS
:
2302 assert(!"unknown operation");
2306 if (operation
== PY_ITERSEARCH_INDEX
) {
2307 if (n
== PY_SSIZE_T_MAX
)
2313 if (operation
!= PY_ITERSEARCH_INDEX
)
2316 PyErr_SetString(PyExc_ValueError
,
2317 "sequence.index(x): x not in sequence");
2318 /* fall into failure code */
2328 /* Return # of times o appears in s. */
2330 PySequence_Count(PyObject
*s
, PyObject
*o
)
2332 return _PySequence_IterSearch(s
, o
, PY_ITERSEARCH_COUNT
);
2335 /* Return -1 if error; 1 if ob in seq; 0 if ob not in seq.
2336 * Use sq_contains if possible, else defer to _PySequence_IterSearch().
2339 PySequence_Contains(PyObject
*seq
, PyObject
*ob
)
2342 if (PyType_HasFeature(seq
->ob_type
, Py_TPFLAGS_HAVE_SEQUENCE_IN
)) {
2343 PySequenceMethods
*sqm
= seq
->ob_type
->tp_as_sequence
;
2344 if (sqm
!= NULL
&& sqm
->sq_contains
!= NULL
)
2345 return (*sqm
->sq_contains
)(seq
, ob
);
2347 result
= _PySequence_IterSearch(seq
, ob
, PY_ITERSEARCH_CONTAINS
);
2348 return Py_SAFE_DOWNCAST(result
, Py_ssize_t
, int);
2351 /* Backwards compatibility */
2352 #undef PySequence_In
2354 PySequence_In(PyObject
*w
, PyObject
*v
)
2356 return PySequence_Contains(w
, v
);
2360 PySequence_Index(PyObject
*s
, PyObject
*o
)
2362 return _PySequence_IterSearch(s
, o
, PY_ITERSEARCH_INDEX
);
2365 /* Operations on mappings */
2368 PyMapping_Check(PyObject
*o
)
2370 if (o
&& PyInstance_Check(o
))
2371 return PyObject_HasAttrString(o
, "__getitem__");
2373 return o
&& o
->ob_type
->tp_as_mapping
&&
2374 o
->ob_type
->tp_as_mapping
->mp_subscript
&&
2375 !(o
->ob_type
->tp_as_sequence
&&
2376 o
->ob_type
->tp_as_sequence
->sq_slice
);
2380 PyMapping_Size(PyObject
*o
)
2382 PyMappingMethods
*m
;
2389 m
= o
->ob_type
->tp_as_mapping
;
2390 if (m
&& m
->mp_length
)
2391 return m
->mp_length(o
);
2393 type_error("object of type '%.200s' has no len()", o
);
2397 #undef PyMapping_Length
2399 PyMapping_Length(PyObject
*o
)
2401 return PyMapping_Size(o
);
2403 #define PyMapping_Length PyMapping_Size
2406 PyMapping_GetItemString(PyObject
*o
, char *key
)
2411 return null_error();
2413 okey
= PyString_FromString(key
);
2416 r
= PyObject_GetItem(o
, okey
);
2422 PyMapping_SetItemString(PyObject
*o
, char *key
, PyObject
*value
)
2432 okey
= PyString_FromString(key
);
2435 r
= PyObject_SetItem(o
, okey
, value
);
2441 PyMapping_HasKeyString(PyObject
*o
, char *key
)
2445 v
= PyMapping_GetItemString(o
, key
);
2455 PyMapping_HasKey(PyObject
*o
, PyObject
*key
)
2459 v
= PyObject_GetItem(o
, key
);
2468 /* Operations on callable objects */
2470 /* XXX PyCallable_Check() is in object.c */
2473 PyObject_CallObject(PyObject
*o
, PyObject
*a
)
2475 return PyEval_CallObjectWithKeywords(o
, a
, NULL
);
2479 PyObject_Call(PyObject
*func
, PyObject
*arg
, PyObject
*kw
)
2483 if ((call
= func
->ob_type
->tp_call
) != NULL
) {
2485 if (Py_EnterRecursiveCall(" while calling a Python object"))
2487 result
= (*call
)(func
, arg
, kw
);
2488 Py_LeaveRecursiveCall();
2489 if (result
== NULL
&& !PyErr_Occurred())
2492 "NULL result without error in PyObject_Call");
2495 PyErr_Format(PyExc_TypeError
, "'%.200s' object is not callable",
2496 func
->ob_type
->tp_name
);
2501 call_function_tail(PyObject
*callable
, PyObject
*args
)
2508 if (!PyTuple_Check(args
)) {
2516 PyTuple_SET_ITEM(a
, 0, args
);
2519 retval
= PyObject_Call(callable
, args
, NULL
);
2527 PyObject_CallFunction(PyObject
*callable
, char *format
, ...)
2532 if (callable
== NULL
)
2533 return null_error();
2535 if (format
&& *format
) {
2536 va_start(va
, format
);
2537 args
= Py_VaBuildValue(format
, va
);
2541 args
= PyTuple_New(0);
2543 return call_function_tail(callable
, args
);
2547 _PyObject_CallFunction_SizeT(PyObject
*callable
, char *format
, ...)
2552 if (callable
== NULL
)
2553 return null_error();
2555 if (format
&& *format
) {
2556 va_start(va
, format
);
2557 args
= _Py_VaBuildValue_SizeT(format
, va
);
2561 args
= PyTuple_New(0);
2563 return call_function_tail(callable
, args
);
2567 PyObject_CallMethod(PyObject
*o
, char *name
, char *format
, ...)
2571 PyObject
*func
= NULL
;
2572 PyObject
*retval
= NULL
;
2574 if (o
== NULL
|| name
== NULL
)
2575 return null_error();
2577 func
= PyObject_GetAttrString(o
, name
);
2579 PyErr_SetString(PyExc_AttributeError
, name
);
2583 if (!PyCallable_Check(func
)) {
2584 type_error("attribute of type '%.200s' is not callable", func
);
2588 if (format
&& *format
) {
2589 va_start(va
, format
);
2590 args
= Py_VaBuildValue(format
, va
);
2594 args
= PyTuple_New(0);
2596 retval
= call_function_tail(func
, args
);
2599 /* args gets consumed in call_function_tail */
2606 _PyObject_CallMethod_SizeT(PyObject
*o
, char *name
, char *format
, ...)
2610 PyObject
*func
= NULL
;
2611 PyObject
*retval
= NULL
;
2613 if (o
== NULL
|| name
== NULL
)
2614 return null_error();
2616 func
= PyObject_GetAttrString(o
, name
);
2618 PyErr_SetString(PyExc_AttributeError
, name
);
2622 if (!PyCallable_Check(func
)) {
2623 type_error("attribute of type '%.200s' is not callable", func
);
2627 if (format
&& *format
) {
2628 va_start(va
, format
);
2629 args
= _Py_VaBuildValue_SizeT(format
, va
);
2633 args
= PyTuple_New(0);
2635 retval
= call_function_tail(func
, args
);
2638 /* args gets consumed in call_function_tail */
2646 objargs_mktuple(va_list va
)
2650 PyObject
*result
, *tmp
;
2652 #ifdef VA_LIST_IS_ARRAY
2653 memcpy(countva
, va
, sizeof(va_list));
2656 __va_copy(countva
, va
);
2662 while (((PyObject
*)va_arg(countva
, PyObject
*)) != NULL
)
2664 result
= PyTuple_New(n
);
2665 if (result
!= NULL
&& n
> 0) {
2666 for (i
= 0; i
< n
; ++i
) {
2667 tmp
= (PyObject
*)va_arg(va
, PyObject
*);
2668 PyTuple_SET_ITEM(result
, i
, tmp
);
2676 PyObject_CallMethodObjArgs(PyObject
*callable
, PyObject
*name
, ...)
2678 PyObject
*args
, *tmp
;
2681 if (callable
== NULL
|| name
== NULL
)
2682 return null_error();
2684 callable
= PyObject_GetAttr(callable
, name
);
2685 if (callable
== NULL
)
2688 /* count the args */
2689 va_start(vargs
, name
);
2690 args
= objargs_mktuple(vargs
);
2693 Py_DECREF(callable
);
2696 tmp
= PyObject_Call(callable
, args
, NULL
);
2698 Py_DECREF(callable
);
2704 PyObject_CallFunctionObjArgs(PyObject
*callable
, ...)
2706 PyObject
*args
, *tmp
;
2709 if (callable
== NULL
)
2710 return null_error();
2712 /* count the args */
2713 va_start(vargs
, callable
);
2714 args
= objargs_mktuple(vargs
);
2718 tmp
= PyObject_Call(callable
, args
, NULL
);
2725 /* isinstance(), issubclass() */
2727 /* abstract_get_bases() has logically 4 return states, with a sort of 0th
2728 * state that will almost never happen.
2730 * 0. creating the __bases__ static string could get a MemoryError
2731 * 1. getattr(cls, '__bases__') could raise an AttributeError
2732 * 2. getattr(cls, '__bases__') could raise some other exception
2733 * 3. getattr(cls, '__bases__') could return a tuple
2734 * 4. getattr(cls, '__bases__') could return something other than a tuple
2736 * Only state #3 is a non-error state and only it returns a non-NULL object
2737 * (it returns the retrieved tuple).
2739 * Any raised AttributeErrors are masked by clearing the exception and
2740 * returning NULL. If an object other than a tuple comes out of __bases__,
2741 * then again, the return value is NULL. So yes, these two situations
2742 * produce exactly the same results: NULL is returned and no error is set.
2744 * If some exception other than AttributeError is raised, then NULL is also
2745 * returned, but the exception is not cleared. That's because we want the
2746 * exception to be propagated along.
2748 * Callers are expected to test for PyErr_Occurred() when the return value
2749 * is NULL to decide whether a valid exception should be propagated or not.
2750 * When there's no exception to propagate, it's customary for the caller to
2754 abstract_get_bases(PyObject
*cls
)
2756 static PyObject
*__bases__
= NULL
;
2759 if (__bases__
== NULL
) {
2760 __bases__
= PyString_InternFromString("__bases__");
2761 if (__bases__
== NULL
)
2764 bases
= PyObject_GetAttr(cls
, __bases__
);
2765 if (bases
== NULL
) {
2766 if (PyErr_ExceptionMatches(PyExc_AttributeError
))
2770 if (!PyTuple_Check(bases
)) {
2779 abstract_issubclass(PyObject
*derived
, PyObject
*cls
)
2781 PyObject
*bases
= NULL
;
2788 bases
= abstract_get_bases(derived
);
2789 if (bases
== NULL
) {
2790 if (PyErr_Occurred())
2794 n
= PyTuple_GET_SIZE(bases
);
2799 /* Avoid recursivity in the single inheritance case */
2801 derived
= PyTuple_GET_ITEM(bases
, 0);
2805 for (i
= 0; i
< n
; i
++) {
2806 r
= abstract_issubclass(PyTuple_GET_ITEM(bases
, i
), cls
);
2816 check_class(PyObject
*cls
, const char *error
)
2818 PyObject
*bases
= abstract_get_bases(cls
);
2819 if (bases
== NULL
) {
2820 /* Do not mask errors. */
2821 if (!PyErr_Occurred())
2822 PyErr_SetString(PyExc_TypeError
, error
);
2830 recursive_isinstance(PyObject
*inst
, PyObject
*cls
)
2833 static PyObject
*__class__
= NULL
;
2836 if (__class__
== NULL
) {
2837 __class__
= PyString_InternFromString("__class__");
2838 if (__class__
== NULL
)
2842 if (PyClass_Check(cls
) && PyInstance_Check(inst
)) {
2844 (PyObject
*)((PyInstanceObject
*)inst
)->in_class
;
2845 retval
= PyClass_IsSubclass(inclass
, cls
);
2847 else if (PyType_Check(cls
)) {
2848 retval
= PyObject_TypeCheck(inst
, (PyTypeObject
*)cls
);
2850 PyObject
*c
= PyObject_GetAttr(inst
, __class__
);
2855 if (c
!= (PyObject
*)(inst
->ob_type
) &&
2857 retval
= PyType_IsSubtype(
2859 (PyTypeObject
*)cls
);
2865 if (!check_class(cls
,
2866 "isinstance() arg 2 must be a class, type,"
2867 " or tuple of classes and types"))
2869 icls
= PyObject_GetAttr(inst
, __class__
);
2875 retval
= abstract_issubclass(icls
, cls
);
2884 PyObject_IsInstance(PyObject
*inst
, PyObject
*cls
)
2886 static PyObject
*name
= NULL
;
2889 /* Quick test for an exact match */
2890 if (Py_TYPE(inst
) == (PyTypeObject
*)cls
)
2893 if (PyTuple_Check(cls
)) {
2898 if (Py_EnterRecursiveCall(" in __instancecheck__"))
2900 n
= PyTuple_GET_SIZE(cls
);
2901 for (i
= 0; i
< n
; ++i
) {
2902 PyObject
*item
= PyTuple_GET_ITEM(cls
, i
);
2903 r
= PyObject_IsInstance(inst
, item
);
2905 /* either found it, or got an error */
2908 Py_LeaveRecursiveCall();
2912 name
= PyString_InternFromString("__instancecheck__");
2916 checker
= PyObject_GetAttr(cls
, name
);
2917 if (checker
== NULL
&& PyErr_Occurred())
2919 if (checker
!= NULL
) {
2922 if (Py_EnterRecursiveCall(" in __instancecheck__")) {
2926 res
= PyObject_CallFunctionObjArgs(checker
, inst
, NULL
);
2927 Py_LeaveRecursiveCall();
2930 ok
= PyObject_IsTrue(res
);
2935 return recursive_isinstance(inst
, cls
);
2939 recursive_issubclass(PyObject
*derived
, PyObject
*cls
)
2943 if (PyType_Check(cls
) && PyType_Check(derived
)) {
2944 /* Fast path (non-recursive) */
2945 return PyType_IsSubtype(
2946 (PyTypeObject
*)derived
, (PyTypeObject
*)cls
);
2948 if (!PyClass_Check(derived
) || !PyClass_Check(cls
)) {
2949 if (!check_class(derived
,
2950 "issubclass() arg 1 must be a class"))
2953 if (!check_class(cls
,
2954 "issubclass() arg 2 must be a class"
2955 " or tuple of classes"))
2957 retval
= abstract_issubclass(derived
, cls
);
2961 if (!(retval
= (derived
== cls
)))
2962 retval
= PyClass_IsSubclass(derived
, cls
);
2969 PyObject_IsSubclass(PyObject
*derived
, PyObject
*cls
)
2971 static PyObject
*name
= NULL
;
2972 PyObject
*t
, *v
, *tb
;
2975 if (PyTuple_Check(cls
)) {
2980 if (Py_EnterRecursiveCall(" in __subclasscheck__"))
2982 n
= PyTuple_GET_SIZE(cls
);
2983 for (i
= 0; i
< n
; ++i
) {
2984 PyObject
*item
= PyTuple_GET_ITEM(cls
, i
);
2985 r
= PyObject_IsSubclass(derived
, item
);
2987 /* either found it, or got an error */
2990 Py_LeaveRecursiveCall();
2994 name
= PyString_InternFromString("__subclasscheck__");
2998 PyErr_Fetch(&t
, &v
, &tb
);
2999 checker
= PyObject_GetAttr(cls
, name
);
3000 PyErr_Restore(t
, v
, tb
);
3001 if (checker
!= NULL
) {
3004 if (Py_EnterRecursiveCall(" in __subclasscheck__")) {
3008 res
= PyObject_CallFunctionObjArgs(checker
, derived
, NULL
);
3009 Py_LeaveRecursiveCall();
3012 ok
= PyObject_IsTrue(res
);
3017 return recursive_issubclass(derived
, cls
);
3021 _PyObject_RealIsInstance(PyObject
*inst
, PyObject
*cls
)
3023 return recursive_isinstance(inst
, cls
);
3027 _PyObject_RealIsSubclass(PyObject
*derived
, PyObject
*cls
)
3029 return recursive_issubclass(derived
, cls
);
3034 PyObject_GetIter(PyObject
*o
)
3036 PyTypeObject
*t
= o
->ob_type
;
3037 getiterfunc f
= NULL
;
3038 if (PyType_HasFeature(t
, Py_TPFLAGS_HAVE_ITER
))
3041 if (PySequence_Check(o
))
3042 return PySeqIter_New(o
);
3043 return type_error("'%.200s' object is not iterable", o
);
3046 PyObject
*res
= (*f
)(o
);
3047 if (res
!= NULL
&& !PyIter_Check(res
)) {
3048 PyErr_Format(PyExc_TypeError
,
3049 "iter() returned non-iterator "
3051 res
->ob_type
->tp_name
);
3059 /* Return next item.
3060 * If an error occurs, return NULL. PyErr_Occurred() will be true.
3061 * If the iteration terminates normally, return NULL and clear the
3062 * PyExc_StopIteration exception (if it was set). PyErr_Occurred()
3064 * Else return the next object. PyErr_Occurred() will be false.
3067 PyIter_Next(PyObject
*iter
)
3070 assert(PyIter_Check(iter
));
3071 result
= (*iter
->ob_type
->tp_iternext
)(iter
);
3072 if (result
== NULL
&&
3074 PyErr_ExceptionMatches(PyExc_StopIteration
))