Merged revisions 78818 via svnmerge from
[python/dscho.git] / Objects / abstract.c
blob52478247706666c355237287c54705d492b7844d
1 /* Abstract Object Interface (many thanks to Jim Fulton) */
3 #include "Python.h"
4 #include <ctype.h>
5 #include "structmember.h" /* we need the offsetof() macro from there */
6 #include "longintrepr.h"
10 /* Shorthands to return certain errors */
12 static PyObject *
13 type_error(const char *msg, PyObject *obj)
15 PyErr_Format(PyExc_TypeError, msg, obj->ob_type->tp_name);
16 return NULL;
19 static PyObject *
20 null_error(void)
22 if (!PyErr_Occurred())
23 PyErr_SetString(PyExc_SystemError,
24 "null argument to internal routine");
25 return NULL;
28 /* Operations on any object */
30 PyObject *
31 PyObject_Type(PyObject *o)
33 PyObject *v;
35 if (o == NULL)
36 return null_error();
37 v = (PyObject *)o->ob_type;
38 Py_INCREF(v);
39 return v;
42 Py_ssize_t
43 PyObject_Size(PyObject *o)
45 PySequenceMethods *m;
47 if (o == NULL) {
48 null_error();
49 return -1;
52 m = o->ob_type->tp_as_sequence;
53 if (m && m->sq_length)
54 return m->sq_length(o);
56 return PyMapping_Size(o);
59 #undef PyObject_Length
60 Py_ssize_t
61 PyObject_Length(PyObject *o)
63 return PyObject_Size(o);
65 #define PyObject_Length PyObject_Size
68 /* The length hint function returns a non-negative value from o.__len__()
69 or o.__length_hint__(). If those methods aren't found or return a negative
70 value, then the defaultvalue is returned. If one of the calls fails,
71 this function returns -1.
74 Py_ssize_t
75 _PyObject_LengthHint(PyObject *o, Py_ssize_t defaultvalue)
77 static PyObject *hintstrobj = NULL;
78 PyObject *ro, *hintmeth;
79 Py_ssize_t rv;
81 /* try o.__len__() */
82 rv = PyObject_Size(o);
83 if (rv >= 0)
84 return rv;
85 if (PyErr_Occurred()) {
86 if (!PyErr_ExceptionMatches(PyExc_TypeError))
87 return -1;
88 PyErr_Clear();
91 /* try o.__length_hint__() */
92 hintmeth = _PyObject_LookupSpecial(o, "__length_hint__", &hintstrobj);
93 if (hintmeth == NULL) {
94 if (PyErr_Occurred())
95 return -1;
96 else
97 return defaultvalue;
99 ro = PyObject_CallFunctionObjArgs(hintmeth, NULL);
100 Py_DECREF(hintmeth);
101 if (ro == NULL) {
102 if (!PyErr_ExceptionMatches(PyExc_TypeError))
103 return -1;
104 PyErr_Clear();
105 return defaultvalue;
107 rv = PyLong_Check(ro) ? PyLong_AsSsize_t(ro) : defaultvalue;
108 Py_DECREF(ro);
109 return rv;
112 PyObject *
113 PyObject_GetItem(PyObject *o, PyObject *key)
115 PyMappingMethods *m;
117 if (o == NULL || key == NULL)
118 return null_error();
120 m = o->ob_type->tp_as_mapping;
121 if (m && m->mp_subscript)
122 return m->mp_subscript(o, key);
124 if (o->ob_type->tp_as_sequence) {
125 if (PyIndex_Check(key)) {
126 Py_ssize_t key_value;
127 key_value = PyNumber_AsSsize_t(key, PyExc_IndexError);
128 if (key_value == -1 && PyErr_Occurred())
129 return NULL;
130 return PySequence_GetItem(o, key_value);
132 else if (o->ob_type->tp_as_sequence->sq_item)
133 return type_error("sequence index must "
134 "be integer, not '%.200s'", key);
137 return type_error("'%.200s' object is not subscriptable", o);
141 PyObject_SetItem(PyObject *o, PyObject *key, PyObject *value)
143 PyMappingMethods *m;
145 if (o == NULL || key == NULL || value == NULL) {
146 null_error();
147 return -1;
149 m = o->ob_type->tp_as_mapping;
150 if (m && m->mp_ass_subscript)
151 return m->mp_ass_subscript(o, key, value);
153 if (o->ob_type->tp_as_sequence) {
154 if (PyIndex_Check(key)) {
155 Py_ssize_t key_value;
156 key_value = PyNumber_AsSsize_t(key, PyExc_IndexError);
157 if (key_value == -1 && PyErr_Occurred())
158 return -1;
159 return PySequence_SetItem(o, key_value, value);
161 else if (o->ob_type->tp_as_sequence->sq_ass_item) {
162 type_error("sequence index must be "
163 "integer, not '%.200s'", key);
164 return -1;
168 type_error("'%.200s' object does not support item assignment", o);
169 return -1;
173 PyObject_DelItem(PyObject *o, PyObject *key)
175 PyMappingMethods *m;
177 if (o == NULL || key == NULL) {
178 null_error();
179 return -1;
181 m = o->ob_type->tp_as_mapping;
182 if (m && m->mp_ass_subscript)
183 return m->mp_ass_subscript(o, key, (PyObject*)NULL);
185 if (o->ob_type->tp_as_sequence) {
186 if (PyIndex_Check(key)) {
187 Py_ssize_t key_value;
188 key_value = PyNumber_AsSsize_t(key, PyExc_IndexError);
189 if (key_value == -1 && PyErr_Occurred())
190 return -1;
191 return PySequence_DelItem(o, key_value);
193 else if (o->ob_type->tp_as_sequence->sq_ass_item) {
194 type_error("sequence index must be "
195 "integer, not '%.200s'", key);
196 return -1;
200 type_error("'%.200s' object does not support item deletion", o);
201 return -1;
205 PyObject_DelItemString(PyObject *o, char *key)
207 PyObject *okey;
208 int ret;
210 if (o == NULL || key == NULL) {
211 null_error();
212 return -1;
214 okey = PyUnicode_FromString(key);
215 if (okey == NULL)
216 return -1;
217 ret = PyObject_DelItem(o, okey);
218 Py_DECREF(okey);
219 return ret;
222 /* We release the buffer right after use of this function which could
223 cause issues later on. Don't use these functions in new code.
226 PyObject_AsCharBuffer(PyObject *obj,
227 const char **buffer,
228 Py_ssize_t *buffer_len)
230 PyBufferProcs *pb;
231 Py_buffer view;
233 if (obj == NULL || buffer == NULL || buffer_len == NULL) {
234 null_error();
235 return -1;
237 pb = obj->ob_type->tp_as_buffer;
238 if (pb == NULL || pb->bf_getbuffer == NULL) {
239 PyErr_SetString(PyExc_TypeError,
240 "expected an object with the buffer interface");
241 return -1;
243 if ((*pb->bf_getbuffer)(obj, &view, PyBUF_SIMPLE)) return -1;
245 *buffer = view.buf;
246 *buffer_len = view.len;
247 if (pb->bf_releasebuffer != NULL)
248 (*pb->bf_releasebuffer)(obj, &view);
249 Py_XDECREF(view.obj);
250 return 0;
254 PyObject_CheckReadBuffer(PyObject *obj)
256 PyBufferProcs *pb = obj->ob_type->tp_as_buffer;
257 Py_buffer view;
259 if (pb == NULL ||
260 pb->bf_getbuffer == NULL)
261 return 0;
262 if ((*pb->bf_getbuffer)(obj, &view, PyBUF_SIMPLE) == -1) {
263 PyErr_Clear();
264 return 0;
266 PyBuffer_Release(&view);
267 return 1;
270 int PyObject_AsReadBuffer(PyObject *obj,
271 const void **buffer,
272 Py_ssize_t *buffer_len)
274 PyBufferProcs *pb;
275 Py_buffer view;
277 if (obj == NULL || buffer == NULL || buffer_len == NULL) {
278 null_error();
279 return -1;
281 pb = obj->ob_type->tp_as_buffer;
282 if (pb == NULL ||
283 pb->bf_getbuffer == NULL) {
284 PyErr_SetString(PyExc_TypeError,
285 "expected an object with a buffer interface");
286 return -1;
289 if ((*pb->bf_getbuffer)(obj, &view, PyBUF_SIMPLE)) return -1;
291 *buffer = view.buf;
292 *buffer_len = view.len;
293 if (pb->bf_releasebuffer != NULL)
294 (*pb->bf_releasebuffer)(obj, &view);
295 Py_XDECREF(view.obj);
296 return 0;
299 int PyObject_AsWriteBuffer(PyObject *obj,
300 void **buffer,
301 Py_ssize_t *buffer_len)
303 PyBufferProcs *pb;
304 Py_buffer view;
306 if (obj == NULL || buffer == NULL || buffer_len == NULL) {
307 null_error();
308 return -1;
310 pb = obj->ob_type->tp_as_buffer;
311 if (pb == NULL ||
312 pb->bf_getbuffer == NULL ||
313 ((*pb->bf_getbuffer)(obj, &view, PyBUF_WRITABLE) != 0)) {
314 PyErr_SetString(PyExc_TypeError,
315 "expected an object with a writable buffer interface");
316 return -1;
319 *buffer = view.buf;
320 *buffer_len = view.len;
321 if (pb->bf_releasebuffer != NULL)
322 (*pb->bf_releasebuffer)(obj, &view);
323 Py_XDECREF(view.obj);
324 return 0;
327 /* Buffer C-API for Python 3.0 */
330 PyObject_GetBuffer(PyObject *obj, Py_buffer *view, int flags)
332 if (!PyObject_CheckBuffer(obj)) {
333 PyErr_Format(PyExc_TypeError,
334 "'%100s' does not support the buffer interface",
335 Py_TYPE(obj)->tp_name);
336 return -1;
338 return (*(obj->ob_type->tp_as_buffer->bf_getbuffer))(obj, view, flags);
341 static int
342 _IsFortranContiguous(Py_buffer *view)
344 Py_ssize_t sd, dim;
345 int i;
347 if (view->ndim == 0) return 1;
348 if (view->strides == NULL) return (view->ndim == 1);
350 sd = view->itemsize;
351 if (view->ndim == 1) return (view->shape[0] == 1 ||
352 sd == view->strides[0]);
353 for (i=0; i<view->ndim; i++) {
354 dim = view->shape[i];
355 if (dim == 0) return 1;
356 if (view->strides[i] != sd) return 0;
357 sd *= dim;
359 return 1;
362 static int
363 _IsCContiguous(Py_buffer *view)
365 Py_ssize_t sd, dim;
366 int i;
368 if (view->ndim == 0) return 1;
369 if (view->strides == NULL) return 1;
371 sd = view->itemsize;
372 if (view->ndim == 1) return (view->shape[0] == 1 ||
373 sd == view->strides[0]);
374 for (i=view->ndim-1; i>=0; i--) {
375 dim = view->shape[i];
376 if (dim == 0) return 1;
377 if (view->strides[i] != sd) return 0;
378 sd *= dim;
380 return 1;
384 PyBuffer_IsContiguous(Py_buffer *view, char fort)
387 if (view->suboffsets != NULL) return 0;
389 if (fort == 'C')
390 return _IsCContiguous(view);
391 else if (fort == 'F')
392 return _IsFortranContiguous(view);
393 else if (fort == 'A')
394 return (_IsCContiguous(view) || _IsFortranContiguous(view));
395 return 0;
399 void*
400 PyBuffer_GetPointer(Py_buffer *view, Py_ssize_t *indices)
402 char* pointer;
403 int i;
404 pointer = (char *)view->buf;
405 for (i = 0; i < view->ndim; i++) {
406 pointer += view->strides[i]*indices[i];
407 if ((view->suboffsets != NULL) && (view->suboffsets[i] >= 0)) {
408 pointer = *((char**)pointer) + view->suboffsets[i];
411 return (void*)pointer;
415 void
416 _add_one_to_index_F(int nd, Py_ssize_t *index, Py_ssize_t *shape)
418 int k;
420 for (k=0; k<nd; k++) {
421 if (index[k] < shape[k]-1) {
422 index[k]++;
423 break;
425 else {
426 index[k] = 0;
431 void
432 _add_one_to_index_C(int nd, Py_ssize_t *index, Py_ssize_t *shape)
434 int k;
436 for (k=nd-1; k>=0; k--) {
437 if (index[k] < shape[k]-1) {
438 index[k]++;
439 break;
441 else {
442 index[k] = 0;
447 /* view is not checked for consistency in either of these. It is
448 assumed that the size of the buffer is view->len in
449 view->len / view->itemsize elements.
453 PyBuffer_ToContiguous(void *buf, Py_buffer *view, Py_ssize_t len, char fort)
455 int k;
456 void (*addone)(int, Py_ssize_t *, Py_ssize_t *);
457 Py_ssize_t *indices, elements;
458 char *dest, *ptr;
460 if (len > view->len) {
461 len = view->len;
464 if (PyBuffer_IsContiguous(view, fort)) {
465 /* simplest copy is all that is needed */
466 memcpy(buf, view->buf, len);
467 return 0;
470 /* Otherwise a more elaborate scheme is needed */
472 /* XXX(nnorwitz): need to check for overflow! */
473 indices = (Py_ssize_t *)PyMem_Malloc(sizeof(Py_ssize_t)*(view->ndim));
474 if (indices == NULL) {
475 PyErr_NoMemory();
476 return -1;
478 for (k=0; k<view->ndim;k++) {
479 indices[k] = 0;
482 if (fort == 'F') {
483 addone = _add_one_to_index_F;
485 else {
486 addone = _add_one_to_index_C;
488 dest = buf;
489 /* XXX : This is not going to be the fastest code in the world
490 several optimizations are possible.
492 elements = len / view->itemsize;
493 while (elements--) {
494 addone(view->ndim, indices, view->shape);
495 ptr = PyBuffer_GetPointer(view, indices);
496 memcpy(dest, ptr, view->itemsize);
497 dest += view->itemsize;
499 PyMem_Free(indices);
500 return 0;
504 PyBuffer_FromContiguous(Py_buffer *view, void *buf, Py_ssize_t len, char fort)
506 int k;
507 void (*addone)(int, Py_ssize_t *, Py_ssize_t *);
508 Py_ssize_t *indices, elements;
509 char *src, *ptr;
511 if (len > view->len) {
512 len = view->len;
515 if (PyBuffer_IsContiguous(view, fort)) {
516 /* simplest copy is all that is needed */
517 memcpy(view->buf, buf, len);
518 return 0;
521 /* Otherwise a more elaborate scheme is needed */
523 /* XXX(nnorwitz): need to check for overflow! */
524 indices = (Py_ssize_t *)PyMem_Malloc(sizeof(Py_ssize_t)*(view->ndim));
525 if (indices == NULL) {
526 PyErr_NoMemory();
527 return -1;
529 for (k=0; k<view->ndim;k++) {
530 indices[k] = 0;
533 if (fort == 'F') {
534 addone = _add_one_to_index_F;
536 else {
537 addone = _add_one_to_index_C;
539 src = buf;
540 /* XXX : This is not going to be the fastest code in the world
541 several optimizations are possible.
543 elements = len / view->itemsize;
544 while (elements--) {
545 addone(view->ndim, indices, view->shape);
546 ptr = PyBuffer_GetPointer(view, indices);
547 memcpy(ptr, src, view->itemsize);
548 src += view->itemsize;
551 PyMem_Free(indices);
552 return 0;
555 int PyObject_CopyData(PyObject *dest, PyObject *src)
557 Py_buffer view_dest, view_src;
558 int k;
559 Py_ssize_t *indices, elements;
560 char *dptr, *sptr;
562 if (!PyObject_CheckBuffer(dest) ||
563 !PyObject_CheckBuffer(src)) {
564 PyErr_SetString(PyExc_TypeError,
565 "both destination and source must have the "\
566 "buffer interface");
567 return -1;
570 if (PyObject_GetBuffer(dest, &view_dest, PyBUF_FULL) != 0) return -1;
571 if (PyObject_GetBuffer(src, &view_src, PyBUF_FULL_RO) != 0) {
572 PyBuffer_Release(&view_dest);
573 return -1;
576 if (view_dest.len < view_src.len) {
577 PyErr_SetString(PyExc_BufferError,
578 "destination is too small to receive data from source");
579 PyBuffer_Release(&view_dest);
580 PyBuffer_Release(&view_src);
581 return -1;
584 if ((PyBuffer_IsContiguous(&view_dest, 'C') &&
585 PyBuffer_IsContiguous(&view_src, 'C')) ||
586 (PyBuffer_IsContiguous(&view_dest, 'F') &&
587 PyBuffer_IsContiguous(&view_src, 'F'))) {
588 /* simplest copy is all that is needed */
589 memcpy(view_dest.buf, view_src.buf, view_src.len);
590 PyBuffer_Release(&view_dest);
591 PyBuffer_Release(&view_src);
592 return 0;
595 /* Otherwise a more elaborate copy scheme is needed */
597 /* XXX(nnorwitz): need to check for overflow! */
598 indices = (Py_ssize_t *)PyMem_Malloc(sizeof(Py_ssize_t)*view_src.ndim);
599 if (indices == NULL) {
600 PyErr_NoMemory();
601 PyBuffer_Release(&view_dest);
602 PyBuffer_Release(&view_src);
603 return -1;
605 for (k=0; k<view_src.ndim;k++) {
606 indices[k] = 0;
608 elements = 1;
609 for (k=0; k<view_src.ndim; k++) {
610 /* XXX(nnorwitz): can this overflow? */
611 elements *= view_src.shape[k];
613 while (elements--) {
614 _add_one_to_index_C(view_src.ndim, indices, view_src.shape);
615 dptr = PyBuffer_GetPointer(&view_dest, indices);
616 sptr = PyBuffer_GetPointer(&view_src, indices);
617 memcpy(dptr, sptr, view_src.itemsize);
619 PyMem_Free(indices);
620 PyBuffer_Release(&view_dest);
621 PyBuffer_Release(&view_src);
622 return 0;
625 void
626 PyBuffer_FillContiguousStrides(int nd, Py_ssize_t *shape,
627 Py_ssize_t *strides, int itemsize,
628 char fort)
630 int k;
631 Py_ssize_t sd;
633 sd = itemsize;
634 if (fort == 'F') {
635 for (k=0; k<nd; k++) {
636 strides[k] = sd;
637 sd *= shape[k];
640 else {
641 for (k=nd-1; k>=0; k--) {
642 strides[k] = sd;
643 sd *= shape[k];
646 return;
650 PyBuffer_FillInfo(Py_buffer *view, PyObject *obj, void *buf, Py_ssize_t len,
651 int readonly, int flags)
653 if (view == NULL) return 0;
654 if (((flags & PyBUF_WRITABLE) == PyBUF_WRITABLE) &&
655 (readonly == 1)) {
656 PyErr_SetString(PyExc_BufferError,
657 "Object is not writable.");
658 return -1;
661 view->obj = obj;
662 if (obj)
663 Py_INCREF(obj);
664 view->buf = buf;
665 view->len = len;
666 view->readonly = readonly;
667 view->itemsize = 1;
668 view->format = NULL;
669 if ((flags & PyBUF_FORMAT) == PyBUF_FORMAT)
670 view->format = "B";
671 view->ndim = 1;
672 view->shape = NULL;
673 if ((flags & PyBUF_ND) == PyBUF_ND)
674 view->shape = &(view->len);
675 view->strides = NULL;
676 if ((flags & PyBUF_STRIDES) == PyBUF_STRIDES)
677 view->strides = &(view->itemsize);
678 view->suboffsets = NULL;
679 view->internal = NULL;
680 return 0;
683 void
684 PyBuffer_Release(Py_buffer *view)
686 PyObject *obj = view->obj;
687 if (obj && Py_TYPE(obj)->tp_as_buffer && Py_TYPE(obj)->tp_as_buffer->bf_releasebuffer)
688 Py_TYPE(obj)->tp_as_buffer->bf_releasebuffer(obj, view);
689 Py_XDECREF(obj);
690 view->obj = NULL;
693 PyObject *
694 PyObject_Format(PyObject *obj, PyObject *format_spec)
696 static PyObject * str__format__ = NULL;
697 PyObject *meth;
698 PyObject *empty = NULL;
699 PyObject *result = NULL;
701 /* Initialize cached value */
702 if (str__format__ == NULL) {
703 /* Initialize static variable needed by _PyType_Lookup */
704 str__format__ = PyUnicode_FromString("__format__");
705 if (str__format__ == NULL)
706 goto done;
709 /* If no format_spec is provided, use an empty string */
710 if (format_spec == NULL) {
711 empty = PyUnicode_FromUnicode(NULL, 0);
712 format_spec = empty;
715 /* Make sure the type is initialized. float gets initialized late */
716 if (Py_TYPE(obj)->tp_dict == NULL)
717 if (PyType_Ready(Py_TYPE(obj)) < 0)
718 goto done;
720 /* Find the (unbound!) __format__ method (a borrowed reference) */
721 meth = _PyType_Lookup(Py_TYPE(obj), str__format__);
722 if (meth == NULL) {
723 PyErr_Format(PyExc_TypeError,
724 "Type %.100s doesn't define __format__",
725 Py_TYPE(obj)->tp_name);
726 goto done;
729 /* And call it, binding it to the value */
730 result = PyObject_CallFunctionObjArgs(meth, obj, format_spec, NULL);
732 if (result && !PyUnicode_Check(result)) {
733 PyErr_SetString(PyExc_TypeError,
734 "__format__ method did not return string");
735 Py_DECREF(result);
736 result = NULL;
737 goto done;
740 done:
741 Py_XDECREF(empty);
742 return result;
744 /* Operations on numbers */
747 PyNumber_Check(PyObject *o)
749 return o && o->ob_type->tp_as_number &&
750 (o->ob_type->tp_as_number->nb_int ||
751 o->ob_type->tp_as_number->nb_float);
754 /* Binary operators */
756 #define NB_SLOT(x) offsetof(PyNumberMethods, x)
757 #define NB_BINOP(nb_methods, slot) \
758 (*(binaryfunc*)(& ((char*)nb_methods)[slot]))
759 #define NB_TERNOP(nb_methods, slot) \
760 (*(ternaryfunc*)(& ((char*)nb_methods)[slot]))
763 Calling scheme used for binary operations:
765 Order operations are tried until either a valid result or error:
766 w.op(v,w)[*], v.op(v,w), w.op(v,w)
768 [*] only when v->ob_type != w->ob_type && w->ob_type is a subclass of
769 v->ob_type
772 static PyObject *
773 binary_op1(PyObject *v, PyObject *w, const int op_slot)
775 PyObject *x;
776 binaryfunc slotv = NULL;
777 binaryfunc slotw = NULL;
779 if (v->ob_type->tp_as_number != NULL)
780 slotv = NB_BINOP(v->ob_type->tp_as_number, op_slot);
781 if (w->ob_type != v->ob_type &&
782 w->ob_type->tp_as_number != NULL) {
783 slotw = NB_BINOP(w->ob_type->tp_as_number, op_slot);
784 if (slotw == slotv)
785 slotw = NULL;
787 if (slotv) {
788 if (slotw && PyType_IsSubtype(w->ob_type, v->ob_type)) {
789 x = slotw(v, w);
790 if (x != Py_NotImplemented)
791 return x;
792 Py_DECREF(x); /* can't do it */
793 slotw = NULL;
795 x = slotv(v, w);
796 if (x != Py_NotImplemented)
797 return x;
798 Py_DECREF(x); /* can't do it */
800 if (slotw) {
801 x = slotw(v, w);
802 if (x != Py_NotImplemented)
803 return x;
804 Py_DECREF(x); /* can't do it */
806 Py_INCREF(Py_NotImplemented);
807 return Py_NotImplemented;
810 static PyObject *
811 binop_type_error(PyObject *v, PyObject *w, const char *op_name)
813 PyErr_Format(PyExc_TypeError,
814 "unsupported operand type(s) for %.100s: "
815 "'%.100s' and '%.100s'",
816 op_name,
817 v->ob_type->tp_name,
818 w->ob_type->tp_name);
819 return NULL;
822 static PyObject *
823 binary_op(PyObject *v, PyObject *w, const int op_slot, const char *op_name)
825 PyObject *result = binary_op1(v, w, op_slot);
826 if (result == Py_NotImplemented) {
827 Py_DECREF(result);
828 return binop_type_error(v, w, op_name);
830 return result;
835 Calling scheme used for ternary operations:
837 Order operations are tried until either a valid result or error:
838 v.op(v,w,z), w.op(v,w,z), z.op(v,w,z)
841 static PyObject *
842 ternary_op(PyObject *v,
843 PyObject *w,
844 PyObject *z,
845 const int op_slot,
846 const char *op_name)
848 PyNumberMethods *mv, *mw, *mz;
849 PyObject *x = NULL;
850 ternaryfunc slotv = NULL;
851 ternaryfunc slotw = NULL;
852 ternaryfunc slotz = NULL;
854 mv = v->ob_type->tp_as_number;
855 mw = w->ob_type->tp_as_number;
856 if (mv != NULL)
857 slotv = NB_TERNOP(mv, op_slot);
858 if (w->ob_type != v->ob_type &&
859 mw != NULL) {
860 slotw = NB_TERNOP(mw, op_slot);
861 if (slotw == slotv)
862 slotw = NULL;
864 if (slotv) {
865 if (slotw && PyType_IsSubtype(w->ob_type, v->ob_type)) {
866 x = slotw(v, w, z);
867 if (x != Py_NotImplemented)
868 return x;
869 Py_DECREF(x); /* can't do it */
870 slotw = NULL;
872 x = slotv(v, w, z);
873 if (x != Py_NotImplemented)
874 return x;
875 Py_DECREF(x); /* can't do it */
877 if (slotw) {
878 x = slotw(v, w, z);
879 if (x != Py_NotImplemented)
880 return x;
881 Py_DECREF(x); /* can't do it */
883 mz = z->ob_type->tp_as_number;
884 if (mz != NULL) {
885 slotz = NB_TERNOP(mz, op_slot);
886 if (slotz == slotv || slotz == slotw)
887 slotz = NULL;
888 if (slotz) {
889 x = slotz(v, w, z);
890 if (x != Py_NotImplemented)
891 return x;
892 Py_DECREF(x); /* can't do it */
896 if (z == Py_None)
897 PyErr_Format(
898 PyExc_TypeError,
899 "unsupported operand type(s) for ** or pow(): "
900 "'%.100s' and '%.100s'",
901 v->ob_type->tp_name,
902 w->ob_type->tp_name);
903 else
904 PyErr_Format(
905 PyExc_TypeError,
906 "unsupported operand type(s) for pow(): "
907 "'%.100s', '%.100s', '%.100s'",
908 v->ob_type->tp_name,
909 w->ob_type->tp_name,
910 z->ob_type->tp_name);
911 return NULL;
914 #define BINARY_FUNC(func, op, op_name) \
915 PyObject * \
916 func(PyObject *v, PyObject *w) { \
917 return binary_op(v, w, NB_SLOT(op), op_name); \
920 BINARY_FUNC(PyNumber_Or, nb_or, "|")
921 BINARY_FUNC(PyNumber_Xor, nb_xor, "^")
922 BINARY_FUNC(PyNumber_And, nb_and, "&")
923 BINARY_FUNC(PyNumber_Lshift, nb_lshift, "<<")
924 BINARY_FUNC(PyNumber_Rshift, nb_rshift, ">>")
925 BINARY_FUNC(PyNumber_Subtract, nb_subtract, "-")
926 BINARY_FUNC(PyNumber_Divmod, nb_divmod, "divmod()")
928 PyObject *
929 PyNumber_Add(PyObject *v, PyObject *w)
931 PyObject *result = binary_op1(v, w, NB_SLOT(nb_add));
932 if (result == Py_NotImplemented) {
933 PySequenceMethods *m = v->ob_type->tp_as_sequence;
934 Py_DECREF(result);
935 if (m && m->sq_concat) {
936 return (*m->sq_concat)(v, w);
938 result = binop_type_error(v, w, "+");
940 return result;
943 static PyObject *
944 sequence_repeat(ssizeargfunc repeatfunc, PyObject *seq, PyObject *n)
946 Py_ssize_t count;
947 if (PyIndex_Check(n)) {
948 count = PyNumber_AsSsize_t(n, PyExc_OverflowError);
949 if (count == -1 && PyErr_Occurred())
950 return NULL;
952 else {
953 return type_error("can't multiply sequence by "
954 "non-int of type '%.200s'", n);
956 return (*repeatfunc)(seq, count);
959 PyObject *
960 PyNumber_Multiply(PyObject *v, PyObject *w)
962 PyObject *result = binary_op1(v, w, NB_SLOT(nb_multiply));
963 if (result == Py_NotImplemented) {
964 PySequenceMethods *mv = v->ob_type->tp_as_sequence;
965 PySequenceMethods *mw = w->ob_type->tp_as_sequence;
966 Py_DECREF(result);
967 if (mv && mv->sq_repeat) {
968 return sequence_repeat(mv->sq_repeat, v, w);
970 else if (mw && mw->sq_repeat) {
971 return sequence_repeat(mw->sq_repeat, w, v);
973 result = binop_type_error(v, w, "*");
975 return result;
978 PyObject *
979 PyNumber_FloorDivide(PyObject *v, PyObject *w)
981 return binary_op(v, w, NB_SLOT(nb_floor_divide), "//");
984 PyObject *
985 PyNumber_TrueDivide(PyObject *v, PyObject *w)
987 return binary_op(v, w, NB_SLOT(nb_true_divide), "/");
990 PyObject *
991 PyNumber_Remainder(PyObject *v, PyObject *w)
993 return binary_op(v, w, NB_SLOT(nb_remainder), "%");
996 PyObject *
997 PyNumber_Power(PyObject *v, PyObject *w, PyObject *z)
999 return ternary_op(v, w, z, NB_SLOT(nb_power), "** or pow()");
1002 /* Binary in-place operators */
1004 /* The in-place operators are defined to fall back to the 'normal',
1005 non in-place operations, if the in-place methods are not in place.
1007 - If the left hand object has the appropriate struct members, and
1008 they are filled, call the appropriate function and return the
1009 result. No coercion is done on the arguments; the left-hand object
1010 is the one the operation is performed on, and it's up to the
1011 function to deal with the right-hand object.
1013 - Otherwise, in-place modification is not supported. Handle it exactly as
1014 a non in-place operation of the same kind.
1018 static PyObject *
1019 binary_iop1(PyObject *v, PyObject *w, const int iop_slot, const int op_slot)
1021 PyNumberMethods *mv = v->ob_type->tp_as_number;
1022 if (mv != NULL) {
1023 binaryfunc slot = NB_BINOP(mv, iop_slot);
1024 if (slot) {
1025 PyObject *x = (slot)(v, w);
1026 if (x != Py_NotImplemented) {
1027 return x;
1029 Py_DECREF(x);
1032 return binary_op1(v, w, op_slot);
1035 static PyObject *
1036 binary_iop(PyObject *v, PyObject *w, const int iop_slot, const int op_slot,
1037 const char *op_name)
1039 PyObject *result = binary_iop1(v, w, iop_slot, op_slot);
1040 if (result == Py_NotImplemented) {
1041 Py_DECREF(result);
1042 return binop_type_error(v, w, op_name);
1044 return result;
1047 #define INPLACE_BINOP(func, iop, op, op_name) \
1048 PyObject * \
1049 func(PyObject *v, PyObject *w) { \
1050 return binary_iop(v, w, NB_SLOT(iop), NB_SLOT(op), op_name); \
1053 INPLACE_BINOP(PyNumber_InPlaceOr, nb_inplace_or, nb_or, "|=")
1054 INPLACE_BINOP(PyNumber_InPlaceXor, nb_inplace_xor, nb_xor, "^=")
1055 INPLACE_BINOP(PyNumber_InPlaceAnd, nb_inplace_and, nb_and, "&=")
1056 INPLACE_BINOP(PyNumber_InPlaceLshift, nb_inplace_lshift, nb_lshift, "<<=")
1057 INPLACE_BINOP(PyNumber_InPlaceRshift, nb_inplace_rshift, nb_rshift, ">>=")
1058 INPLACE_BINOP(PyNumber_InPlaceSubtract, nb_inplace_subtract, nb_subtract, "-=")
1060 PyObject *
1061 PyNumber_InPlaceFloorDivide(PyObject *v, PyObject *w)
1063 return binary_iop(v, w, NB_SLOT(nb_inplace_floor_divide),
1064 NB_SLOT(nb_floor_divide), "//=");
1067 PyObject *
1068 PyNumber_InPlaceTrueDivide(PyObject *v, PyObject *w)
1070 return binary_iop(v, w, NB_SLOT(nb_inplace_true_divide),
1071 NB_SLOT(nb_true_divide), "/=");
1074 PyObject *
1075 PyNumber_InPlaceAdd(PyObject *v, PyObject *w)
1077 PyObject *result = binary_iop1(v, w, NB_SLOT(nb_inplace_add),
1078 NB_SLOT(nb_add));
1079 if (result == Py_NotImplemented) {
1080 PySequenceMethods *m = v->ob_type->tp_as_sequence;
1081 Py_DECREF(result);
1082 if (m != NULL) {
1083 binaryfunc f = NULL;
1084 f = m->sq_inplace_concat;
1085 if (f == NULL)
1086 f = m->sq_concat;
1087 if (f != NULL)
1088 return (*f)(v, w);
1090 result = binop_type_error(v, w, "+=");
1092 return result;
1095 PyObject *
1096 PyNumber_InPlaceMultiply(PyObject *v, PyObject *w)
1098 PyObject *result = binary_iop1(v, w, NB_SLOT(nb_inplace_multiply),
1099 NB_SLOT(nb_multiply));
1100 if (result == Py_NotImplemented) {
1101 ssizeargfunc f = NULL;
1102 PySequenceMethods *mv = v->ob_type->tp_as_sequence;
1103 PySequenceMethods *mw = w->ob_type->tp_as_sequence;
1104 Py_DECREF(result);
1105 if (mv != NULL) {
1106 f = mv->sq_inplace_repeat;
1107 if (f == NULL)
1108 f = mv->sq_repeat;
1109 if (f != NULL)
1110 return sequence_repeat(f, v, w);
1112 else if (mw != NULL) {
1113 /* Note that the right hand operand should not be
1114 * mutated in this case so sq_inplace_repeat is not
1115 * used. */
1116 if (mw->sq_repeat)
1117 return sequence_repeat(mw->sq_repeat, w, v);
1119 result = binop_type_error(v, w, "*=");
1121 return result;
1124 PyObject *
1125 PyNumber_InPlaceRemainder(PyObject *v, PyObject *w)
1127 return binary_iop(v, w, NB_SLOT(nb_inplace_remainder),
1128 NB_SLOT(nb_remainder), "%=");
1131 PyObject *
1132 PyNumber_InPlacePower(PyObject *v, PyObject *w, PyObject *z)
1134 if (v->ob_type->tp_as_number &&
1135 v->ob_type->tp_as_number->nb_inplace_power != NULL) {
1136 return ternary_op(v, w, z, NB_SLOT(nb_inplace_power), "**=");
1138 else {
1139 return ternary_op(v, w, z, NB_SLOT(nb_power), "**=");
1144 /* Unary operators and functions */
1146 PyObject *
1147 PyNumber_Negative(PyObject *o)
1149 PyNumberMethods *m;
1151 if (o == NULL)
1152 return null_error();
1153 m = o->ob_type->tp_as_number;
1154 if (m && m->nb_negative)
1155 return (*m->nb_negative)(o);
1157 return type_error("bad operand type for unary -: '%.200s'", o);
1160 PyObject *
1161 PyNumber_Positive(PyObject *o)
1163 PyNumberMethods *m;
1165 if (o == NULL)
1166 return null_error();
1167 m = o->ob_type->tp_as_number;
1168 if (m && m->nb_positive)
1169 return (*m->nb_positive)(o);
1171 return type_error("bad operand type for unary +: '%.200s'", o);
1174 PyObject *
1175 PyNumber_Invert(PyObject *o)
1177 PyNumberMethods *m;
1179 if (o == NULL)
1180 return null_error();
1181 m = o->ob_type->tp_as_number;
1182 if (m && m->nb_invert)
1183 return (*m->nb_invert)(o);
1185 return type_error("bad operand type for unary ~: '%.200s'", o);
1188 PyObject *
1189 PyNumber_Absolute(PyObject *o)
1191 PyNumberMethods *m;
1193 if (o == NULL)
1194 return null_error();
1195 m = o->ob_type->tp_as_number;
1196 if (m && m->nb_absolute)
1197 return m->nb_absolute(o);
1199 return type_error("bad operand type for abs(): '%.200s'", o);
1202 /* Return a Python Int or Long from the object item
1203 Raise TypeError if the result is not an int-or-long
1204 or if the object cannot be interpreted as an index.
1206 PyObject *
1207 PyNumber_Index(PyObject *item)
1209 PyObject *result = NULL;
1210 if (item == NULL)
1211 return null_error();
1212 if (PyLong_Check(item)) {
1213 Py_INCREF(item);
1214 return item;
1216 if (PyIndex_Check(item)) {
1217 result = item->ob_type->tp_as_number->nb_index(item);
1218 if (result && !PyLong_Check(result)) {
1219 PyErr_Format(PyExc_TypeError,
1220 "__index__ returned non-int "
1221 "(type %.200s)",
1222 result->ob_type->tp_name);
1223 Py_DECREF(result);
1224 return NULL;
1227 else {
1228 PyErr_Format(PyExc_TypeError,
1229 "'%.200s' object cannot be interpreted "
1230 "as an integer", item->ob_type->tp_name);
1232 return result;
1235 /* Return an error on Overflow only if err is not NULL*/
1237 Py_ssize_t
1238 PyNumber_AsSsize_t(PyObject *item, PyObject *err)
1240 Py_ssize_t result;
1241 PyObject *runerr;
1242 PyObject *value = PyNumber_Index(item);
1243 if (value == NULL)
1244 return -1;
1246 /* We're done if PyLong_AsSsize_t() returns without error. */
1247 result = PyLong_AsSsize_t(value);
1248 if (result != -1 || !(runerr = PyErr_Occurred()))
1249 goto finish;
1251 /* Error handling code -- only manage OverflowError differently */
1252 if (!PyErr_GivenExceptionMatches(runerr, PyExc_OverflowError))
1253 goto finish;
1255 PyErr_Clear();
1256 /* If no error-handling desired then the default clipping
1257 is sufficient.
1259 if (!err) {
1260 assert(PyLong_Check(value));
1261 /* Whether or not it is less than or equal to
1262 zero is determined by the sign of ob_size
1264 if (_PyLong_Sign(value) < 0)
1265 result = PY_SSIZE_T_MIN;
1266 else
1267 result = PY_SSIZE_T_MAX;
1269 else {
1270 /* Otherwise replace the error with caller's error object. */
1271 PyErr_Format(err,
1272 "cannot fit '%.200s' into an index-sized integer",
1273 item->ob_type->tp_name);
1276 finish:
1277 Py_DECREF(value);
1278 return result;
1282 PyObject *
1283 _PyNumber_ConvertIntegralToInt(PyObject *integral, const char* error_format)
1285 static PyObject *int_name = NULL;
1286 if (int_name == NULL) {
1287 int_name = PyUnicode_InternFromString("__int__");
1288 if (int_name == NULL)
1289 return NULL;
1292 if (integral && !PyLong_Check(integral)) {
1293 /* Don't go through tp_as_number->nb_int to avoid
1294 hitting the classic class fallback to __trunc__. */
1295 PyObject *int_func = PyObject_GetAttr(integral, int_name);
1296 if (int_func == NULL) {
1297 PyErr_Clear(); /* Raise a different error. */
1298 goto non_integral_error;
1300 Py_DECREF(integral);
1301 integral = PyEval_CallObject(int_func, NULL);
1302 Py_DECREF(int_func);
1303 if (integral && !PyLong_Check(integral)) {
1304 goto non_integral_error;
1307 return integral;
1309 non_integral_error:
1310 PyErr_Format(PyExc_TypeError, error_format, Py_TYPE(integral)->tp_name);
1311 Py_DECREF(integral);
1312 return NULL;
1316 /* Add a check for embedded NULL-bytes in the argument. */
1317 static PyObject *
1318 long_from_string(const char *s, Py_ssize_t len)
1320 char *end;
1321 PyObject *x;
1323 x = PyLong_FromString((char*)s, &end, 10);
1324 if (x == NULL)
1325 return NULL;
1326 if (end != s + len) {
1327 PyErr_SetString(PyExc_ValueError,
1328 "null byte in argument for int()");
1329 Py_DECREF(x);
1330 return NULL;
1332 return x;
1335 PyObject *
1336 PyNumber_Long(PyObject *o)
1338 PyNumberMethods *m;
1339 static PyObject *trunc_name = NULL;
1340 PyObject *trunc_func;
1341 const char *buffer;
1342 Py_ssize_t buffer_len;
1344 if (trunc_name == NULL) {
1345 trunc_name = PyUnicode_InternFromString("__trunc__");
1346 if (trunc_name == NULL)
1347 return NULL;
1350 if (o == NULL)
1351 return null_error();
1352 if (PyLong_CheckExact(o)) {
1353 Py_INCREF(o);
1354 return o;
1356 m = o->ob_type->tp_as_number;
1357 if (m && m->nb_int) { /* This should include subclasses of int */
1358 PyObject *res = m->nb_int(o);
1359 if (res && !PyLong_Check(res)) {
1360 PyErr_Format(PyExc_TypeError,
1361 "__int__ returned non-int (type %.200s)",
1362 res->ob_type->tp_name);
1363 Py_DECREF(res);
1364 return NULL;
1366 return res;
1368 if (PyLong_Check(o)) /* An int subclass without nb_int */
1369 return _PyLong_Copy((PyLongObject *)o);
1370 trunc_func = PyObject_GetAttr(o, trunc_name);
1371 if (trunc_func) {
1372 PyObject *truncated = PyEval_CallObject(trunc_func, NULL);
1373 PyObject *int_instance;
1374 Py_DECREF(trunc_func);
1375 /* __trunc__ is specified to return an Integral type,
1376 but long() needs to return a long. */
1377 int_instance = _PyNumber_ConvertIntegralToInt(
1378 truncated,
1379 "__trunc__ returned non-Integral (type %.200s)");
1380 return int_instance;
1382 PyErr_Clear(); /* It's not an error if o.__trunc__ doesn't exist. */
1384 if (PyBytes_Check(o))
1385 /* need to do extra error checking that PyLong_FromString()
1386 * doesn't do. In particular long('9.5') must raise an
1387 * exception, not truncate the float.
1389 return long_from_string(PyBytes_AS_STRING(o),
1390 PyBytes_GET_SIZE(o));
1391 if (PyUnicode_Check(o))
1392 /* The above check is done in PyLong_FromUnicode(). */
1393 return PyLong_FromUnicode(PyUnicode_AS_UNICODE(o),
1394 PyUnicode_GET_SIZE(o),
1395 10);
1396 if (!PyObject_AsCharBuffer(o, &buffer, &buffer_len))
1397 return long_from_string(buffer, buffer_len);
1399 return type_error("int() argument must be a string or a "
1400 "number, not '%.200s'", o);
1403 PyObject *
1404 PyNumber_Float(PyObject *o)
1406 PyNumberMethods *m;
1408 if (o == NULL)
1409 return null_error();
1410 m = o->ob_type->tp_as_number;
1411 if (m && m->nb_float) { /* This should include subclasses of float */
1412 PyObject *res = m->nb_float(o);
1413 if (res && !PyFloat_Check(res)) {
1414 PyErr_Format(PyExc_TypeError,
1415 "__float__ returned non-float (type %.200s)",
1416 res->ob_type->tp_name);
1417 Py_DECREF(res);
1418 return NULL;
1420 return res;
1422 if (PyFloat_Check(o)) { /* A float subclass with nb_float == NULL */
1423 PyFloatObject *po = (PyFloatObject *)o;
1424 return PyFloat_FromDouble(po->ob_fval);
1426 return PyFloat_FromString(o);
1430 PyObject *
1431 PyNumber_ToBase(PyObject *n, int base)
1433 PyObject *res = NULL;
1434 PyObject *index = PyNumber_Index(n);
1436 if (!index)
1437 return NULL;
1438 if (PyLong_Check(index))
1439 res = _PyLong_Format(index, base);
1440 else
1441 /* It should not be possible to get here, as
1442 PyNumber_Index already has a check for the same
1443 condition */
1444 PyErr_SetString(PyExc_ValueError, "PyNumber_ToBase: index not "
1445 "int or long");
1446 Py_DECREF(index);
1447 return res;
1451 /* Operations on sequences */
1454 PySequence_Check(PyObject *s)
1456 if (PyObject_IsInstance(s, (PyObject *)&PyDict_Type))
1457 return 0;
1458 return s != NULL && s->ob_type->tp_as_sequence &&
1459 s->ob_type->tp_as_sequence->sq_item != NULL;
1462 Py_ssize_t
1463 PySequence_Size(PyObject *s)
1465 PySequenceMethods *m;
1467 if (s == NULL) {
1468 null_error();
1469 return -1;
1472 m = s->ob_type->tp_as_sequence;
1473 if (m && m->sq_length)
1474 return m->sq_length(s);
1476 type_error("object of type '%.200s' has no len()", s);
1477 return -1;
1480 #undef PySequence_Length
1481 Py_ssize_t
1482 PySequence_Length(PyObject *s)
1484 return PySequence_Size(s);
1486 #define PySequence_Length PySequence_Size
1488 PyObject *
1489 PySequence_Concat(PyObject *s, PyObject *o)
1491 PySequenceMethods *m;
1493 if (s == NULL || o == NULL)
1494 return null_error();
1496 m = s->ob_type->tp_as_sequence;
1497 if (m && m->sq_concat)
1498 return m->sq_concat(s, o);
1500 /* Instances of user classes defining an __add__() method only
1501 have an nb_add slot, not an sq_concat slot. So we fall back
1502 to nb_add if both arguments appear to be sequences. */
1503 if (PySequence_Check(s) && PySequence_Check(o)) {
1504 PyObject *result = binary_op1(s, o, NB_SLOT(nb_add));
1505 if (result != Py_NotImplemented)
1506 return result;
1507 Py_DECREF(result);
1509 return type_error("'%.200s' object can't be concatenated", s);
1512 PyObject *
1513 PySequence_Repeat(PyObject *o, Py_ssize_t count)
1515 PySequenceMethods *m;
1517 if (o == NULL)
1518 return null_error();
1520 m = o->ob_type->tp_as_sequence;
1521 if (m && m->sq_repeat)
1522 return m->sq_repeat(o, count);
1524 /* Instances of user classes defining a __mul__() method only
1525 have an nb_multiply slot, not an sq_repeat slot. so we fall back
1526 to nb_multiply if o appears to be a sequence. */
1527 if (PySequence_Check(o)) {
1528 PyObject *n, *result;
1529 n = PyLong_FromSsize_t(count);
1530 if (n == NULL)
1531 return NULL;
1532 result = binary_op1(o, n, NB_SLOT(nb_multiply));
1533 Py_DECREF(n);
1534 if (result != Py_NotImplemented)
1535 return result;
1536 Py_DECREF(result);
1538 return type_error("'%.200s' object can't be repeated", o);
1541 PyObject *
1542 PySequence_InPlaceConcat(PyObject *s, PyObject *o)
1544 PySequenceMethods *m;
1546 if (s == NULL || o == NULL)
1547 return null_error();
1549 m = s->ob_type->tp_as_sequence;
1550 if (m && m->sq_inplace_concat)
1551 return m->sq_inplace_concat(s, o);
1552 if (m && m->sq_concat)
1553 return m->sq_concat(s, o);
1555 if (PySequence_Check(s) && PySequence_Check(o)) {
1556 PyObject *result = binary_iop1(s, o, NB_SLOT(nb_inplace_add),
1557 NB_SLOT(nb_add));
1558 if (result != Py_NotImplemented)
1559 return result;
1560 Py_DECREF(result);
1562 return type_error("'%.200s' object can't be concatenated", s);
1565 PyObject *
1566 PySequence_InPlaceRepeat(PyObject *o, Py_ssize_t count)
1568 PySequenceMethods *m;
1570 if (o == NULL)
1571 return null_error();
1573 m = o->ob_type->tp_as_sequence;
1574 if (m && m->sq_inplace_repeat)
1575 return m->sq_inplace_repeat(o, count);
1576 if (m && m->sq_repeat)
1577 return m->sq_repeat(o, count);
1579 if (PySequence_Check(o)) {
1580 PyObject *n, *result;
1581 n = PyLong_FromSsize_t(count);
1582 if (n == NULL)
1583 return NULL;
1584 result = binary_iop1(o, n, NB_SLOT(nb_inplace_multiply),
1585 NB_SLOT(nb_multiply));
1586 Py_DECREF(n);
1587 if (result != Py_NotImplemented)
1588 return result;
1589 Py_DECREF(result);
1591 return type_error("'%.200s' object can't be repeated", o);
1594 PyObject *
1595 PySequence_GetItem(PyObject *s, Py_ssize_t i)
1597 PySequenceMethods *m;
1599 if (s == NULL)
1600 return null_error();
1602 m = s->ob_type->tp_as_sequence;
1603 if (m && m->sq_item) {
1604 if (i < 0) {
1605 if (m->sq_length) {
1606 Py_ssize_t l = (*m->sq_length)(s);
1607 if (l < 0)
1608 return NULL;
1609 i += l;
1612 return m->sq_item(s, i);
1615 return type_error("'%.200s' object does not support indexing", s);
1618 PyObject *
1619 PySequence_GetSlice(PyObject *s, Py_ssize_t i1, Py_ssize_t i2)
1621 PyMappingMethods *mp;
1623 if (!s) return null_error();
1625 mp = s->ob_type->tp_as_mapping;
1626 if (mp->mp_subscript) {
1627 PyObject *res;
1628 PyObject *slice = _PySlice_FromIndices(i1, i2);
1629 if (!slice)
1630 return NULL;
1631 res = mp->mp_subscript(s, slice);
1632 Py_DECREF(slice);
1633 return res;
1636 return type_error("'%.200s' object is unsliceable", s);
1640 PySequence_SetItem(PyObject *s, Py_ssize_t i, PyObject *o)
1642 PySequenceMethods *m;
1644 if (s == NULL) {
1645 null_error();
1646 return -1;
1649 m = s->ob_type->tp_as_sequence;
1650 if (m && m->sq_ass_item) {
1651 if (i < 0) {
1652 if (m->sq_length) {
1653 Py_ssize_t l = (*m->sq_length)(s);
1654 if (l < 0)
1655 return -1;
1656 i += l;
1659 return m->sq_ass_item(s, i, o);
1662 type_error("'%.200s' object does not support item assignment", s);
1663 return -1;
1667 PySequence_DelItem(PyObject *s, Py_ssize_t i)
1669 PySequenceMethods *m;
1671 if (s == NULL) {
1672 null_error();
1673 return -1;
1676 m = s->ob_type->tp_as_sequence;
1677 if (m && m->sq_ass_item) {
1678 if (i < 0) {
1679 if (m->sq_length) {
1680 Py_ssize_t l = (*m->sq_length)(s);
1681 if (l < 0)
1682 return -1;
1683 i += l;
1686 return m->sq_ass_item(s, i, (PyObject *)NULL);
1689 type_error("'%.200s' object doesn't support item deletion", s);
1690 return -1;
1694 PySequence_SetSlice(PyObject *s, Py_ssize_t i1, Py_ssize_t i2, PyObject *o)
1696 PyMappingMethods *mp;
1698 if (s == NULL) {
1699 null_error();
1700 return -1;
1703 mp = s->ob_type->tp_as_mapping;
1704 if (mp->mp_ass_subscript) {
1705 int res;
1706 PyObject *slice = _PySlice_FromIndices(i1, i2);
1707 if (!slice)
1708 return -1;
1709 res = mp->mp_ass_subscript(s, slice, o);
1710 Py_DECREF(slice);
1711 return res;
1714 type_error("'%.200s' object doesn't support slice assignment", s);
1715 return -1;
1719 PySequence_DelSlice(PyObject *s, Py_ssize_t i1, Py_ssize_t i2)
1721 PyMappingMethods *mp;
1723 if (s == NULL) {
1724 null_error();
1725 return -1;
1728 mp = s->ob_type->tp_as_mapping;
1729 if (mp->mp_ass_subscript) {
1730 int res;
1731 PyObject *slice = _PySlice_FromIndices(i1, i2);
1732 if (!slice)
1733 return -1;
1734 res = mp->mp_ass_subscript(s, slice, NULL);
1735 Py_DECREF(slice);
1736 return res;
1738 type_error("'%.200s' object doesn't support slice deletion", s);
1739 return -1;
1742 PyObject *
1743 PySequence_Tuple(PyObject *v)
1745 PyObject *it; /* iter(v) */
1746 Py_ssize_t n; /* guess for result tuple size */
1747 PyObject *result = NULL;
1748 Py_ssize_t j;
1750 if (v == NULL)
1751 return null_error();
1753 /* Special-case the common tuple and list cases, for efficiency. */
1754 if (PyTuple_CheckExact(v)) {
1755 /* Note that we can't know whether it's safe to return
1756 a tuple *subclass* instance as-is, hence the restriction
1757 to exact tuples here. In contrast, lists always make
1758 a copy, so there's no need for exactness below. */
1759 Py_INCREF(v);
1760 return v;
1762 if (PyList_Check(v))
1763 return PyList_AsTuple(v);
1765 /* Get iterator. */
1766 it = PyObject_GetIter(v);
1767 if (it == NULL)
1768 return NULL;
1770 /* Guess result size and allocate space. */
1771 n = _PyObject_LengthHint(v, 10);
1772 if (n == -1)
1773 goto Fail;
1774 result = PyTuple_New(n);
1775 if (result == NULL)
1776 goto Fail;
1778 /* Fill the tuple. */
1779 for (j = 0; ; ++j) {
1780 PyObject *item = PyIter_Next(it);
1781 if (item == NULL) {
1782 if (PyErr_Occurred())
1783 goto Fail;
1784 break;
1786 if (j >= n) {
1787 Py_ssize_t oldn = n;
1788 /* The over-allocation strategy can grow a bit faster
1789 than for lists because unlike lists the
1790 over-allocation isn't permanent -- we reclaim
1791 the excess before the end of this routine.
1792 So, grow by ten and then add 25%.
1794 n += 10;
1795 n += n >> 2;
1796 if (n < oldn) {
1797 /* Check for overflow */
1798 PyErr_NoMemory();
1799 Py_DECREF(item);
1800 goto Fail;
1802 if (_PyTuple_Resize(&result, n) != 0) {
1803 Py_DECREF(item);
1804 goto Fail;
1807 PyTuple_SET_ITEM(result, j, item);
1810 /* Cut tuple back if guess was too large. */
1811 if (j < n &&
1812 _PyTuple_Resize(&result, j) != 0)
1813 goto Fail;
1815 Py_DECREF(it);
1816 return result;
1818 Fail:
1819 Py_XDECREF(result);
1820 Py_DECREF(it);
1821 return NULL;
1824 PyObject *
1825 PySequence_List(PyObject *v)
1827 PyObject *result; /* result list */
1828 PyObject *rv; /* return value from PyList_Extend */
1830 if (v == NULL)
1831 return null_error();
1833 result = PyList_New(0);
1834 if (result == NULL)
1835 return NULL;
1837 rv = _PyList_Extend((PyListObject *)result, v);
1838 if (rv == NULL) {
1839 Py_DECREF(result);
1840 return NULL;
1842 Py_DECREF(rv);
1843 return result;
1846 PyObject *
1847 PySequence_Fast(PyObject *v, const char *m)
1849 PyObject *it;
1851 if (v == NULL)
1852 return null_error();
1854 if (PyList_CheckExact(v) || PyTuple_CheckExact(v)) {
1855 Py_INCREF(v);
1856 return v;
1859 it = PyObject_GetIter(v);
1860 if (it == NULL) {
1861 if (PyErr_ExceptionMatches(PyExc_TypeError))
1862 PyErr_SetString(PyExc_TypeError, m);
1863 return NULL;
1866 v = PySequence_List(it);
1867 Py_DECREF(it);
1869 return v;
1872 /* Iterate over seq. Result depends on the operation:
1873 PY_ITERSEARCH_COUNT: -1 if error, else # of times obj appears in seq.
1874 PY_ITERSEARCH_INDEX: 0-based index of first occurrence of obj in seq;
1875 set ValueError and return -1 if none found; also return -1 on error.
1876 Py_ITERSEARCH_CONTAINS: return 1 if obj in seq, else 0; -1 on error.
1878 Py_ssize_t
1879 _PySequence_IterSearch(PyObject *seq, PyObject *obj, int operation)
1881 Py_ssize_t n;
1882 int wrapped; /* for PY_ITERSEARCH_INDEX, true iff n wrapped around */
1883 PyObject *it; /* iter(seq) */
1885 if (seq == NULL || obj == NULL) {
1886 null_error();
1887 return -1;
1890 it = PyObject_GetIter(seq);
1891 if (it == NULL) {
1892 type_error("argument of type '%.200s' is not iterable", seq);
1893 return -1;
1896 n = wrapped = 0;
1897 for (;;) {
1898 int cmp;
1899 PyObject *item = PyIter_Next(it);
1900 if (item == NULL) {
1901 if (PyErr_Occurred())
1902 goto Fail;
1903 break;
1906 cmp = PyObject_RichCompareBool(obj, item, Py_EQ);
1907 Py_DECREF(item);
1908 if (cmp < 0)
1909 goto Fail;
1910 if (cmp > 0) {
1911 switch (operation) {
1912 case PY_ITERSEARCH_COUNT:
1913 if (n == PY_SSIZE_T_MAX) {
1914 PyErr_SetString(PyExc_OverflowError,
1915 "count exceeds C integer size");
1916 goto Fail;
1918 ++n;
1919 break;
1921 case PY_ITERSEARCH_INDEX:
1922 if (wrapped) {
1923 PyErr_SetString(PyExc_OverflowError,
1924 "index exceeds C integer size");
1925 goto Fail;
1927 goto Done;
1929 case PY_ITERSEARCH_CONTAINS:
1930 n = 1;
1931 goto Done;
1933 default:
1934 assert(!"unknown operation");
1938 if (operation == PY_ITERSEARCH_INDEX) {
1939 if (n == PY_SSIZE_T_MAX)
1940 wrapped = 1;
1941 ++n;
1945 if (operation != PY_ITERSEARCH_INDEX)
1946 goto Done;
1948 PyErr_SetString(PyExc_ValueError,
1949 "sequence.index(x): x not in sequence");
1950 /* fall into failure code */
1951 Fail:
1952 n = -1;
1953 /* fall through */
1954 Done:
1955 Py_DECREF(it);
1956 return n;
1960 /* Return # of times o appears in s. */
1961 Py_ssize_t
1962 PySequence_Count(PyObject *s, PyObject *o)
1964 return _PySequence_IterSearch(s, o, PY_ITERSEARCH_COUNT);
1967 /* Return -1 if error; 1 if ob in seq; 0 if ob not in seq.
1968 * Use sq_contains if possible, else defer to _PySequence_IterSearch().
1971 PySequence_Contains(PyObject *seq, PyObject *ob)
1973 Py_ssize_t result;
1974 PySequenceMethods *sqm = seq->ob_type->tp_as_sequence;
1975 if (sqm != NULL && sqm->sq_contains != NULL)
1976 return (*sqm->sq_contains)(seq, ob);
1977 result = _PySequence_IterSearch(seq, ob, PY_ITERSEARCH_CONTAINS);
1978 return Py_SAFE_DOWNCAST(result, Py_ssize_t, int);
1981 /* Backwards compatibility */
1982 #undef PySequence_In
1984 PySequence_In(PyObject *w, PyObject *v)
1986 return PySequence_Contains(w, v);
1989 Py_ssize_t
1990 PySequence_Index(PyObject *s, PyObject *o)
1992 return _PySequence_IterSearch(s, o, PY_ITERSEARCH_INDEX);
1995 /* Operations on mappings */
1998 PyMapping_Check(PyObject *o)
2000 return o && o->ob_type->tp_as_mapping &&
2001 o->ob_type->tp_as_mapping->mp_subscript;
2004 Py_ssize_t
2005 PyMapping_Size(PyObject *o)
2007 PyMappingMethods *m;
2009 if (o == NULL) {
2010 null_error();
2011 return -1;
2014 m = o->ob_type->tp_as_mapping;
2015 if (m && m->mp_length)
2016 return m->mp_length(o);
2018 type_error("object of type '%.200s' has no len()", o);
2019 return -1;
2022 #undef PyMapping_Length
2023 Py_ssize_t
2024 PyMapping_Length(PyObject *o)
2026 return PyMapping_Size(o);
2028 #define PyMapping_Length PyMapping_Size
2030 PyObject *
2031 PyMapping_GetItemString(PyObject *o, char *key)
2033 PyObject *okey, *r;
2035 if (key == NULL)
2036 return null_error();
2038 okey = PyUnicode_FromString(key);
2039 if (okey == NULL)
2040 return NULL;
2041 r = PyObject_GetItem(o, okey);
2042 Py_DECREF(okey);
2043 return r;
2047 PyMapping_SetItemString(PyObject *o, char *key, PyObject *value)
2049 PyObject *okey;
2050 int r;
2052 if (key == NULL) {
2053 null_error();
2054 return -1;
2057 okey = PyUnicode_FromString(key);
2058 if (okey == NULL)
2059 return -1;
2060 r = PyObject_SetItem(o, okey, value);
2061 Py_DECREF(okey);
2062 return r;
2066 PyMapping_HasKeyString(PyObject *o, char *key)
2068 PyObject *v;
2070 v = PyMapping_GetItemString(o, key);
2071 if (v) {
2072 Py_DECREF(v);
2073 return 1;
2075 PyErr_Clear();
2076 return 0;
2080 PyMapping_HasKey(PyObject *o, PyObject *key)
2082 PyObject *v;
2084 v = PyObject_GetItem(o, key);
2085 if (v) {
2086 Py_DECREF(v);
2087 return 1;
2089 PyErr_Clear();
2090 return 0;
2093 PyObject *
2094 PyMapping_Keys(PyObject *o)
2096 PyObject *keys;
2097 PyObject *fast;
2099 if (PyDict_CheckExact(o))
2100 return PyDict_Keys(o);
2101 keys = PyObject_CallMethod(o, "keys", NULL);
2102 if (keys == NULL)
2103 return NULL;
2104 fast = PySequence_Fast(keys, "o.keys() are not iterable");
2105 Py_DECREF(keys);
2106 return fast;
2109 PyObject *
2110 PyMapping_Items(PyObject *o)
2112 PyObject *items;
2113 PyObject *fast;
2115 if (PyDict_CheckExact(o))
2116 return PyDict_Items(o);
2117 items = PyObject_CallMethod(o, "items", NULL);
2118 if (items == NULL)
2119 return NULL;
2120 fast = PySequence_Fast(items, "o.items() are not iterable");
2121 Py_DECREF(items);
2122 return fast;
2125 PyObject *
2126 PyMapping_Values(PyObject *o)
2128 PyObject *values;
2129 PyObject *fast;
2131 if (PyDict_CheckExact(o))
2132 return PyDict_Values(o);
2133 values = PyObject_CallMethod(o, "values", NULL);
2134 if (values == NULL)
2135 return NULL;
2136 fast = PySequence_Fast(values, "o.values() are not iterable");
2137 Py_DECREF(values);
2138 return fast;
2141 /* Operations on callable objects */
2143 /* XXX PyCallable_Check() is in object.c */
2145 PyObject *
2146 PyObject_CallObject(PyObject *o, PyObject *a)
2148 return PyEval_CallObjectWithKeywords(o, a, NULL);
2151 PyObject *
2152 PyObject_Call(PyObject *func, PyObject *arg, PyObject *kw)
2154 ternaryfunc call;
2156 if ((call = func->ob_type->tp_call) != NULL) {
2157 PyObject *result;
2158 if (Py_EnterRecursiveCall(" while calling a Python object"))
2159 return NULL;
2160 result = (*call)(func, arg, kw);
2161 Py_LeaveRecursiveCall();
2162 if (result == NULL && !PyErr_Occurred())
2163 PyErr_SetString(
2164 PyExc_SystemError,
2165 "NULL result without error in PyObject_Call");
2166 return result;
2168 PyErr_Format(PyExc_TypeError, "'%.200s' object is not callable",
2169 func->ob_type->tp_name);
2170 return NULL;
2173 static PyObject*
2174 call_function_tail(PyObject *callable, PyObject *args)
2176 PyObject *retval;
2178 if (args == NULL)
2179 return NULL;
2181 if (!PyTuple_Check(args)) {
2182 PyObject *a;
2184 a = PyTuple_New(1);
2185 if (a == NULL) {
2186 Py_DECREF(args);
2187 return NULL;
2189 PyTuple_SET_ITEM(a, 0, args);
2190 args = a;
2192 retval = PyObject_Call(callable, args, NULL);
2194 Py_DECREF(args);
2196 return retval;
2199 PyObject *
2200 PyObject_CallFunction(PyObject *callable, char *format, ...)
2202 va_list va;
2203 PyObject *args;
2205 if (callable == NULL)
2206 return null_error();
2208 if (format && *format) {
2209 va_start(va, format);
2210 args = Py_VaBuildValue(format, va);
2211 va_end(va);
2213 else
2214 args = PyTuple_New(0);
2216 return call_function_tail(callable, args);
2219 PyObject *
2220 _PyObject_CallFunction_SizeT(PyObject *callable, char *format, ...)
2222 va_list va;
2223 PyObject *args;
2225 if (callable == NULL)
2226 return null_error();
2228 if (format && *format) {
2229 va_start(va, format);
2230 args = _Py_VaBuildValue_SizeT(format, va);
2231 va_end(va);
2233 else
2234 args = PyTuple_New(0);
2236 return call_function_tail(callable, args);
2239 PyObject *
2240 PyObject_CallMethod(PyObject *o, char *name, char *format, ...)
2242 va_list va;
2243 PyObject *args;
2244 PyObject *func = NULL;
2245 PyObject *retval = NULL;
2247 if (o == NULL || name == NULL)
2248 return null_error();
2250 func = PyObject_GetAttrString(o, name);
2251 if (func == NULL) {
2252 PyErr_SetString(PyExc_AttributeError, name);
2253 return 0;
2256 if (!PyCallable_Check(func)) {
2257 type_error("attribute of type '%.200s' is not callable", func);
2258 goto exit;
2261 if (format && *format) {
2262 va_start(va, format);
2263 args = Py_VaBuildValue(format, va);
2264 va_end(va);
2266 else
2267 args = PyTuple_New(0);
2269 retval = call_function_tail(func, args);
2271 exit:
2272 /* args gets consumed in call_function_tail */
2273 Py_XDECREF(func);
2275 return retval;
2278 PyObject *
2279 _PyObject_CallMethod_SizeT(PyObject *o, char *name, char *format, ...)
2281 va_list va;
2282 PyObject *args;
2283 PyObject *func = NULL;
2284 PyObject *retval = NULL;
2286 if (o == NULL || name == NULL)
2287 return null_error();
2289 func = PyObject_GetAttrString(o, name);
2290 if (func == NULL) {
2291 PyErr_SetString(PyExc_AttributeError, name);
2292 return 0;
2295 if (!PyCallable_Check(func)) {
2296 type_error("attribute of type '%.200s' is not callable", func);
2297 goto exit;
2300 if (format && *format) {
2301 va_start(va, format);
2302 args = _Py_VaBuildValue_SizeT(format, va);
2303 va_end(va);
2305 else
2306 args = PyTuple_New(0);
2308 retval = call_function_tail(func, args);
2310 exit:
2311 /* args gets consumed in call_function_tail */
2312 Py_XDECREF(func);
2314 return retval;
2318 static PyObject *
2319 objargs_mktuple(va_list va)
2321 int i, n = 0;
2322 va_list countva;
2323 PyObject *result, *tmp;
2325 #ifdef VA_LIST_IS_ARRAY
2326 memcpy(countva, va, sizeof(va_list));
2327 #else
2328 #ifdef __va_copy
2329 __va_copy(countva, va);
2330 #else
2331 countva = va;
2332 #endif
2333 #endif
2335 while (((PyObject *)va_arg(countva, PyObject *)) != NULL)
2336 ++n;
2337 result = PyTuple_New(n);
2338 if (result != NULL && n > 0) {
2339 for (i = 0; i < n; ++i) {
2340 tmp = (PyObject *)va_arg(va, PyObject *);
2341 PyTuple_SET_ITEM(result, i, tmp);
2342 Py_INCREF(tmp);
2345 return result;
2348 PyObject *
2349 PyObject_CallMethodObjArgs(PyObject *callable, PyObject *name, ...)
2351 PyObject *args, *tmp;
2352 va_list vargs;
2354 if (callable == NULL || name == NULL)
2355 return null_error();
2357 callable = PyObject_GetAttr(callable, name);
2358 if (callable == NULL)
2359 return NULL;
2361 /* count the args */
2362 va_start(vargs, name);
2363 args = objargs_mktuple(vargs);
2364 va_end(vargs);
2365 if (args == NULL) {
2366 Py_DECREF(callable);
2367 return NULL;
2369 tmp = PyObject_Call(callable, args, NULL);
2370 Py_DECREF(args);
2371 Py_DECREF(callable);
2373 return tmp;
2376 PyObject *
2377 PyObject_CallFunctionObjArgs(PyObject *callable, ...)
2379 PyObject *args, *tmp;
2380 va_list vargs;
2382 if (callable == NULL)
2383 return null_error();
2385 /* count the args */
2386 va_start(vargs, callable);
2387 args = objargs_mktuple(vargs);
2388 va_end(vargs);
2389 if (args == NULL)
2390 return NULL;
2391 tmp = PyObject_Call(callable, args, NULL);
2392 Py_DECREF(args);
2394 return tmp;
2398 /* isinstance(), issubclass() */
2400 /* abstract_get_bases() has logically 4 return states, with a sort of 0th
2401 * state that will almost never happen.
2403 * 0. creating the __bases__ static string could get a MemoryError
2404 * 1. getattr(cls, '__bases__') could raise an AttributeError
2405 * 2. getattr(cls, '__bases__') could raise some other exception
2406 * 3. getattr(cls, '__bases__') could return a tuple
2407 * 4. getattr(cls, '__bases__') could return something other than a tuple
2409 * Only state #3 is a non-error state and only it returns a non-NULL object
2410 * (it returns the retrieved tuple).
2412 * Any raised AttributeErrors are masked by clearing the exception and
2413 * returning NULL. If an object other than a tuple comes out of __bases__,
2414 * then again, the return value is NULL. So yes, these two situations
2415 * produce exactly the same results: NULL is returned and no error is set.
2417 * If some exception other than AttributeError is raised, then NULL is also
2418 * returned, but the exception is not cleared. That's because we want the
2419 * exception to be propagated along.
2421 * Callers are expected to test for PyErr_Occurred() when the return value
2422 * is NULL to decide whether a valid exception should be propagated or not.
2423 * When there's no exception to propagate, it's customary for the caller to
2424 * set a TypeError.
2426 static PyObject *
2427 abstract_get_bases(PyObject *cls)
2429 static PyObject *__bases__ = NULL;
2430 PyObject *bases;
2432 if (__bases__ == NULL) {
2433 __bases__ = PyUnicode_InternFromString("__bases__");
2434 if (__bases__ == NULL)
2435 return NULL;
2437 Py_ALLOW_RECURSION
2438 bases = PyObject_GetAttr(cls, __bases__);
2439 Py_END_ALLOW_RECURSION
2440 if (bases == NULL) {
2441 if (PyErr_ExceptionMatches(PyExc_AttributeError))
2442 PyErr_Clear();
2443 return NULL;
2445 if (!PyTuple_Check(bases)) {
2446 Py_DECREF(bases);
2447 return NULL;
2449 return bases;
2453 static int
2454 abstract_issubclass(PyObject *derived, PyObject *cls)
2456 PyObject *bases = NULL;
2457 Py_ssize_t i, n;
2458 int r = 0;
2460 while (1) {
2461 if (derived == cls)
2462 return 1;
2463 bases = abstract_get_bases(derived);
2464 if (bases == NULL) {
2465 if (PyErr_Occurred())
2466 return -1;
2467 return 0;
2469 n = PyTuple_GET_SIZE(bases);
2470 if (n == 0) {
2471 Py_DECREF(bases);
2472 return 0;
2474 /* Avoid recursivity in the single inheritance case */
2475 if (n == 1) {
2476 derived = PyTuple_GET_ITEM(bases, 0);
2477 Py_DECREF(bases);
2478 continue;
2480 for (i = 0; i < n; i++) {
2481 r = abstract_issubclass(PyTuple_GET_ITEM(bases, i), cls);
2482 if (r != 0)
2483 break;
2485 Py_DECREF(bases);
2486 return r;
2490 static int
2491 check_class(PyObject *cls, const char *error)
2493 PyObject *bases = abstract_get_bases(cls);
2494 if (bases == NULL) {
2495 /* Do not mask errors. */
2496 if (!PyErr_Occurred())
2497 PyErr_SetString(PyExc_TypeError, error);
2498 return 0;
2500 Py_DECREF(bases);
2501 return -1;
2504 static int
2505 recursive_isinstance(PyObject *inst, PyObject *cls)
2507 PyObject *icls;
2508 static PyObject *__class__ = NULL;
2509 int retval = 0;
2511 if (__class__ == NULL) {
2512 __class__ = PyUnicode_InternFromString("__class__");
2513 if (__class__ == NULL)
2514 return -1;
2517 if (PyType_Check(cls)) {
2518 retval = PyObject_TypeCheck(inst, (PyTypeObject *)cls);
2519 if (retval == 0) {
2520 PyObject *c = PyObject_GetAttr(inst, __class__);
2521 if (c == NULL) {
2522 PyErr_Clear();
2524 else {
2525 if (c != (PyObject *)(inst->ob_type) &&
2526 PyType_Check(c))
2527 retval = PyType_IsSubtype(
2528 (PyTypeObject *)c,
2529 (PyTypeObject *)cls);
2530 Py_DECREF(c);
2534 else {
2535 if (!check_class(cls,
2536 "isinstance() arg 2 must be a class, type,"
2537 " or tuple of classes and types"))
2538 return -1;
2539 icls = PyObject_GetAttr(inst, __class__);
2540 if (icls == NULL) {
2541 PyErr_Clear();
2542 retval = 0;
2544 else {
2545 retval = abstract_issubclass(icls, cls);
2546 Py_DECREF(icls);
2550 return retval;
2554 PyObject_IsInstance(PyObject *inst, PyObject *cls)
2556 static PyObject *name = NULL;
2557 PyObject *checker;
2559 /* Quick test for an exact match */
2560 if (Py_TYPE(inst) == (PyTypeObject *)cls)
2561 return 1;
2563 if (PyTuple_Check(cls)) {
2564 Py_ssize_t i;
2565 Py_ssize_t n;
2566 int r = 0;
2568 if (Py_EnterRecursiveCall(" in __instancecheck__"))
2569 return -1;
2570 n = PyTuple_GET_SIZE(cls);
2571 for (i = 0; i < n; ++i) {
2572 PyObject *item = PyTuple_GET_ITEM(cls, i);
2573 r = PyObject_IsInstance(inst, item);
2574 if (r != 0)
2575 /* either found it, or got an error */
2576 break;
2578 Py_LeaveRecursiveCall();
2579 return r;
2582 checker = _PyObject_LookupSpecial(cls, "__instancecheck__", &name);
2583 if (checker != NULL) {
2584 PyObject *res;
2585 int ok = -1;
2586 if (Py_EnterRecursiveCall(" in __instancecheck__")) {
2587 Py_DECREF(checker);
2588 return ok;
2590 res = PyObject_CallFunctionObjArgs(checker, inst, NULL);
2591 Py_LeaveRecursiveCall();
2592 Py_DECREF(checker);
2593 if (res != NULL) {
2594 ok = PyObject_IsTrue(res);
2595 Py_DECREF(res);
2597 return ok;
2599 else if (PyErr_Occurred())
2600 return -1;
2601 return recursive_isinstance(inst, cls);
2604 static int
2605 recursive_issubclass(PyObject *derived, PyObject *cls)
2607 if (PyType_Check(cls) && PyType_Check(derived)) {
2608 /* Fast path (non-recursive) */
2609 return PyType_IsSubtype((PyTypeObject *)derived, (PyTypeObject *)cls);
2611 if (!check_class(derived,
2612 "issubclass() arg 1 must be a class"))
2613 return -1;
2614 if (!check_class(cls,
2615 "issubclass() arg 2 must be a class"
2616 " or tuple of classes"))
2617 return -1;
2619 return abstract_issubclass(derived, cls);
2623 PyObject_IsSubclass(PyObject *derived, PyObject *cls)
2625 static PyObject *name = NULL;
2626 PyObject *checker;
2628 if (PyTuple_Check(cls)) {
2629 Py_ssize_t i;
2630 Py_ssize_t n;
2631 int r = 0;
2633 if (Py_EnterRecursiveCall(" in __subclasscheck__"))
2634 return -1;
2635 n = PyTuple_GET_SIZE(cls);
2636 for (i = 0; i < n; ++i) {
2637 PyObject *item = PyTuple_GET_ITEM(cls, i);
2638 r = PyObject_IsSubclass(derived, item);
2639 if (r != 0)
2640 /* either found it, or got an error */
2641 break;
2643 Py_LeaveRecursiveCall();
2644 return r;
2647 checker = _PyObject_LookupSpecial(cls, "__subclasscheck__", &name);
2648 if (checker != NULL) {
2649 PyObject *res;
2650 int ok = -1;
2651 if (Py_EnterRecursiveCall(" in __subclasscheck__")) {
2652 Py_DECREF(checker);
2653 return ok;
2655 res = PyObject_CallFunctionObjArgs(checker, derived, NULL);
2656 Py_LeaveRecursiveCall();
2657 Py_DECREF(checker);
2658 if (res != NULL) {
2659 ok = PyObject_IsTrue(res);
2660 Py_DECREF(res);
2662 return ok;
2664 else if (PyErr_Occurred())
2665 return -1;
2666 return recursive_issubclass(derived, cls);
2670 _PyObject_RealIsInstance(PyObject *inst, PyObject *cls)
2672 return recursive_isinstance(inst, cls);
2676 _PyObject_RealIsSubclass(PyObject *derived, PyObject *cls)
2678 return recursive_issubclass(derived, cls);
2682 PyObject *
2683 PyObject_GetIter(PyObject *o)
2685 PyTypeObject *t = o->ob_type;
2686 getiterfunc f = NULL;
2687 f = t->tp_iter;
2688 if (f == NULL) {
2689 if (PySequence_Check(o))
2690 return PySeqIter_New(o);
2691 return type_error("'%.200s' object is not iterable", o);
2693 else {
2694 PyObject *res = (*f)(o);
2695 if (res != NULL && !PyIter_Check(res)) {
2696 PyErr_Format(PyExc_TypeError,
2697 "iter() returned non-iterator "
2698 "of type '%.100s'",
2699 res->ob_type->tp_name);
2700 Py_DECREF(res);
2701 res = NULL;
2703 return res;
2707 /* Return next item.
2708 * If an error occurs, return NULL. PyErr_Occurred() will be true.
2709 * If the iteration terminates normally, return NULL and clear the
2710 * PyExc_StopIteration exception (if it was set). PyErr_Occurred()
2711 * will be false.
2712 * Else return the next object. PyErr_Occurred() will be false.
2714 PyObject *
2715 PyIter_Next(PyObject *iter)
2717 PyObject *result;
2718 result = (*iter->ob_type->tp_iternext)(iter);
2719 if (result == NULL &&
2720 PyErr_Occurred() &&
2721 PyErr_ExceptionMatches(PyExc_StopIteration))
2722 PyErr_Clear();
2723 return result;