Add better error reporting for MemoryErrors caused by str->float conversions.
[python.git] / Objects / abstract.c
blob8d6f023c47b11e43111ed395f1ed9f0496f44c88
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"
8 #define NEW_STYLE_NUMBER(o) PyType_HasFeature((o)->ob_type, \
9 Py_TPFLAGS_CHECKTYPES)
12 /* Shorthands to return certain errors */
14 static PyObject *
15 type_error(const char *msg, PyObject *obj)
17 PyErr_Format(PyExc_TypeError, msg, obj->ob_type->tp_name);
18 return NULL;
21 static PyObject *
22 null_error(void)
24 if (!PyErr_Occurred())
25 PyErr_SetString(PyExc_SystemError,
26 "null argument to internal routine");
27 return NULL;
30 /* Operations on any object */
32 int
33 PyObject_Cmp(PyObject *o1, PyObject *o2, int *result)
35 int r;
37 if (o1 == NULL || o2 == NULL) {
38 null_error();
39 return -1;
41 r = PyObject_Compare(o1, o2);
42 if (PyErr_Occurred())
43 return -1;
44 *result = r;
45 return 0;
48 PyObject *
49 PyObject_Type(PyObject *o)
51 PyObject *v;
53 if (o == NULL)
54 return null_error();
55 v = (PyObject *)o->ob_type;
56 Py_INCREF(v);
57 return v;
60 Py_ssize_t
61 PyObject_Size(PyObject *o)
63 PySequenceMethods *m;
65 if (o == NULL) {
66 null_error();
67 return -1;
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
78 Py_ssize_t
79 PyObject_Length(PyObject *o)
81 return PyObject_Size(o);
83 #define PyObject_Length PyObject_Size
86 /* The length hint function returns a non-negative value from o.__len__()
87 or o.__length_hint__(). If those methods aren't found or return a negative
88 value, then the defaultvalue is returned. If one of the calls fails,
89 this function returns -1.
92 Py_ssize_t
93 _PyObject_LengthHint(PyObject *o, Py_ssize_t defaultvalue)
95 static PyObject *hintstrobj = NULL;
96 PyObject *ro, *hintmeth;
97 Py_ssize_t rv;
99 /* try o.__len__() */
100 rv = PyObject_Size(o);
101 if (rv >= 0)
102 return rv;
103 if (PyErr_Occurred()) {
104 if (!PyErr_ExceptionMatches(PyExc_TypeError) &&
105 !PyErr_ExceptionMatches(PyExc_AttributeError))
106 return -1;
107 PyErr_Clear();
110 if (PyInstance_Check(o))
111 return defaultvalue;
112 /* try o.__length_hint__() */
113 hintmeth = _PyObject_LookupSpecial(o, "__length_hint__", &hintstrobj);
114 if (hintmeth == NULL) {
115 if (PyErr_Occurred())
116 return -1;
117 else
118 return defaultvalue;
120 ro = PyObject_CallFunctionObjArgs(hintmeth, NULL);
121 Py_DECREF(hintmeth);
122 if (ro == NULL) {
123 if (!PyErr_ExceptionMatches(PyExc_TypeError) &&
124 !PyErr_ExceptionMatches(PyExc_AttributeError))
125 return -1;
126 PyErr_Clear();
127 return defaultvalue;
129 rv = PyLong_Check(ro) ? PyLong_AsSsize_t(ro) : defaultvalue;
130 Py_DECREF(ro);
131 return rv;
134 PyObject *
135 PyObject_GetItem(PyObject *o, PyObject *key)
137 PyMappingMethods *m;
139 if (o == NULL || key == NULL)
140 return null_error();
142 m = o->ob_type->tp_as_mapping;
143 if (m && m->mp_subscript)
144 return m->mp_subscript(o, key);
146 if (o->ob_type->tp_as_sequence) {
147 if (PyIndex_Check(key)) {
148 Py_ssize_t key_value;
149 key_value = PyNumber_AsSsize_t(key, PyExc_IndexError);
150 if (key_value == -1 && PyErr_Occurred())
151 return NULL;
152 return PySequence_GetItem(o, key_value);
154 else if (o->ob_type->tp_as_sequence->sq_item)
155 return type_error("sequence index must "
156 "be integer, not '%.200s'", key);
159 return type_error("'%.200s' object is not subscriptable", o);
163 PyObject_SetItem(PyObject *o, PyObject *key, PyObject *value)
165 PyMappingMethods *m;
167 if (o == NULL || key == NULL || value == NULL) {
168 null_error();
169 return -1;
171 m = o->ob_type->tp_as_mapping;
172 if (m && m->mp_ass_subscript)
173 return m->mp_ass_subscript(o, key, value);
175 if (o->ob_type->tp_as_sequence) {
176 if (PyIndex_Check(key)) {
177 Py_ssize_t key_value;
178 key_value = PyNumber_AsSsize_t(key, PyExc_IndexError);
179 if (key_value == -1 && PyErr_Occurred())
180 return -1;
181 return PySequence_SetItem(o, key_value, value);
183 else if (o->ob_type->tp_as_sequence->sq_ass_item) {
184 type_error("sequence index must be "
185 "integer, not '%.200s'", key);
186 return -1;
190 type_error("'%.200s' object does not support item assignment", o);
191 return -1;
195 PyObject_DelItem(PyObject *o, PyObject *key)
197 PyMappingMethods *m;
199 if (o == NULL || key == NULL) {
200 null_error();
201 return -1;
203 m = o->ob_type->tp_as_mapping;
204 if (m && m->mp_ass_subscript)
205 return m->mp_ass_subscript(o, key, (PyObject*)NULL);
207 if (o->ob_type->tp_as_sequence) {
208 if (PyIndex_Check(key)) {
209 Py_ssize_t key_value;
210 key_value = PyNumber_AsSsize_t(key, PyExc_IndexError);
211 if (key_value == -1 && PyErr_Occurred())
212 return -1;
213 return PySequence_DelItem(o, key_value);
215 else if (o->ob_type->tp_as_sequence->sq_ass_item) {
216 type_error("sequence index must be "
217 "integer, not '%.200s'", key);
218 return -1;
222 type_error("'%.200s' object does not support item deletion", o);
223 return -1;
227 PyObject_DelItemString(PyObject *o, char *key)
229 PyObject *okey;
230 int ret;
232 if (o == NULL || key == NULL) {
233 null_error();
234 return -1;
236 okey = PyString_FromString(key);
237 if (okey == NULL)
238 return -1;
239 ret = PyObject_DelItem(o, okey);
240 Py_DECREF(okey);
241 return ret;
245 PyObject_AsCharBuffer(PyObject *obj,
246 const char **buffer,
247 Py_ssize_t *buffer_len)
249 PyBufferProcs *pb;
250 char *pp;
251 Py_ssize_t len;
253 if (obj == NULL || buffer == NULL || buffer_len == NULL) {
254 null_error();
255 return -1;
257 pb = obj->ob_type->tp_as_buffer;
258 if (pb == NULL ||
259 pb->bf_getcharbuffer == NULL ||
260 pb->bf_getsegcount == NULL) {
261 PyErr_SetString(PyExc_TypeError,
262 "expected a character buffer object");
263 return -1;
265 if ((*pb->bf_getsegcount)(obj,NULL) != 1) {
266 PyErr_SetString(PyExc_TypeError,
267 "expected a single-segment buffer object");
268 return -1;
270 len = (*pb->bf_getcharbuffer)(obj, 0, &pp);
271 if (len < 0)
272 return -1;
273 *buffer = pp;
274 *buffer_len = len;
275 return 0;
279 PyObject_CheckReadBuffer(PyObject *obj)
281 PyBufferProcs *pb = obj->ob_type->tp_as_buffer;
283 if (pb == NULL ||
284 pb->bf_getreadbuffer == NULL ||
285 pb->bf_getsegcount == NULL ||
286 (*pb->bf_getsegcount)(obj, NULL) != 1)
287 return 0;
288 return 1;
291 int PyObject_AsReadBuffer(PyObject *obj,
292 const void **buffer,
293 Py_ssize_t *buffer_len)
295 PyBufferProcs *pb;
296 void *pp;
297 Py_ssize_t len;
299 if (obj == NULL || buffer == NULL || buffer_len == NULL) {
300 null_error();
301 return -1;
303 pb = obj->ob_type->tp_as_buffer;
304 if (pb == NULL ||
305 pb->bf_getreadbuffer == NULL ||
306 pb->bf_getsegcount == NULL) {
307 PyErr_SetString(PyExc_TypeError,
308 "expected a readable buffer object");
309 return -1;
311 if ((*pb->bf_getsegcount)(obj, NULL) != 1) {
312 PyErr_SetString(PyExc_TypeError,
313 "expected a single-segment buffer object");
314 return -1;
316 len = (*pb->bf_getreadbuffer)(obj, 0, &pp);
317 if (len < 0)
318 return -1;
319 *buffer = pp;
320 *buffer_len = len;
321 return 0;
324 int PyObject_AsWriteBuffer(PyObject *obj,
325 void **buffer,
326 Py_ssize_t *buffer_len)
328 PyBufferProcs *pb;
329 void*pp;
330 Py_ssize_t len;
332 if (obj == NULL || buffer == NULL || buffer_len == NULL) {
333 null_error();
334 return -1;
336 pb = obj->ob_type->tp_as_buffer;
337 if (pb == NULL ||
338 pb->bf_getwritebuffer == NULL ||
339 pb->bf_getsegcount == NULL) {
340 PyErr_SetString(PyExc_TypeError,
341 "expected a writeable buffer object");
342 return -1;
344 if ((*pb->bf_getsegcount)(obj, NULL) != 1) {
345 PyErr_SetString(PyExc_TypeError,
346 "expected a single-segment buffer object");
347 return -1;
349 len = (*pb->bf_getwritebuffer)(obj,0,&pp);
350 if (len < 0)
351 return -1;
352 *buffer = pp;
353 *buffer_len = len;
354 return 0;
357 /* Buffer C-API for Python 3.0 */
360 PyObject_GetBuffer(PyObject *obj, Py_buffer *view, int flags)
362 if (!PyObject_CheckBuffer(obj)) {
363 PyErr_Format(PyExc_TypeError,
364 "'%100s' does not have the buffer interface",
365 Py_TYPE(obj)->tp_name);
366 return -1;
368 return (*(obj->ob_type->tp_as_buffer->bf_getbuffer))(obj, view, flags);
371 static int
372 _IsFortranContiguous(Py_buffer *view)
374 Py_ssize_t sd, dim;
375 int i;
377 if (view->ndim == 0) return 1;
378 if (view->strides == NULL) return (view->ndim == 1);
380 sd = view->itemsize;
381 if (view->ndim == 1) return (view->shape[0] == 1 ||
382 sd == view->strides[0]);
383 for (i=0; i<view->ndim; i++) {
384 dim = view->shape[i];
385 if (dim == 0) return 1;
386 if (view->strides[i] != sd) return 0;
387 sd *= dim;
389 return 1;
392 static int
393 _IsCContiguous(Py_buffer *view)
395 Py_ssize_t sd, dim;
396 int i;
398 if (view->ndim == 0) return 1;
399 if (view->strides == NULL) return 1;
401 sd = view->itemsize;
402 if (view->ndim == 1) return (view->shape[0] == 1 ||
403 sd == view->strides[0]);
404 for (i=view->ndim-1; i>=0; i--) {
405 dim = view->shape[i];
406 if (dim == 0) return 1;
407 if (view->strides[i] != sd) return 0;
408 sd *= dim;
410 return 1;
414 PyBuffer_IsContiguous(Py_buffer *view, char fort)
417 if (view->suboffsets != NULL) return 0;
419 if (fort == 'C')
420 return _IsCContiguous(view);
421 else if (fort == 'F')
422 return _IsFortranContiguous(view);
423 else if (fort == 'A')
424 return (_IsCContiguous(view) || _IsFortranContiguous(view));
425 return 0;
429 void*
430 PyBuffer_GetPointer(Py_buffer *view, Py_ssize_t *indices)
432 char* pointer;
433 int i;
434 pointer = (char *)view->buf;
435 for (i = 0; i < view->ndim; i++) {
436 pointer += view->strides[i]*indices[i];
437 if ((view->suboffsets != NULL) && (view->suboffsets[i] >= 0)) {
438 pointer = *((char**)pointer) + view->suboffsets[i];
441 return (void*)pointer;
445 void
446 _add_one_to_index_F(int nd, Py_ssize_t *index, Py_ssize_t *shape)
448 int k;
450 for (k=0; k<nd; k++) {
451 if (index[k] < shape[k]-1) {
452 index[k]++;
453 break;
455 else {
456 index[k] = 0;
461 void
462 _add_one_to_index_C(int nd, Py_ssize_t *index, Py_ssize_t *shape)
464 int k;
466 for (k=nd-1; k>=0; k--) {
467 if (index[k] < shape[k]-1) {
468 index[k]++;
469 break;
471 else {
472 index[k] = 0;
477 /* view is not checked for consistency in either of these. It is
478 assumed that the size of the buffer is view->len in
479 view->len / view->itemsize elements.
483 PyBuffer_ToContiguous(void *buf, Py_buffer *view, Py_ssize_t len, char fort)
485 int k;
486 void (*addone)(int, Py_ssize_t *, Py_ssize_t *);
487 Py_ssize_t *indices, elements;
488 char *dest, *ptr;
490 if (len > view->len) {
491 len = view->len;
494 if (PyBuffer_IsContiguous(view, fort)) {
495 /* simplest copy is all that is needed */
496 memcpy(buf, view->buf, len);
497 return 0;
500 /* Otherwise a more elaborate scheme is needed */
502 /* XXX(nnorwitz): need to check for overflow! */
503 indices = (Py_ssize_t *)PyMem_Malloc(sizeof(Py_ssize_t)*(view->ndim));
504 if (indices == NULL) {
505 PyErr_NoMemory();
506 return -1;
508 for (k=0; k<view->ndim;k++) {
509 indices[k] = 0;
512 if (fort == 'F') {
513 addone = _add_one_to_index_F;
515 else {
516 addone = _add_one_to_index_C;
518 dest = buf;
519 /* XXX : This is not going to be the fastest code in the world
520 several optimizations are possible.
522 elements = len / view->itemsize;
523 while (elements--) {
524 addone(view->ndim, indices, view->shape);
525 ptr = PyBuffer_GetPointer(view, indices);
526 memcpy(dest, ptr, view->itemsize);
527 dest += view->itemsize;
529 PyMem_Free(indices);
530 return 0;
534 PyBuffer_FromContiguous(Py_buffer *view, void *buf, Py_ssize_t len, char fort)
536 int k;
537 void (*addone)(int, Py_ssize_t *, Py_ssize_t *);
538 Py_ssize_t *indices, elements;
539 char *src, *ptr;
541 if (len > view->len) {
542 len = view->len;
545 if (PyBuffer_IsContiguous(view, fort)) {
546 /* simplest copy is all that is needed */
547 memcpy(view->buf, buf, len);
548 return 0;
551 /* Otherwise a more elaborate scheme is needed */
553 /* XXX(nnorwitz): need to check for overflow! */
554 indices = (Py_ssize_t *)PyMem_Malloc(sizeof(Py_ssize_t)*(view->ndim));
555 if (indices == NULL) {
556 PyErr_NoMemory();
557 return -1;
559 for (k=0; k<view->ndim;k++) {
560 indices[k] = 0;
563 if (fort == 'F') {
564 addone = _add_one_to_index_F;
566 else {
567 addone = _add_one_to_index_C;
569 src = buf;
570 /* XXX : This is not going to be the fastest code in the world
571 several optimizations are possible.
573 elements = len / view->itemsize;
574 while (elements--) {
575 addone(view->ndim, indices, view->shape);
576 ptr = PyBuffer_GetPointer(view, indices);
577 memcpy(ptr, src, view->itemsize);
578 src += view->itemsize;
581 PyMem_Free(indices);
582 return 0;
585 int PyObject_CopyData(PyObject *dest, PyObject *src)
587 Py_buffer view_dest, view_src;
588 int k;
589 Py_ssize_t *indices, elements;
590 char *dptr, *sptr;
592 if (!PyObject_CheckBuffer(dest) ||
593 !PyObject_CheckBuffer(src)) {
594 PyErr_SetString(PyExc_TypeError,
595 "both destination and source must have the "\
596 "buffer interface");
597 return -1;
600 if (PyObject_GetBuffer(dest, &view_dest, PyBUF_FULL) != 0) return -1;
601 if (PyObject_GetBuffer(src, &view_src, PyBUF_FULL_RO) != 0) {
602 PyBuffer_Release(&view_dest);
603 return -1;
606 if (view_dest.len < view_src.len) {
607 PyErr_SetString(PyExc_BufferError,
608 "destination is too small to receive data from source");
609 PyBuffer_Release(&view_dest);
610 PyBuffer_Release(&view_src);
611 return -1;
614 if ((PyBuffer_IsContiguous(&view_dest, 'C') &&
615 PyBuffer_IsContiguous(&view_src, 'C')) ||
616 (PyBuffer_IsContiguous(&view_dest, 'F') &&
617 PyBuffer_IsContiguous(&view_src, 'F'))) {
618 /* simplest copy is all that is needed */
619 memcpy(view_dest.buf, view_src.buf, view_src.len);
620 PyBuffer_Release(&view_dest);
621 PyBuffer_Release(&view_src);
622 return 0;
625 /* Otherwise a more elaborate copy scheme is needed */
627 /* XXX(nnorwitz): need to check for overflow! */
628 indices = (Py_ssize_t *)PyMem_Malloc(sizeof(Py_ssize_t)*view_src.ndim);
629 if (indices == NULL) {
630 PyErr_NoMemory();
631 PyBuffer_Release(&view_dest);
632 PyBuffer_Release(&view_src);
633 return -1;
635 for (k=0; k<view_src.ndim;k++) {
636 indices[k] = 0;
638 elements = 1;
639 for (k=0; k<view_src.ndim; k++) {
640 /* XXX(nnorwitz): can this overflow? */
641 elements *= view_src.shape[k];
643 while (elements--) {
644 _add_one_to_index_C(view_src.ndim, indices, view_src.shape);
645 dptr = PyBuffer_GetPointer(&view_dest, indices);
646 sptr = PyBuffer_GetPointer(&view_src, indices);
647 memcpy(dptr, sptr, view_src.itemsize);
649 PyMem_Free(indices);
650 PyBuffer_Release(&view_dest);
651 PyBuffer_Release(&view_src);
652 return 0;
655 void
656 PyBuffer_FillContiguousStrides(int nd, Py_ssize_t *shape,
657 Py_ssize_t *strides, int itemsize,
658 char fort)
660 int k;
661 Py_ssize_t sd;
663 sd = itemsize;
664 if (fort == 'F') {
665 for (k=0; k<nd; k++) {
666 strides[k] = sd;
667 sd *= shape[k];
670 else {
671 for (k=nd-1; k>=0; k--) {
672 strides[k] = sd;
673 sd *= shape[k];
676 return;
680 PyBuffer_FillInfo(Py_buffer *view, PyObject *obj, void *buf, Py_ssize_t len,
681 int readonly, int flags)
683 if (view == NULL) return 0;
684 if (((flags & PyBUF_WRITABLE) == PyBUF_WRITABLE) &&
685 (readonly == 1)) {
686 PyErr_SetString(PyExc_BufferError,
687 "Object is not writable.");
688 return -1;
691 view->obj = obj;
692 if (obj)
693 Py_INCREF(obj);
694 view->buf = buf;
695 view->len = len;
696 view->readonly = readonly;
697 view->itemsize = 1;
698 view->format = NULL;
699 if ((flags & PyBUF_FORMAT) == PyBUF_FORMAT)
700 view->format = "B";
701 view->ndim = 1;
702 view->shape = NULL;
703 if ((flags & PyBUF_ND) == PyBUF_ND)
704 view->shape = &(view->len);
705 view->strides = NULL;
706 if ((flags & PyBUF_STRIDES) == PyBUF_STRIDES)
707 view->strides = &(view->itemsize);
708 view->suboffsets = NULL;
709 view->internal = NULL;
710 return 0;
713 void
714 PyBuffer_Release(Py_buffer *view)
716 PyObject *obj = view->obj;
717 if (obj && Py_TYPE(obj)->tp_as_buffer && Py_TYPE(obj)->tp_as_buffer->bf_releasebuffer)
718 Py_TYPE(obj)->tp_as_buffer->bf_releasebuffer(obj, view);
719 Py_XDECREF(obj);
720 view->obj = NULL;
723 PyObject *
724 PyObject_Format(PyObject* obj, PyObject *format_spec)
726 static PyObject * str__format__ = NULL;
727 PyObject *empty = NULL;
728 PyObject *result = NULL;
729 #ifdef Py_USING_UNICODE
730 int spec_is_unicode;
731 int result_is_unicode;
732 #endif
734 /* Initialize cached value */
735 if (str__format__ == NULL) {
736 /* Initialize static variable needed by _PyType_Lookup */
737 str__format__ = PyString_InternFromString("__format__");
738 if (str__format__ == NULL)
739 goto done;
742 /* If no format_spec is provided, use an empty string */
743 if (format_spec == NULL) {
744 empty = PyString_FromStringAndSize(NULL, 0);
745 format_spec = empty;
748 /* Check the format_spec type, and make sure it's str or unicode */
749 #ifdef Py_USING_UNICODE
750 if (PyUnicode_Check(format_spec))
751 spec_is_unicode = 1;
752 else if (PyString_Check(format_spec))
753 spec_is_unicode = 0;
754 else {
755 #else
756 if (!PyString_Check(format_spec)) {
757 #endif
758 PyErr_Format(PyExc_TypeError,
759 "format expects arg 2 to be string "
760 "or unicode, not %.100s", Py_TYPE(format_spec)->tp_name);
761 goto done;
764 /* Make sure the type is initialized. float gets initialized late */
765 if (Py_TYPE(obj)->tp_dict == NULL)
766 if (PyType_Ready(Py_TYPE(obj)) < 0)
767 goto done;
769 /* Check for a __format__ method and call it. */
770 if (PyInstance_Check(obj)) {
771 /* We're an instance of a classic class */
772 PyObject *bound_method = PyObject_GetAttr(obj,
773 str__format__);
774 if (bound_method != NULL) {
775 result = PyObject_CallFunctionObjArgs(bound_method,
776 format_spec,
777 NULL);
778 Py_DECREF(bound_method);
779 } else {
780 PyObject *self_as_str;
781 PyObject *format_method;
783 PyErr_Clear();
784 /* Per the PEP, convert to str (or unicode,
785 depending on the type of the format
786 specifier). For new-style classes, this
787 logic is done by object.__format__(). */
788 #ifdef Py_USING_UNICODE
789 if (spec_is_unicode)
790 self_as_str = PyObject_Unicode(obj);
791 else
792 #endif
793 self_as_str = PyObject_Str(obj);
794 if (self_as_str == NULL)
795 goto done;
797 /* Then call str.__format__ on that result */
798 format_method = PyObject_GetAttr(self_as_str,
799 str__format__);
800 if (format_method == NULL) {
801 Py_DECREF(self_as_str);
802 goto done;
804 result = PyObject_CallFunctionObjArgs(format_method,
805 format_spec,
806 NULL);
807 Py_DECREF(self_as_str);
808 Py_DECREF(format_method);
809 if (result == NULL)
810 goto done;
812 } else {
813 /* Not an instance of a classic class, use the code
814 from py3k */
816 /* Find the (unbound!) __format__ method (a borrowed
817 reference) */
818 PyObject *method = _PyType_Lookup(Py_TYPE(obj),
819 str__format__);
820 if (method == NULL) {
821 PyErr_Format(PyExc_TypeError,
822 "Type %.100s doesn't define __format__",
823 Py_TYPE(obj)->tp_name);
824 goto done;
826 /* And call it, binding it to the value */
827 result = PyObject_CallFunctionObjArgs(method, obj,
828 format_spec, NULL);
831 if (result == NULL)
832 goto done;
834 /* Check the result type, and make sure it's str or unicode */
835 #ifdef Py_USING_UNICODE
836 if (PyUnicode_Check(result))
837 result_is_unicode = 1;
838 else if (PyString_Check(result))
839 result_is_unicode = 0;
840 else {
841 #else
842 if (!PyString_Check(result)) {
843 #endif
844 PyErr_Format(PyExc_TypeError,
845 "%.100s.__format__ must return string or "
846 "unicode, not %.100s", Py_TYPE(obj)->tp_name,
847 Py_TYPE(result)->tp_name);
848 Py_DECREF(result);
849 result = NULL;
850 goto done;
853 /* Convert to unicode, if needed. Required if spec is unicode
854 and result is str */
855 #ifdef Py_USING_UNICODE
856 if (spec_is_unicode && !result_is_unicode) {
857 PyObject *tmp = PyObject_Unicode(result);
858 /* This logic works whether or not tmp is NULL */
859 Py_DECREF(result);
860 result = tmp;
862 #endif
864 done:
865 Py_XDECREF(empty);
866 return result;
869 /* Operations on numbers */
872 PyNumber_Check(PyObject *o)
874 return o && o->ob_type->tp_as_number &&
875 (o->ob_type->tp_as_number->nb_int ||
876 o->ob_type->tp_as_number->nb_float);
879 /* Binary operators */
881 /* New style number protocol support */
883 #define NB_SLOT(x) offsetof(PyNumberMethods, x)
884 #define NB_BINOP(nb_methods, slot) \
885 (*(binaryfunc*)(& ((char*)nb_methods)[slot]))
886 #define NB_TERNOP(nb_methods, slot) \
887 (*(ternaryfunc*)(& ((char*)nb_methods)[slot]))
890 Calling scheme used for binary operations:
892 v w Action
893 -------------------------------------------------------------------
894 new new w.op(v,w)[*], v.op(v,w), w.op(v,w)
895 new old v.op(v,w), coerce(v,w), v.op(v,w)
896 old new w.op(v,w), coerce(v,w), v.op(v,w)
897 old old coerce(v,w), v.op(v,w)
899 [*] only when v->ob_type != w->ob_type && w->ob_type is a subclass of
900 v->ob_type
902 Legend:
903 -------
904 * new == new style number
905 * old == old style number
906 * Action indicates the order in which operations are tried until either
907 a valid result is produced or an error occurs.
911 static PyObject *
912 binary_op1(PyObject *v, PyObject *w, const int op_slot)
914 PyObject *x;
915 binaryfunc slotv = NULL;
916 binaryfunc slotw = NULL;
918 if (v->ob_type->tp_as_number != NULL && NEW_STYLE_NUMBER(v))
919 slotv = NB_BINOP(v->ob_type->tp_as_number, op_slot);
920 if (w->ob_type != v->ob_type &&
921 w->ob_type->tp_as_number != NULL && NEW_STYLE_NUMBER(w)) {
922 slotw = NB_BINOP(w->ob_type->tp_as_number, op_slot);
923 if (slotw == slotv)
924 slotw = NULL;
926 if (slotv) {
927 if (slotw && PyType_IsSubtype(w->ob_type, v->ob_type)) {
928 x = slotw(v, w);
929 if (x != Py_NotImplemented)
930 return x;
931 Py_DECREF(x); /* can't do it */
932 slotw = NULL;
934 x = slotv(v, w);
935 if (x != Py_NotImplemented)
936 return x;
937 Py_DECREF(x); /* can't do it */
939 if (slotw) {
940 x = slotw(v, w);
941 if (x != Py_NotImplemented)
942 return x;
943 Py_DECREF(x); /* can't do it */
945 if (!NEW_STYLE_NUMBER(v) || !NEW_STYLE_NUMBER(w)) {
946 int err = PyNumber_CoerceEx(&v, &w);
947 if (err < 0) {
948 return NULL;
950 if (err == 0) {
951 PyNumberMethods *mv = v->ob_type->tp_as_number;
952 if (mv) {
953 binaryfunc slot;
954 slot = NB_BINOP(mv, op_slot);
955 if (slot) {
956 x = slot(v, w);
957 Py_DECREF(v);
958 Py_DECREF(w);
959 return x;
962 /* CoerceEx incremented the reference counts */
963 Py_DECREF(v);
964 Py_DECREF(w);
967 Py_INCREF(Py_NotImplemented);
968 return Py_NotImplemented;
971 static PyObject *
972 binop_type_error(PyObject *v, PyObject *w, const char *op_name)
974 PyErr_Format(PyExc_TypeError,
975 "unsupported operand type(s) for %.100s: "
976 "'%.100s' and '%.100s'",
977 op_name,
978 v->ob_type->tp_name,
979 w->ob_type->tp_name);
980 return NULL;
983 static PyObject *
984 binary_op(PyObject *v, PyObject *w, const int op_slot, const char *op_name)
986 PyObject *result = binary_op1(v, w, op_slot);
987 if (result == Py_NotImplemented) {
988 Py_DECREF(result);
989 return binop_type_error(v, w, op_name);
991 return result;
996 Calling scheme used for ternary operations:
998 *** In some cases, w.op is called before v.op; see binary_op1. ***
1000 v w z Action
1001 -------------------------------------------------------------------
1002 new new new v.op(v,w,z), w.op(v,w,z), z.op(v,w,z)
1003 new old new v.op(v,w,z), z.op(v,w,z), coerce(v,w,z), v.op(v,w,z)
1004 old new new w.op(v,w,z), z.op(v,w,z), coerce(v,w,z), v.op(v,w,z)
1005 old old new z.op(v,w,z), coerce(v,w,z), v.op(v,w,z)
1006 new new old v.op(v,w,z), w.op(v,w,z), coerce(v,w,z), v.op(v,w,z)
1007 new old old v.op(v,w,z), coerce(v,w,z), v.op(v,w,z)
1008 old new old w.op(v,w,z), coerce(v,w,z), v.op(v,w,z)
1009 old old old coerce(v,w,z), v.op(v,w,z)
1011 Legend:
1012 -------
1013 * new == new style number
1014 * old == old style number
1015 * Action indicates the order in which operations are tried until either
1016 a valid result is produced or an error occurs.
1017 * coerce(v,w,z) actually does: coerce(v,w), coerce(v,z), coerce(w,z) and
1018 only if z != Py_None; if z == Py_None, then it is treated as absent
1019 variable and only coerce(v,w) is tried.
1023 static PyObject *
1024 ternary_op(PyObject *v,
1025 PyObject *w,
1026 PyObject *z,
1027 const int op_slot,
1028 const char *op_name)
1030 PyNumberMethods *mv, *mw, *mz;
1031 PyObject *x = NULL;
1032 ternaryfunc slotv = NULL;
1033 ternaryfunc slotw = NULL;
1034 ternaryfunc slotz = NULL;
1036 mv = v->ob_type->tp_as_number;
1037 mw = w->ob_type->tp_as_number;
1038 if (mv != NULL && NEW_STYLE_NUMBER(v))
1039 slotv = NB_TERNOP(mv, op_slot);
1040 if (w->ob_type != v->ob_type &&
1041 mw != NULL && NEW_STYLE_NUMBER(w)) {
1042 slotw = NB_TERNOP(mw, op_slot);
1043 if (slotw == slotv)
1044 slotw = NULL;
1046 if (slotv) {
1047 if (slotw && PyType_IsSubtype(w->ob_type, v->ob_type)) {
1048 x = slotw(v, w, z);
1049 if (x != Py_NotImplemented)
1050 return x;
1051 Py_DECREF(x); /* can't do it */
1052 slotw = NULL;
1054 x = slotv(v, w, z);
1055 if (x != Py_NotImplemented)
1056 return x;
1057 Py_DECREF(x); /* can't do it */
1059 if (slotw) {
1060 x = slotw(v, w, z);
1061 if (x != Py_NotImplemented)
1062 return x;
1063 Py_DECREF(x); /* can't do it */
1065 mz = z->ob_type->tp_as_number;
1066 if (mz != NULL && NEW_STYLE_NUMBER(z)) {
1067 slotz = NB_TERNOP(mz, op_slot);
1068 if (slotz == slotv || slotz == slotw)
1069 slotz = NULL;
1070 if (slotz) {
1071 x = slotz(v, w, z);
1072 if (x != Py_NotImplemented)
1073 return x;
1074 Py_DECREF(x); /* can't do it */
1078 if (!NEW_STYLE_NUMBER(v) || !NEW_STYLE_NUMBER(w) ||
1079 (z != Py_None && !NEW_STYLE_NUMBER(z))) {
1080 /* we have an old style operand, coerce */
1081 PyObject *v1, *z1, *w2, *z2;
1082 int c;
1084 c = PyNumber_Coerce(&v, &w);
1085 if (c != 0)
1086 goto error3;
1088 /* Special case: if the third argument is None, it is
1089 treated as absent argument and not coerced. */
1090 if (z == Py_None) {
1091 if (v->ob_type->tp_as_number) {
1092 slotz = NB_TERNOP(v->ob_type->tp_as_number,
1093 op_slot);
1094 if (slotz)
1095 x = slotz(v, w, z);
1096 else
1097 c = -1;
1099 else
1100 c = -1;
1101 goto error2;
1103 v1 = v;
1104 z1 = z;
1105 c = PyNumber_Coerce(&v1, &z1);
1106 if (c != 0)
1107 goto error2;
1108 w2 = w;
1109 z2 = z1;
1110 c = PyNumber_Coerce(&w2, &z2);
1111 if (c != 0)
1112 goto error1;
1114 if (v1->ob_type->tp_as_number != NULL) {
1115 slotv = NB_TERNOP(v1->ob_type->tp_as_number,
1116 op_slot);
1117 if (slotv)
1118 x = slotv(v1, w2, z2);
1119 else
1120 c = -1;
1122 else
1123 c = -1;
1125 Py_DECREF(w2);
1126 Py_DECREF(z2);
1127 error1:
1128 Py_DECREF(v1);
1129 Py_DECREF(z1);
1130 error2:
1131 Py_DECREF(v);
1132 Py_DECREF(w);
1133 error3:
1134 if (c >= 0)
1135 return x;
1138 if (z == Py_None)
1139 PyErr_Format(
1140 PyExc_TypeError,
1141 "unsupported operand type(s) for ** or pow(): "
1142 "'%.100s' and '%.100s'",
1143 v->ob_type->tp_name,
1144 w->ob_type->tp_name);
1145 else
1146 PyErr_Format(
1147 PyExc_TypeError,
1148 "unsupported operand type(s) for pow(): "
1149 "'%.100s', '%.100s', '%.100s'",
1150 v->ob_type->tp_name,
1151 w->ob_type->tp_name,
1152 z->ob_type->tp_name);
1153 return NULL;
1156 #define BINARY_FUNC(func, op, op_name) \
1157 PyObject * \
1158 func(PyObject *v, PyObject *w) { \
1159 return binary_op(v, w, NB_SLOT(op), op_name); \
1162 BINARY_FUNC(PyNumber_Or, nb_or, "|")
1163 BINARY_FUNC(PyNumber_Xor, nb_xor, "^")
1164 BINARY_FUNC(PyNumber_And, nb_and, "&")
1165 BINARY_FUNC(PyNumber_Lshift, nb_lshift, "<<")
1166 BINARY_FUNC(PyNumber_Rshift, nb_rshift, ">>")
1167 BINARY_FUNC(PyNumber_Subtract, nb_subtract, "-")
1168 BINARY_FUNC(PyNumber_Divide, nb_divide, "/")
1169 BINARY_FUNC(PyNumber_Divmod, nb_divmod, "divmod()")
1171 PyObject *
1172 PyNumber_Add(PyObject *v, PyObject *w)
1174 PyObject *result = binary_op1(v, w, NB_SLOT(nb_add));
1175 if (result == Py_NotImplemented) {
1176 PySequenceMethods *m = v->ob_type->tp_as_sequence;
1177 Py_DECREF(result);
1178 if (m && m->sq_concat) {
1179 return (*m->sq_concat)(v, w);
1181 result = binop_type_error(v, w, "+");
1183 return result;
1186 static PyObject *
1187 sequence_repeat(ssizeargfunc repeatfunc, PyObject *seq, PyObject *n)
1189 Py_ssize_t count;
1190 if (PyIndex_Check(n)) {
1191 count = PyNumber_AsSsize_t(n, PyExc_OverflowError);
1192 if (count == -1 && PyErr_Occurred())
1193 return NULL;
1195 else {
1196 return type_error("can't multiply sequence by "
1197 "non-int of type '%.200s'", n);
1199 return (*repeatfunc)(seq, count);
1202 PyObject *
1203 PyNumber_Multiply(PyObject *v, PyObject *w)
1205 PyObject *result = binary_op1(v, w, NB_SLOT(nb_multiply));
1206 if (result == Py_NotImplemented) {
1207 PySequenceMethods *mv = v->ob_type->tp_as_sequence;
1208 PySequenceMethods *mw = w->ob_type->tp_as_sequence;
1209 Py_DECREF(result);
1210 if (mv && mv->sq_repeat) {
1211 return sequence_repeat(mv->sq_repeat, v, w);
1213 else if (mw && mw->sq_repeat) {
1214 return sequence_repeat(mw->sq_repeat, w, v);
1216 result = binop_type_error(v, w, "*");
1218 return result;
1221 PyObject *
1222 PyNumber_FloorDivide(PyObject *v, PyObject *w)
1224 /* XXX tp_flags test */
1225 return binary_op(v, w, NB_SLOT(nb_floor_divide), "//");
1228 PyObject *
1229 PyNumber_TrueDivide(PyObject *v, PyObject *w)
1231 /* XXX tp_flags test */
1232 return binary_op(v, w, NB_SLOT(nb_true_divide), "/");
1235 PyObject *
1236 PyNumber_Remainder(PyObject *v, PyObject *w)
1238 return binary_op(v, w, NB_SLOT(nb_remainder), "%");
1241 PyObject *
1242 PyNumber_Power(PyObject *v, PyObject *w, PyObject *z)
1244 return ternary_op(v, w, z, NB_SLOT(nb_power), "** or pow()");
1247 /* Binary in-place operators */
1249 /* The in-place operators are defined to fall back to the 'normal',
1250 non in-place operations, if the in-place methods are not in place.
1252 - If the left hand object has the appropriate struct members, and
1253 they are filled, call the appropriate function and return the
1254 result. No coercion is done on the arguments; the left-hand object
1255 is the one the operation is performed on, and it's up to the
1256 function to deal with the right-hand object.
1258 - Otherwise, in-place modification is not supported. Handle it exactly as
1259 a non in-place operation of the same kind.
1263 #define HASINPLACE(t) \
1264 PyType_HasFeature((t)->ob_type, Py_TPFLAGS_HAVE_INPLACEOPS)
1266 static PyObject *
1267 binary_iop1(PyObject *v, PyObject *w, const int iop_slot, const int op_slot)
1269 PyNumberMethods *mv = v->ob_type->tp_as_number;
1270 if (mv != NULL && HASINPLACE(v)) {
1271 binaryfunc slot = NB_BINOP(mv, iop_slot);
1272 if (slot) {
1273 PyObject *x = (slot)(v, w);
1274 if (x != Py_NotImplemented) {
1275 return x;
1277 Py_DECREF(x);
1280 return binary_op1(v, w, op_slot);
1283 static PyObject *
1284 binary_iop(PyObject *v, PyObject *w, const int iop_slot, const int op_slot,
1285 const char *op_name)
1287 PyObject *result = binary_iop1(v, w, iop_slot, op_slot);
1288 if (result == Py_NotImplemented) {
1289 Py_DECREF(result);
1290 return binop_type_error(v, w, op_name);
1292 return result;
1295 #define INPLACE_BINOP(func, iop, op, op_name) \
1296 PyObject * \
1297 func(PyObject *v, PyObject *w) { \
1298 return binary_iop(v, w, NB_SLOT(iop), NB_SLOT(op), op_name); \
1301 INPLACE_BINOP(PyNumber_InPlaceOr, nb_inplace_or, nb_or, "|=")
1302 INPLACE_BINOP(PyNumber_InPlaceXor, nb_inplace_xor, nb_xor, "^=")
1303 INPLACE_BINOP(PyNumber_InPlaceAnd, nb_inplace_and, nb_and, "&=")
1304 INPLACE_BINOP(PyNumber_InPlaceLshift, nb_inplace_lshift, nb_lshift, "<<=")
1305 INPLACE_BINOP(PyNumber_InPlaceRshift, nb_inplace_rshift, nb_rshift, ">>=")
1306 INPLACE_BINOP(PyNumber_InPlaceSubtract, nb_inplace_subtract, nb_subtract, "-=")
1307 INPLACE_BINOP(PyNumber_InPlaceDivide, nb_inplace_divide, nb_divide, "/=")
1309 PyObject *
1310 PyNumber_InPlaceFloorDivide(PyObject *v, PyObject *w)
1312 /* XXX tp_flags test */
1313 return binary_iop(v, w, NB_SLOT(nb_inplace_floor_divide),
1314 NB_SLOT(nb_floor_divide), "//=");
1317 PyObject *
1318 PyNumber_InPlaceTrueDivide(PyObject *v, PyObject *w)
1320 /* XXX tp_flags test */
1321 return binary_iop(v, w, NB_SLOT(nb_inplace_true_divide),
1322 NB_SLOT(nb_true_divide), "/=");
1325 PyObject *
1326 PyNumber_InPlaceAdd(PyObject *v, PyObject *w)
1328 PyObject *result = binary_iop1(v, w, NB_SLOT(nb_inplace_add),
1329 NB_SLOT(nb_add));
1330 if (result == Py_NotImplemented) {
1331 PySequenceMethods *m = v->ob_type->tp_as_sequence;
1332 Py_DECREF(result);
1333 if (m != NULL) {
1334 binaryfunc f = NULL;
1335 if (HASINPLACE(v))
1336 f = m->sq_inplace_concat;
1337 if (f == NULL)
1338 f = m->sq_concat;
1339 if (f != NULL)
1340 return (*f)(v, w);
1342 result = binop_type_error(v, w, "+=");
1344 return result;
1347 PyObject *
1348 PyNumber_InPlaceMultiply(PyObject *v, PyObject *w)
1350 PyObject *result = binary_iop1(v, w, NB_SLOT(nb_inplace_multiply),
1351 NB_SLOT(nb_multiply));
1352 if (result == Py_NotImplemented) {
1353 ssizeargfunc f = NULL;
1354 PySequenceMethods *mv = v->ob_type->tp_as_sequence;
1355 PySequenceMethods *mw = w->ob_type->tp_as_sequence;
1356 Py_DECREF(result);
1357 if (mv != NULL) {
1358 if (HASINPLACE(v))
1359 f = mv->sq_inplace_repeat;
1360 if (f == NULL)
1361 f = mv->sq_repeat;
1362 if (f != NULL)
1363 return sequence_repeat(f, v, w);
1365 else if (mw != NULL) {
1366 /* Note that the right hand operand should not be
1367 * mutated in this case so sq_inplace_repeat is not
1368 * used. */
1369 if (mw->sq_repeat)
1370 return sequence_repeat(mw->sq_repeat, w, v);
1372 result = binop_type_error(v, w, "*=");
1374 return result;
1377 PyObject *
1378 PyNumber_InPlaceRemainder(PyObject *v, PyObject *w)
1380 return binary_iop(v, w, NB_SLOT(nb_inplace_remainder),
1381 NB_SLOT(nb_remainder), "%=");
1384 PyObject *
1385 PyNumber_InPlacePower(PyObject *v, PyObject *w, PyObject *z)
1387 if (HASINPLACE(v) && v->ob_type->tp_as_number &&
1388 v->ob_type->tp_as_number->nb_inplace_power != NULL) {
1389 return ternary_op(v, w, z, NB_SLOT(nb_inplace_power), "**=");
1391 else {
1392 return ternary_op(v, w, z, NB_SLOT(nb_power), "**=");
1397 /* Unary operators and functions */
1399 PyObject *
1400 PyNumber_Negative(PyObject *o)
1402 PyNumberMethods *m;
1404 if (o == NULL)
1405 return null_error();
1406 m = o->ob_type->tp_as_number;
1407 if (m && m->nb_negative)
1408 return (*m->nb_negative)(o);
1410 return type_error("bad operand type for unary -: '%.200s'", o);
1413 PyObject *
1414 PyNumber_Positive(PyObject *o)
1416 PyNumberMethods *m;
1418 if (o == NULL)
1419 return null_error();
1420 m = o->ob_type->tp_as_number;
1421 if (m && m->nb_positive)
1422 return (*m->nb_positive)(o);
1424 return type_error("bad operand type for unary +: '%.200s'", o);
1427 PyObject *
1428 PyNumber_Invert(PyObject *o)
1430 PyNumberMethods *m;
1432 if (o == NULL)
1433 return null_error();
1434 m = o->ob_type->tp_as_number;
1435 if (m && m->nb_invert)
1436 return (*m->nb_invert)(o);
1438 return type_error("bad operand type for unary ~: '%.200s'", o);
1441 PyObject *
1442 PyNumber_Absolute(PyObject *o)
1444 PyNumberMethods *m;
1446 if (o == NULL)
1447 return null_error();
1448 m = o->ob_type->tp_as_number;
1449 if (m && m->nb_absolute)
1450 return m->nb_absolute(o);
1452 return type_error("bad operand type for abs(): '%.200s'", o);
1455 /* Add a check for embedded NULL-bytes in the argument. */
1456 static PyObject *
1457 int_from_string(const char *s, Py_ssize_t len)
1459 char *end;
1460 PyObject *x;
1462 x = PyInt_FromString((char*)s, &end, 10);
1463 if (x == NULL)
1464 return NULL;
1465 if (end != s + len) {
1466 PyErr_SetString(PyExc_ValueError,
1467 "null byte in argument for int()");
1468 Py_DECREF(x);
1469 return NULL;
1471 return x;
1474 /* Return a Python Int or Long from the object item
1475 Raise TypeError if the result is not an int-or-long
1476 or if the object cannot be interpreted as an index.
1478 PyObject *
1479 PyNumber_Index(PyObject *item)
1481 PyObject *result = NULL;
1482 if (item == NULL)
1483 return null_error();
1484 if (PyInt_Check(item) || PyLong_Check(item)) {
1485 Py_INCREF(item);
1486 return item;
1488 if (PyIndex_Check(item)) {
1489 result = item->ob_type->tp_as_number->nb_index(item);
1490 if (result &&
1491 !PyInt_Check(result) && !PyLong_Check(result)) {
1492 PyErr_Format(PyExc_TypeError,
1493 "__index__ returned non-(int,long) " \
1494 "(type %.200s)",
1495 result->ob_type->tp_name);
1496 Py_DECREF(result);
1497 return NULL;
1500 else {
1501 PyErr_Format(PyExc_TypeError,
1502 "'%.200s' object cannot be interpreted "
1503 "as an index", item->ob_type->tp_name);
1505 return result;
1508 /* Return an error on Overflow only if err is not NULL*/
1510 Py_ssize_t
1511 PyNumber_AsSsize_t(PyObject *item, PyObject *err)
1513 Py_ssize_t result;
1514 PyObject *runerr;
1515 PyObject *value = PyNumber_Index(item);
1516 if (value == NULL)
1517 return -1;
1519 /* We're done if PyInt_AsSsize_t() returns without error. */
1520 result = PyInt_AsSsize_t(value);
1521 if (result != -1 || !(runerr = PyErr_Occurred()))
1522 goto finish;
1524 /* Error handling code -- only manage OverflowError differently */
1525 if (!PyErr_GivenExceptionMatches(runerr, PyExc_OverflowError))
1526 goto finish;
1528 PyErr_Clear();
1529 /* If no error-handling desired then the default clipping
1530 is sufficient.
1532 if (!err) {
1533 assert(PyLong_Check(value));
1534 /* Whether or not it is less than or equal to
1535 zero is determined by the sign of ob_size
1537 if (_PyLong_Sign(value) < 0)
1538 result = PY_SSIZE_T_MIN;
1539 else
1540 result = PY_SSIZE_T_MAX;
1542 else {
1543 /* Otherwise replace the error with caller's error object. */
1544 PyErr_Format(err,
1545 "cannot fit '%.200s' into an index-sized integer",
1546 item->ob_type->tp_name);
1549 finish:
1550 Py_DECREF(value);
1551 return result;
1555 PyObject *
1556 _PyNumber_ConvertIntegralToInt(PyObject *integral, const char* error_format)
1558 const char *type_name;
1559 static PyObject *int_name = NULL;
1560 if (int_name == NULL) {
1561 int_name = PyString_InternFromString("__int__");
1562 if (int_name == NULL)
1563 return NULL;
1566 if (integral && (!PyInt_Check(integral) &&
1567 !PyLong_Check(integral))) {
1568 /* Don't go through tp_as_number->nb_int to avoid
1569 hitting the classic class fallback to __trunc__. */
1570 PyObject *int_func = PyObject_GetAttr(integral, int_name);
1571 if (int_func == NULL) {
1572 PyErr_Clear(); /* Raise a different error. */
1573 goto non_integral_error;
1575 Py_DECREF(integral);
1576 integral = PyEval_CallObject(int_func, NULL);
1577 Py_DECREF(int_func);
1578 if (integral && (!PyInt_Check(integral) &&
1579 !PyLong_Check(integral))) {
1580 goto non_integral_error;
1583 return integral;
1585 non_integral_error:
1586 if (PyInstance_Check(integral)) {
1587 type_name = PyString_AS_STRING(((PyInstanceObject *)integral)
1588 ->in_class->cl_name);
1590 else {
1591 type_name = integral->ob_type->tp_name;
1593 PyErr_Format(PyExc_TypeError, error_format, type_name);
1594 Py_DECREF(integral);
1595 return NULL;
1599 PyObject *
1600 PyNumber_Int(PyObject *o)
1602 PyNumberMethods *m;
1603 static PyObject *trunc_name = NULL;
1604 PyObject *trunc_func;
1605 const char *buffer;
1606 Py_ssize_t buffer_len;
1608 if (trunc_name == NULL) {
1609 trunc_name = PyString_InternFromString("__trunc__");
1610 if (trunc_name == NULL)
1611 return NULL;
1614 if (o == NULL)
1615 return null_error();
1616 if (PyInt_CheckExact(o)) {
1617 Py_INCREF(o);
1618 return o;
1620 m = o->ob_type->tp_as_number;
1621 if (m && m->nb_int) { /* This should include subclasses of int */
1622 /* Classic classes always take this branch. */
1623 PyObject *res = m->nb_int(o);
1624 if (res && (!PyInt_Check(res) && !PyLong_Check(res))) {
1625 PyErr_Format(PyExc_TypeError,
1626 "__int__ returned non-int (type %.200s)",
1627 res->ob_type->tp_name);
1628 Py_DECREF(res);
1629 return NULL;
1631 return res;
1633 if (PyInt_Check(o)) { /* A int subclass without nb_int */
1634 PyIntObject *io = (PyIntObject*)o;
1635 return PyInt_FromLong(io->ob_ival);
1637 trunc_func = PyObject_GetAttr(o, trunc_name);
1638 if (trunc_func) {
1639 PyObject *truncated = PyEval_CallObject(trunc_func, NULL);
1640 Py_DECREF(trunc_func);
1641 /* __trunc__ is specified to return an Integral type, but
1642 int() needs to return an int. */
1643 return _PyNumber_ConvertIntegralToInt(
1644 truncated,
1645 "__trunc__ returned non-Integral (type %.200s)");
1647 PyErr_Clear(); /* It's not an error if o.__trunc__ doesn't exist. */
1649 if (PyString_Check(o))
1650 return int_from_string(PyString_AS_STRING(o),
1651 PyString_GET_SIZE(o));
1652 #ifdef Py_USING_UNICODE
1653 if (PyUnicode_Check(o))
1654 return PyInt_FromUnicode(PyUnicode_AS_UNICODE(o),
1655 PyUnicode_GET_SIZE(o),
1656 10);
1657 #endif
1658 if (!PyObject_AsCharBuffer(o, &buffer, &buffer_len))
1659 return int_from_string((char*)buffer, buffer_len);
1661 return type_error("int() argument must be a string or a "
1662 "number, not '%.200s'", o);
1665 /* Add a check for embedded NULL-bytes in the argument. */
1666 static PyObject *
1667 long_from_string(const char *s, Py_ssize_t len)
1669 char *end;
1670 PyObject *x;
1672 x = PyLong_FromString((char*)s, &end, 10);
1673 if (x == NULL)
1674 return NULL;
1675 if (end != s + len) {
1676 PyErr_SetString(PyExc_ValueError,
1677 "null byte in argument for long()");
1678 Py_DECREF(x);
1679 return NULL;
1681 return x;
1684 PyObject *
1685 PyNumber_Long(PyObject *o)
1687 PyNumberMethods *m;
1688 static PyObject *trunc_name = NULL;
1689 PyObject *trunc_func;
1690 const char *buffer;
1691 Py_ssize_t buffer_len;
1693 if (trunc_name == NULL) {
1694 trunc_name = PyString_InternFromString("__trunc__");
1695 if (trunc_name == NULL)
1696 return NULL;
1699 if (o == NULL)
1700 return null_error();
1701 m = o->ob_type->tp_as_number;
1702 if (m && m->nb_long) { /* This should include subclasses of long */
1703 /* Classic classes always take this branch. */
1704 PyObject *res = m->nb_long(o);
1705 if (res && (!PyInt_Check(res) && !PyLong_Check(res))) {
1706 PyErr_Format(PyExc_TypeError,
1707 "__long__ returned non-long (type %.200s)",
1708 res->ob_type->tp_name);
1709 Py_DECREF(res);
1710 return NULL;
1712 return res;
1714 if (PyLong_Check(o)) /* A long subclass without nb_long */
1715 return _PyLong_Copy((PyLongObject *)o);
1716 trunc_func = PyObject_GetAttr(o, trunc_name);
1717 if (trunc_func) {
1718 PyObject *truncated = PyEval_CallObject(trunc_func, NULL);
1719 PyObject *int_instance;
1720 Py_DECREF(trunc_func);
1721 /* __trunc__ is specified to return an Integral type,
1722 but long() needs to return a long. */
1723 int_instance = _PyNumber_ConvertIntegralToInt(
1724 truncated,
1725 "__trunc__ returned non-Integral (type %.200s)");
1726 if (int_instance && PyInt_Check(int_instance)) {
1727 /* Make sure that long() returns a long instance. */
1728 long value = PyInt_AS_LONG(int_instance);
1729 Py_DECREF(int_instance);
1730 return PyLong_FromLong(value);
1732 return int_instance;
1734 PyErr_Clear(); /* It's not an error if o.__trunc__ doesn't exist. */
1736 if (PyString_Check(o))
1737 /* need to do extra error checking that PyLong_FromString()
1738 * doesn't do. In particular long('9.5') must raise an
1739 * exception, not truncate the float.
1741 return long_from_string(PyString_AS_STRING(o),
1742 PyString_GET_SIZE(o));
1743 #ifdef Py_USING_UNICODE
1744 if (PyUnicode_Check(o))
1745 /* The above check is done in PyLong_FromUnicode(). */
1746 return PyLong_FromUnicode(PyUnicode_AS_UNICODE(o),
1747 PyUnicode_GET_SIZE(o),
1748 10);
1749 #endif
1750 if (!PyObject_AsCharBuffer(o, &buffer, &buffer_len))
1751 return long_from_string(buffer, buffer_len);
1753 return type_error("long() argument must be a string or a "
1754 "number, not '%.200s'", o);
1757 PyObject *
1758 PyNumber_Float(PyObject *o)
1760 PyNumberMethods *m;
1762 if (o == NULL)
1763 return null_error();
1764 m = o->ob_type->tp_as_number;
1765 if (m && m->nb_float) { /* This should include subclasses of float */
1766 PyObject *res = m->nb_float(o);
1767 if (res && !PyFloat_Check(res)) {
1768 PyErr_Format(PyExc_TypeError,
1769 "__float__ returned non-float (type %.200s)",
1770 res->ob_type->tp_name);
1771 Py_DECREF(res);
1772 return NULL;
1774 return res;
1776 if (PyFloat_Check(o)) { /* A float subclass with nb_float == NULL */
1777 PyFloatObject *po = (PyFloatObject *)o;
1778 return PyFloat_FromDouble(po->ob_fval);
1780 return PyFloat_FromString(o, NULL);
1783 PyObject *
1784 PyNumber_ToBase(PyObject *n, int base)
1786 PyObject *res = NULL;
1787 PyObject *index = PyNumber_Index(n);
1789 if (!index)
1790 return NULL;
1791 if (PyLong_Check(index))
1792 res = _PyLong_Format(index, base, 0, 1);
1793 else if (PyInt_Check(index))
1794 res = _PyInt_Format((PyIntObject*)index, base, 1);
1795 else
1796 /* It should not be possible to get here, as
1797 PyNumber_Index already has a check for the same
1798 condition */
1799 PyErr_SetString(PyExc_ValueError, "PyNumber_ToBase: index not "
1800 "int or long");
1801 Py_DECREF(index);
1802 return res;
1806 /* Operations on sequences */
1809 PySequence_Check(PyObject *s)
1811 if (s && PyInstance_Check(s))
1812 return PyObject_HasAttrString(s, "__getitem__");
1813 if (PyDict_Check(s))
1814 return 0;
1815 return s != NULL && s->ob_type->tp_as_sequence &&
1816 s->ob_type->tp_as_sequence->sq_item != NULL;
1819 Py_ssize_t
1820 PySequence_Size(PyObject *s)
1822 PySequenceMethods *m;
1824 if (s == NULL) {
1825 null_error();
1826 return -1;
1829 m = s->ob_type->tp_as_sequence;
1830 if (m && m->sq_length)
1831 return m->sq_length(s);
1833 type_error("object of type '%.200s' has no len()", s);
1834 return -1;
1837 #undef PySequence_Length
1838 Py_ssize_t
1839 PySequence_Length(PyObject *s)
1841 return PySequence_Size(s);
1843 #define PySequence_Length PySequence_Size
1845 PyObject *
1846 PySequence_Concat(PyObject *s, PyObject *o)
1848 PySequenceMethods *m;
1850 if (s == NULL || o == NULL)
1851 return null_error();
1853 m = s->ob_type->tp_as_sequence;
1854 if (m && m->sq_concat)
1855 return m->sq_concat(s, o);
1857 /* Instances of user classes defining an __add__() method only
1858 have an nb_add slot, not an sq_concat slot. So we fall back
1859 to nb_add if both arguments appear to be sequences. */
1860 if (PySequence_Check(s) && PySequence_Check(o)) {
1861 PyObject *result = binary_op1(s, o, NB_SLOT(nb_add));
1862 if (result != Py_NotImplemented)
1863 return result;
1864 Py_DECREF(result);
1866 return type_error("'%.200s' object can't be concatenated", s);
1869 PyObject *
1870 PySequence_Repeat(PyObject *o, Py_ssize_t count)
1872 PySequenceMethods *m;
1874 if (o == NULL)
1875 return null_error();
1877 m = o->ob_type->tp_as_sequence;
1878 if (m && m->sq_repeat)
1879 return m->sq_repeat(o, count);
1881 /* Instances of user classes defining a __mul__() method only
1882 have an nb_multiply slot, not an sq_repeat slot. so we fall back
1883 to nb_multiply if o appears to be a sequence. */
1884 if (PySequence_Check(o)) {
1885 PyObject *n, *result;
1886 n = PyInt_FromSsize_t(count);
1887 if (n == NULL)
1888 return NULL;
1889 result = binary_op1(o, n, NB_SLOT(nb_multiply));
1890 Py_DECREF(n);
1891 if (result != Py_NotImplemented)
1892 return result;
1893 Py_DECREF(result);
1895 return type_error("'%.200s' object can't be repeated", o);
1898 PyObject *
1899 PySequence_InPlaceConcat(PyObject *s, PyObject *o)
1901 PySequenceMethods *m;
1903 if (s == NULL || o == NULL)
1904 return null_error();
1906 m = s->ob_type->tp_as_sequence;
1907 if (m && HASINPLACE(s) && m->sq_inplace_concat)
1908 return m->sq_inplace_concat(s, o);
1909 if (m && m->sq_concat)
1910 return m->sq_concat(s, o);
1912 if (PySequence_Check(s) && PySequence_Check(o)) {
1913 PyObject *result = binary_iop1(s, o, NB_SLOT(nb_inplace_add),
1914 NB_SLOT(nb_add));
1915 if (result != Py_NotImplemented)
1916 return result;
1917 Py_DECREF(result);
1919 return type_error("'%.200s' object can't be concatenated", s);
1922 PyObject *
1923 PySequence_InPlaceRepeat(PyObject *o, Py_ssize_t count)
1925 PySequenceMethods *m;
1927 if (o == NULL)
1928 return null_error();
1930 m = o->ob_type->tp_as_sequence;
1931 if (m && HASINPLACE(o) && m->sq_inplace_repeat)
1932 return m->sq_inplace_repeat(o, count);
1933 if (m && m->sq_repeat)
1934 return m->sq_repeat(o, count);
1936 if (PySequence_Check(o)) {
1937 PyObject *n, *result;
1938 n = PyInt_FromSsize_t(count);
1939 if (n == NULL)
1940 return NULL;
1941 result = binary_iop1(o, n, NB_SLOT(nb_inplace_multiply),
1942 NB_SLOT(nb_multiply));
1943 Py_DECREF(n);
1944 if (result != Py_NotImplemented)
1945 return result;
1946 Py_DECREF(result);
1948 return type_error("'%.200s' object can't be repeated", o);
1951 PyObject *
1952 PySequence_GetItem(PyObject *s, Py_ssize_t i)
1954 PySequenceMethods *m;
1956 if (s == NULL)
1957 return null_error();
1959 m = s->ob_type->tp_as_sequence;
1960 if (m && m->sq_item) {
1961 if (i < 0) {
1962 if (m->sq_length) {
1963 Py_ssize_t l = (*m->sq_length)(s);
1964 if (l < 0)
1965 return NULL;
1966 i += l;
1969 return m->sq_item(s, i);
1972 return type_error("'%.200s' object does not support indexing", s);
1975 PyObject *
1976 PySequence_GetSlice(PyObject *s, Py_ssize_t i1, Py_ssize_t i2)
1978 PySequenceMethods *m;
1979 PyMappingMethods *mp;
1981 if (!s) return null_error();
1983 m = s->ob_type->tp_as_sequence;
1984 if (m && m->sq_slice) {
1985 if (i1 < 0 || i2 < 0) {
1986 if (m->sq_length) {
1987 Py_ssize_t l = (*m->sq_length)(s);
1988 if (l < 0)
1989 return NULL;
1990 if (i1 < 0)
1991 i1 += l;
1992 if (i2 < 0)
1993 i2 += l;
1996 return m->sq_slice(s, i1, i2);
1997 } else if ((mp = s->ob_type->tp_as_mapping) && mp->mp_subscript) {
1998 PyObject *res;
1999 PyObject *slice = _PySlice_FromIndices(i1, i2);
2000 if (!slice)
2001 return NULL;
2002 res = mp->mp_subscript(s, slice);
2003 Py_DECREF(slice);
2004 return res;
2007 return type_error("'%.200s' object is unsliceable", s);
2011 PySequence_SetItem(PyObject *s, Py_ssize_t i, PyObject *o)
2013 PySequenceMethods *m;
2015 if (s == NULL) {
2016 null_error();
2017 return -1;
2020 m = s->ob_type->tp_as_sequence;
2021 if (m && m->sq_ass_item) {
2022 if (i < 0) {
2023 if (m->sq_length) {
2024 Py_ssize_t l = (*m->sq_length)(s);
2025 if (l < 0)
2026 return -1;
2027 i += l;
2030 return m->sq_ass_item(s, i, o);
2033 type_error("'%.200s' object does not support item assignment", s);
2034 return -1;
2038 PySequence_DelItem(PyObject *s, Py_ssize_t i)
2040 PySequenceMethods *m;
2042 if (s == NULL) {
2043 null_error();
2044 return -1;
2047 m = s->ob_type->tp_as_sequence;
2048 if (m && m->sq_ass_item) {
2049 if (i < 0) {
2050 if (m->sq_length) {
2051 Py_ssize_t l = (*m->sq_length)(s);
2052 if (l < 0)
2053 return -1;
2054 i += l;
2057 return m->sq_ass_item(s, i, (PyObject *)NULL);
2060 type_error("'%.200s' object doesn't support item deletion", s);
2061 return -1;
2065 PySequence_SetSlice(PyObject *s, Py_ssize_t i1, Py_ssize_t i2, PyObject *o)
2067 PySequenceMethods *m;
2068 PyMappingMethods *mp;
2070 if (s == NULL) {
2071 null_error();
2072 return -1;
2075 m = s->ob_type->tp_as_sequence;
2076 if (m && m->sq_ass_slice) {
2077 if (i1 < 0 || i2 < 0) {
2078 if (m->sq_length) {
2079 Py_ssize_t l = (*m->sq_length)(s);
2080 if (l < 0)
2081 return -1;
2082 if (i1 < 0)
2083 i1 += l;
2084 if (i2 < 0)
2085 i2 += l;
2088 return m->sq_ass_slice(s, i1, i2, o);
2089 } else if ((mp = s->ob_type->tp_as_mapping) && mp->mp_ass_subscript) {
2090 int res;
2091 PyObject *slice = _PySlice_FromIndices(i1, i2);
2092 if (!slice)
2093 return -1;
2094 res = mp->mp_ass_subscript(s, slice, o);
2095 Py_DECREF(slice);
2096 return res;
2099 type_error("'%.200s' object doesn't support slice assignment", s);
2100 return -1;
2104 PySequence_DelSlice(PyObject *s, Py_ssize_t i1, Py_ssize_t i2)
2106 PySequenceMethods *m;
2108 if (s == NULL) {
2109 null_error();
2110 return -1;
2113 m = s->ob_type->tp_as_sequence;
2114 if (m && m->sq_ass_slice) {
2115 if (i1 < 0 || i2 < 0) {
2116 if (m->sq_length) {
2117 Py_ssize_t l = (*m->sq_length)(s);
2118 if (l < 0)
2119 return -1;
2120 if (i1 < 0)
2121 i1 += l;
2122 if (i2 < 0)
2123 i2 += l;
2126 return m->sq_ass_slice(s, i1, i2, (PyObject *)NULL);
2128 type_error("'%.200s' object doesn't support slice deletion", s);
2129 return -1;
2132 PyObject *
2133 PySequence_Tuple(PyObject *v)
2135 PyObject *it; /* iter(v) */
2136 Py_ssize_t n; /* guess for result tuple size */
2137 PyObject *result = NULL;
2138 Py_ssize_t j;
2140 if (v == NULL)
2141 return null_error();
2143 /* Special-case the common tuple and list cases, for efficiency. */
2144 if (PyTuple_CheckExact(v)) {
2145 /* Note that we can't know whether it's safe to return
2146 a tuple *subclass* instance as-is, hence the restriction
2147 to exact tuples here. In contrast, lists always make
2148 a copy, so there's no need for exactness below. */
2149 Py_INCREF(v);
2150 return v;
2152 if (PyList_Check(v))
2153 return PyList_AsTuple(v);
2155 /* Get iterator. */
2156 it = PyObject_GetIter(v);
2157 if (it == NULL)
2158 return NULL;
2160 /* Guess result size and allocate space. */
2161 n = _PyObject_LengthHint(v, 10);
2162 if (n == -1)
2163 goto Fail;
2164 result = PyTuple_New(n);
2165 if (result == NULL)
2166 goto Fail;
2168 /* Fill the tuple. */
2169 for (j = 0; ; ++j) {
2170 PyObject *item = PyIter_Next(it);
2171 if (item == NULL) {
2172 if (PyErr_Occurred())
2173 goto Fail;
2174 break;
2176 if (j >= n) {
2177 Py_ssize_t oldn = n;
2178 /* The over-allocation strategy can grow a bit faster
2179 than for lists because unlike lists the
2180 over-allocation isn't permanent -- we reclaim
2181 the excess before the end of this routine.
2182 So, grow by ten and then add 25%.
2184 n += 10;
2185 n += n >> 2;
2186 if (n < oldn) {
2187 /* Check for overflow */
2188 PyErr_NoMemory();
2189 Py_DECREF(item);
2190 goto Fail;
2192 if (_PyTuple_Resize(&result, n) != 0) {
2193 Py_DECREF(item);
2194 goto Fail;
2197 PyTuple_SET_ITEM(result, j, item);
2200 /* Cut tuple back if guess was too large. */
2201 if (j < n &&
2202 _PyTuple_Resize(&result, j) != 0)
2203 goto Fail;
2205 Py_DECREF(it);
2206 return result;
2208 Fail:
2209 Py_XDECREF(result);
2210 Py_DECREF(it);
2211 return NULL;
2214 PyObject *
2215 PySequence_List(PyObject *v)
2217 PyObject *result; /* result list */
2218 PyObject *rv; /* return value from PyList_Extend */
2220 if (v == NULL)
2221 return null_error();
2223 result = PyList_New(0);
2224 if (result == NULL)
2225 return NULL;
2227 rv = _PyList_Extend((PyListObject *)result, v);
2228 if (rv == NULL) {
2229 Py_DECREF(result);
2230 return NULL;
2232 Py_DECREF(rv);
2233 return result;
2236 PyObject *
2237 PySequence_Fast(PyObject *v, const char *m)
2239 PyObject *it;
2241 if (v == NULL)
2242 return null_error();
2244 if (PyList_CheckExact(v) || PyTuple_CheckExact(v)) {
2245 Py_INCREF(v);
2246 return v;
2249 it = PyObject_GetIter(v);
2250 if (it == NULL) {
2251 if (PyErr_ExceptionMatches(PyExc_TypeError))
2252 PyErr_SetString(PyExc_TypeError, m);
2253 return NULL;
2256 v = PySequence_List(it);
2257 Py_DECREF(it);
2259 return v;
2262 /* Iterate over seq. Result depends on the operation:
2263 PY_ITERSEARCH_COUNT: -1 if error, else # of times obj appears in seq.
2264 PY_ITERSEARCH_INDEX: 0-based index of first occurrence of obj in seq;
2265 set ValueError and return -1 if none found; also return -1 on error.
2266 Py_ITERSEARCH_CONTAINS: return 1 if obj in seq, else 0; -1 on error.
2268 Py_ssize_t
2269 _PySequence_IterSearch(PyObject *seq, PyObject *obj, int operation)
2271 Py_ssize_t n;
2272 int wrapped; /* for PY_ITERSEARCH_INDEX, true iff n wrapped around */
2273 PyObject *it; /* iter(seq) */
2275 if (seq == NULL || obj == NULL) {
2276 null_error();
2277 return -1;
2280 it = PyObject_GetIter(seq);
2281 if (it == NULL) {
2282 type_error("argument of type '%.200s' is not iterable", seq);
2283 return -1;
2286 n = wrapped = 0;
2287 for (;;) {
2288 int cmp;
2289 PyObject *item = PyIter_Next(it);
2290 if (item == NULL) {
2291 if (PyErr_Occurred())
2292 goto Fail;
2293 break;
2296 cmp = PyObject_RichCompareBool(obj, item, Py_EQ);
2297 Py_DECREF(item);
2298 if (cmp < 0)
2299 goto Fail;
2300 if (cmp > 0) {
2301 switch (operation) {
2302 case PY_ITERSEARCH_COUNT:
2303 if (n == PY_SSIZE_T_MAX) {
2304 PyErr_SetString(PyExc_OverflowError,
2305 "count exceeds C integer size");
2306 goto Fail;
2308 ++n;
2309 break;
2311 case PY_ITERSEARCH_INDEX:
2312 if (wrapped) {
2313 PyErr_SetString(PyExc_OverflowError,
2314 "index exceeds C integer size");
2315 goto Fail;
2317 goto Done;
2319 case PY_ITERSEARCH_CONTAINS:
2320 n = 1;
2321 goto Done;
2323 default:
2324 assert(!"unknown operation");
2328 if (operation == PY_ITERSEARCH_INDEX) {
2329 if (n == PY_SSIZE_T_MAX)
2330 wrapped = 1;
2331 ++n;
2335 if (operation != PY_ITERSEARCH_INDEX)
2336 goto Done;
2338 PyErr_SetString(PyExc_ValueError,
2339 "sequence.index(x): x not in sequence");
2340 /* fall into failure code */
2341 Fail:
2342 n = -1;
2343 /* fall through */
2344 Done:
2345 Py_DECREF(it);
2346 return n;
2350 /* Return # of times o appears in s. */
2351 Py_ssize_t
2352 PySequence_Count(PyObject *s, PyObject *o)
2354 return _PySequence_IterSearch(s, o, PY_ITERSEARCH_COUNT);
2357 /* Return -1 if error; 1 if ob in seq; 0 if ob not in seq.
2358 * Use sq_contains if possible, else defer to _PySequence_IterSearch().
2361 PySequence_Contains(PyObject *seq, PyObject *ob)
2363 Py_ssize_t result;
2364 if (PyType_HasFeature(seq->ob_type, Py_TPFLAGS_HAVE_SEQUENCE_IN)) {
2365 PySequenceMethods *sqm = seq->ob_type->tp_as_sequence;
2366 if (sqm != NULL && sqm->sq_contains != NULL)
2367 return (*sqm->sq_contains)(seq, ob);
2369 result = _PySequence_IterSearch(seq, ob, PY_ITERSEARCH_CONTAINS);
2370 return Py_SAFE_DOWNCAST(result, Py_ssize_t, int);
2373 /* Backwards compatibility */
2374 #undef PySequence_In
2376 PySequence_In(PyObject *w, PyObject *v)
2378 return PySequence_Contains(w, v);
2381 Py_ssize_t
2382 PySequence_Index(PyObject *s, PyObject *o)
2384 return _PySequence_IterSearch(s, o, PY_ITERSEARCH_INDEX);
2387 /* Operations on mappings */
2390 PyMapping_Check(PyObject *o)
2392 if (o && PyInstance_Check(o))
2393 return PyObject_HasAttrString(o, "__getitem__");
2395 return o && o->ob_type->tp_as_mapping &&
2396 o->ob_type->tp_as_mapping->mp_subscript &&
2397 !(o->ob_type->tp_as_sequence &&
2398 o->ob_type->tp_as_sequence->sq_slice);
2401 Py_ssize_t
2402 PyMapping_Size(PyObject *o)
2404 PyMappingMethods *m;
2406 if (o == NULL) {
2407 null_error();
2408 return -1;
2411 m = o->ob_type->tp_as_mapping;
2412 if (m && m->mp_length)
2413 return m->mp_length(o);
2415 type_error("object of type '%.200s' has no len()", o);
2416 return -1;
2419 #undef PyMapping_Length
2420 Py_ssize_t
2421 PyMapping_Length(PyObject *o)
2423 return PyMapping_Size(o);
2425 #define PyMapping_Length PyMapping_Size
2427 PyObject *
2428 PyMapping_GetItemString(PyObject *o, char *key)
2430 PyObject *okey, *r;
2432 if (key == NULL)
2433 return null_error();
2435 okey = PyString_FromString(key);
2436 if (okey == NULL)
2437 return NULL;
2438 r = PyObject_GetItem(o, okey);
2439 Py_DECREF(okey);
2440 return r;
2444 PyMapping_SetItemString(PyObject *o, char *key, PyObject *value)
2446 PyObject *okey;
2447 int r;
2449 if (key == NULL) {
2450 null_error();
2451 return -1;
2454 okey = PyString_FromString(key);
2455 if (okey == NULL)
2456 return -1;
2457 r = PyObject_SetItem(o, okey, value);
2458 Py_DECREF(okey);
2459 return r;
2463 PyMapping_HasKeyString(PyObject *o, char *key)
2465 PyObject *v;
2467 v = PyMapping_GetItemString(o, key);
2468 if (v) {
2469 Py_DECREF(v);
2470 return 1;
2472 PyErr_Clear();
2473 return 0;
2477 PyMapping_HasKey(PyObject *o, PyObject *key)
2479 PyObject *v;
2481 v = PyObject_GetItem(o, key);
2482 if (v) {
2483 Py_DECREF(v);
2484 return 1;
2486 PyErr_Clear();
2487 return 0;
2490 /* Operations on callable objects */
2492 /* XXX PyCallable_Check() is in object.c */
2494 PyObject *
2495 PyObject_CallObject(PyObject *o, PyObject *a)
2497 return PyEval_CallObjectWithKeywords(o, a, NULL);
2500 PyObject *
2501 PyObject_Call(PyObject *func, PyObject *arg, PyObject *kw)
2503 ternaryfunc call;
2505 if ((call = func->ob_type->tp_call) != NULL) {
2506 PyObject *result;
2507 if (Py_EnterRecursiveCall(" while calling a Python object"))
2508 return NULL;
2509 result = (*call)(func, arg, kw);
2510 Py_LeaveRecursiveCall();
2511 if (result == NULL && !PyErr_Occurred())
2512 PyErr_SetString(
2513 PyExc_SystemError,
2514 "NULL result without error in PyObject_Call");
2515 return result;
2517 PyErr_Format(PyExc_TypeError, "'%.200s' object is not callable",
2518 func->ob_type->tp_name);
2519 return NULL;
2522 static PyObject*
2523 call_function_tail(PyObject *callable, PyObject *args)
2525 PyObject *retval;
2527 if (args == NULL)
2528 return NULL;
2530 if (!PyTuple_Check(args)) {
2531 PyObject *a;
2533 a = PyTuple_New(1);
2534 if (a == NULL) {
2535 Py_DECREF(args);
2536 return NULL;
2538 PyTuple_SET_ITEM(a, 0, args);
2539 args = a;
2541 retval = PyObject_Call(callable, args, NULL);
2543 Py_DECREF(args);
2545 return retval;
2548 PyObject *
2549 PyObject_CallFunction(PyObject *callable, char *format, ...)
2551 va_list va;
2552 PyObject *args;
2554 if (callable == NULL)
2555 return null_error();
2557 if (format && *format) {
2558 va_start(va, format);
2559 args = Py_VaBuildValue(format, va);
2560 va_end(va);
2562 else
2563 args = PyTuple_New(0);
2565 return call_function_tail(callable, args);
2568 PyObject *
2569 _PyObject_CallFunction_SizeT(PyObject *callable, char *format, ...)
2571 va_list va;
2572 PyObject *args;
2574 if (callable == NULL)
2575 return null_error();
2577 if (format && *format) {
2578 va_start(va, format);
2579 args = _Py_VaBuildValue_SizeT(format, va);
2580 va_end(va);
2582 else
2583 args = PyTuple_New(0);
2585 return call_function_tail(callable, args);
2588 PyObject *
2589 PyObject_CallMethod(PyObject *o, char *name, char *format, ...)
2591 va_list va;
2592 PyObject *args;
2593 PyObject *func = NULL;
2594 PyObject *retval = NULL;
2596 if (o == NULL || name == NULL)
2597 return null_error();
2599 func = PyObject_GetAttrString(o, name);
2600 if (func == NULL) {
2601 PyErr_SetString(PyExc_AttributeError, name);
2602 return 0;
2605 if (!PyCallable_Check(func)) {
2606 type_error("attribute of type '%.200s' is not callable", func);
2607 goto exit;
2610 if (format && *format) {
2611 va_start(va, format);
2612 args = Py_VaBuildValue(format, va);
2613 va_end(va);
2615 else
2616 args = PyTuple_New(0);
2618 retval = call_function_tail(func, args);
2620 exit:
2621 /* args gets consumed in call_function_tail */
2622 Py_XDECREF(func);
2624 return retval;
2627 PyObject *
2628 _PyObject_CallMethod_SizeT(PyObject *o, char *name, char *format, ...)
2630 va_list va;
2631 PyObject *args;
2632 PyObject *func = NULL;
2633 PyObject *retval = NULL;
2635 if (o == NULL || name == NULL)
2636 return null_error();
2638 func = PyObject_GetAttrString(o, name);
2639 if (func == NULL) {
2640 PyErr_SetString(PyExc_AttributeError, name);
2641 return 0;
2644 if (!PyCallable_Check(func)) {
2645 type_error("attribute of type '%.200s' is not callable", func);
2646 goto exit;
2649 if (format && *format) {
2650 va_start(va, format);
2651 args = _Py_VaBuildValue_SizeT(format, va);
2652 va_end(va);
2654 else
2655 args = PyTuple_New(0);
2657 retval = call_function_tail(func, args);
2659 exit:
2660 /* args gets consumed in call_function_tail */
2661 Py_XDECREF(func);
2663 return retval;
2667 static PyObject *
2668 objargs_mktuple(va_list va)
2670 int i, n = 0;
2671 va_list countva;
2672 PyObject *result, *tmp;
2674 #ifdef VA_LIST_IS_ARRAY
2675 memcpy(countva, va, sizeof(va_list));
2676 #else
2677 #ifdef __va_copy
2678 __va_copy(countva, va);
2679 #else
2680 countva = va;
2681 #endif
2682 #endif
2684 while (((PyObject *)va_arg(countva, PyObject *)) != NULL)
2685 ++n;
2686 result = PyTuple_New(n);
2687 if (result != NULL && n > 0) {
2688 for (i = 0; i < n; ++i) {
2689 tmp = (PyObject *)va_arg(va, PyObject *);
2690 PyTuple_SET_ITEM(result, i, tmp);
2691 Py_INCREF(tmp);
2694 return result;
2697 PyObject *
2698 PyObject_CallMethodObjArgs(PyObject *callable, PyObject *name, ...)
2700 PyObject *args, *tmp;
2701 va_list vargs;
2703 if (callable == NULL || name == NULL)
2704 return null_error();
2706 callable = PyObject_GetAttr(callable, name);
2707 if (callable == NULL)
2708 return NULL;
2710 /* count the args */
2711 va_start(vargs, name);
2712 args = objargs_mktuple(vargs);
2713 va_end(vargs);
2714 if (args == NULL) {
2715 Py_DECREF(callable);
2716 return NULL;
2718 tmp = PyObject_Call(callable, args, NULL);
2719 Py_DECREF(args);
2720 Py_DECREF(callable);
2722 return tmp;
2725 PyObject *
2726 PyObject_CallFunctionObjArgs(PyObject *callable, ...)
2728 PyObject *args, *tmp;
2729 va_list vargs;
2731 if (callable == NULL)
2732 return null_error();
2734 /* count the args */
2735 va_start(vargs, callable);
2736 args = objargs_mktuple(vargs);
2737 va_end(vargs);
2738 if (args == NULL)
2739 return NULL;
2740 tmp = PyObject_Call(callable, args, NULL);
2741 Py_DECREF(args);
2743 return tmp;
2747 /* isinstance(), issubclass() */
2749 /* abstract_get_bases() has logically 4 return states, with a sort of 0th
2750 * state that will almost never happen.
2752 * 0. creating the __bases__ static string could get a MemoryError
2753 * 1. getattr(cls, '__bases__') could raise an AttributeError
2754 * 2. getattr(cls, '__bases__') could raise some other exception
2755 * 3. getattr(cls, '__bases__') could return a tuple
2756 * 4. getattr(cls, '__bases__') could return something other than a tuple
2758 * Only state #3 is a non-error state and only it returns a non-NULL object
2759 * (it returns the retrieved tuple).
2761 * Any raised AttributeErrors are masked by clearing the exception and
2762 * returning NULL. If an object other than a tuple comes out of __bases__,
2763 * then again, the return value is NULL. So yes, these two situations
2764 * produce exactly the same results: NULL is returned and no error is set.
2766 * If some exception other than AttributeError is raised, then NULL is also
2767 * returned, but the exception is not cleared. That's because we want the
2768 * exception to be propagated along.
2770 * Callers are expected to test for PyErr_Occurred() when the return value
2771 * is NULL to decide whether a valid exception should be propagated or not.
2772 * When there's no exception to propagate, it's customary for the caller to
2773 * set a TypeError.
2775 static PyObject *
2776 abstract_get_bases(PyObject *cls)
2778 static PyObject *__bases__ = NULL;
2779 PyObject *bases;
2781 if (__bases__ == NULL) {
2782 __bases__ = PyString_InternFromString("__bases__");
2783 if (__bases__ == NULL)
2784 return NULL;
2786 bases = PyObject_GetAttr(cls, __bases__);
2787 if (bases == NULL) {
2788 if (PyErr_ExceptionMatches(PyExc_AttributeError))
2789 PyErr_Clear();
2790 return NULL;
2792 if (!PyTuple_Check(bases)) {
2793 Py_DECREF(bases);
2794 return NULL;
2796 return bases;
2800 static int
2801 abstract_issubclass(PyObject *derived, PyObject *cls)
2803 PyObject *bases = NULL;
2804 Py_ssize_t i, n;
2805 int r = 0;
2807 while (1) {
2808 if (derived == cls)
2809 return 1;
2810 bases = abstract_get_bases(derived);
2811 if (bases == NULL) {
2812 if (PyErr_Occurred())
2813 return -1;
2814 return 0;
2816 n = PyTuple_GET_SIZE(bases);
2817 if (n == 0) {
2818 Py_DECREF(bases);
2819 return 0;
2821 /* Avoid recursivity in the single inheritance case */
2822 if (n == 1) {
2823 derived = PyTuple_GET_ITEM(bases, 0);
2824 Py_DECREF(bases);
2825 continue;
2827 for (i = 0; i < n; i++) {
2828 r = abstract_issubclass(PyTuple_GET_ITEM(bases, i), cls);
2829 if (r != 0)
2830 break;
2832 Py_DECREF(bases);
2833 return r;
2837 static int
2838 check_class(PyObject *cls, const char *error)
2840 PyObject *bases = abstract_get_bases(cls);
2841 if (bases == NULL) {
2842 /* Do not mask errors. */
2843 if (!PyErr_Occurred())
2844 PyErr_SetString(PyExc_TypeError, error);
2845 return 0;
2847 Py_DECREF(bases);
2848 return -1;
2851 static int
2852 recursive_isinstance(PyObject *inst, PyObject *cls)
2854 PyObject *icls;
2855 static PyObject *__class__ = NULL;
2856 int retval = 0;
2858 if (__class__ == NULL) {
2859 __class__ = PyString_InternFromString("__class__");
2860 if (__class__ == NULL)
2861 return -1;
2864 if (PyClass_Check(cls) && PyInstance_Check(inst)) {
2865 PyObject *inclass =
2866 (PyObject*)((PyInstanceObject*)inst)->in_class;
2867 retval = PyClass_IsSubclass(inclass, cls);
2869 else if (PyType_Check(cls)) {
2870 retval = PyObject_TypeCheck(inst, (PyTypeObject *)cls);
2871 if (retval == 0) {
2872 PyObject *c = PyObject_GetAttr(inst, __class__);
2873 if (c == NULL) {
2874 PyErr_Clear();
2876 else {
2877 if (c != (PyObject *)(inst->ob_type) &&
2878 PyType_Check(c))
2879 retval = PyType_IsSubtype(
2880 (PyTypeObject *)c,
2881 (PyTypeObject *)cls);
2882 Py_DECREF(c);
2886 else {
2887 if (!check_class(cls,
2888 "isinstance() arg 2 must be a class, type,"
2889 " or tuple of classes and types"))
2890 return -1;
2891 icls = PyObject_GetAttr(inst, __class__);
2892 if (icls == NULL) {
2893 PyErr_Clear();
2894 retval = 0;
2896 else {
2897 retval = abstract_issubclass(icls, cls);
2898 Py_DECREF(icls);
2902 return retval;
2906 PyObject_IsInstance(PyObject *inst, PyObject *cls)
2908 static PyObject *name = NULL;
2910 /* Quick test for an exact match */
2911 if (Py_TYPE(inst) == (PyTypeObject *)cls)
2912 return 1;
2914 if (PyTuple_Check(cls)) {
2915 Py_ssize_t i;
2916 Py_ssize_t n;
2917 int r = 0;
2919 if (Py_EnterRecursiveCall(" in __instancecheck__"))
2920 return -1;
2921 n = PyTuple_GET_SIZE(cls);
2922 for (i = 0; i < n; ++i) {
2923 PyObject *item = PyTuple_GET_ITEM(cls, i);
2924 r = PyObject_IsInstance(inst, item);
2925 if (r != 0)
2926 /* either found it, or got an error */
2927 break;
2929 Py_LeaveRecursiveCall();
2930 return r;
2933 if (!(PyClass_Check(cls) || PyInstance_Check(cls))) {
2934 PyObject *checker;
2935 checker = _PyObject_LookupSpecial(cls, "__instancecheck__", &name);
2936 if (checker != NULL) {
2937 PyObject *res;
2938 int ok = -1;
2939 if (Py_EnterRecursiveCall(" in __instancecheck__")) {
2940 Py_DECREF(checker);
2941 return ok;
2943 res = PyObject_CallFunctionObjArgs(checker, inst, NULL);
2944 Py_LeaveRecursiveCall();
2945 Py_DECREF(checker);
2946 if (res != NULL) {
2947 ok = PyObject_IsTrue(res);
2948 Py_DECREF(res);
2950 return ok;
2952 else if (PyErr_Occurred())
2953 return -1;
2955 return recursive_isinstance(inst, cls);
2958 static int
2959 recursive_issubclass(PyObject *derived, PyObject *cls)
2961 int retval;
2963 if (PyType_Check(cls) && PyType_Check(derived)) {
2964 /* Fast path (non-recursive) */
2965 return PyType_IsSubtype(
2966 (PyTypeObject *)derived, (PyTypeObject *)cls);
2968 if (!PyClass_Check(derived) || !PyClass_Check(cls)) {
2969 if (!check_class(derived,
2970 "issubclass() arg 1 must be a class"))
2971 return -1;
2973 if (!check_class(cls,
2974 "issubclass() arg 2 must be a class"
2975 " or tuple of classes"))
2976 return -1;
2977 retval = abstract_issubclass(derived, cls);
2979 else {
2980 /* shortcut */
2981 if (!(retval = (derived == cls)))
2982 retval = PyClass_IsSubclass(derived, cls);
2985 return retval;
2989 PyObject_IsSubclass(PyObject *derived, PyObject *cls)
2991 static PyObject *name = NULL;
2993 if (PyTuple_Check(cls)) {
2994 Py_ssize_t i;
2995 Py_ssize_t n;
2996 int r = 0;
2998 if (Py_EnterRecursiveCall(" in __subclasscheck__"))
2999 return -1;
3000 n = PyTuple_GET_SIZE(cls);
3001 for (i = 0; i < n; ++i) {
3002 PyObject *item = PyTuple_GET_ITEM(cls, i);
3003 r = PyObject_IsSubclass(derived, item);
3004 if (r != 0)
3005 /* either found it, or got an error */
3006 break;
3008 Py_LeaveRecursiveCall();
3009 return r;
3011 if (!(PyClass_Check(cls) || PyInstance_Check(cls))) {
3012 PyObject *checker;
3013 checker = _PyObject_LookupSpecial(cls, "__subclasscheck__", &name);
3014 if (checker != NULL) {
3015 PyObject *res;
3016 int ok = -1;
3017 if (Py_EnterRecursiveCall(" in __subclasscheck__")) {
3018 Py_DECREF(checker);
3019 return ok;
3021 res = PyObject_CallFunctionObjArgs(checker, derived, NULL);
3022 Py_LeaveRecursiveCall();
3023 Py_DECREF(checker);
3024 if (res != NULL) {
3025 ok = PyObject_IsTrue(res);
3026 Py_DECREF(res);
3028 return ok;
3030 else if (PyErr_Occurred()) {
3031 return -1;
3034 return recursive_issubclass(derived, cls);
3038 _PyObject_RealIsInstance(PyObject *inst, PyObject *cls)
3040 return recursive_isinstance(inst, cls);
3044 _PyObject_RealIsSubclass(PyObject *derived, PyObject *cls)
3046 return recursive_issubclass(derived, cls);
3050 PyObject *
3051 PyObject_GetIter(PyObject *o)
3053 PyTypeObject *t = o->ob_type;
3054 getiterfunc f = NULL;
3055 if (PyType_HasFeature(t, Py_TPFLAGS_HAVE_ITER))
3056 f = t->tp_iter;
3057 if (f == NULL) {
3058 if (PySequence_Check(o))
3059 return PySeqIter_New(o);
3060 return type_error("'%.200s' object is not iterable", o);
3062 else {
3063 PyObject *res = (*f)(o);
3064 if (res != NULL && !PyIter_Check(res)) {
3065 PyErr_Format(PyExc_TypeError,
3066 "iter() returned non-iterator "
3067 "of type '%.100s'",
3068 res->ob_type->tp_name);
3069 Py_DECREF(res);
3070 res = NULL;
3072 return res;
3076 /* Return next item.
3077 * If an error occurs, return NULL. PyErr_Occurred() will be true.
3078 * If the iteration terminates normally, return NULL and clear the
3079 * PyExc_StopIteration exception (if it was set). PyErr_Occurred()
3080 * will be false.
3081 * Else return the next object. PyErr_Occurred() will be false.
3083 PyObject *
3084 PyIter_Next(PyObject *iter)
3086 PyObject *result;
3087 result = (*iter->ob_type->tp_iternext)(iter);
3088 if (result == NULL &&
3089 PyErr_Occurred() &&
3090 PyErr_ExceptionMatches(PyExc_StopIteration))
3091 PyErr_Clear();
3092 return result;