1 /* Abstract Object Interface (many thanks to Jim Fulton) */
6 #include "structmember.h" /* we need the offsetof() macro from there */
7 #include "longintrepr.h"
9 #define NEW_STYLE_NUMBER(o) PyType_HasFeature((o)->ob_type, \
10 Py_TPFLAGS_CHECKTYPES)
12 /* Shorthands to return certain errors */
15 type_error(const char *msg
)
17 PyErr_SetString(PyExc_TypeError
, msg
);
24 if (!PyErr_Occurred())
25 PyErr_SetString(PyExc_SystemError
,
26 "null argument to internal routine");
30 /* Operations on any object */
33 PyObject_Cmp(PyObject
*o1
, PyObject
*o2
, int *result
)
37 if (o1
== NULL
|| o2
== NULL
) {
41 r
= PyObject_Compare(o1
, o2
);
49 PyObject_Type(PyObject
*o
)
55 v
= (PyObject
*)o
->ob_type
;
61 PyObject_Size(PyObject
*o
)
70 m
= o
->ob_type
->tp_as_sequence
;
71 if (m
&& m
->sq_length
)
72 return m
->sq_length(o
);
74 return PyMapping_Size(o
);
77 #undef PyObject_Length
79 PyObject_Length(PyObject
*o
)
81 return PyObject_Size(o
);
83 #define PyObject_Length PyObject_Size
86 PyObject_GetItem(PyObject
*o
, PyObject
*key
)
90 if (o
== NULL
|| key
== NULL
)
93 m
= o
->ob_type
->tp_as_mapping
;
94 if (m
&& m
->mp_subscript
)
95 return m
->mp_subscript(o
, key
);
97 if (o
->ob_type
->tp_as_sequence
) {
99 return PySequence_GetItem(o
, PyInt_AsLong(key
));
100 else if (PyLong_Check(key
)) {
101 long key_value
= PyLong_AsLong(key
);
102 if (key_value
== -1 && PyErr_Occurred())
104 return PySequence_GetItem(o
, key_value
);
106 else if (o
->ob_type
->tp_as_sequence
->sq_item
)
107 return type_error("sequence index must be integer");
110 return type_error("unsubscriptable object");
114 PyObject_SetItem(PyObject
*o
, PyObject
*key
, PyObject
*value
)
118 if (o
== NULL
|| key
== NULL
|| value
== NULL
) {
122 m
= o
->ob_type
->tp_as_mapping
;
123 if (m
&& m
->mp_ass_subscript
)
124 return m
->mp_ass_subscript(o
, key
, value
);
126 if (o
->ob_type
->tp_as_sequence
) {
127 if (PyInt_Check(key
))
128 return PySequence_SetItem(o
, PyInt_AsLong(key
), value
);
129 else if (PyLong_Check(key
)) {
130 long key_value
= PyLong_AsLong(key
);
131 if (key_value
== -1 && PyErr_Occurred())
133 return PySequence_SetItem(o
, key_value
, value
);
135 else if (o
->ob_type
->tp_as_sequence
->sq_ass_item
) {
136 type_error("sequence index must be integer");
141 type_error("object does not support item assignment");
146 PyObject_DelItem(PyObject
*o
, PyObject
*key
)
150 if (o
== NULL
|| key
== NULL
) {
154 m
= o
->ob_type
->tp_as_mapping
;
155 if (m
&& m
->mp_ass_subscript
)
156 return m
->mp_ass_subscript(o
, key
, (PyObject
*)NULL
);
158 if (o
->ob_type
->tp_as_sequence
) {
159 if (PyInt_Check(key
))
160 return PySequence_DelItem(o
, PyInt_AsLong(key
));
161 else if (PyLong_Check(key
)) {
162 long key_value
= PyLong_AsLong(key
);
163 if (key_value
== -1 && PyErr_Occurred())
165 return PySequence_DelItem(o
, key_value
);
167 else if (o
->ob_type
->tp_as_sequence
->sq_ass_item
) {
168 type_error("sequence index must be integer");
173 type_error("object does not support item deletion");
177 int PyObject_AsCharBuffer(PyObject
*obj
,
185 if (obj
== NULL
|| buffer
== NULL
|| buffer_len
== NULL
) {
189 pb
= obj
->ob_type
->tp_as_buffer
;
191 pb
->bf_getcharbuffer
== NULL
||
192 pb
->bf_getsegcount
== NULL
) {
193 PyErr_SetString(PyExc_TypeError
,
194 "expected a character buffer object");
197 if ((*pb
->bf_getsegcount
)(obj
,NULL
) != 1) {
198 PyErr_SetString(PyExc_TypeError
,
199 "expected a single-segment buffer object");
202 len
= (*pb
->bf_getcharbuffer
)(obj
, 0, &pp
);
211 PyObject_CheckReadBuffer(PyObject
*obj
)
213 PyBufferProcs
*pb
= obj
->ob_type
->tp_as_buffer
;
216 pb
->bf_getreadbuffer
== NULL
||
217 pb
->bf_getsegcount
== NULL
||
218 (*pb
->bf_getsegcount
)(obj
, NULL
) != 1)
223 int PyObject_AsReadBuffer(PyObject
*obj
,
231 if (obj
== NULL
|| buffer
== NULL
|| buffer_len
== NULL
) {
235 pb
= obj
->ob_type
->tp_as_buffer
;
237 pb
->bf_getreadbuffer
== NULL
||
238 pb
->bf_getsegcount
== NULL
) {
239 PyErr_SetString(PyExc_TypeError
,
240 "expected a readable buffer object");
243 if ((*pb
->bf_getsegcount
)(obj
, NULL
) != 1) {
244 PyErr_SetString(PyExc_TypeError
,
245 "expected a single-segment buffer object");
248 len
= (*pb
->bf_getreadbuffer
)(obj
, 0, &pp
);
256 int PyObject_AsWriteBuffer(PyObject
*obj
,
264 if (obj
== NULL
|| buffer
== NULL
|| buffer_len
== NULL
) {
268 pb
= obj
->ob_type
->tp_as_buffer
;
270 pb
->bf_getwritebuffer
== NULL
||
271 pb
->bf_getsegcount
== NULL
) {
272 PyErr_SetString(PyExc_TypeError
,
273 "expected a writeable buffer object");
276 if ((*pb
->bf_getsegcount
)(obj
, NULL
) != 1) {
277 PyErr_SetString(PyExc_TypeError
,
278 "expected a single-segment buffer object");
281 len
= (*pb
->bf_getwritebuffer
)(obj
,0,&pp
);
289 /* Operations on numbers */
292 PyNumber_Check(PyObject
*o
)
294 return o
&& o
->ob_type
->tp_as_number
;
297 /* Binary operators */
299 /* New style number protocol support */
301 #define NB_SLOT(x) offsetof(PyNumberMethods, x)
302 #define NB_BINOP(nb_methods, slot) \
303 ((binaryfunc*)(& ((char*)nb_methods)[slot] ))
304 #define NB_TERNOP(nb_methods, slot) \
305 ((ternaryfunc*)(& ((char*)nb_methods)[slot] ))
308 Calling scheme used for binary operations:
311 -------------------------------------------------------------------
312 new new w.op(v,w)[*], v.op(v,w), w.op(v,w)
313 new old v.op(v,w), coerce(v,w), v.op(v,w)
314 old new w.op(v,w), coerce(v,w), v.op(v,w)
315 old old coerce(v,w), v.op(v,w)
317 [*] only when v->ob_type != w->ob_type && w->ob_type is a subclass of
322 * new == new style number
323 * old == old style number
324 * Action indicates the order in which operations are tried until either
325 a valid result is produced or an error occurs.
330 binary_op1(PyObject
*v
, PyObject
*w
, const int op_slot
)
333 binaryfunc slotv
= NULL
;
334 binaryfunc slotw
= NULL
;
336 if (v
->ob_type
->tp_as_number
!= NULL
&& NEW_STYLE_NUMBER(v
))
337 slotv
= *NB_BINOP(v
->ob_type
->tp_as_number
, op_slot
);
338 if (w
->ob_type
!= v
->ob_type
&&
339 w
->ob_type
->tp_as_number
!= NULL
&& NEW_STYLE_NUMBER(w
)) {
340 slotw
= *NB_BINOP(w
->ob_type
->tp_as_number
, op_slot
);
345 if (slotw
&& PyType_IsSubtype(w
->ob_type
, v
->ob_type
)) {
347 if (x
!= Py_NotImplemented
)
349 Py_DECREF(x
); /* can't do it */
353 if (x
!= Py_NotImplemented
)
355 Py_DECREF(x
); /* can't do it */
359 if (x
!= Py_NotImplemented
)
361 Py_DECREF(x
); /* can't do it */
363 if (!NEW_STYLE_NUMBER(v
) || !NEW_STYLE_NUMBER(w
)) {
364 int err
= PyNumber_CoerceEx(&v
, &w
);
369 PyNumberMethods
*mv
= v
->ob_type
->tp_as_number
;
372 slot
= *NB_BINOP(mv
, op_slot
);
374 PyObject
*x
= slot(v
, w
);
380 /* CoerceEx incremented the reference counts */
385 Py_INCREF(Py_NotImplemented
);
386 return Py_NotImplemented
;
390 binary_op(PyObject
*v
, PyObject
*w
, const int op_slot
, const char *op_name
)
392 PyObject
*result
= binary_op1(v
, w
, op_slot
);
393 if (result
== Py_NotImplemented
) {
394 Py_DECREF(Py_NotImplemented
);
397 "unsupported operand type(s) for %s: '%s' and '%s'",
400 w
->ob_type
->tp_name
);
408 Calling scheme used for ternary operations:
410 *** In some cases, w.op is called before v.op; see binary_op1. ***
413 -------------------------------------------------------------------
414 new new new v.op(v,w,z), w.op(v,w,z), z.op(v,w,z)
415 new old new v.op(v,w,z), z.op(v,w,z), coerce(v,w,z), v.op(v,w,z)
416 old new new w.op(v,w,z), z.op(v,w,z), coerce(v,w,z), v.op(v,w,z)
417 old old new z.op(v,w,z), coerce(v,w,z), v.op(v,w,z)
418 new new old v.op(v,w,z), w.op(v,w,z), coerce(v,w,z), v.op(v,w,z)
419 new old old v.op(v,w,z), coerce(v,w,z), v.op(v,w,z)
420 old new old w.op(v,w,z), coerce(v,w,z), v.op(v,w,z)
421 old old old coerce(v,w,z), v.op(v,w,z)
425 * new == new style number
426 * old == old style number
427 * Action indicates the order in which operations are tried until either
428 a valid result is produced or an error occurs.
429 * coerce(v,w,z) actually does: coerce(v,w), coerce(v,z), coerce(w,z) and
430 only if z != Py_None; if z == Py_None, then it is treated as absent
431 variable and only coerce(v,w) is tried.
436 ternary_op(PyObject
*v
,
442 PyNumberMethods
*mv
, *mw
, *mz
;
444 ternaryfunc slotv
= NULL
;
445 ternaryfunc slotw
= NULL
;
446 ternaryfunc slotz
= NULL
;
448 mv
= v
->ob_type
->tp_as_number
;
449 mw
= w
->ob_type
->tp_as_number
;
450 if (mv
!= NULL
&& NEW_STYLE_NUMBER(v
))
451 slotv
= *NB_TERNOP(mv
, op_slot
);
452 if (w
->ob_type
!= v
->ob_type
&&
453 mv
!= NULL
&& NEW_STYLE_NUMBER(w
)) {
454 slotw
= *NB_TERNOP(mw
, op_slot
);
459 if (slotw
&& PyType_IsSubtype(w
->ob_type
, v
->ob_type
)) {
461 if (x
!= Py_NotImplemented
)
463 Py_DECREF(x
); /* can't do it */
467 if (x
!= Py_NotImplemented
)
469 Py_DECREF(x
); /* can't do it */
473 if (x
!= Py_NotImplemented
)
475 Py_DECREF(x
); /* can't do it */
477 mz
= z
->ob_type
->tp_as_number
;
478 if (mz
!= NULL
&& NEW_STYLE_NUMBER(z
)) {
479 slotz
= *NB_TERNOP(mz
, op_slot
);
480 if (slotz
== slotv
|| slotz
== slotw
)
484 if (x
!= Py_NotImplemented
)
486 Py_DECREF(x
); /* can't do it */
490 if (!NEW_STYLE_NUMBER(v
) || !NEW_STYLE_NUMBER(w
) ||
491 (z
!= Py_None
&& !NEW_STYLE_NUMBER(z
))) {
492 /* we have an old style operand, coerce */
493 PyObject
*v1
, *z1
, *w2
, *z2
;
496 c
= PyNumber_Coerce(&v
, &w
);
500 /* Special case: if the third argument is None, it is
501 treated as absent argument and not coerced. */
503 if (v
->ob_type
->tp_as_number
) {
504 slotz
= *NB_TERNOP(v
->ob_type
->tp_as_number
,
517 c
= PyNumber_Coerce(&v1
, &z1
);
522 c
= PyNumber_Coerce(&w2
, &z2
);
526 if (v1
->ob_type
->tp_as_number
!= NULL
) {
527 slotv
= *NB_TERNOP(v1
->ob_type
->tp_as_number
,
530 x
= slotv(v1
, w2
, z2
);
553 "unsupported operand type(s) for ** or pow(): "
556 w
->ob_type
->tp_name
);
560 "unsupported operand type(s) for pow(): "
564 z
->ob_type
->tp_name
);
568 #define BINARY_FUNC(func, op, op_name) \
570 func(PyObject *v, PyObject *w) { \
571 return binary_op(v, w, NB_SLOT(op), op_name); \
574 BINARY_FUNC(PyNumber_Or
, nb_or
, "|")
575 BINARY_FUNC(PyNumber_Xor
, nb_xor
, "^")
576 BINARY_FUNC(PyNumber_And
, nb_and
, "&")
577 BINARY_FUNC(PyNumber_Lshift
, nb_lshift
, "<<")
578 BINARY_FUNC(PyNumber_Rshift
, nb_rshift
, ">>")
579 BINARY_FUNC(PyNumber_Subtract
, nb_subtract
, "-")
580 BINARY_FUNC(PyNumber_Multiply
, nb_multiply
, "*")
581 BINARY_FUNC(PyNumber_Divide
, nb_divide
, "/")
582 BINARY_FUNC(PyNumber_Divmod
, nb_divmod
, "divmod()")
585 PyNumber_Add(PyObject
*v
, PyObject
*w
)
587 PyObject
*result
= binary_op1(v
, w
, NB_SLOT(nb_add
));
588 if (result
== Py_NotImplemented
) {
589 PySequenceMethods
*m
= v
->ob_type
->tp_as_sequence
;
590 Py_DECREF(Py_NotImplemented
);
591 if (m
&& m
->sq_concat
) {
592 result
= (*m
->sq_concat
)(v
, w
);
597 "unsupported operand types for +: '%s' and '%s'",
599 w
->ob_type
->tp_name
);
607 PyNumber_FloorDivide(PyObject
*v
, PyObject
*w
)
609 /* XXX tp_flags test */
610 return binary_op(v
, w
, NB_SLOT(nb_floor_divide
), "//");
614 PyNumber_TrueDivide(PyObject
*v
, PyObject
*w
)
616 /* XXX tp_flags test */
617 return binary_op(v
, w
, NB_SLOT(nb_true_divide
), "/");
621 PyNumber_Remainder(PyObject
*v
, PyObject
*w
)
623 if (PyString_Check(v
))
624 return PyString_Format(v
, w
);
625 #ifdef Py_USING_UNICODE
626 else if (PyUnicode_Check(v
))
627 return PyUnicode_Format(v
, w
);
629 return binary_op(v
, w
, NB_SLOT(nb_remainder
), "%");
633 PyNumber_Power(PyObject
*v
, PyObject
*w
, PyObject
*z
)
635 return ternary_op(v
, w
, z
, NB_SLOT(nb_power
), "** or pow()");
638 /* Binary in-place operators */
640 /* The in-place operators are defined to fall back to the 'normal',
641 non in-place operations, if the in-place methods are not in place.
643 - If the left hand object has the appropriate struct members, and
644 they are filled, call the appropriate function and return the
645 result. No coercion is done on the arguments; the left-hand object
646 is the one the operation is performed on, and it's up to the
647 function to deal with the right-hand object.
649 - Otherwise, in-place modification is not supported. Handle it exactly as
650 a non in-place operation of the same kind.
654 #define HASINPLACE(t) PyType_HasFeature((t)->ob_type, Py_TPFLAGS_HAVE_INPLACEOPS)
657 binary_iop(PyObject
*v
, PyObject
*w
, const int iop_slot
, const int op_slot
,
660 PyNumberMethods
*mv
= v
->ob_type
->tp_as_number
;
661 if (mv
!= NULL
&& HASINPLACE(v
)) {
662 binaryfunc
*slot
= NB_BINOP(mv
, iop_slot
);
664 PyObject
*x
= (*slot
)(v
, w
);
665 if (x
!= Py_NotImplemented
) {
671 return binary_op(v
, w
, op_slot
, op_name
);
674 #define INPLACE_BINOP(func, iop, op, op_name) \
676 func(PyObject *v, PyObject *w) { \
677 return binary_iop(v, w, NB_SLOT(iop), NB_SLOT(op), op_name); \
680 INPLACE_BINOP(PyNumber_InPlaceOr
, nb_inplace_or
, nb_or
, "|=")
681 INPLACE_BINOP(PyNumber_InPlaceXor
, nb_inplace_xor
, nb_xor
, "^=")
682 INPLACE_BINOP(PyNumber_InPlaceAnd
, nb_inplace_and
, nb_and
, "&=")
683 INPLACE_BINOP(PyNumber_InPlaceLshift
, nb_inplace_lshift
, nb_lshift
, "<<=")
684 INPLACE_BINOP(PyNumber_InPlaceRshift
, nb_inplace_rshift
, nb_rshift
, ">>=")
685 INPLACE_BINOP(PyNumber_InPlaceSubtract
, nb_inplace_subtract
, nb_subtract
, "-=")
686 INPLACE_BINOP(PyNumber_InPlaceDivide
, nb_inplace_divide
, nb_divide
, "/=")
689 PyNumber_InPlaceFloorDivide(PyObject
*v
, PyObject
*w
)
691 /* XXX tp_flags test */
692 return binary_iop(v
, w
, NB_SLOT(nb_inplace_floor_divide
),
693 NB_SLOT(nb_floor_divide
), "//=");
697 PyNumber_InPlaceTrueDivide(PyObject
*v
, PyObject
*w
)
699 /* XXX tp_flags test */
700 return binary_iop(v
, w
, NB_SLOT(nb_inplace_true_divide
),
701 NB_SLOT(nb_true_divide
), "/=");
705 PyNumber_InPlaceAdd(PyObject
*v
, PyObject
*w
)
709 if (v
->ob_type
->tp_as_sequence
!= NULL
) {
711 f
= v
->ob_type
->tp_as_sequence
->sq_inplace_concat
;
713 f
= v
->ob_type
->tp_as_sequence
->sq_concat
;
717 return binary_iop(v
, w
, NB_SLOT(nb_inplace_add
), NB_SLOT(nb_add
), "+=");
721 PyNumber_InPlaceMultiply(PyObject
*v
, PyObject
*w
)
723 PyObject
* (*g
)(PyObject
*, int) = NULL
;
724 if (HASINPLACE(v
) && v
->ob_type
->tp_as_sequence
&&
725 (g
= v
->ob_type
->tp_as_sequence
->sq_inplace_repeat
)) {
727 if (PyInt_Check(w
)) {
730 else if (PyLong_Check(w
)) {
731 n
= PyLong_AsLong(w
);
732 if (n
== -1 && PyErr_Occurred())
736 return type_error("can't multiply sequence to non-int");
738 return (*g
)(v
, (int)n
);
740 return binary_iop(v
, w
, NB_SLOT(nb_inplace_multiply
),
741 NB_SLOT(nb_multiply
), "*=");
747 PyNumber_InPlaceRemainder(PyObject
*v
, PyObject
*w
)
749 if (PyString_Check(v
))
750 return PyString_Format(v
, w
);
751 #ifdef Py_USING_UNICODE
752 else if (PyUnicode_Check(v
))
753 return PyUnicode_Format(v
, w
);
756 return binary_iop(v
, w
, NB_SLOT(nb_inplace_remainder
),
757 NB_SLOT(nb_remainder
), "%=");
762 PyNumber_InPlacePower(PyObject
*v
, PyObject
*w
, PyObject
*z
)
764 if (HASINPLACE(v
) && v
->ob_type
->tp_as_number
&&
765 v
->ob_type
->tp_as_number
->nb_inplace_power
!= NULL
) {
766 return ternary_op(v
, w
, z
, NB_SLOT(nb_inplace_power
), "**=");
769 return ternary_op(v
, w
, z
, NB_SLOT(nb_power
), "**=");
774 /* Unary operators and functions */
777 PyNumber_Negative(PyObject
*o
)
783 m
= o
->ob_type
->tp_as_number
;
784 if (m
&& m
->nb_negative
)
785 return (*m
->nb_negative
)(o
);
787 return type_error("bad operand type for unary -");
791 PyNumber_Positive(PyObject
*o
)
797 m
= o
->ob_type
->tp_as_number
;
798 if (m
&& m
->nb_positive
)
799 return (*m
->nb_positive
)(o
);
801 return type_error("bad operand type for unary +");
805 PyNumber_Invert(PyObject
*o
)
811 m
= o
->ob_type
->tp_as_number
;
812 if (m
&& m
->nb_invert
)
813 return (*m
->nb_invert
)(o
);
815 return type_error("bad operand type for unary ~");
819 PyNumber_Absolute(PyObject
*o
)
825 m
= o
->ob_type
->tp_as_number
;
826 if (m
&& m
->nb_absolute
)
827 return m
->nb_absolute(o
);
829 return type_error("bad operand type for abs()");
832 /* Add a check for embedded NULL-bytes in the argument. */
834 int_from_string(const char *s
, int len
)
839 x
= PyInt_FromString((char*)s
, &end
, 10);
842 if (end
!= s
+ len
) {
843 PyErr_SetString(PyExc_ValueError
,
844 "null byte in argument for int()");
852 PyNumber_Int(PyObject
*o
)
860 if (PyInt_CheckExact(o
)) {
864 if (PyInt_Check(o
)) {
865 PyIntObject
*io
= (PyIntObject
*)o
;
866 return PyInt_FromLong(io
->ob_ival
);
868 if (PyString_Check(o
))
869 return int_from_string(PyString_AS_STRING(o
),
870 PyString_GET_SIZE(o
));
871 #ifdef Py_USING_UNICODE
872 if (PyUnicode_Check(o
))
873 return PyInt_FromUnicode(PyUnicode_AS_UNICODE(o
),
874 PyUnicode_GET_SIZE(o
),
877 m
= o
->ob_type
->tp_as_number
;
880 if (!PyObject_AsCharBuffer(o
, &buffer
, &buffer_len
))
881 return int_from_string((char*)buffer
, buffer_len
);
883 return type_error("object can't be converted to int");
886 /* Add a check for embedded NULL-bytes in the argument. */
888 long_from_string(const char *s
, int len
)
893 x
= PyLong_FromString((char*)s
, &end
, 10);
896 if (end
!= s
+ len
) {
897 PyErr_SetString(PyExc_ValueError
,
898 "null byte in argument for long()");
906 PyNumber_Long(PyObject
*o
)
914 if (PyLong_CheckExact(o
)) {
919 return _PyLong_Copy((PyLongObject
*)o
);
920 if (PyString_Check(o
))
921 /* need to do extra error checking that PyLong_FromString()
922 * doesn't do. In particular long('9.5') must raise an
923 * exception, not truncate the float.
925 return long_from_string(PyString_AS_STRING(o
),
926 PyString_GET_SIZE(o
));
927 #ifdef Py_USING_UNICODE
928 if (PyUnicode_Check(o
))
929 /* The above check is done in PyLong_FromUnicode(). */
930 return PyLong_FromUnicode(PyUnicode_AS_UNICODE(o
),
931 PyUnicode_GET_SIZE(o
),
934 m
= o
->ob_type
->tp_as_number
;
936 return m
->nb_long(o
);
937 if (!PyObject_AsCharBuffer(o
, &buffer
, &buffer_len
))
938 return long_from_string(buffer
, buffer_len
);
940 return type_error("object can't be converted to long");
944 PyNumber_Float(PyObject
*o
)
950 if (PyFloat_CheckExact(o
)) {
954 if (PyFloat_Check(o
)) {
955 PyFloatObject
*po
= (PyFloatObject
*)o
;
956 return PyFloat_FromDouble(po
->ob_fval
);
958 if (!PyString_Check(o
)) {
959 m
= o
->ob_type
->tp_as_number
;
960 if (m
&& m
->nb_float
)
961 return m
->nb_float(o
);
963 return PyFloat_FromString(o
, NULL
);
966 /* Operations on sequences */
969 PySequence_Check(PyObject
*s
)
971 return s
!= NULL
&& s
->ob_type
->tp_as_sequence
&&
972 s
->ob_type
->tp_as_sequence
->sq_item
!= NULL
;
976 PySequence_Size(PyObject
*s
)
978 PySequenceMethods
*m
;
985 m
= s
->ob_type
->tp_as_sequence
;
986 if (m
&& m
->sq_length
)
987 return m
->sq_length(s
);
989 type_error("len() of unsized object");
993 #undef PySequence_Length
995 PySequence_Length(PyObject
*s
)
997 return PySequence_Size(s
);
999 #define PySequence_Length PySequence_Size
1002 PySequence_Concat(PyObject
*s
, PyObject
*o
)
1004 PySequenceMethods
*m
;
1006 if (s
== NULL
|| o
== NULL
)
1007 return null_error();
1009 m
= s
->ob_type
->tp_as_sequence
;
1010 if (m
&& m
->sq_concat
)
1011 return m
->sq_concat(s
, o
);
1013 return type_error("object can't be concatenated");
1017 PySequence_Repeat(PyObject
*o
, int count
)
1019 PySequenceMethods
*m
;
1022 return null_error();
1024 m
= o
->ob_type
->tp_as_sequence
;
1025 if (m
&& m
->sq_repeat
)
1026 return m
->sq_repeat(o
, count
);
1028 return type_error("object can't be repeated");
1032 PySequence_InPlaceConcat(PyObject
*s
, PyObject
*o
)
1034 PySequenceMethods
*m
;
1036 if (s
== NULL
|| o
== NULL
)
1037 return null_error();
1039 m
= s
->ob_type
->tp_as_sequence
;
1040 if (m
&& HASINPLACE(s
) && m
->sq_inplace_concat
)
1041 return m
->sq_inplace_concat(s
, o
);
1042 if (m
&& m
->sq_concat
)
1043 return m
->sq_concat(s
, o
);
1045 return type_error("object can't be concatenated");
1049 PySequence_InPlaceRepeat(PyObject
*o
, int count
)
1051 PySequenceMethods
*m
;
1054 return null_error();
1056 m
= o
->ob_type
->tp_as_sequence
;
1057 if (m
&& HASINPLACE(o
) && m
->sq_inplace_repeat
)
1058 return m
->sq_inplace_repeat(o
, count
);
1059 if (m
&& m
->sq_repeat
)
1060 return m
->sq_repeat(o
, count
);
1062 return type_error("object can't be repeated");
1066 PySequence_GetItem(PyObject
*s
, int i
)
1068 PySequenceMethods
*m
;
1071 return null_error();
1073 m
= s
->ob_type
->tp_as_sequence
;
1074 if (m
&& m
->sq_item
) {
1077 int l
= (*m
->sq_length
)(s
);
1083 return m
->sq_item(s
, i
);
1086 return type_error("unindexable object");
1090 sliceobj_from_intint(int i
, int j
)
1092 PyObject
*start
, *end
, *slice
;
1093 start
= PyInt_FromLong((long)i
);
1096 end
= PyInt_FromLong((long)j
);
1101 slice
= PySlice_New(start
, end
, NULL
);
1108 PySequence_GetSlice(PyObject
*s
, int i1
, int i2
)
1110 PySequenceMethods
*m
;
1111 PyMappingMethods
*mp
;
1113 if (!s
) return null_error();
1115 m
= s
->ob_type
->tp_as_sequence
;
1116 if (m
&& m
->sq_slice
) {
1117 if (i1
< 0 || i2
< 0) {
1119 int l
= (*m
->sq_length
)(s
);
1128 return m
->sq_slice(s
, i1
, i2
);
1129 } else if ((mp
= s
->ob_type
->tp_as_mapping
) && mp
->mp_subscript
) {
1131 PyObject
*slice
= sliceobj_from_intint(i1
, i2
);
1134 res
= mp
->mp_subscript(s
, slice
);
1139 return type_error("unsliceable object");
1143 PySequence_SetItem(PyObject
*s
, int i
, PyObject
*o
)
1145 PySequenceMethods
*m
;
1152 m
= s
->ob_type
->tp_as_sequence
;
1153 if (m
&& m
->sq_ass_item
) {
1156 int l
= (*m
->sq_length
)(s
);
1162 return m
->sq_ass_item(s
, i
, o
);
1165 type_error("object doesn't support item assignment");
1170 PySequence_DelItem(PyObject
*s
, int i
)
1172 PySequenceMethods
*m
;
1179 m
= s
->ob_type
->tp_as_sequence
;
1180 if (m
&& m
->sq_ass_item
) {
1183 int l
= (*m
->sq_length
)(s
);
1189 return m
->sq_ass_item(s
, i
, (PyObject
*)NULL
);
1192 type_error("object doesn't support item deletion");
1197 PySequence_SetSlice(PyObject
*s
, int i1
, int i2
, PyObject
*o
)
1199 PySequenceMethods
*m
;
1200 PyMappingMethods
*mp
;
1207 m
= s
->ob_type
->tp_as_sequence
;
1208 if (m
&& m
->sq_ass_slice
) {
1209 if (i1
< 0 || i2
< 0) {
1211 int l
= (*m
->sq_length
)(s
);
1220 return m
->sq_ass_slice(s
, i1
, i2
, o
);
1221 } else if ((mp
= s
->ob_type
->tp_as_mapping
) && mp
->mp_ass_subscript
) {
1223 PyObject
*slice
= sliceobj_from_intint(i1
, i2
);
1226 res
= mp
->mp_ass_subscript(s
, slice
, o
);
1231 type_error("object doesn't support slice assignment");
1236 PySequence_DelSlice(PyObject
*s
, int i1
, int i2
)
1238 PySequenceMethods
*m
;
1245 m
= s
->ob_type
->tp_as_sequence
;
1246 if (m
&& m
->sq_ass_slice
) {
1247 if (i1
< 0 || i2
< 0) {
1249 int l
= (*m
->sq_length
)(s
);
1258 return m
->sq_ass_slice(s
, i1
, i2
, (PyObject
*)NULL
);
1260 type_error("object doesn't support slice deletion");
1265 PySequence_Tuple(PyObject
*v
)
1267 PyObject
*it
; /* iter(v) */
1268 int n
; /* guess for result tuple size */
1273 return null_error();
1275 /* Special-case the common tuple and list cases, for efficiency. */
1276 if (PyTuple_CheckExact(v
)) {
1277 /* Note that we can't know whether it's safe to return
1278 a tuple *subclass* instance as-is, hence the restriction
1279 to exact tuples here. In contrast, lists always make
1280 a copy, so there's no need for exactness below. */
1284 if (PyList_Check(v
))
1285 return PyList_AsTuple(v
);
1288 it
= PyObject_GetIter(v
);
1292 /* Guess result size and allocate space. */
1293 n
= PySequence_Size(v
);
1296 n
= 10; /* arbitrary */
1298 result
= PyTuple_New(n
);
1302 /* Fill the tuple. */
1303 for (j
= 0; ; ++j
) {
1304 PyObject
*item
= PyIter_Next(it
);
1306 if (PyErr_Occurred())
1315 if (_PyTuple_Resize(&result
, n
) != 0) {
1320 PyTuple_SET_ITEM(result
, j
, item
);
1323 /* Cut tuple back if guess was too large. */
1325 _PyTuple_Resize(&result
, j
) != 0)
1338 PySequence_List(PyObject
*v
)
1340 PyObject
*it
; /* iter(v) */
1341 PyObject
*result
; /* result list */
1342 int n
; /* guess for result list size */
1346 return null_error();
1348 /* Special-case list(a_list), for speed. */
1349 if (PyList_Check(v
))
1350 return PyList_GetSlice(v
, 0, PyList_GET_SIZE(v
));
1352 /* Get iterator. There may be some low-level efficiency to be gained
1353 * by caching the tp_iternext slot instead of using PyIter_Next()
1354 * later, but premature optimization is the root etc.
1356 it
= PyObject_GetIter(v
);
1360 /* Guess a result list size. */
1361 n
= -1; /* unknown */
1362 if (PySequence_Check(v
) &&
1363 v
->ob_type
->tp_as_sequence
->sq_length
) {
1364 n
= PySequence_Size(v
);
1369 n
= 8; /* arbitrary */
1370 result
= PyList_New(n
);
1371 if (result
== NULL
) {
1376 /* Run iterator to exhaustion. */
1377 for (i
= 0; ; i
++) {
1378 PyObject
*item
= PyIter_Next(it
);
1380 if (PyErr_Occurred()) {
1387 PyList_SET_ITEM(result
, i
, item
); /* steals ref */
1389 int status
= PyList_Append(result
, item
);
1390 Py_DECREF(item
); /* append creates a new ref */
1399 /* Cut back result list if initial guess was too large. */
1400 if (i
< n
&& result
!= NULL
) {
1401 if (PyList_SetSlice(result
, i
, n
, (PyObject
*)NULL
) != 0) {
1411 PySequence_Fast(PyObject
*v
, const char *m
)
1414 return null_error();
1416 if (PyList_Check(v
) || PyTuple_Check(v
)) {
1421 v
= PySequence_Tuple(v
);
1422 if (v
== NULL
&& PyErr_ExceptionMatches(PyExc_TypeError
))
1423 return type_error(m
);
1428 /* Iterate over seq. Result depends on the operation:
1429 PY_ITERSEARCH_COUNT: -1 if error, else # of times obj appears in seq.
1430 PY_ITERSEARCH_INDEX: 0-based index of first occurence of obj in seq;
1431 set ValueError and return -1 if none found; also return -1 on error.
1432 Py_ITERSEARCH_CONTAINS: return 1 if obj in seq, else 0; -1 on error.
1435 _PySequence_IterSearch(PyObject
*seq
, PyObject
*obj
, int operation
)
1438 int wrapped
; /* for PY_ITERSEARCH_INDEX, true iff n wrapped around */
1439 PyObject
*it
; /* iter(seq) */
1441 if (seq
== NULL
|| obj
== NULL
) {
1446 it
= PyObject_GetIter(seq
);
1448 type_error("iterable argument required");
1455 PyObject
*item
= PyIter_Next(it
);
1457 if (PyErr_Occurred())
1462 cmp
= PyObject_RichCompareBool(obj
, item
, Py_EQ
);
1467 switch (operation
) {
1468 case PY_ITERSEARCH_COUNT
:
1471 PyErr_SetString(PyExc_OverflowError
,
1472 "count exceeds C int size");
1477 case PY_ITERSEARCH_INDEX
:
1479 PyErr_SetString(PyExc_OverflowError
,
1480 "index exceeds C int size");
1485 case PY_ITERSEARCH_CONTAINS
:
1490 assert(!"unknown operation");
1494 if (operation
== PY_ITERSEARCH_INDEX
) {
1501 if (operation
!= PY_ITERSEARCH_INDEX
)
1504 PyErr_SetString(PyExc_ValueError
,
1505 "sequence.index(x): x not in sequence");
1506 /* fall into failure code */
1516 /* Return # of times o appears in s. */
1518 PySequence_Count(PyObject
*s
, PyObject
*o
)
1520 return _PySequence_IterSearch(s
, o
, PY_ITERSEARCH_COUNT
);
1523 /* Return -1 if error; 1 if ob in seq; 0 if ob not in seq.
1524 * Use sq_contains if possible, else defer to _PySequence_IterSearch().
1527 PySequence_Contains(PyObject
*seq
, PyObject
*ob
)
1529 if (PyType_HasFeature(seq
->ob_type
, Py_TPFLAGS_HAVE_SEQUENCE_IN
)) {
1530 PySequenceMethods
*sqm
= seq
->ob_type
->tp_as_sequence
;
1531 if (sqm
!= NULL
&& sqm
->sq_contains
!= NULL
)
1532 return (*sqm
->sq_contains
)(seq
, ob
);
1534 return _PySequence_IterSearch(seq
, ob
, PY_ITERSEARCH_CONTAINS
);
1537 /* Backwards compatibility */
1538 #undef PySequence_In
1540 PySequence_In(PyObject
*w
, PyObject
*v
)
1542 return PySequence_Contains(w
, v
);
1546 PySequence_Index(PyObject
*s
, PyObject
*o
)
1548 return _PySequence_IterSearch(s
, o
, PY_ITERSEARCH_INDEX
);
1551 /* Operations on mappings */
1554 PyMapping_Check(PyObject
*o
)
1556 return o
&& o
->ob_type
->tp_as_mapping
&&
1557 o
->ob_type
->tp_as_mapping
->mp_subscript
;
1561 PyMapping_Size(PyObject
*o
)
1563 PyMappingMethods
*m
;
1570 m
= o
->ob_type
->tp_as_mapping
;
1571 if (m
&& m
->mp_length
)
1572 return m
->mp_length(o
);
1574 type_error("len() of unsized object");
1578 #undef PyMapping_Length
1580 PyMapping_Length(PyObject
*o
)
1582 return PyMapping_Size(o
);
1584 #define PyMapping_Length PyMapping_Size
1587 PyMapping_GetItemString(PyObject
*o
, char *key
)
1592 return null_error();
1594 okey
= PyString_FromString(key
);
1597 r
= PyObject_GetItem(o
, okey
);
1603 PyMapping_SetItemString(PyObject
*o
, char *key
, PyObject
*value
)
1613 okey
= PyString_FromString(key
);
1616 r
= PyObject_SetItem(o
, okey
, value
);
1622 PyMapping_HasKeyString(PyObject
*o
, char *key
)
1626 v
= PyMapping_GetItemString(o
, key
);
1636 PyMapping_HasKey(PyObject
*o
, PyObject
*key
)
1640 v
= PyObject_GetItem(o
, key
);
1649 /* Operations on callable objects */
1651 /* XXX PyCallable_Check() is in object.c */
1654 PyObject_CallObject(PyObject
*o
, PyObject
*a
)
1656 return PyEval_CallObjectWithKeywords(o
, a
, NULL
);
1660 PyObject_Call(PyObject
*func
, PyObject
*arg
, PyObject
*kw
)
1664 if ((call
= func
->ob_type
->tp_call
) != NULL
) {
1665 PyObject
*result
= (*call
)(func
, arg
, kw
);
1666 if (result
== NULL
&& !PyErr_Occurred())
1669 "NULL result without error in PyObject_Call");
1672 PyErr_Format(PyExc_TypeError
, "'%s' object is not callable",
1673 func
->ob_type
->tp_name
);
1678 PyObject_CallFunction(PyObject
*callable
, char *format
, ...)
1681 PyObject
*args
, *retval
;
1683 if (callable
== NULL
)
1684 return null_error();
1686 if (format
&& *format
) {
1687 va_start(va
, format
);
1688 args
= Py_VaBuildValue(format
, va
);
1692 args
= PyTuple_New(0);
1697 if (!PyTuple_Check(args
)) {
1703 if (PyTuple_SetItem(a
, 0, args
) < 0)
1707 retval
= PyObject_CallObject(callable
, args
);
1715 PyObject_CallMethod(PyObject
*o
, char *name
, char *format
, ...)
1718 PyObject
*args
, *func
= 0, *retval
;
1720 if (o
== NULL
|| name
== NULL
)
1721 return null_error();
1723 func
= PyObject_GetAttrString(o
, name
);
1725 PyErr_SetString(PyExc_AttributeError
, name
);
1729 if (!PyCallable_Check(func
))
1730 return type_error("call of non-callable attribute");
1732 if (format
&& *format
) {
1733 va_start(va
, format
);
1734 args
= Py_VaBuildValue(format
, va
);
1738 args
= PyTuple_New(0);
1743 if (!PyTuple_Check(args
)) {
1749 if (PyTuple_SetItem(a
, 0, args
) < 0)
1754 retval
= PyObject_CallObject(func
, args
);
1764 objargs_mktuple(va_list va
)
1768 PyObject
*result
, *tmp
;
1770 #ifdef VA_LIST_IS_ARRAY
1771 memcpy(countva
, va
, sizeof(va_list));
1776 while (((PyObject
*)va_arg(countva
, PyObject
*)) != NULL
)
1778 result
= PyTuple_New(n
);
1779 if (result
!= NULL
&& n
> 0) {
1780 for (i
= 0; i
< n
; ++i
) {
1781 tmp
= (PyObject
*)va_arg(va
, PyObject
*);
1782 PyTuple_SET_ITEM(result
, i
, tmp
);
1790 PyObject_CallMethodObjArgs(PyObject
*callable
, PyObject
*name
, ...)
1792 PyObject
*args
, *tmp
;
1795 if (callable
== NULL
|| name
== NULL
)
1796 return null_error();
1798 callable
= PyObject_GetAttr(callable
, name
);
1799 if (callable
== NULL
)
1802 /* count the args */
1803 va_start(vargs
, name
);
1804 args
= objargs_mktuple(vargs
);
1807 Py_DECREF(callable
);
1810 tmp
= PyObject_Call(callable
, args
, NULL
);
1812 Py_DECREF(callable
);
1818 PyObject_CallFunctionObjArgs(PyObject
*callable
, ...)
1820 PyObject
*args
, *tmp
;
1823 if (callable
== NULL
)
1824 return null_error();
1826 /* count the args */
1827 va_start(vargs
, callable
);
1828 args
= objargs_mktuple(vargs
);
1832 tmp
= PyObject_Call(callable
, args
, NULL
);
1839 /* isinstance(), issubclass() */
1842 abstract_get_bases(PyObject
*cls
)
1844 static PyObject
*__bases__
= NULL
;
1847 if (__bases__
== NULL
) {
1848 __bases__
= PyString_FromString("__bases__");
1849 if (__bases__
== NULL
)
1853 bases
= PyObject_GetAttr(cls
, __bases__
);
1854 if (bases
== NULL
|| !PyTuple_Check(bases
)) {
1864 abstract_issubclass(PyObject
*derived
, PyObject
*cls
)
1874 bases
= abstract_get_bases(derived
);
1878 n
= PyTuple_GET_SIZE(bases
);
1879 for (i
= 0; i
< n
; i
++) {
1880 r
= abstract_issubclass(PyTuple_GET_ITEM(bases
, i
), cls
);
1891 PyObject_IsInstance(PyObject
*inst
, PyObject
*cls
)
1894 static PyObject
*__class__
= NULL
;
1897 if (PyClass_Check(cls
) && PyInstance_Check(inst
)) {
1899 (PyObject
*)((PyInstanceObject
*)inst
)->in_class
;
1900 retval
= PyClass_IsSubclass(inclass
, cls
);
1902 else if (PyType_Check(cls
)) {
1903 retval
= PyObject_TypeCheck(inst
, (PyTypeObject
*)cls
);
1905 else if (PyTuple_Check(cls
)) {
1906 /* Not a general sequence -- that opens up the road to
1907 recursion and stack overflow. */
1910 n
= PyTuple_GET_SIZE(cls
);
1911 for (i
= 0; i
< n
; i
++) {
1912 retval
= PyObject_IsInstance(
1913 inst
, PyTuple_GET_ITEM(cls
, i
));
1920 PyObject
*cls_bases
= abstract_get_bases(cls
);
1921 if (cls_bases
== NULL
) {
1922 PyErr_SetString(PyExc_TypeError
,
1923 "isinstance() arg 2 must be a class or type");
1926 Py_DECREF(cls_bases
);
1927 if (__class__
== NULL
) {
1928 __class__
= PyString_FromString("__class__");
1929 if (__class__
== NULL
)
1932 icls
= PyObject_GetAttr(inst
, __class__
);
1938 retval
= abstract_issubclass(icls
, cls
);
1947 PyObject_IsSubclass(PyObject
*derived
, PyObject
*cls
)
1951 if (!PyClass_Check(derived
) || !PyClass_Check(cls
)) {
1952 PyObject
*derived_bases
;
1953 PyObject
*cls_bases
;
1955 derived_bases
= abstract_get_bases(derived
);
1956 if (derived_bases
== NULL
) {
1957 PyErr_SetString(PyExc_TypeError
,
1958 "issubclass() arg 1 must be a class");
1961 Py_DECREF(derived_bases
);
1963 cls_bases
= abstract_get_bases(cls
);
1964 if (cls_bases
== NULL
) {
1965 PyErr_SetString(PyExc_TypeError
,
1966 "issubclass() arg 2 must be a class");
1969 Py_DECREF(cls_bases
);
1971 retval
= abstract_issubclass(derived
, cls
);
1975 if (!(retval
= (derived
== cls
)))
1976 retval
= PyClass_IsSubclass(derived
, cls
);
1983 PyObject_GetIter(PyObject
*o
)
1985 PyTypeObject
*t
= o
->ob_type
;
1986 getiterfunc f
= NULL
;
1987 if (PyType_HasFeature(t
, Py_TPFLAGS_HAVE_ITER
))
1990 if (PySequence_Check(o
))
1991 return PySeqIter_New(o
);
1992 PyErr_SetString(PyExc_TypeError
,
1993 "iteration over non-sequence");
1997 PyObject
*res
= (*f
)(o
);
1998 if (res
!= NULL
&& !PyIter_Check(res
)) {
1999 PyErr_Format(PyExc_TypeError
,
2000 "iter() returned non-iterator "
2002 res
->ob_type
->tp_name
);
2010 /* Return next item.
2011 * If an error occurs, return NULL. PyErr_Occurred() will be true.
2012 * If the iteration terminates normally, return NULL and clear the
2013 * PyExc_StopIteration exception (if it was set). PyErr_Occurred()
2015 * Else return the next object. PyErr_Occurred() will be false.
2018 PyIter_Next(PyObject
*iter
)
2021 if (!PyIter_Check(iter
)) {
2022 PyErr_Format(PyExc_TypeError
,
2023 "'%.100s' object is not an iterator",
2024 iter
->ob_type
->tp_name
);
2027 result
= (*iter
->ob_type
->tp_iternext
)(iter
);
2028 if (result
== NULL
&&
2030 PyErr_ExceptionMatches(PyExc_StopIteration
))