FL, flp, and fl from IRIX have been deprecated for removal in 3.0.
[python.git] / Objects / abstract.c
blob83de88f6e4cea4f1f809fcc513e695164d04b727
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. This function never fails.
89 Accordingly, it will mask exceptions raised in either method.
92 Py_ssize_t
93 _PyObject_LengthHint(PyObject *o, Py_ssize_t defaultvalue)
95 static PyObject *hintstrobj = NULL;
96 PyObject *ro;
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 PyErr_Clear();
106 /* cache a hashed version of the attribute string */
107 if (hintstrobj == NULL) {
108 hintstrobj = PyString_InternFromString("__length_hint__");
109 if (hintstrobj == NULL)
110 goto defaultcase;
113 /* try o.__length_hint__() */
114 ro = PyObject_CallMethodObjArgs(o, hintstrobj, NULL);
115 if (ro == NULL)
116 goto defaultcase;
117 rv = PyInt_AsLong(ro);
118 Py_DECREF(ro);
119 if (rv >= 0)
120 return rv;
122 defaultcase:
123 if (PyErr_Occurred())
124 PyErr_Clear();
125 return defaultvalue;
128 PyObject *
129 PyObject_GetItem(PyObject *o, PyObject *key)
131 PyMappingMethods *m;
133 if (o == NULL || key == NULL)
134 return null_error();
136 m = o->ob_type->tp_as_mapping;
137 if (m && m->mp_subscript)
138 return m->mp_subscript(o, key);
140 if (o->ob_type->tp_as_sequence) {
141 if (PyIndex_Check(key)) {
142 Py_ssize_t key_value;
143 key_value = PyNumber_AsSsize_t(key, PyExc_IndexError);
144 if (key_value == -1 && PyErr_Occurred())
145 return NULL;
146 return PySequence_GetItem(o, key_value);
148 else if (o->ob_type->tp_as_sequence->sq_item)
149 return type_error("sequence index must "
150 "be integer, not '%.200s'", key);
153 return type_error("'%.200s' object is unsubscriptable", o);
157 PyObject_SetItem(PyObject *o, PyObject *key, PyObject *value)
159 PyMappingMethods *m;
161 if (o == NULL || key == NULL || value == NULL) {
162 null_error();
163 return -1;
165 m = o->ob_type->tp_as_mapping;
166 if (m && m->mp_ass_subscript)
167 return m->mp_ass_subscript(o, key, value);
169 if (o->ob_type->tp_as_sequence) {
170 if (PyIndex_Check(key)) {
171 Py_ssize_t key_value;
172 key_value = PyNumber_AsSsize_t(key, PyExc_IndexError);
173 if (key_value == -1 && PyErr_Occurred())
174 return -1;
175 return PySequence_SetItem(o, key_value, value);
177 else if (o->ob_type->tp_as_sequence->sq_ass_item) {
178 type_error("sequence index must be "
179 "integer, not '%.200s'", key);
180 return -1;
184 type_error("'%.200s' object does not support item assignment", o);
185 return -1;
189 PyObject_DelItem(PyObject *o, PyObject *key)
191 PyMappingMethods *m;
193 if (o == NULL || key == NULL) {
194 null_error();
195 return -1;
197 m = o->ob_type->tp_as_mapping;
198 if (m && m->mp_ass_subscript)
199 return m->mp_ass_subscript(o, key, (PyObject*)NULL);
201 if (o->ob_type->tp_as_sequence) {
202 if (PyIndex_Check(key)) {
203 Py_ssize_t key_value;
204 key_value = PyNumber_AsSsize_t(key, PyExc_IndexError);
205 if (key_value == -1 && PyErr_Occurred())
206 return -1;
207 return PySequence_DelItem(o, key_value);
209 else if (o->ob_type->tp_as_sequence->sq_ass_item) {
210 type_error("sequence index must be "
211 "integer, not '%.200s'", key);
212 return -1;
216 type_error("'%.200s' object does not support item deletion", o);
217 return -1;
221 PyObject_DelItemString(PyObject *o, char *key)
223 PyObject *okey;
224 int ret;
226 if (o == NULL || key == NULL) {
227 null_error();
228 return -1;
230 okey = PyString_FromString(key);
231 if (okey == NULL)
232 return -1;
233 ret = PyObject_DelItem(o, okey);
234 Py_DECREF(okey);
235 return ret;
239 PyObject_AsCharBuffer(PyObject *obj,
240 const char **buffer,
241 Py_ssize_t *buffer_len)
243 PyBufferProcs *pb;
244 char *pp;
245 Py_ssize_t len;
247 if (obj == NULL || buffer == NULL || buffer_len == NULL) {
248 null_error();
249 return -1;
251 pb = obj->ob_type->tp_as_buffer;
252 if (pb == NULL ||
253 pb->bf_getcharbuffer == NULL ||
254 pb->bf_getsegcount == NULL) {
255 PyErr_SetString(PyExc_TypeError,
256 "expected a character buffer object");
257 return -1;
259 if ((*pb->bf_getsegcount)(obj,NULL) != 1) {
260 PyErr_SetString(PyExc_TypeError,
261 "expected a single-segment buffer object");
262 return -1;
264 len = (*pb->bf_getcharbuffer)(obj, 0, &pp);
265 if (len < 0)
266 return -1;
267 *buffer = pp;
268 *buffer_len = len;
269 return 0;
273 PyObject_CheckReadBuffer(PyObject *obj)
275 PyBufferProcs *pb = obj->ob_type->tp_as_buffer;
277 if (pb == NULL ||
278 pb->bf_getreadbuffer == NULL ||
279 pb->bf_getsegcount == NULL ||
280 (*pb->bf_getsegcount)(obj, NULL) != 1)
281 return 0;
282 return 1;
285 int PyObject_AsReadBuffer(PyObject *obj,
286 const void **buffer,
287 Py_ssize_t *buffer_len)
289 PyBufferProcs *pb;
290 void *pp;
291 Py_ssize_t len;
293 if (obj == NULL || buffer == NULL || buffer_len == NULL) {
294 null_error();
295 return -1;
297 pb = obj->ob_type->tp_as_buffer;
298 if (pb == NULL ||
299 pb->bf_getreadbuffer == NULL ||
300 pb->bf_getsegcount == NULL) {
301 PyErr_SetString(PyExc_TypeError,
302 "expected a readable buffer object");
303 return -1;
305 if ((*pb->bf_getsegcount)(obj, NULL) != 1) {
306 PyErr_SetString(PyExc_TypeError,
307 "expected a single-segment buffer object");
308 return -1;
310 len = (*pb->bf_getreadbuffer)(obj, 0, &pp);
311 if (len < 0)
312 return -1;
313 *buffer = pp;
314 *buffer_len = len;
315 return 0;
318 int PyObject_AsWriteBuffer(PyObject *obj,
319 void **buffer,
320 Py_ssize_t *buffer_len)
322 PyBufferProcs *pb;
323 void*pp;
324 Py_ssize_t len;
326 if (obj == NULL || buffer == NULL || buffer_len == NULL) {
327 null_error();
328 return -1;
330 pb = obj->ob_type->tp_as_buffer;
331 if (pb == NULL ||
332 pb->bf_getwritebuffer == NULL ||
333 pb->bf_getsegcount == NULL) {
334 PyErr_SetString(PyExc_TypeError,
335 "expected a writeable buffer object");
336 return -1;
338 if ((*pb->bf_getsegcount)(obj, NULL) != 1) {
339 PyErr_SetString(PyExc_TypeError,
340 "expected a single-segment buffer object");
341 return -1;
343 len = (*pb->bf_getwritebuffer)(obj,0,&pp);
344 if (len < 0)
345 return -1;
346 *buffer = pp;
347 *buffer_len = len;
348 return 0;
351 /* Buffer C-API for Python 3.0 */
354 PyObject_GetBuffer(PyObject *obj, Py_buffer *view, int flags)
356 if (!PyObject_CheckBuffer(obj)) {
357 PyErr_Format(PyExc_TypeError,
358 "'%100s' does not have the buffer interface",
359 Py_TYPE(obj)->tp_name);
360 return -1;
362 return (*(obj->ob_type->tp_as_buffer->bf_getbuffer))(obj, view, flags);
365 void
366 PyObject_ReleaseBuffer(PyObject *obj, Py_buffer *view)
368 if (obj->ob_type->tp_as_buffer != NULL &&
369 obj->ob_type->tp_as_buffer->bf_releasebuffer != NULL) {
370 (*(obj->ob_type->tp_as_buffer->bf_releasebuffer))(obj, view);
375 static int
376 _IsFortranContiguous(Py_buffer *view)
378 Py_ssize_t sd, dim;
379 int i;
381 if (view->ndim == 0) return 1;
382 if (view->strides == NULL) return (view->ndim == 1);
384 sd = view->itemsize;
385 if (view->ndim == 1) return (view->shape[0] == 1 ||
386 sd == view->strides[0]);
387 for (i=0; i<view->ndim; i++) {
388 dim = view->shape[i];
389 if (dim == 0) return 1;
390 if (view->strides[i] != sd) return 0;
391 sd *= dim;
393 return 1;
396 static int
397 _IsCContiguous(Py_buffer *view)
399 Py_ssize_t sd, dim;
400 int i;
402 if (view->ndim == 0) return 1;
403 if (view->strides == NULL) return 1;
405 sd = view->itemsize;
406 if (view->ndim == 1) return (view->shape[0] == 1 ||
407 sd == view->strides[0]);
408 for (i=view->ndim-1; i>=0; i--) {
409 dim = view->shape[i];
410 if (dim == 0) return 1;
411 if (view->strides[i] != sd) return 0;
412 sd *= dim;
414 return 1;
418 PyBuffer_IsContiguous(Py_buffer *view, char fort)
421 if (view->suboffsets != NULL) return 0;
423 if (fort == 'C')
424 return _IsCContiguous(view);
425 else if (fort == 'F')
426 return _IsFortranContiguous(view);
427 else if (fort == 'A')
428 return (_IsCContiguous(view) || _IsFortranContiguous(view));
429 return 0;
433 void*
434 PyBuffer_GetPointer(Py_buffer *view, Py_ssize_t *indices)
436 char* pointer;
437 int i;
438 pointer = (char *)view->buf;
439 for (i = 0; i < view->ndim; i++) {
440 pointer += view->strides[i]*indices[i];
441 if ((view->suboffsets != NULL) && (view->suboffsets[i] >= 0)) {
442 pointer = *((char**)pointer) + view->suboffsets[i];
445 return (void*)pointer;
449 static void
450 _add_one_to_index_F(int nd, Py_ssize_t *index, Py_ssize_t *shape)
452 int k;
454 for (k=0; k<nd; k++) {
455 if (index[k] < shape[k]-1) {
456 index[k]++;
457 break;
459 else {
460 index[k] = 0;
465 static void
466 _add_one_to_index_C(int nd, Py_ssize_t *index, Py_ssize_t *shape)
468 int k;
470 for (k=nd-1; k>=0; k--) {
471 if (index[k] < shape[k]-1) {
472 index[k]++;
473 break;
475 else {
476 index[k] = 0;
481 /* view is not checked for consistency in either of these. It is
482 assumed that the size of the buffer is view->len in
483 view->len / view->itemsize elements.
487 PyBuffer_ToContiguous(void *buf, Py_buffer *view, Py_ssize_t len, char fort)
489 int k;
490 void (*addone)(int, Py_ssize_t *, Py_ssize_t *);
491 Py_ssize_t *indices, elements;
492 char *dest, *ptr;
494 if (len > view->len) {
495 len = view->len;
498 if (PyBuffer_IsContiguous(view, fort)) {
499 /* simplest copy is all that is needed */
500 memcpy(buf, view->buf, len);
501 return 0;
504 /* Otherwise a more elaborate scheme is needed */
506 /* XXX(nnorwitz): need to check for overflow! */
507 indices = (Py_ssize_t *)PyMem_Malloc(sizeof(Py_ssize_t)*(view->ndim));
508 if (indices == NULL) {
509 PyErr_NoMemory();
510 return -1;
512 for (k=0; k<view->ndim;k++) {
513 indices[k] = 0;
516 if (fort == 'F') {
517 addone = _add_one_to_index_F;
519 else {
520 addone = _add_one_to_index_C;
522 dest = buf;
523 /* XXX : This is not going to be the fastest code in the world
524 several optimizations are possible.
526 elements = len / view->itemsize;
527 while (elements--) {
528 addone(view->ndim, indices, view->shape);
529 ptr = PyBuffer_GetPointer(view, indices);
530 memcpy(dest, ptr, view->itemsize);
531 dest += view->itemsize;
533 PyMem_Free(indices);
534 return 0;
538 PyBuffer_FromContiguous(Py_buffer *view, void *buf, Py_ssize_t len, char fort)
540 int k;
541 void (*addone)(int, Py_ssize_t *, Py_ssize_t *);
542 Py_ssize_t *indices, elements;
543 char *src, *ptr;
545 if (len > view->len) {
546 len = view->len;
549 if (PyBuffer_IsContiguous(view, fort)) {
550 /* simplest copy is all that is needed */
551 memcpy(view->buf, buf, len);
552 return 0;
555 /* Otherwise a more elaborate scheme is needed */
557 /* XXX(nnorwitz): need to check for overflow! */
558 indices = (Py_ssize_t *)PyMem_Malloc(sizeof(Py_ssize_t)*(view->ndim));
559 if (indices == NULL) {
560 PyErr_NoMemory();
561 return -1;
563 for (k=0; k<view->ndim;k++) {
564 indices[k] = 0;
567 if (fort == 'F') {
568 addone = _add_one_to_index_F;
570 else {
571 addone = _add_one_to_index_C;
573 src = buf;
574 /* XXX : This is not going to be the fastest code in the world
575 several optimizations are possible.
577 elements = len / view->itemsize;
578 while (elements--) {
579 addone(view->ndim, indices, view->shape);
580 ptr = PyBuffer_GetPointer(view, indices);
581 memcpy(ptr, src, view->itemsize);
582 src += view->itemsize;
585 PyMem_Free(indices);
586 return 0;
589 int PyObject_CopyData(PyObject *dest, PyObject *src)
591 Py_buffer view_dest, view_src;
592 int k;
593 Py_ssize_t *indices, elements;
594 char *dptr, *sptr;
596 if (!PyObject_CheckBuffer(dest) ||
597 !PyObject_CheckBuffer(src)) {
598 PyErr_SetString(PyExc_TypeError,
599 "both destination and source must have the "\
600 "buffer interface");
601 return -1;
604 if (PyObject_GetBuffer(dest, &view_dest, PyBUF_FULL) != 0) return -1;
605 if (PyObject_GetBuffer(src, &view_src, PyBUF_FULL_RO) != 0) {
606 PyObject_ReleaseBuffer(dest, &view_dest);
607 return -1;
610 if (view_dest.len < view_src.len) {
611 PyErr_SetString(PyExc_BufferError,
612 "destination is too small to receive data from source");
613 PyObject_ReleaseBuffer(dest, &view_dest);
614 PyObject_ReleaseBuffer(src, &view_src);
615 return -1;
618 if ((PyBuffer_IsContiguous(&view_dest, 'C') &&
619 PyBuffer_IsContiguous(&view_src, 'C')) ||
620 (PyBuffer_IsContiguous(&view_dest, 'F') &&
621 PyBuffer_IsContiguous(&view_src, 'F'))) {
622 /* simplest copy is all that is needed */
623 memcpy(view_dest.buf, view_src.buf, view_src.len);
624 PyObject_ReleaseBuffer(dest, &view_dest);
625 PyObject_ReleaseBuffer(src, &view_src);
626 return 0;
629 /* Otherwise a more elaborate copy scheme is needed */
631 /* XXX(nnorwitz): need to check for overflow! */
632 indices = (Py_ssize_t *)PyMem_Malloc(sizeof(Py_ssize_t)*view_src.ndim);
633 if (indices == NULL) {
634 PyErr_NoMemory();
635 PyObject_ReleaseBuffer(dest, &view_dest);
636 PyObject_ReleaseBuffer(src, &view_src);
637 return -1;
639 for (k=0; k<view_src.ndim;k++) {
640 indices[k] = 0;
642 elements = 1;
643 for (k=0; k<view_src.ndim; k++) {
644 /* XXX(nnorwitz): can this overflow? */
645 elements *= view_src.shape[k];
647 while (elements--) {
648 _add_one_to_index_C(view_src.ndim, indices, view_src.shape);
649 dptr = PyBuffer_GetPointer(&view_dest, indices);
650 sptr = PyBuffer_GetPointer(&view_src, indices);
651 memcpy(dptr, sptr, view_src.itemsize);
653 PyMem_Free(indices);
654 PyObject_ReleaseBuffer(dest, &view_dest);
655 PyObject_ReleaseBuffer(src, &view_src);
656 return 0;
659 void
660 PyBuffer_FillContiguousStrides(int nd, Py_ssize_t *shape,
661 Py_ssize_t *strides, int itemsize,
662 char fort)
664 int k;
665 Py_ssize_t sd;
667 sd = itemsize;
668 if (fort == 'F') {
669 for (k=0; k<nd; k++) {
670 strides[k] = sd;
671 sd *= shape[k];
674 else {
675 for (k=nd-1; k>=0; k--) {
676 strides[k] = sd;
677 sd *= shape[k];
680 return;
684 PyBuffer_FillInfo(Py_buffer *view, void *buf, Py_ssize_t len,
685 int readonly, int flags)
687 if (view == NULL) return 0;
688 if (((flags & PyBUF_LOCK) == PyBUF_LOCK) &&
689 readonly != 0) {
690 PyErr_SetString(PyExc_BufferError,
691 "Cannot lock this object.");
692 return -1;
694 if (((flags & PyBUF_WRITABLE) == PyBUF_WRITABLE) &&
695 (readonly == 1)) {
696 PyErr_SetString(PyExc_BufferError,
697 "Object is not writable.");
698 return -1;
701 view->buf = buf;
702 view->len = len;
703 view->readonly = readonly;
704 view->itemsize = 1;
705 view->format = NULL;
706 if ((flags & PyBUF_FORMAT) == PyBUF_FORMAT)
707 view->format = "B";
708 view->ndim = 1;
709 view->shape = NULL;
710 if ((flags & PyBUF_ND) == PyBUF_ND)
711 view->shape = &(view->len);
712 view->strides = NULL;
713 if ((flags & PyBUF_STRIDES) == PyBUF_STRIDES)
714 view->strides = &(view->itemsize);
715 view->suboffsets = NULL;
716 view->internal = NULL;
717 return 0;
720 PyObject *
721 PyObject_Format(PyObject* obj, PyObject *format_spec)
723 static PyObject * str__format__ = NULL;
724 PyObject *empty = NULL;
725 PyObject *result = NULL;
726 int spec_is_unicode;
727 int result_is_unicode;
729 /* Initialize cached value */
730 if (str__format__ == NULL) {
731 /* Initialize static variable needed by _PyType_Lookup */
732 str__format__ = PyString_InternFromString("__format__");
733 if (str__format__ == NULL)
734 goto done;
737 /* If no format_spec is provided, use an empty string */
738 if (format_spec == NULL) {
739 empty = PyString_FromStringAndSize(NULL, 0);
740 format_spec = empty;
743 /* Check the format_spec type, and make sure it's str or unicode */
744 if (PyUnicode_Check(format_spec))
745 spec_is_unicode = 1;
746 else if (PyString_Check(format_spec))
747 spec_is_unicode = 0;
748 else {
749 PyErr_Format(PyExc_TypeError,
750 "format expects arg 2 to be string "
751 "or unicode, not %.100s", Py_TYPE(format_spec)->tp_name);
752 goto done;
755 /* Make sure the type is initialized. float gets initialized late */
756 if (Py_TYPE(obj)->tp_dict == NULL)
757 if (PyType_Ready(Py_TYPE(obj)) < 0)
758 goto done;
760 /* Check for a __format__ method and call it. */
761 if (PyInstance_Check(obj)) {
762 /* We're an instance of a classic class */
763 PyObject *bound_method = PyObject_GetAttr(obj,
764 str__format__);
765 if (bound_method != NULL) {
766 result = PyObject_CallFunctionObjArgs(bound_method,
767 format_spec,
768 NULL);
769 Py_DECREF(bound_method);
770 } else {
771 PyObject *self_as_str;
772 PyObject *format_method;
774 PyErr_Clear();
775 /* Per the PEP, convert to str (or unicode,
776 depending on the type of the format
777 specifier). For new-style classes, this
778 logic is done by object.__format__(). */
779 if (spec_is_unicode)
780 self_as_str = PyObject_Unicode(obj);
781 else
782 self_as_str = PyObject_Str(obj);
783 if (self_as_str == NULL)
784 goto done;
786 /* Then call str.__format__ on that result */
787 format_method = PyObject_GetAttr(self_as_str,
788 str__format__);
789 if (format_method == NULL) {
790 Py_DECREF(self_as_str);
791 goto done;
793 result = PyObject_CallFunctionObjArgs(format_method,
794 format_spec,
795 NULL);
796 Py_DECREF(self_as_str);
797 Py_DECREF(format_method);
798 if (result == NULL)
799 goto done;
801 } else {
802 /* Not an instance of a classic class, use the code
803 from py3k */
805 /* Find the (unbound!) __format__ method (a borrowed
806 reference) */
807 PyObject *method = _PyType_Lookup(Py_TYPE(obj),
808 str__format__);
809 if (method == NULL) {
810 PyErr_Format(PyExc_TypeError,
811 "Type %.100s doesn't define __format__",
812 Py_TYPE(obj)->tp_name);
813 goto done;
815 /* And call it, binding it to the value */
816 result = PyObject_CallFunctionObjArgs(method, obj,
817 format_spec, NULL);
820 if (result == NULL)
821 goto done;
823 /* Check the result type, and make sure it's str or unicode */
824 if (PyUnicode_Check(result))
825 result_is_unicode = 1;
826 else if (PyString_Check(result))
827 result_is_unicode = 0;
828 else {
829 PyErr_Format(PyExc_TypeError,
830 "%.100s.__format__ must return string or "
831 "unicode, not %.100s", Py_TYPE(obj)->tp_name,
832 Py_TYPE(result)->tp_name);
833 Py_DECREF(result);
834 result = NULL;
835 goto done;
838 /* Convert to unicode, if needed. Required if spec is unicode
839 and result is str */
840 if (spec_is_unicode && !result_is_unicode) {
841 PyObject *tmp = PyObject_Unicode(result);
842 /* This logic works whether or not tmp is NULL */
843 Py_DECREF(result);
844 result = tmp;
847 done:
848 Py_XDECREF(empty);
849 return result;
852 /* Operations on numbers */
855 PyNumber_Check(PyObject *o)
857 return o && o->ob_type->tp_as_number &&
858 (o->ob_type->tp_as_number->nb_int ||
859 o->ob_type->tp_as_number->nb_float);
862 /* Binary operators */
864 /* New style number protocol support */
866 #define NB_SLOT(x) offsetof(PyNumberMethods, x)
867 #define NB_BINOP(nb_methods, slot) \
868 (*(binaryfunc*)(& ((char*)nb_methods)[slot]))
869 #define NB_TERNOP(nb_methods, slot) \
870 (*(ternaryfunc*)(& ((char*)nb_methods)[slot]))
873 Calling scheme used for binary operations:
875 v w Action
876 -------------------------------------------------------------------
877 new new w.op(v,w)[*], v.op(v,w), w.op(v,w)
878 new old v.op(v,w), coerce(v,w), v.op(v,w)
879 old new w.op(v,w), coerce(v,w), v.op(v,w)
880 old old coerce(v,w), v.op(v,w)
882 [*] only when v->ob_type != w->ob_type && w->ob_type is a subclass of
883 v->ob_type
885 Legend:
886 -------
887 * new == new style number
888 * old == old style number
889 * Action indicates the order in which operations are tried until either
890 a valid result is produced or an error occurs.
894 static PyObject *
895 binary_op1(PyObject *v, PyObject *w, const int op_slot)
897 PyObject *x;
898 binaryfunc slotv = NULL;
899 binaryfunc slotw = NULL;
901 if (v->ob_type->tp_as_number != NULL && NEW_STYLE_NUMBER(v))
902 slotv = NB_BINOP(v->ob_type->tp_as_number, op_slot);
903 if (w->ob_type != v->ob_type &&
904 w->ob_type->tp_as_number != NULL && NEW_STYLE_NUMBER(w)) {
905 slotw = NB_BINOP(w->ob_type->tp_as_number, op_slot);
906 if (slotw == slotv)
907 slotw = NULL;
909 if (slotv) {
910 if (slotw && PyType_IsSubtype(w->ob_type, v->ob_type)) {
911 x = slotw(v, w);
912 if (x != Py_NotImplemented)
913 return x;
914 Py_DECREF(x); /* can't do it */
915 slotw = NULL;
917 x = slotv(v, w);
918 if (x != Py_NotImplemented)
919 return x;
920 Py_DECREF(x); /* can't do it */
922 if (slotw) {
923 x = slotw(v, w);
924 if (x != Py_NotImplemented)
925 return x;
926 Py_DECREF(x); /* can't do it */
928 if (!NEW_STYLE_NUMBER(v) || !NEW_STYLE_NUMBER(w)) {
929 int err = PyNumber_CoerceEx(&v, &w);
930 if (err < 0) {
931 return NULL;
933 if (err == 0) {
934 PyNumberMethods *mv = v->ob_type->tp_as_number;
935 if (mv) {
936 binaryfunc slot;
937 slot = NB_BINOP(mv, op_slot);
938 if (slot) {
939 x = slot(v, w);
940 Py_DECREF(v);
941 Py_DECREF(w);
942 return x;
945 /* CoerceEx incremented the reference counts */
946 Py_DECREF(v);
947 Py_DECREF(w);
950 Py_INCREF(Py_NotImplemented);
951 return Py_NotImplemented;
954 static PyObject *
955 binop_type_error(PyObject *v, PyObject *w, const char *op_name)
957 PyErr_Format(PyExc_TypeError,
958 "unsupported operand type(s) for %.100s: "
959 "'%.100s' and '%.100s'",
960 op_name,
961 v->ob_type->tp_name,
962 w->ob_type->tp_name);
963 return NULL;
966 static PyObject *
967 binary_op(PyObject *v, PyObject *w, const int op_slot, const char *op_name)
969 PyObject *result = binary_op1(v, w, op_slot);
970 if (result == Py_NotImplemented) {
971 Py_DECREF(result);
972 return binop_type_error(v, w, op_name);
974 return result;
979 Calling scheme used for ternary operations:
981 *** In some cases, w.op is called before v.op; see binary_op1. ***
983 v w z Action
984 -------------------------------------------------------------------
985 new new new v.op(v,w,z), w.op(v,w,z), z.op(v,w,z)
986 new old new v.op(v,w,z), z.op(v,w,z), coerce(v,w,z), v.op(v,w,z)
987 old new new w.op(v,w,z), z.op(v,w,z), coerce(v,w,z), v.op(v,w,z)
988 old old new z.op(v,w,z), coerce(v,w,z), v.op(v,w,z)
989 new new old v.op(v,w,z), w.op(v,w,z), coerce(v,w,z), v.op(v,w,z)
990 new old old v.op(v,w,z), coerce(v,w,z), v.op(v,w,z)
991 old new old w.op(v,w,z), coerce(v,w,z), v.op(v,w,z)
992 old old old coerce(v,w,z), v.op(v,w,z)
994 Legend:
995 -------
996 * new == new style number
997 * old == old style number
998 * Action indicates the order in which operations are tried until either
999 a valid result is produced or an error occurs.
1000 * coerce(v,w,z) actually does: coerce(v,w), coerce(v,z), coerce(w,z) and
1001 only if z != Py_None; if z == Py_None, then it is treated as absent
1002 variable and only coerce(v,w) is tried.
1006 static PyObject *
1007 ternary_op(PyObject *v,
1008 PyObject *w,
1009 PyObject *z,
1010 const int op_slot,
1011 const char *op_name)
1013 PyNumberMethods *mv, *mw, *mz;
1014 PyObject *x = NULL;
1015 ternaryfunc slotv = NULL;
1016 ternaryfunc slotw = NULL;
1017 ternaryfunc slotz = NULL;
1019 mv = v->ob_type->tp_as_number;
1020 mw = w->ob_type->tp_as_number;
1021 if (mv != NULL && NEW_STYLE_NUMBER(v))
1022 slotv = NB_TERNOP(mv, op_slot);
1023 if (w->ob_type != v->ob_type &&
1024 mw != NULL && NEW_STYLE_NUMBER(w)) {
1025 slotw = NB_TERNOP(mw, op_slot);
1026 if (slotw == slotv)
1027 slotw = NULL;
1029 if (slotv) {
1030 if (slotw && PyType_IsSubtype(w->ob_type, v->ob_type)) {
1031 x = slotw(v, w, z);
1032 if (x != Py_NotImplemented)
1033 return x;
1034 Py_DECREF(x); /* can't do it */
1035 slotw = NULL;
1037 x = slotv(v, w, z);
1038 if (x != Py_NotImplemented)
1039 return x;
1040 Py_DECREF(x); /* can't do it */
1042 if (slotw) {
1043 x = slotw(v, w, z);
1044 if (x != Py_NotImplemented)
1045 return x;
1046 Py_DECREF(x); /* can't do it */
1048 mz = z->ob_type->tp_as_number;
1049 if (mz != NULL && NEW_STYLE_NUMBER(z)) {
1050 slotz = NB_TERNOP(mz, op_slot);
1051 if (slotz == slotv || slotz == slotw)
1052 slotz = NULL;
1053 if (slotz) {
1054 x = slotz(v, w, z);
1055 if (x != Py_NotImplemented)
1056 return x;
1057 Py_DECREF(x); /* can't do it */
1061 if (!NEW_STYLE_NUMBER(v) || !NEW_STYLE_NUMBER(w) ||
1062 (z != Py_None && !NEW_STYLE_NUMBER(z))) {
1063 /* we have an old style operand, coerce */
1064 PyObject *v1, *z1, *w2, *z2;
1065 int c;
1067 c = PyNumber_Coerce(&v, &w);
1068 if (c != 0)
1069 goto error3;
1071 /* Special case: if the third argument is None, it is
1072 treated as absent argument and not coerced. */
1073 if (z == Py_None) {
1074 if (v->ob_type->tp_as_number) {
1075 slotz = NB_TERNOP(v->ob_type->tp_as_number,
1076 op_slot);
1077 if (slotz)
1078 x = slotz(v, w, z);
1079 else
1080 c = -1;
1082 else
1083 c = -1;
1084 goto error2;
1086 v1 = v;
1087 z1 = z;
1088 c = PyNumber_Coerce(&v1, &z1);
1089 if (c != 0)
1090 goto error2;
1091 w2 = w;
1092 z2 = z1;
1093 c = PyNumber_Coerce(&w2, &z2);
1094 if (c != 0)
1095 goto error1;
1097 if (v1->ob_type->tp_as_number != NULL) {
1098 slotv = NB_TERNOP(v1->ob_type->tp_as_number,
1099 op_slot);
1100 if (slotv)
1101 x = slotv(v1, w2, z2);
1102 else
1103 c = -1;
1105 else
1106 c = -1;
1108 Py_DECREF(w2);
1109 Py_DECREF(z2);
1110 error1:
1111 Py_DECREF(v1);
1112 Py_DECREF(z1);
1113 error2:
1114 Py_DECREF(v);
1115 Py_DECREF(w);
1116 error3:
1117 if (c >= 0)
1118 return x;
1121 if (z == Py_None)
1122 PyErr_Format(
1123 PyExc_TypeError,
1124 "unsupported operand type(s) for ** or pow(): "
1125 "'%.100s' and '%.100s'",
1126 v->ob_type->tp_name,
1127 w->ob_type->tp_name);
1128 else
1129 PyErr_Format(
1130 PyExc_TypeError,
1131 "unsupported operand type(s) for pow(): "
1132 "'%.100s', '%.100s', '%.100s'",
1133 v->ob_type->tp_name,
1134 w->ob_type->tp_name,
1135 z->ob_type->tp_name);
1136 return NULL;
1139 #define BINARY_FUNC(func, op, op_name) \
1140 PyObject * \
1141 func(PyObject *v, PyObject *w) { \
1142 return binary_op(v, w, NB_SLOT(op), op_name); \
1145 BINARY_FUNC(PyNumber_Or, nb_or, "|")
1146 BINARY_FUNC(PyNumber_Xor, nb_xor, "^")
1147 BINARY_FUNC(PyNumber_And, nb_and, "&")
1148 BINARY_FUNC(PyNumber_Lshift, nb_lshift, "<<")
1149 BINARY_FUNC(PyNumber_Rshift, nb_rshift, ">>")
1150 BINARY_FUNC(PyNumber_Subtract, nb_subtract, "-")
1151 BINARY_FUNC(PyNumber_Divide, nb_divide, "/")
1152 BINARY_FUNC(PyNumber_Divmod, nb_divmod, "divmod()")
1154 PyObject *
1155 PyNumber_Add(PyObject *v, PyObject *w)
1157 PyObject *result = binary_op1(v, w, NB_SLOT(nb_add));
1158 if (result == Py_NotImplemented) {
1159 PySequenceMethods *m = v->ob_type->tp_as_sequence;
1160 Py_DECREF(result);
1161 if (m && m->sq_concat) {
1162 return (*m->sq_concat)(v, w);
1164 result = binop_type_error(v, w, "+");
1166 return result;
1169 static PyObject *
1170 sequence_repeat(ssizeargfunc repeatfunc, PyObject *seq, PyObject *n)
1172 Py_ssize_t count;
1173 if (PyIndex_Check(n)) {
1174 count = PyNumber_AsSsize_t(n, PyExc_OverflowError);
1175 if (count == -1 && PyErr_Occurred())
1176 return NULL;
1178 else {
1179 return type_error("can't multiply sequence by "
1180 "non-int of type '%.200s'", n);
1182 return (*repeatfunc)(seq, count);
1185 PyObject *
1186 PyNumber_Multiply(PyObject *v, PyObject *w)
1188 PyObject *result = binary_op1(v, w, NB_SLOT(nb_multiply));
1189 if (result == Py_NotImplemented) {
1190 PySequenceMethods *mv = v->ob_type->tp_as_sequence;
1191 PySequenceMethods *mw = w->ob_type->tp_as_sequence;
1192 Py_DECREF(result);
1193 if (mv && mv->sq_repeat) {
1194 return sequence_repeat(mv->sq_repeat, v, w);
1196 else if (mw && mw->sq_repeat) {
1197 return sequence_repeat(mw->sq_repeat, w, v);
1199 result = binop_type_error(v, w, "*");
1201 return result;
1204 PyObject *
1205 PyNumber_FloorDivide(PyObject *v, PyObject *w)
1207 /* XXX tp_flags test */
1208 return binary_op(v, w, NB_SLOT(nb_floor_divide), "//");
1211 PyObject *
1212 PyNumber_TrueDivide(PyObject *v, PyObject *w)
1214 /* XXX tp_flags test */
1215 return binary_op(v, w, NB_SLOT(nb_true_divide), "/");
1218 PyObject *
1219 PyNumber_Remainder(PyObject *v, PyObject *w)
1221 return binary_op(v, w, NB_SLOT(nb_remainder), "%");
1224 PyObject *
1225 PyNumber_Power(PyObject *v, PyObject *w, PyObject *z)
1227 return ternary_op(v, w, z, NB_SLOT(nb_power), "** or pow()");
1230 /* Binary in-place operators */
1232 /* The in-place operators are defined to fall back to the 'normal',
1233 non in-place operations, if the in-place methods are not in place.
1235 - If the left hand object has the appropriate struct members, and
1236 they are filled, call the appropriate function and return the
1237 result. No coercion is done on the arguments; the left-hand object
1238 is the one the operation is performed on, and it's up to the
1239 function to deal with the right-hand object.
1241 - Otherwise, in-place modification is not supported. Handle it exactly as
1242 a non in-place operation of the same kind.
1246 #define HASINPLACE(t) \
1247 PyType_HasFeature((t)->ob_type, Py_TPFLAGS_HAVE_INPLACEOPS)
1249 static PyObject *
1250 binary_iop1(PyObject *v, PyObject *w, const int iop_slot, const int op_slot)
1252 PyNumberMethods *mv = v->ob_type->tp_as_number;
1253 if (mv != NULL && HASINPLACE(v)) {
1254 binaryfunc slot = NB_BINOP(mv, iop_slot);
1255 if (slot) {
1256 PyObject *x = (slot)(v, w);
1257 if (x != Py_NotImplemented) {
1258 return x;
1260 Py_DECREF(x);
1263 return binary_op1(v, w, op_slot);
1266 static PyObject *
1267 binary_iop(PyObject *v, PyObject *w, const int iop_slot, const int op_slot,
1268 const char *op_name)
1270 PyObject *result = binary_iop1(v, w, iop_slot, op_slot);
1271 if (result == Py_NotImplemented) {
1272 Py_DECREF(result);
1273 return binop_type_error(v, w, op_name);
1275 return result;
1278 #define INPLACE_BINOP(func, iop, op, op_name) \
1279 PyObject * \
1280 func(PyObject *v, PyObject *w) { \
1281 return binary_iop(v, w, NB_SLOT(iop), NB_SLOT(op), op_name); \
1284 INPLACE_BINOP(PyNumber_InPlaceOr, nb_inplace_or, nb_or, "|=")
1285 INPLACE_BINOP(PyNumber_InPlaceXor, nb_inplace_xor, nb_xor, "^=")
1286 INPLACE_BINOP(PyNumber_InPlaceAnd, nb_inplace_and, nb_and, "&=")
1287 INPLACE_BINOP(PyNumber_InPlaceLshift, nb_inplace_lshift, nb_lshift, "<<=")
1288 INPLACE_BINOP(PyNumber_InPlaceRshift, nb_inplace_rshift, nb_rshift, ">>=")
1289 INPLACE_BINOP(PyNumber_InPlaceSubtract, nb_inplace_subtract, nb_subtract, "-=")
1290 INPLACE_BINOP(PyNumber_InPlaceDivide, nb_inplace_divide, nb_divide, "/=")
1292 PyObject *
1293 PyNumber_InPlaceFloorDivide(PyObject *v, PyObject *w)
1295 /* XXX tp_flags test */
1296 return binary_iop(v, w, NB_SLOT(nb_inplace_floor_divide),
1297 NB_SLOT(nb_floor_divide), "//=");
1300 PyObject *
1301 PyNumber_InPlaceTrueDivide(PyObject *v, PyObject *w)
1303 /* XXX tp_flags test */
1304 return binary_iop(v, w, NB_SLOT(nb_inplace_true_divide),
1305 NB_SLOT(nb_true_divide), "/=");
1308 PyObject *
1309 PyNumber_InPlaceAdd(PyObject *v, PyObject *w)
1311 PyObject *result = binary_iop1(v, w, NB_SLOT(nb_inplace_add),
1312 NB_SLOT(nb_add));
1313 if (result == Py_NotImplemented) {
1314 PySequenceMethods *m = v->ob_type->tp_as_sequence;
1315 Py_DECREF(result);
1316 if (m != NULL) {
1317 binaryfunc f = NULL;
1318 if (HASINPLACE(v))
1319 f = m->sq_inplace_concat;
1320 if (f == NULL)
1321 f = m->sq_concat;
1322 if (f != NULL)
1323 return (*f)(v, w);
1325 result = binop_type_error(v, w, "+=");
1327 return result;
1330 PyObject *
1331 PyNumber_InPlaceMultiply(PyObject *v, PyObject *w)
1333 PyObject *result = binary_iop1(v, w, NB_SLOT(nb_inplace_multiply),
1334 NB_SLOT(nb_multiply));
1335 if (result == Py_NotImplemented) {
1336 ssizeargfunc f = NULL;
1337 PySequenceMethods *mv = v->ob_type->tp_as_sequence;
1338 PySequenceMethods *mw = w->ob_type->tp_as_sequence;
1339 Py_DECREF(result);
1340 if (mv != NULL) {
1341 if (HASINPLACE(v))
1342 f = mv->sq_inplace_repeat;
1343 if (f == NULL)
1344 f = mv->sq_repeat;
1345 if (f != NULL)
1346 return sequence_repeat(f, v, w);
1348 else if (mw != NULL) {
1349 /* Note that the right hand operand should not be
1350 * mutated in this case so sq_inplace_repeat is not
1351 * used. */
1352 if (mw->sq_repeat)
1353 return sequence_repeat(mw->sq_repeat, w, v);
1355 result = binop_type_error(v, w, "*=");
1357 return result;
1360 PyObject *
1361 PyNumber_InPlaceRemainder(PyObject *v, PyObject *w)
1363 return binary_iop(v, w, NB_SLOT(nb_inplace_remainder),
1364 NB_SLOT(nb_remainder), "%=");
1367 PyObject *
1368 PyNumber_InPlacePower(PyObject *v, PyObject *w, PyObject *z)
1370 if (HASINPLACE(v) && v->ob_type->tp_as_number &&
1371 v->ob_type->tp_as_number->nb_inplace_power != NULL) {
1372 return ternary_op(v, w, z, NB_SLOT(nb_inplace_power), "**=");
1374 else {
1375 return ternary_op(v, w, z, NB_SLOT(nb_power), "**=");
1380 /* Unary operators and functions */
1382 PyObject *
1383 PyNumber_Negative(PyObject *o)
1385 PyNumberMethods *m;
1387 if (o == NULL)
1388 return null_error();
1389 m = o->ob_type->tp_as_number;
1390 if (m && m->nb_negative)
1391 return (*m->nb_negative)(o);
1393 return type_error("bad operand type for unary -: '%.200s'", o);
1396 PyObject *
1397 PyNumber_Positive(PyObject *o)
1399 PyNumberMethods *m;
1401 if (o == NULL)
1402 return null_error();
1403 m = o->ob_type->tp_as_number;
1404 if (m && m->nb_positive)
1405 return (*m->nb_positive)(o);
1407 return type_error("bad operand type for unary +: '%.200s'", o);
1410 PyObject *
1411 PyNumber_Invert(PyObject *o)
1413 PyNumberMethods *m;
1415 if (o == NULL)
1416 return null_error();
1417 m = o->ob_type->tp_as_number;
1418 if (m && m->nb_invert)
1419 return (*m->nb_invert)(o);
1421 return type_error("bad operand type for unary ~: '%.200s'", o);
1424 PyObject *
1425 PyNumber_Absolute(PyObject *o)
1427 PyNumberMethods *m;
1429 if (o == NULL)
1430 return null_error();
1431 m = o->ob_type->tp_as_number;
1432 if (m && m->nb_absolute)
1433 return m->nb_absolute(o);
1435 return type_error("bad operand type for abs(): '%.200s'", o);
1438 /* Add a check for embedded NULL-bytes in the argument. */
1439 static PyObject *
1440 int_from_string(const char *s, Py_ssize_t len)
1442 char *end;
1443 PyObject *x;
1445 x = PyInt_FromString((char*)s, &end, 10);
1446 if (x == NULL)
1447 return NULL;
1448 if (end != s + len) {
1449 PyErr_SetString(PyExc_ValueError,
1450 "null byte in argument for int()");
1451 Py_DECREF(x);
1452 return NULL;
1454 return x;
1457 /* Return a Python Int or Long from the object item
1458 Raise TypeError if the result is not an int-or-long
1459 or if the object cannot be interpreted as an index.
1461 PyObject *
1462 PyNumber_Index(PyObject *item)
1464 PyObject *result = NULL;
1465 if (item == NULL)
1466 return null_error();
1467 if (PyInt_Check(item) || PyLong_Check(item)) {
1468 Py_INCREF(item);
1469 return item;
1471 if (PyIndex_Check(item)) {
1472 result = item->ob_type->tp_as_number->nb_index(item);
1473 if (result &&
1474 !PyInt_Check(result) && !PyLong_Check(result)) {
1475 PyErr_Format(PyExc_TypeError,
1476 "__index__ returned non-(int,long) " \
1477 "(type %.200s)",
1478 result->ob_type->tp_name);
1479 Py_DECREF(result);
1480 return NULL;
1483 else {
1484 PyErr_Format(PyExc_TypeError,
1485 "'%.200s' object cannot be interpreted "
1486 "as an index", item->ob_type->tp_name);
1488 return result;
1491 /* Return an error on Overflow only if err is not NULL*/
1493 Py_ssize_t
1494 PyNumber_AsSsize_t(PyObject *item, PyObject *err)
1496 Py_ssize_t result;
1497 PyObject *runerr;
1498 PyObject *value = PyNumber_Index(item);
1499 if (value == NULL)
1500 return -1;
1502 /* We're done if PyInt_AsSsize_t() returns without error. */
1503 result = PyInt_AsSsize_t(value);
1504 if (result != -1 || !(runerr = PyErr_Occurred()))
1505 goto finish;
1507 /* Error handling code -- only manage OverflowError differently */
1508 if (!PyErr_GivenExceptionMatches(runerr, PyExc_OverflowError))
1509 goto finish;
1511 PyErr_Clear();
1512 /* If no error-handling desired then the default clipping
1513 is sufficient.
1515 if (!err) {
1516 assert(PyLong_Check(value));
1517 /* Whether or not it is less than or equal to
1518 zero is determined by the sign of ob_size
1520 if (_PyLong_Sign(value) < 0)
1521 result = PY_SSIZE_T_MIN;
1522 else
1523 result = PY_SSIZE_T_MAX;
1525 else {
1526 /* Otherwise replace the error with caller's error object. */
1527 PyErr_Format(err,
1528 "cannot fit '%.200s' into an index-sized integer",
1529 item->ob_type->tp_name);
1532 finish:
1533 Py_DECREF(value);
1534 return result;
1538 PyObject *
1539 _PyNumber_ConvertIntegralToInt(PyObject *integral, const char* error_format)
1541 const char *type_name;
1542 static PyObject *int_name = NULL;
1543 if (int_name == NULL) {
1544 int_name = PyString_InternFromString("__int__");
1545 if (int_name == NULL)
1546 return NULL;
1549 if (integral && (!PyInt_Check(integral) &&
1550 !PyLong_Check(integral))) {
1551 /* Don't go through tp_as_number->nb_int to avoid
1552 hitting the classic class fallback to __trunc__. */
1553 PyObject *int_func = PyObject_GetAttr(integral, int_name);
1554 if (int_func == NULL) {
1555 PyErr_Clear(); /* Raise a different error. */
1556 goto non_integral_error;
1558 Py_DECREF(integral);
1559 integral = PyEval_CallObject(int_func, NULL);
1560 Py_DECREF(int_func);
1561 if (integral && (!PyInt_Check(integral) &&
1562 !PyLong_Check(integral))) {
1563 goto non_integral_error;
1566 return integral;
1568 non_integral_error:
1569 if (PyInstance_Check(integral)) {
1570 type_name = PyString_AS_STRING(((PyInstanceObject *)integral)
1571 ->in_class->cl_name);
1573 else {
1574 type_name = integral->ob_type->tp_name;
1576 PyErr_Format(PyExc_TypeError, error_format, type_name);
1577 Py_DECREF(integral);
1578 return NULL;
1582 PyObject *
1583 PyNumber_Int(PyObject *o)
1585 PyNumberMethods *m;
1586 static PyObject *trunc_name = NULL;
1587 PyObject *trunc_func;
1588 const char *buffer;
1589 Py_ssize_t buffer_len;
1591 if (trunc_name == NULL) {
1592 trunc_name = PyString_InternFromString("__trunc__");
1593 if (trunc_name == NULL)
1594 return NULL;
1597 if (o == NULL)
1598 return null_error();
1599 if (PyInt_CheckExact(o)) {
1600 Py_INCREF(o);
1601 return o;
1603 m = o->ob_type->tp_as_number;
1604 if (m && m->nb_int) { /* This should include subclasses of int */
1605 /* Classic classes always take this branch. */
1606 PyObject *res = m->nb_int(o);
1607 if (res && (!PyInt_Check(res) && !PyLong_Check(res))) {
1608 PyErr_Format(PyExc_TypeError,
1609 "__int__ returned non-int (type %.200s)",
1610 res->ob_type->tp_name);
1611 Py_DECREF(res);
1612 return NULL;
1614 return res;
1616 if (PyInt_Check(o)) { /* A int subclass without nb_int */
1617 PyIntObject *io = (PyIntObject*)o;
1618 return PyInt_FromLong(io->ob_ival);
1620 trunc_func = PyObject_GetAttr(o, trunc_name);
1621 if (trunc_func) {
1622 PyObject *truncated = PyEval_CallObject(trunc_func, NULL);
1623 Py_DECREF(trunc_func);
1624 /* __trunc__ is specified to return an Integral type, but
1625 int() needs to return an int. */
1626 return _PyNumber_ConvertIntegralToInt(
1627 truncated,
1628 "__trunc__ returned non-Integral (type %.200s)");
1630 PyErr_Clear(); /* It's not an error if o.__trunc__ doesn't exist. */
1632 if (PyString_Check(o))
1633 return int_from_string(PyString_AS_STRING(o),
1634 PyString_GET_SIZE(o));
1635 #ifdef Py_USING_UNICODE
1636 if (PyUnicode_Check(o))
1637 return PyInt_FromUnicode(PyUnicode_AS_UNICODE(o),
1638 PyUnicode_GET_SIZE(o),
1639 10);
1640 #endif
1641 if (!PyObject_AsCharBuffer(o, &buffer, &buffer_len))
1642 return int_from_string((char*)buffer, buffer_len);
1644 return type_error("int() argument must be a string or a "
1645 "number, not '%.200s'", o);
1648 /* Add a check for embedded NULL-bytes in the argument. */
1649 static PyObject *
1650 long_from_string(const char *s, Py_ssize_t len)
1652 char *end;
1653 PyObject *x;
1655 x = PyLong_FromString((char*)s, &end, 10);
1656 if (x == NULL)
1657 return NULL;
1658 if (end != s + len) {
1659 PyErr_SetString(PyExc_ValueError,
1660 "null byte in argument for long()");
1661 Py_DECREF(x);
1662 return NULL;
1664 return x;
1667 PyObject *
1668 PyNumber_Long(PyObject *o)
1670 PyNumberMethods *m;
1671 static PyObject *trunc_name = NULL;
1672 PyObject *trunc_func;
1673 const char *buffer;
1674 Py_ssize_t buffer_len;
1676 if (trunc_name == NULL) {
1677 trunc_name = PyString_InternFromString("__trunc__");
1678 if (trunc_name == NULL)
1679 return NULL;
1682 if (o == NULL)
1683 return null_error();
1684 m = o->ob_type->tp_as_number;
1685 if (m && m->nb_long) { /* This should include subclasses of long */
1686 /* Classic classes always take this branch. */
1687 PyObject *res = m->nb_long(o);
1688 if (res && (!PyInt_Check(res) && !PyLong_Check(res))) {
1689 PyErr_Format(PyExc_TypeError,
1690 "__long__ returned non-long (type %.200s)",
1691 res->ob_type->tp_name);
1692 Py_DECREF(res);
1693 return NULL;
1695 return res;
1697 if (PyLong_Check(o)) /* A long subclass without nb_long */
1698 return _PyLong_Copy((PyLongObject *)o);
1699 trunc_func = PyObject_GetAttr(o, trunc_name);
1700 if (trunc_func) {
1701 PyObject *truncated = PyEval_CallObject(trunc_func, NULL);
1702 PyObject *int_instance;
1703 Py_DECREF(trunc_func);
1704 /* __trunc__ is specified to return an Integral type,
1705 but long() needs to return a long. */
1706 int_instance = _PyNumber_ConvertIntegralToInt(
1707 truncated,
1708 "__trunc__ returned non-Integral (type %.200s)");
1709 if (int_instance && PyInt_Check(int_instance)) {
1710 /* Make sure that long() returns a long instance. */
1711 long value = PyInt_AS_LONG(int_instance);
1712 Py_DECREF(int_instance);
1713 return PyLong_FromLong(value);
1715 return int_instance;
1717 PyErr_Clear(); /* It's not an error if o.__trunc__ doesn't exist. */
1719 if (PyString_Check(o))
1720 /* need to do extra error checking that PyLong_FromString()
1721 * doesn't do. In particular long('9.5') must raise an
1722 * exception, not truncate the float.
1724 return long_from_string(PyString_AS_STRING(o),
1725 PyString_GET_SIZE(o));
1726 #ifdef Py_USING_UNICODE
1727 if (PyUnicode_Check(o))
1728 /* The above check is done in PyLong_FromUnicode(). */
1729 return PyLong_FromUnicode(PyUnicode_AS_UNICODE(o),
1730 PyUnicode_GET_SIZE(o),
1731 10);
1732 #endif
1733 if (!PyObject_AsCharBuffer(o, &buffer, &buffer_len))
1734 return long_from_string(buffer, buffer_len);
1736 return type_error("long() argument must be a string or a "
1737 "number, not '%.200s'", o);
1740 PyObject *
1741 PyNumber_Float(PyObject *o)
1743 PyNumberMethods *m;
1745 if (o == NULL)
1746 return null_error();
1747 m = o->ob_type->tp_as_number;
1748 if (m && m->nb_float) { /* This should include subclasses of float */
1749 PyObject *res = m->nb_float(o);
1750 if (res && !PyFloat_Check(res)) {
1751 PyErr_Format(PyExc_TypeError,
1752 "__float__ returned non-float (type %.200s)",
1753 res->ob_type->tp_name);
1754 Py_DECREF(res);
1755 return NULL;
1757 return res;
1759 if (PyFloat_Check(o)) { /* A float subclass with nb_float == NULL */
1760 PyFloatObject *po = (PyFloatObject *)o;
1761 return PyFloat_FromDouble(po->ob_fval);
1763 return PyFloat_FromString(o, NULL);
1766 PyObject *
1767 PyNumber_ToBase(PyObject *n, int base)
1769 PyObject *res = NULL;
1770 PyObject *index = PyNumber_Index(n);
1772 if (!index)
1773 return NULL;
1774 if (PyLong_Check(index))
1775 res = _PyLong_Format(index, base, 0, 1);
1776 else if (PyInt_Check(index))
1777 res = _PyInt_Format((PyIntObject*)index, base, 1);
1778 else
1779 /* It should not be possible to get here, as
1780 PyNumber_Index already has a check for the same
1781 condition */
1782 PyErr_SetString(PyExc_ValueError, "PyNumber_ToBase: index not "
1783 "int or long");
1784 Py_DECREF(index);
1785 return res;
1789 /* Operations on sequences */
1792 PySequence_Check(PyObject *s)
1794 if (s && PyInstance_Check(s))
1795 return PyObject_HasAttrString(s, "__getitem__");
1796 if (PyObject_IsInstance(s, (PyObject *)&PyDict_Type))
1797 return 0;
1798 return s != NULL && s->ob_type->tp_as_sequence &&
1799 s->ob_type->tp_as_sequence->sq_item != NULL;
1802 Py_ssize_t
1803 PySequence_Size(PyObject *s)
1805 PySequenceMethods *m;
1807 if (s == NULL) {
1808 null_error();
1809 return -1;
1812 m = s->ob_type->tp_as_sequence;
1813 if (m && m->sq_length)
1814 return m->sq_length(s);
1816 type_error("object of type '%.200s' has no len()", s);
1817 return -1;
1820 #undef PySequence_Length
1821 Py_ssize_t
1822 PySequence_Length(PyObject *s)
1824 return PySequence_Size(s);
1826 #define PySequence_Length PySequence_Size
1828 PyObject *
1829 PySequence_Concat(PyObject *s, PyObject *o)
1831 PySequenceMethods *m;
1833 if (s == NULL || o == NULL)
1834 return null_error();
1836 m = s->ob_type->tp_as_sequence;
1837 if (m && m->sq_concat)
1838 return m->sq_concat(s, o);
1840 /* Instances of user classes defining an __add__() method only
1841 have an nb_add slot, not an sq_concat slot. So we fall back
1842 to nb_add if both arguments appear to be sequences. */
1843 if (PySequence_Check(s) && PySequence_Check(o)) {
1844 PyObject *result = binary_op1(s, o, NB_SLOT(nb_add));
1845 if (result != Py_NotImplemented)
1846 return result;
1847 Py_DECREF(result);
1849 return type_error("'%.200s' object can't be concatenated", s);
1852 PyObject *
1853 PySequence_Repeat(PyObject *o, Py_ssize_t count)
1855 PySequenceMethods *m;
1857 if (o == NULL)
1858 return null_error();
1860 m = o->ob_type->tp_as_sequence;
1861 if (m && m->sq_repeat)
1862 return m->sq_repeat(o, count);
1864 /* Instances of user classes defining a __mul__() method only
1865 have an nb_multiply slot, not an sq_repeat slot. so we fall back
1866 to nb_multiply if o appears to be a sequence. */
1867 if (PySequence_Check(o)) {
1868 PyObject *n, *result;
1869 n = PyInt_FromSsize_t(count);
1870 if (n == NULL)
1871 return NULL;
1872 result = binary_op1(o, n, NB_SLOT(nb_multiply));
1873 Py_DECREF(n);
1874 if (result != Py_NotImplemented)
1875 return result;
1876 Py_DECREF(result);
1878 return type_error("'%.200s' object can't be repeated", o);
1881 PyObject *
1882 PySequence_InPlaceConcat(PyObject *s, PyObject *o)
1884 PySequenceMethods *m;
1886 if (s == NULL || o == NULL)
1887 return null_error();
1889 m = s->ob_type->tp_as_sequence;
1890 if (m && HASINPLACE(s) && m->sq_inplace_concat)
1891 return m->sq_inplace_concat(s, o);
1892 if (m && m->sq_concat)
1893 return m->sq_concat(s, o);
1895 if (PySequence_Check(s) && PySequence_Check(o)) {
1896 PyObject *result = binary_iop1(s, o, NB_SLOT(nb_inplace_add),
1897 NB_SLOT(nb_add));
1898 if (result != Py_NotImplemented)
1899 return result;
1900 Py_DECREF(result);
1902 return type_error("'%.200s' object can't be concatenated", s);
1905 PyObject *
1906 PySequence_InPlaceRepeat(PyObject *o, Py_ssize_t count)
1908 PySequenceMethods *m;
1910 if (o == NULL)
1911 return null_error();
1913 m = o->ob_type->tp_as_sequence;
1914 if (m && HASINPLACE(o) && m->sq_inplace_repeat)
1915 return m->sq_inplace_repeat(o, count);
1916 if (m && m->sq_repeat)
1917 return m->sq_repeat(o, count);
1919 if (PySequence_Check(o)) {
1920 PyObject *n, *result;
1921 n = PyInt_FromSsize_t(count);
1922 if (n == NULL)
1923 return NULL;
1924 result = binary_iop1(o, n, NB_SLOT(nb_inplace_multiply),
1925 NB_SLOT(nb_multiply));
1926 Py_DECREF(n);
1927 if (result != Py_NotImplemented)
1928 return result;
1929 Py_DECREF(result);
1931 return type_error("'%.200s' object can't be repeated", o);
1934 PyObject *
1935 PySequence_GetItem(PyObject *s, Py_ssize_t i)
1937 PySequenceMethods *m;
1939 if (s == NULL)
1940 return null_error();
1942 m = s->ob_type->tp_as_sequence;
1943 if (m && m->sq_item) {
1944 if (i < 0) {
1945 if (m->sq_length) {
1946 Py_ssize_t l = (*m->sq_length)(s);
1947 if (l < 0)
1948 return NULL;
1949 i += l;
1952 return m->sq_item(s, i);
1955 return type_error("'%.200s' object is unindexable", s);
1958 PyObject *
1959 PySequence_GetSlice(PyObject *s, Py_ssize_t i1, Py_ssize_t i2)
1961 PySequenceMethods *m;
1962 PyMappingMethods *mp;
1964 if (!s) return null_error();
1966 m = s->ob_type->tp_as_sequence;
1967 if (m && m->sq_slice) {
1968 if (i1 < 0 || i2 < 0) {
1969 if (m->sq_length) {
1970 Py_ssize_t l = (*m->sq_length)(s);
1971 if (l < 0)
1972 return NULL;
1973 if (i1 < 0)
1974 i1 += l;
1975 if (i2 < 0)
1976 i2 += l;
1979 return m->sq_slice(s, i1, i2);
1980 } else if ((mp = s->ob_type->tp_as_mapping) && mp->mp_subscript) {
1981 PyObject *res;
1982 PyObject *slice = _PySlice_FromIndices(i1, i2);
1983 if (!slice)
1984 return NULL;
1985 res = mp->mp_subscript(s, slice);
1986 Py_DECREF(slice);
1987 return res;
1990 return type_error("'%.200s' object is unsliceable", s);
1994 PySequence_SetItem(PyObject *s, Py_ssize_t i, PyObject *o)
1996 PySequenceMethods *m;
1998 if (s == NULL) {
1999 null_error();
2000 return -1;
2003 m = s->ob_type->tp_as_sequence;
2004 if (m && m->sq_ass_item) {
2005 if (i < 0) {
2006 if (m->sq_length) {
2007 Py_ssize_t l = (*m->sq_length)(s);
2008 if (l < 0)
2009 return -1;
2010 i += l;
2013 return m->sq_ass_item(s, i, o);
2016 type_error("'%.200s' object does not support item assignment", s);
2017 return -1;
2021 PySequence_DelItem(PyObject *s, Py_ssize_t i)
2023 PySequenceMethods *m;
2025 if (s == NULL) {
2026 null_error();
2027 return -1;
2030 m = s->ob_type->tp_as_sequence;
2031 if (m && m->sq_ass_item) {
2032 if (i < 0) {
2033 if (m->sq_length) {
2034 Py_ssize_t l = (*m->sq_length)(s);
2035 if (l < 0)
2036 return -1;
2037 i += l;
2040 return m->sq_ass_item(s, i, (PyObject *)NULL);
2043 type_error("'%.200s' object doesn't support item deletion", s);
2044 return -1;
2048 PySequence_SetSlice(PyObject *s, Py_ssize_t i1, Py_ssize_t i2, PyObject *o)
2050 PySequenceMethods *m;
2051 PyMappingMethods *mp;
2053 if (s == NULL) {
2054 null_error();
2055 return -1;
2058 m = s->ob_type->tp_as_sequence;
2059 if (m && m->sq_ass_slice) {
2060 if (i1 < 0 || i2 < 0) {
2061 if (m->sq_length) {
2062 Py_ssize_t l = (*m->sq_length)(s);
2063 if (l < 0)
2064 return -1;
2065 if (i1 < 0)
2066 i1 += l;
2067 if (i2 < 0)
2068 i2 += l;
2071 return m->sq_ass_slice(s, i1, i2, o);
2072 } else if ((mp = s->ob_type->tp_as_mapping) && mp->mp_ass_subscript) {
2073 int res;
2074 PyObject *slice = _PySlice_FromIndices(i1, i2);
2075 if (!slice)
2076 return -1;
2077 res = mp->mp_ass_subscript(s, slice, o);
2078 Py_DECREF(slice);
2079 return res;
2082 type_error("'%.200s' object doesn't support slice assignment", s);
2083 return -1;
2087 PySequence_DelSlice(PyObject *s, Py_ssize_t i1, Py_ssize_t i2)
2089 PySequenceMethods *m;
2091 if (s == NULL) {
2092 null_error();
2093 return -1;
2096 m = s->ob_type->tp_as_sequence;
2097 if (m && m->sq_ass_slice) {
2098 if (i1 < 0 || i2 < 0) {
2099 if (m->sq_length) {
2100 Py_ssize_t l = (*m->sq_length)(s);
2101 if (l < 0)
2102 return -1;
2103 if (i1 < 0)
2104 i1 += l;
2105 if (i2 < 0)
2106 i2 += l;
2109 return m->sq_ass_slice(s, i1, i2, (PyObject *)NULL);
2111 type_error("'%.200s' object doesn't support slice deletion", s);
2112 return -1;
2115 PyObject *
2116 PySequence_Tuple(PyObject *v)
2118 PyObject *it; /* iter(v) */
2119 Py_ssize_t n; /* guess for result tuple size */
2120 PyObject *result;
2121 Py_ssize_t j;
2123 if (v == NULL)
2124 return null_error();
2126 /* Special-case the common tuple and list cases, for efficiency. */
2127 if (PyTuple_CheckExact(v)) {
2128 /* Note that we can't know whether it's safe to return
2129 a tuple *subclass* instance as-is, hence the restriction
2130 to exact tuples here. In contrast, lists always make
2131 a copy, so there's no need for exactness below. */
2132 Py_INCREF(v);
2133 return v;
2135 if (PyList_Check(v))
2136 return PyList_AsTuple(v);
2138 /* Get iterator. */
2139 it = PyObject_GetIter(v);
2140 if (it == NULL)
2141 return NULL;
2143 /* Guess result size and allocate space. */
2144 n = _PyObject_LengthHint(v, 10);
2145 result = PyTuple_New(n);
2146 if (result == NULL)
2147 goto Fail;
2149 /* Fill the tuple. */
2150 for (j = 0; ; ++j) {
2151 PyObject *item = PyIter_Next(it);
2152 if (item == NULL) {
2153 if (PyErr_Occurred())
2154 goto Fail;
2155 break;
2157 if (j >= n) {
2158 Py_ssize_t oldn = n;
2159 /* The over-allocation strategy can grow a bit faster
2160 than for lists because unlike lists the
2161 over-allocation isn't permanent -- we reclaim
2162 the excess before the end of this routine.
2163 So, grow by ten and then add 25%.
2165 n += 10;
2166 n += n >> 2;
2167 if (n < oldn) {
2168 /* Check for overflow */
2169 PyErr_NoMemory();
2170 Py_DECREF(item);
2171 goto Fail;
2173 if (_PyTuple_Resize(&result, n) != 0) {
2174 Py_DECREF(item);
2175 goto Fail;
2178 PyTuple_SET_ITEM(result, j, item);
2181 /* Cut tuple back if guess was too large. */
2182 if (j < n &&
2183 _PyTuple_Resize(&result, j) != 0)
2184 goto Fail;
2186 Py_DECREF(it);
2187 return result;
2189 Fail:
2190 Py_XDECREF(result);
2191 Py_DECREF(it);
2192 return NULL;
2195 PyObject *
2196 PySequence_List(PyObject *v)
2198 PyObject *result; /* result list */
2199 PyObject *rv; /* return value from PyList_Extend */
2201 if (v == NULL)
2202 return null_error();
2204 result = PyList_New(0);
2205 if (result == NULL)
2206 return NULL;
2208 rv = _PyList_Extend((PyListObject *)result, v);
2209 if (rv == NULL) {
2210 Py_DECREF(result);
2211 return NULL;
2213 Py_DECREF(rv);
2214 return result;
2217 PyObject *
2218 PySequence_Fast(PyObject *v, const char *m)
2220 PyObject *it;
2222 if (v == NULL)
2223 return null_error();
2225 if (PyList_CheckExact(v) || PyTuple_CheckExact(v)) {
2226 Py_INCREF(v);
2227 return v;
2230 it = PyObject_GetIter(v);
2231 if (it == NULL) {
2232 if (PyErr_ExceptionMatches(PyExc_TypeError))
2233 PyErr_SetString(PyExc_TypeError, m);
2234 return NULL;
2237 v = PySequence_List(it);
2238 Py_DECREF(it);
2240 return v;
2243 /* Iterate over seq. Result depends on the operation:
2244 PY_ITERSEARCH_COUNT: -1 if error, else # of times obj appears in seq.
2245 PY_ITERSEARCH_INDEX: 0-based index of first occurence of obj in seq;
2246 set ValueError and return -1 if none found; also return -1 on error.
2247 Py_ITERSEARCH_CONTAINS: return 1 if obj in seq, else 0; -1 on error.
2249 Py_ssize_t
2250 _PySequence_IterSearch(PyObject *seq, PyObject *obj, int operation)
2252 Py_ssize_t n;
2253 int wrapped; /* for PY_ITERSEARCH_INDEX, true iff n wrapped around */
2254 PyObject *it; /* iter(seq) */
2256 if (seq == NULL || obj == NULL) {
2257 null_error();
2258 return -1;
2261 it = PyObject_GetIter(seq);
2262 if (it == NULL) {
2263 type_error("argument of type '%.200s' is not iterable", seq);
2264 return -1;
2267 n = wrapped = 0;
2268 for (;;) {
2269 int cmp;
2270 PyObject *item = PyIter_Next(it);
2271 if (item == NULL) {
2272 if (PyErr_Occurred())
2273 goto Fail;
2274 break;
2277 cmp = PyObject_RichCompareBool(obj, item, Py_EQ);
2278 Py_DECREF(item);
2279 if (cmp < 0)
2280 goto Fail;
2281 if (cmp > 0) {
2282 switch (operation) {
2283 case PY_ITERSEARCH_COUNT:
2284 if (n == PY_SSIZE_T_MAX) {
2285 PyErr_SetString(PyExc_OverflowError,
2286 "count exceeds C integer size");
2287 goto Fail;
2289 ++n;
2290 break;
2292 case PY_ITERSEARCH_INDEX:
2293 if (wrapped) {
2294 PyErr_SetString(PyExc_OverflowError,
2295 "index exceeds C integer size");
2296 goto Fail;
2298 goto Done;
2300 case PY_ITERSEARCH_CONTAINS:
2301 n = 1;
2302 goto Done;
2304 default:
2305 assert(!"unknown operation");
2309 if (operation == PY_ITERSEARCH_INDEX) {
2310 if (n == PY_SSIZE_T_MAX)
2311 wrapped = 1;
2312 ++n;
2316 if (operation != PY_ITERSEARCH_INDEX)
2317 goto Done;
2319 PyErr_SetString(PyExc_ValueError,
2320 "sequence.index(x): x not in sequence");
2321 /* fall into failure code */
2322 Fail:
2323 n = -1;
2324 /* fall through */
2325 Done:
2326 Py_DECREF(it);
2327 return n;
2331 /* Return # of times o appears in s. */
2332 Py_ssize_t
2333 PySequence_Count(PyObject *s, PyObject *o)
2335 return _PySequence_IterSearch(s, o, PY_ITERSEARCH_COUNT);
2338 /* Return -1 if error; 1 if ob in seq; 0 if ob not in seq.
2339 * Use sq_contains if possible, else defer to _PySequence_IterSearch().
2342 PySequence_Contains(PyObject *seq, PyObject *ob)
2344 Py_ssize_t result;
2345 if (PyType_HasFeature(seq->ob_type, Py_TPFLAGS_HAVE_SEQUENCE_IN)) {
2346 PySequenceMethods *sqm = seq->ob_type->tp_as_sequence;
2347 if (sqm != NULL && sqm->sq_contains != NULL)
2348 return (*sqm->sq_contains)(seq, ob);
2350 result = _PySequence_IterSearch(seq, ob, PY_ITERSEARCH_CONTAINS);
2351 return Py_SAFE_DOWNCAST(result, Py_ssize_t, int);
2354 /* Backwards compatibility */
2355 #undef PySequence_In
2357 PySequence_In(PyObject *w, PyObject *v)
2359 return PySequence_Contains(w, v);
2362 Py_ssize_t
2363 PySequence_Index(PyObject *s, PyObject *o)
2365 return _PySequence_IterSearch(s, o, PY_ITERSEARCH_INDEX);
2368 /* Operations on mappings */
2371 PyMapping_Check(PyObject *o)
2373 if (o && PyInstance_Check(o))
2374 return PyObject_HasAttrString(o, "__getitem__");
2376 return o && o->ob_type->tp_as_mapping &&
2377 o->ob_type->tp_as_mapping->mp_subscript &&
2378 !(o->ob_type->tp_as_sequence &&
2379 o->ob_type->tp_as_sequence->sq_slice);
2382 Py_ssize_t
2383 PyMapping_Size(PyObject *o)
2385 PyMappingMethods *m;
2387 if (o == NULL) {
2388 null_error();
2389 return -1;
2392 m = o->ob_type->tp_as_mapping;
2393 if (m && m->mp_length)
2394 return m->mp_length(o);
2396 type_error("object of type '%.200s' has no len()", o);
2397 return -1;
2400 #undef PyMapping_Length
2401 Py_ssize_t
2402 PyMapping_Length(PyObject *o)
2404 return PyMapping_Size(o);
2406 #define PyMapping_Length PyMapping_Size
2408 PyObject *
2409 PyMapping_GetItemString(PyObject *o, char *key)
2411 PyObject *okey, *r;
2413 if (key == NULL)
2414 return null_error();
2416 okey = PyString_FromString(key);
2417 if (okey == NULL)
2418 return NULL;
2419 r = PyObject_GetItem(o, okey);
2420 Py_DECREF(okey);
2421 return r;
2425 PyMapping_SetItemString(PyObject *o, char *key, PyObject *value)
2427 PyObject *okey;
2428 int r;
2430 if (key == NULL) {
2431 null_error();
2432 return -1;
2435 okey = PyString_FromString(key);
2436 if (okey == NULL)
2437 return -1;
2438 r = PyObject_SetItem(o, okey, value);
2439 Py_DECREF(okey);
2440 return r;
2444 PyMapping_HasKeyString(PyObject *o, char *key)
2446 PyObject *v;
2448 v = PyMapping_GetItemString(o, key);
2449 if (v) {
2450 Py_DECREF(v);
2451 return 1;
2453 PyErr_Clear();
2454 return 0;
2458 PyMapping_HasKey(PyObject *o, PyObject *key)
2460 PyObject *v;
2462 v = PyObject_GetItem(o, key);
2463 if (v) {
2464 Py_DECREF(v);
2465 return 1;
2467 PyErr_Clear();
2468 return 0;
2471 /* Operations on callable objects */
2473 /* XXX PyCallable_Check() is in object.c */
2475 PyObject *
2476 PyObject_CallObject(PyObject *o, PyObject *a)
2478 return PyEval_CallObjectWithKeywords(o, a, NULL);
2481 PyObject *
2482 PyObject_Call(PyObject *func, PyObject *arg, PyObject *kw)
2484 ternaryfunc call;
2486 if ((call = func->ob_type->tp_call) != NULL) {
2487 PyObject *result;
2488 if (Py_EnterRecursiveCall(" while calling a Python object"))
2489 return NULL;
2490 result = (*call)(func, arg, kw);
2491 Py_LeaveRecursiveCall();
2492 if (result == NULL && !PyErr_Occurred())
2493 PyErr_SetString(
2494 PyExc_SystemError,
2495 "NULL result without error in PyObject_Call");
2496 return result;
2498 PyErr_Format(PyExc_TypeError, "'%.200s' object is not callable",
2499 func->ob_type->tp_name);
2500 return NULL;
2503 static PyObject*
2504 call_function_tail(PyObject *callable, PyObject *args)
2506 PyObject *retval;
2508 if (args == NULL)
2509 return NULL;
2511 if (!PyTuple_Check(args)) {
2512 PyObject *a;
2514 a = PyTuple_New(1);
2515 if (a == NULL) {
2516 Py_DECREF(args);
2517 return NULL;
2519 PyTuple_SET_ITEM(a, 0, args);
2520 args = a;
2522 retval = PyObject_Call(callable, args, NULL);
2524 Py_DECREF(args);
2526 return retval;
2529 PyObject *
2530 PyObject_CallFunction(PyObject *callable, char *format, ...)
2532 va_list va;
2533 PyObject *args;
2535 if (callable == NULL)
2536 return null_error();
2538 if (format && *format) {
2539 va_start(va, format);
2540 args = Py_VaBuildValue(format, va);
2541 va_end(va);
2543 else
2544 args = PyTuple_New(0);
2546 return call_function_tail(callable, args);
2549 PyObject *
2550 _PyObject_CallFunction_SizeT(PyObject *callable, char *format, ...)
2552 va_list va;
2553 PyObject *args;
2555 if (callable == NULL)
2556 return null_error();
2558 if (format && *format) {
2559 va_start(va, format);
2560 args = _Py_VaBuildValue_SizeT(format, va);
2561 va_end(va);
2563 else
2564 args = PyTuple_New(0);
2566 return call_function_tail(callable, args);
2569 PyObject *
2570 PyObject_CallMethod(PyObject *o, char *name, char *format, ...)
2572 va_list va;
2573 PyObject *args;
2574 PyObject *func = NULL;
2575 PyObject *retval = NULL;
2577 if (o == NULL || name == NULL)
2578 return null_error();
2580 func = PyObject_GetAttrString(o, name);
2581 if (func == NULL) {
2582 PyErr_SetString(PyExc_AttributeError, name);
2583 return 0;
2586 if (!PyCallable_Check(func)) {
2587 type_error("attribute of type '%.200s' is not callable", func);
2588 goto exit;
2591 if (format && *format) {
2592 va_start(va, format);
2593 args = Py_VaBuildValue(format, va);
2594 va_end(va);
2596 else
2597 args = PyTuple_New(0);
2599 retval = call_function_tail(func, args);
2601 exit:
2602 /* args gets consumed in call_function_tail */
2603 Py_XDECREF(func);
2605 return retval;
2608 PyObject *
2609 _PyObject_CallMethod_SizeT(PyObject *o, char *name, char *format, ...)
2611 va_list va;
2612 PyObject *args;
2613 PyObject *func = NULL;
2614 PyObject *retval = NULL;
2616 if (o == NULL || name == NULL)
2617 return null_error();
2619 func = PyObject_GetAttrString(o, name);
2620 if (func == NULL) {
2621 PyErr_SetString(PyExc_AttributeError, name);
2622 return 0;
2625 if (!PyCallable_Check(func)) {
2626 type_error("attribute of type '%.200s' is not callable", func);
2627 goto exit;
2630 if (format && *format) {
2631 va_start(va, format);
2632 args = _Py_VaBuildValue_SizeT(format, va);
2633 va_end(va);
2635 else
2636 args = PyTuple_New(0);
2638 retval = call_function_tail(func, args);
2640 exit:
2641 /* args gets consumed in call_function_tail */
2642 Py_XDECREF(func);
2644 return retval;
2648 static PyObject *
2649 objargs_mktuple(va_list va)
2651 int i, n = 0;
2652 va_list countva;
2653 PyObject *result, *tmp;
2655 #ifdef VA_LIST_IS_ARRAY
2656 memcpy(countva, va, sizeof(va_list));
2657 #else
2658 #ifdef __va_copy
2659 __va_copy(countva, va);
2660 #else
2661 countva = va;
2662 #endif
2663 #endif
2665 while (((PyObject *)va_arg(countva, PyObject *)) != NULL)
2666 ++n;
2667 result = PyTuple_New(n);
2668 if (result != NULL && n > 0) {
2669 for (i = 0; i < n; ++i) {
2670 tmp = (PyObject *)va_arg(va, PyObject *);
2671 PyTuple_SET_ITEM(result, i, tmp);
2672 Py_INCREF(tmp);
2675 return result;
2678 PyObject *
2679 PyObject_CallMethodObjArgs(PyObject *callable, PyObject *name, ...)
2681 PyObject *args, *tmp;
2682 va_list vargs;
2684 if (callable == NULL || name == NULL)
2685 return null_error();
2687 callable = PyObject_GetAttr(callable, name);
2688 if (callable == NULL)
2689 return NULL;
2691 /* count the args */
2692 va_start(vargs, name);
2693 args = objargs_mktuple(vargs);
2694 va_end(vargs);
2695 if (args == NULL) {
2696 Py_DECREF(callable);
2697 return NULL;
2699 tmp = PyObject_Call(callable, args, NULL);
2700 Py_DECREF(args);
2701 Py_DECREF(callable);
2703 return tmp;
2706 PyObject *
2707 PyObject_CallFunctionObjArgs(PyObject *callable, ...)
2709 PyObject *args, *tmp;
2710 va_list vargs;
2712 if (callable == NULL)
2713 return null_error();
2715 /* count the args */
2716 va_start(vargs, callable);
2717 args = objargs_mktuple(vargs);
2718 va_end(vargs);
2719 if (args == NULL)
2720 return NULL;
2721 tmp = PyObject_Call(callable, args, NULL);
2722 Py_DECREF(args);
2724 return tmp;
2728 /* isinstance(), issubclass() */
2730 /* abstract_get_bases() has logically 4 return states, with a sort of 0th
2731 * state that will almost never happen.
2733 * 0. creating the __bases__ static string could get a MemoryError
2734 * 1. getattr(cls, '__bases__') could raise an AttributeError
2735 * 2. getattr(cls, '__bases__') could raise some other exception
2736 * 3. getattr(cls, '__bases__') could return a tuple
2737 * 4. getattr(cls, '__bases__') could return something other than a tuple
2739 * Only state #3 is a non-error state and only it returns a non-NULL object
2740 * (it returns the retrieved tuple).
2742 * Any raised AttributeErrors are masked by clearing the exception and
2743 * returning NULL. If an object other than a tuple comes out of __bases__,
2744 * then again, the return value is NULL. So yes, these two situations
2745 * produce exactly the same results: NULL is returned and no error is set.
2747 * If some exception other than AttributeError is raised, then NULL is also
2748 * returned, but the exception is not cleared. That's because we want the
2749 * exception to be propagated along.
2751 * Callers are expected to test for PyErr_Occurred() when the return value
2752 * is NULL to decide whether a valid exception should be propagated or not.
2753 * When there's no exception to propagate, it's customary for the caller to
2754 * set a TypeError.
2756 static PyObject *
2757 abstract_get_bases(PyObject *cls)
2759 static PyObject *__bases__ = NULL;
2760 PyObject *bases;
2762 if (__bases__ == NULL) {
2763 __bases__ = PyString_InternFromString("__bases__");
2764 if (__bases__ == NULL)
2765 return NULL;
2767 bases = PyObject_GetAttr(cls, __bases__);
2768 if (bases == NULL) {
2769 if (PyErr_ExceptionMatches(PyExc_AttributeError))
2770 PyErr_Clear();
2771 return NULL;
2773 if (!PyTuple_Check(bases)) {
2774 Py_DECREF(bases);
2775 return NULL;
2777 return bases;
2781 static int
2782 abstract_issubclass(PyObject *derived, PyObject *cls)
2784 PyObject *bases;
2785 Py_ssize_t i, n;
2786 int r = 0;
2789 if (derived == cls)
2790 return 1;
2792 if (PyTuple_Check(cls)) {
2793 /* Not a general sequence -- that opens up the road to
2794 recursion and stack overflow. */
2795 n = PyTuple_GET_SIZE(cls);
2796 for (i = 0; i < n; i++) {
2797 if (derived == PyTuple_GET_ITEM(cls, i))
2798 return 1;
2801 bases = abstract_get_bases(derived);
2802 if (bases == NULL) {
2803 if (PyErr_Occurred())
2804 return -1;
2805 return 0;
2807 n = PyTuple_GET_SIZE(bases);
2808 for (i = 0; i < n; i++) {
2809 r = abstract_issubclass(PyTuple_GET_ITEM(bases, i), cls);
2810 if (r != 0)
2811 break;
2814 Py_DECREF(bases);
2816 return r;
2819 static int
2820 check_class(PyObject *cls, const char *error)
2822 PyObject *bases = abstract_get_bases(cls);
2823 if (bases == NULL) {
2824 /* Do not mask errors. */
2825 if (!PyErr_Occurred())
2826 PyErr_SetString(PyExc_TypeError, error);
2827 return 0;
2829 Py_DECREF(bases);
2830 return -1;
2833 static int
2834 recursive_isinstance(PyObject *inst, PyObject *cls, int recursion_depth)
2836 PyObject *icls;
2837 static PyObject *__class__ = NULL;
2838 int retval = 0;
2840 if (__class__ == NULL) {
2841 __class__ = PyString_InternFromString("__class__");
2842 if (__class__ == NULL)
2843 return -1;
2846 if (PyClass_Check(cls) && PyInstance_Check(inst)) {
2847 PyObject *inclass =
2848 (PyObject*)((PyInstanceObject*)inst)->in_class;
2849 retval = PyClass_IsSubclass(inclass, cls);
2851 else if (PyType_Check(cls)) {
2852 retval = PyObject_TypeCheck(inst, (PyTypeObject *)cls);
2853 if (retval == 0) {
2854 PyObject *c = PyObject_GetAttr(inst, __class__);
2855 if (c == NULL) {
2856 PyErr_Clear();
2858 else {
2859 if (c != (PyObject *)(inst->ob_type) &&
2860 PyType_Check(c))
2861 retval = PyType_IsSubtype(
2862 (PyTypeObject *)c,
2863 (PyTypeObject *)cls);
2864 Py_DECREF(c);
2868 else if (PyTuple_Check(cls)) {
2869 Py_ssize_t i, n;
2871 if (!recursion_depth) {
2872 PyErr_SetString(PyExc_RuntimeError,
2873 "nest level of tuple too deep");
2874 return -1;
2877 n = PyTuple_GET_SIZE(cls);
2878 for (i = 0; i < n; i++) {
2879 retval = recursive_isinstance(
2880 inst,
2881 PyTuple_GET_ITEM(cls, i),
2882 recursion_depth-1);
2883 if (retval != 0)
2884 break;
2887 else {
2888 if (!check_class(cls,
2889 "isinstance() arg 2 must be a class, type,"
2890 " or tuple of classes and types"))
2891 return -1;
2892 icls = PyObject_GetAttr(inst, __class__);
2893 if (icls == NULL) {
2894 PyErr_Clear();
2895 retval = 0;
2897 else {
2898 retval = abstract_issubclass(icls, cls);
2899 Py_DECREF(icls);
2903 return retval;
2907 PyObject_IsInstance(PyObject *inst, PyObject *cls)
2909 static PyObject *name = NULL;
2910 PyObject *checker;
2912 /* Quick test for an exact match */
2913 if (Py_TYPE(inst) == (PyTypeObject *)cls)
2914 return 1;
2916 if (name == NULL) {
2917 name = PyString_InternFromString("__instancecheck__");
2918 if (name == NULL)
2919 return -1;
2921 checker = PyObject_GetAttr(cls, name);
2922 if (checker == NULL && PyErr_Occurred())
2923 PyErr_Clear();
2924 if (checker != NULL) {
2925 PyObject *res;
2926 int ok = -1;
2927 if (Py_EnterRecursiveCall(" in __instancecheck__")) {
2928 Py_DECREF(checker);
2929 return ok;
2931 res = PyObject_CallFunctionObjArgs(checker, inst, NULL);
2932 Py_LeaveRecursiveCall();
2933 Py_DECREF(checker);
2934 if (res != NULL) {
2935 ok = PyObject_IsTrue(res);
2936 Py_DECREF(res);
2938 return ok;
2940 return recursive_isinstance(inst, cls, Py_GetRecursionLimit());
2943 static int
2944 recursive_issubclass(PyObject *derived, PyObject *cls, int recursion_depth)
2946 int retval;
2948 if (!PyClass_Check(derived) || !PyClass_Check(cls)) {
2949 if (!check_class(derived,
2950 "issubclass() arg 1 must be a class"))
2951 return -1;
2953 if (PyTuple_Check(cls)) {
2954 Py_ssize_t i;
2955 Py_ssize_t n = PyTuple_GET_SIZE(cls);
2957 if (!recursion_depth) {
2958 PyErr_SetString(PyExc_RuntimeError,
2959 "nest level of tuple too deep");
2960 return -1;
2962 for (i = 0; i < n; ++i) {
2963 retval = recursive_issubclass(
2964 derived,
2965 PyTuple_GET_ITEM(cls, i),
2966 recursion_depth-1);
2967 if (retval != 0) {
2968 /* either found it, or got an error */
2969 return retval;
2972 return 0;
2974 else {
2975 if (!check_class(cls,
2976 "issubclass() arg 2 must be a class"
2977 " or tuple of classes"))
2978 return -1;
2981 retval = abstract_issubclass(derived, cls);
2983 else {
2984 /* shortcut */
2985 if (!(retval = (derived == cls)))
2986 retval = PyClass_IsSubclass(derived, cls);
2989 return retval;
2993 PyObject_IsSubclass(PyObject *derived, PyObject *cls)
2995 static PyObject *name = NULL;
2996 PyObject *t, *v, *tb;
2997 PyObject *checker;
2998 PyErr_Fetch(&t, &v, &tb);
3000 if (name == NULL) {
3001 name = PyString_InternFromString("__subclasscheck__");
3002 if (name == NULL)
3003 return -1;
3005 checker = PyObject_GetAttr(cls, name);
3006 PyErr_Restore(t, v, tb);
3007 if (checker != NULL) {
3008 PyObject *res;
3009 int ok = -1;
3010 if (Py_EnterRecursiveCall(" in __subclasscheck__"))
3011 return ok;
3012 res = PyObject_CallFunctionObjArgs(checker, derived, NULL);
3013 Py_LeaveRecursiveCall();
3014 Py_DECREF(checker);
3015 if (res != NULL) {
3016 ok = PyObject_IsTrue(res);
3017 Py_DECREF(res);
3019 return ok;
3021 return recursive_issubclass(derived, cls, Py_GetRecursionLimit());
3025 PyObject *
3026 PyObject_GetIter(PyObject *o)
3028 PyTypeObject *t = o->ob_type;
3029 getiterfunc f = NULL;
3030 if (PyType_HasFeature(t, Py_TPFLAGS_HAVE_ITER))
3031 f = t->tp_iter;
3032 if (f == NULL) {
3033 if (PySequence_Check(o))
3034 return PySeqIter_New(o);
3035 return type_error("'%.200s' object is not iterable", o);
3037 else {
3038 PyObject *res = (*f)(o);
3039 if (res != NULL && !PyIter_Check(res)) {
3040 PyErr_Format(PyExc_TypeError,
3041 "iter() returned non-iterator "
3042 "of type '%.100s'",
3043 res->ob_type->tp_name);
3044 Py_DECREF(res);
3045 res = NULL;
3047 return res;
3051 /* Return next item.
3052 * If an error occurs, return NULL. PyErr_Occurred() will be true.
3053 * If the iteration terminates normally, return NULL and clear the
3054 * PyExc_StopIteration exception (if it was set). PyErr_Occurred()
3055 * will be false.
3056 * Else return the next object. PyErr_Occurred() will be false.
3058 PyObject *
3059 PyIter_Next(PyObject *iter)
3061 PyObject *result;
3062 assert(PyIter_Check(iter));
3063 result = (*iter->ob_type->tp_iternext)(iter);
3064 if (result == NULL &&
3065 PyErr_Occurred() &&
3066 PyErr_ExceptionMatches(PyExc_StopIteration))
3067 PyErr_Clear();
3068 return result;