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");
178 PyObject_DelItemString(PyObject
*o
, char *key
)
183 if (o
== NULL
|| key
== NULL
) {
187 okey
= PyString_FromString(key
);
190 ret
= PyObject_DelItem(o
, okey
);
195 int PyObject_AsCharBuffer(PyObject
*obj
,
203 if (obj
== NULL
|| buffer
== NULL
|| buffer_len
== NULL
) {
207 pb
= obj
->ob_type
->tp_as_buffer
;
209 pb
->bf_getcharbuffer
== NULL
||
210 pb
->bf_getsegcount
== NULL
) {
211 PyErr_SetString(PyExc_TypeError
,
212 "expected a character buffer object");
215 if ((*pb
->bf_getsegcount
)(obj
,NULL
) != 1) {
216 PyErr_SetString(PyExc_TypeError
,
217 "expected a single-segment buffer object");
220 len
= (*pb
->bf_getcharbuffer
)(obj
, 0, &pp
);
229 PyObject_CheckReadBuffer(PyObject
*obj
)
231 PyBufferProcs
*pb
= obj
->ob_type
->tp_as_buffer
;
234 pb
->bf_getreadbuffer
== NULL
||
235 pb
->bf_getsegcount
== NULL
||
236 (*pb
->bf_getsegcount
)(obj
, NULL
) != 1)
241 int PyObject_AsReadBuffer(PyObject
*obj
,
249 if (obj
== NULL
|| buffer
== NULL
|| buffer_len
== NULL
) {
253 pb
= obj
->ob_type
->tp_as_buffer
;
255 pb
->bf_getreadbuffer
== NULL
||
256 pb
->bf_getsegcount
== NULL
) {
257 PyErr_SetString(PyExc_TypeError
,
258 "expected a readable buffer object");
261 if ((*pb
->bf_getsegcount
)(obj
, NULL
) != 1) {
262 PyErr_SetString(PyExc_TypeError
,
263 "expected a single-segment buffer object");
266 len
= (*pb
->bf_getreadbuffer
)(obj
, 0, &pp
);
274 int PyObject_AsWriteBuffer(PyObject
*obj
,
282 if (obj
== NULL
|| buffer
== NULL
|| buffer_len
== NULL
) {
286 pb
= obj
->ob_type
->tp_as_buffer
;
288 pb
->bf_getwritebuffer
== NULL
||
289 pb
->bf_getsegcount
== NULL
) {
290 PyErr_SetString(PyExc_TypeError
,
291 "expected a writeable buffer object");
294 if ((*pb
->bf_getsegcount
)(obj
, NULL
) != 1) {
295 PyErr_SetString(PyExc_TypeError
,
296 "expected a single-segment buffer object");
299 len
= (*pb
->bf_getwritebuffer
)(obj
,0,&pp
);
307 /* Operations on numbers */
310 PyNumber_Check(PyObject
*o
)
312 return o
&& o
->ob_type
->tp_as_number
;
315 /* Binary operators */
317 /* New style number protocol support */
319 #define NB_SLOT(x) offsetof(PyNumberMethods, x)
320 #define NB_BINOP(nb_methods, slot) \
321 ((binaryfunc*)(& ((char*)nb_methods)[slot] ))
322 #define NB_TERNOP(nb_methods, slot) \
323 ((ternaryfunc*)(& ((char*)nb_methods)[slot] ))
326 Calling scheme used for binary operations:
329 -------------------------------------------------------------------
330 new new w.op(v,w)[*], v.op(v,w), w.op(v,w)
331 new old v.op(v,w), coerce(v,w), v.op(v,w)
332 old new w.op(v,w), coerce(v,w), v.op(v,w)
333 old old coerce(v,w), v.op(v,w)
335 [*] only when v->ob_type != w->ob_type && w->ob_type is a subclass of
340 * new == new style number
341 * old == old style number
342 * Action indicates the order in which operations are tried until either
343 a valid result is produced or an error occurs.
348 binary_op1(PyObject
*v
, PyObject
*w
, const int op_slot
)
351 binaryfunc slotv
= NULL
;
352 binaryfunc slotw
= NULL
;
354 if (v
->ob_type
->tp_as_number
!= NULL
&& NEW_STYLE_NUMBER(v
))
355 slotv
= *NB_BINOP(v
->ob_type
->tp_as_number
, op_slot
);
356 if (w
->ob_type
!= v
->ob_type
&&
357 w
->ob_type
->tp_as_number
!= NULL
&& NEW_STYLE_NUMBER(w
)) {
358 slotw
= *NB_BINOP(w
->ob_type
->tp_as_number
, op_slot
);
363 if (slotw
&& PyType_IsSubtype(w
->ob_type
, v
->ob_type
)) {
365 if (x
!= Py_NotImplemented
)
367 Py_DECREF(x
); /* can't do it */
371 if (x
!= Py_NotImplemented
)
373 Py_DECREF(x
); /* can't do it */
377 if (x
!= Py_NotImplemented
)
379 Py_DECREF(x
); /* can't do it */
381 if (!NEW_STYLE_NUMBER(v
) || !NEW_STYLE_NUMBER(w
)) {
382 int err
= PyNumber_CoerceEx(&v
, &w
);
387 PyNumberMethods
*mv
= v
->ob_type
->tp_as_number
;
390 slot
= *NB_BINOP(mv
, op_slot
);
392 PyObject
*x
= slot(v
, w
);
398 /* CoerceEx incremented the reference counts */
403 Py_INCREF(Py_NotImplemented
);
404 return Py_NotImplemented
;
408 binary_op(PyObject
*v
, PyObject
*w
, const int op_slot
, const char *op_name
)
410 PyObject
*result
= binary_op1(v
, w
, op_slot
);
411 if (result
== Py_NotImplemented
) {
412 Py_DECREF(Py_NotImplemented
);
415 "unsupported operand type(s) for %s: '%s' and '%s'",
418 w
->ob_type
->tp_name
);
426 Calling scheme used for ternary operations:
428 *** In some cases, w.op is called before v.op; see binary_op1. ***
431 -------------------------------------------------------------------
432 new new new v.op(v,w,z), w.op(v,w,z), z.op(v,w,z)
433 new old new v.op(v,w,z), z.op(v,w,z), coerce(v,w,z), v.op(v,w,z)
434 old new new w.op(v,w,z), z.op(v,w,z), coerce(v,w,z), v.op(v,w,z)
435 old old new z.op(v,w,z), coerce(v,w,z), v.op(v,w,z)
436 new new old v.op(v,w,z), w.op(v,w,z), coerce(v,w,z), v.op(v,w,z)
437 new old old v.op(v,w,z), coerce(v,w,z), v.op(v,w,z)
438 old new old w.op(v,w,z), coerce(v,w,z), v.op(v,w,z)
439 old old old coerce(v,w,z), v.op(v,w,z)
443 * new == new style number
444 * old == old style number
445 * Action indicates the order in which operations are tried until either
446 a valid result is produced or an error occurs.
447 * coerce(v,w,z) actually does: coerce(v,w), coerce(v,z), coerce(w,z) and
448 only if z != Py_None; if z == Py_None, then it is treated as absent
449 variable and only coerce(v,w) is tried.
454 ternary_op(PyObject
*v
,
460 PyNumberMethods
*mv
, *mw
, *mz
;
462 ternaryfunc slotv
= NULL
;
463 ternaryfunc slotw
= NULL
;
464 ternaryfunc slotz
= NULL
;
466 mv
= v
->ob_type
->tp_as_number
;
467 mw
= w
->ob_type
->tp_as_number
;
468 if (mv
!= NULL
&& NEW_STYLE_NUMBER(v
))
469 slotv
= *NB_TERNOP(mv
, op_slot
);
470 if (w
->ob_type
!= v
->ob_type
&&
471 mv
!= NULL
&& NEW_STYLE_NUMBER(w
)) {
472 slotw
= *NB_TERNOP(mw
, op_slot
);
477 if (slotw
&& PyType_IsSubtype(w
->ob_type
, v
->ob_type
)) {
479 if (x
!= Py_NotImplemented
)
481 Py_DECREF(x
); /* can't do it */
485 if (x
!= Py_NotImplemented
)
487 Py_DECREF(x
); /* can't do it */
491 if (x
!= Py_NotImplemented
)
493 Py_DECREF(x
); /* can't do it */
495 mz
= z
->ob_type
->tp_as_number
;
496 if (mz
!= NULL
&& NEW_STYLE_NUMBER(z
)) {
497 slotz
= *NB_TERNOP(mz
, op_slot
);
498 if (slotz
== slotv
|| slotz
== slotw
)
502 if (x
!= Py_NotImplemented
)
504 Py_DECREF(x
); /* can't do it */
508 if (!NEW_STYLE_NUMBER(v
) || !NEW_STYLE_NUMBER(w
) ||
509 (z
!= Py_None
&& !NEW_STYLE_NUMBER(z
))) {
510 /* we have an old style operand, coerce */
511 PyObject
*v1
, *z1
, *w2
, *z2
;
514 c
= PyNumber_Coerce(&v
, &w
);
518 /* Special case: if the third argument is None, it is
519 treated as absent argument and not coerced. */
521 if (v
->ob_type
->tp_as_number
) {
522 slotz
= *NB_TERNOP(v
->ob_type
->tp_as_number
,
535 c
= PyNumber_Coerce(&v1
, &z1
);
540 c
= PyNumber_Coerce(&w2
, &z2
);
544 if (v1
->ob_type
->tp_as_number
!= NULL
) {
545 slotv
= *NB_TERNOP(v1
->ob_type
->tp_as_number
,
548 x
= slotv(v1
, w2
, z2
);
571 "unsupported operand type(s) for ** or pow(): "
574 w
->ob_type
->tp_name
);
578 "unsupported operand type(s) for pow(): "
582 z
->ob_type
->tp_name
);
586 #define BINARY_FUNC(func, op, op_name) \
588 func(PyObject *v, PyObject *w) { \
589 return binary_op(v, w, NB_SLOT(op), op_name); \
592 BINARY_FUNC(PyNumber_Or
, nb_or
, "|")
593 BINARY_FUNC(PyNumber_Xor
, nb_xor
, "^")
594 BINARY_FUNC(PyNumber_And
, nb_and
, "&")
595 BINARY_FUNC(PyNumber_Lshift
, nb_lshift
, "<<")
596 BINARY_FUNC(PyNumber_Rshift
, nb_rshift
, ">>")
597 BINARY_FUNC(PyNumber_Subtract
, nb_subtract
, "-")
598 BINARY_FUNC(PyNumber_Multiply
, nb_multiply
, "*")
599 BINARY_FUNC(PyNumber_Divide
, nb_divide
, "/")
600 BINARY_FUNC(PyNumber_Divmod
, nb_divmod
, "divmod()")
603 PyNumber_Add(PyObject
*v
, PyObject
*w
)
605 PyObject
*result
= binary_op1(v
, w
, NB_SLOT(nb_add
));
606 if (result
== Py_NotImplemented
) {
607 PySequenceMethods
*m
= v
->ob_type
->tp_as_sequence
;
608 if (m
&& m
->sq_concat
) {
610 result
= (*m
->sq_concat
)(v
, w
);
612 if (result
== Py_NotImplemented
) {
616 "unsupported operand types for +: '%s' and '%s'",
618 w
->ob_type
->tp_name
);
626 PyNumber_FloorDivide(PyObject
*v
, PyObject
*w
)
628 /* XXX tp_flags test */
629 return binary_op(v
, w
, NB_SLOT(nb_floor_divide
), "//");
633 PyNumber_TrueDivide(PyObject
*v
, PyObject
*w
)
635 /* XXX tp_flags test */
636 return binary_op(v
, w
, NB_SLOT(nb_true_divide
), "/");
640 PyNumber_Remainder(PyObject
*v
, PyObject
*w
)
642 if (PyString_Check(v
))
643 return PyString_Format(v
, w
);
644 #ifdef Py_USING_UNICODE
645 else if (PyUnicode_Check(v
))
646 return PyUnicode_Format(v
, w
);
648 return binary_op(v
, w
, NB_SLOT(nb_remainder
), "%");
652 PyNumber_Power(PyObject
*v
, PyObject
*w
, PyObject
*z
)
654 return ternary_op(v
, w
, z
, NB_SLOT(nb_power
), "** or pow()");
657 /* Binary in-place operators */
659 /* The in-place operators are defined to fall back to the 'normal',
660 non in-place operations, if the in-place methods are not in place.
662 - If the left hand object has the appropriate struct members, and
663 they are filled, call the appropriate function and return the
664 result. No coercion is done on the arguments; the left-hand object
665 is the one the operation is performed on, and it's up to the
666 function to deal with the right-hand object.
668 - Otherwise, in-place modification is not supported. Handle it exactly as
669 a non in-place operation of the same kind.
673 #define HASINPLACE(t) \
674 PyType_HasFeature((t)->ob_type, Py_TPFLAGS_HAVE_INPLACEOPS)
677 binary_iop(PyObject
*v
, PyObject
*w
, const int iop_slot
, const int op_slot
,
680 PyNumberMethods
*mv
= v
->ob_type
->tp_as_number
;
681 if (mv
!= NULL
&& HASINPLACE(v
)) {
682 binaryfunc
*slot
= NB_BINOP(mv
, iop_slot
);
684 PyObject
*x
= (*slot
)(v
, w
);
685 if (x
!= Py_NotImplemented
) {
691 return binary_op(v
, w
, op_slot
, op_name
);
694 #define INPLACE_BINOP(func, iop, op, op_name) \
696 func(PyObject *v, PyObject *w) { \
697 return binary_iop(v, w, NB_SLOT(iop), NB_SLOT(op), op_name); \
700 INPLACE_BINOP(PyNumber_InPlaceOr
, nb_inplace_or
, nb_or
, "|=")
701 INPLACE_BINOP(PyNumber_InPlaceXor
, nb_inplace_xor
, nb_xor
, "^=")
702 INPLACE_BINOP(PyNumber_InPlaceAnd
, nb_inplace_and
, nb_and
, "&=")
703 INPLACE_BINOP(PyNumber_InPlaceLshift
, nb_inplace_lshift
, nb_lshift
, "<<=")
704 INPLACE_BINOP(PyNumber_InPlaceRshift
, nb_inplace_rshift
, nb_rshift
, ">>=")
705 INPLACE_BINOP(PyNumber_InPlaceSubtract
, nb_inplace_subtract
, nb_subtract
, "-=")
706 INPLACE_BINOP(PyNumber_InPlaceDivide
, nb_inplace_divide
, nb_divide
, "/=")
709 PyNumber_InPlaceFloorDivide(PyObject
*v
, PyObject
*w
)
711 /* XXX tp_flags test */
712 return binary_iop(v
, w
, NB_SLOT(nb_inplace_floor_divide
),
713 NB_SLOT(nb_floor_divide
), "//=");
717 PyNumber_InPlaceTrueDivide(PyObject
*v
, PyObject
*w
)
719 /* XXX tp_flags test */
720 return binary_iop(v
, w
, NB_SLOT(nb_inplace_true_divide
),
721 NB_SLOT(nb_true_divide
), "/=");
725 PyNumber_InPlaceAdd(PyObject
*v
, PyObject
*w
)
729 if (v
->ob_type
->tp_as_sequence
!= NULL
) {
731 f
= v
->ob_type
->tp_as_sequence
->sq_inplace_concat
;
733 f
= v
->ob_type
->tp_as_sequence
->sq_concat
;
737 return binary_iop(v
, w
, NB_SLOT(nb_inplace_add
),
738 NB_SLOT(nb_add
), "+=");
742 PyNumber_InPlaceMultiply(PyObject
*v
, PyObject
*w
)
744 PyObject
* (*g
)(PyObject
*, int) = NULL
;
746 v
->ob_type
->tp_as_sequence
&&
747 (g
= v
->ob_type
->tp_as_sequence
->sq_inplace_repeat
) &&
748 !(v
->ob_type
->tp_as_number
&&
749 v
->ob_type
->tp_as_number
->nb_inplace_multiply
))
752 if (PyInt_Check(w
)) {
755 else if (PyLong_Check(w
)) {
756 n
= PyLong_AsLong(w
);
757 if (n
== -1 && PyErr_Occurred())
762 "can't multiply sequence to non-int");
764 return (*g
)(v
, (int)n
);
766 return binary_iop(v
, w
, NB_SLOT(nb_inplace_multiply
),
767 NB_SLOT(nb_multiply
), "*=");
771 PyNumber_InPlaceRemainder(PyObject
*v
, PyObject
*w
)
773 if (PyString_Check(v
))
774 return PyString_Format(v
, w
);
775 #ifdef Py_USING_UNICODE
776 else if (PyUnicode_Check(v
))
777 return PyUnicode_Format(v
, w
);
780 return binary_iop(v
, w
, NB_SLOT(nb_inplace_remainder
),
781 NB_SLOT(nb_remainder
), "%=");
785 PyNumber_InPlacePower(PyObject
*v
, PyObject
*w
, PyObject
*z
)
787 if (HASINPLACE(v
) && v
->ob_type
->tp_as_number
&&
788 v
->ob_type
->tp_as_number
->nb_inplace_power
!= NULL
) {
789 return ternary_op(v
, w
, z
, NB_SLOT(nb_inplace_power
), "**=");
792 return ternary_op(v
, w
, z
, NB_SLOT(nb_power
), "**=");
797 /* Unary operators and functions */
800 PyNumber_Negative(PyObject
*o
)
806 m
= o
->ob_type
->tp_as_number
;
807 if (m
&& m
->nb_negative
)
808 return (*m
->nb_negative
)(o
);
810 return type_error("bad operand type for unary -");
814 PyNumber_Positive(PyObject
*o
)
820 m
= o
->ob_type
->tp_as_number
;
821 if (m
&& m
->nb_positive
)
822 return (*m
->nb_positive
)(o
);
824 return type_error("bad operand type for unary +");
828 PyNumber_Invert(PyObject
*o
)
834 m
= o
->ob_type
->tp_as_number
;
835 if (m
&& m
->nb_invert
)
836 return (*m
->nb_invert
)(o
);
838 return type_error("bad operand type for unary ~");
842 PyNumber_Absolute(PyObject
*o
)
848 m
= o
->ob_type
->tp_as_number
;
849 if (m
&& m
->nb_absolute
)
850 return m
->nb_absolute(o
);
852 return type_error("bad operand type for abs()");
855 /* Add a check for embedded NULL-bytes in the argument. */
857 int_from_string(const char *s
, int len
)
862 x
= PyInt_FromString((char*)s
, &end
, 10);
865 if (end
!= s
+ len
) {
866 PyErr_SetString(PyExc_ValueError
,
867 "null byte in argument for int()");
875 PyNumber_Int(PyObject
*o
)
883 if (PyInt_CheckExact(o
)) {
887 if (PyInt_Check(o
)) {
888 PyIntObject
*io
= (PyIntObject
*)o
;
889 return PyInt_FromLong(io
->ob_ival
);
891 if (PyString_Check(o
))
892 return int_from_string(PyString_AS_STRING(o
),
893 PyString_GET_SIZE(o
));
894 #ifdef Py_USING_UNICODE
895 if (PyUnicode_Check(o
))
896 return PyInt_FromUnicode(PyUnicode_AS_UNICODE(o
),
897 PyUnicode_GET_SIZE(o
),
900 m
= o
->ob_type
->tp_as_number
;
903 if (!PyObject_AsCharBuffer(o
, &buffer
, &buffer_len
))
904 return int_from_string((char*)buffer
, buffer_len
);
906 return type_error("int() argument must be a string or a number");
909 /* Add a check for embedded NULL-bytes in the argument. */
911 long_from_string(const char *s
, int len
)
916 x
= PyLong_FromString((char*)s
, &end
, 10);
919 if (end
!= s
+ len
) {
920 PyErr_SetString(PyExc_ValueError
,
921 "null byte in argument for long()");
929 PyNumber_Long(PyObject
*o
)
937 if (PyLong_CheckExact(o
)) {
942 return _PyLong_Copy((PyLongObject
*)o
);
943 if (PyString_Check(o
))
944 /* need to do extra error checking that PyLong_FromString()
945 * doesn't do. In particular long('9.5') must raise an
946 * exception, not truncate the float.
948 return long_from_string(PyString_AS_STRING(o
),
949 PyString_GET_SIZE(o
));
950 #ifdef Py_USING_UNICODE
951 if (PyUnicode_Check(o
))
952 /* The above check is done in PyLong_FromUnicode(). */
953 return PyLong_FromUnicode(PyUnicode_AS_UNICODE(o
),
954 PyUnicode_GET_SIZE(o
),
957 m
= o
->ob_type
->tp_as_number
;
959 return m
->nb_long(o
);
960 if (!PyObject_AsCharBuffer(o
, &buffer
, &buffer_len
))
961 return long_from_string(buffer
, buffer_len
);
963 return type_error("long() argument must be a string or a number");
967 PyNumber_Float(PyObject
*o
)
973 if (PyFloat_CheckExact(o
)) {
977 if (PyFloat_Check(o
)) {
978 PyFloatObject
*po
= (PyFloatObject
*)o
;
979 return PyFloat_FromDouble(po
->ob_fval
);
981 if (!PyString_Check(o
)) {
982 m
= o
->ob_type
->tp_as_number
;
983 if (m
&& m
->nb_float
)
984 return m
->nb_float(o
);
986 return PyFloat_FromString(o
, NULL
);
989 /* Operations on sequences */
992 PySequence_Check(PyObject
*s
)
994 return s
!= NULL
&& s
->ob_type
->tp_as_sequence
&&
995 s
->ob_type
->tp_as_sequence
->sq_item
!= NULL
;
999 PySequence_Size(PyObject
*s
)
1001 PySequenceMethods
*m
;
1008 m
= s
->ob_type
->tp_as_sequence
;
1009 if (m
&& m
->sq_length
)
1010 return m
->sq_length(s
);
1012 type_error("len() of unsized object");
1016 #undef PySequence_Length
1018 PySequence_Length(PyObject
*s
)
1020 return PySequence_Size(s
);
1022 #define PySequence_Length PySequence_Size
1025 PySequence_Concat(PyObject
*s
, PyObject
*o
)
1027 PySequenceMethods
*m
;
1029 if (s
== NULL
|| o
== NULL
)
1030 return null_error();
1032 m
= s
->ob_type
->tp_as_sequence
;
1033 if (m
&& m
->sq_concat
)
1034 return m
->sq_concat(s
, o
);
1036 return type_error("object can't be concatenated");
1040 PySequence_Repeat(PyObject
*o
, int count
)
1042 PySequenceMethods
*m
;
1045 return null_error();
1047 m
= o
->ob_type
->tp_as_sequence
;
1048 if (m
&& m
->sq_repeat
)
1049 return m
->sq_repeat(o
, count
);
1051 return type_error("object can't be repeated");
1055 PySequence_InPlaceConcat(PyObject
*s
, PyObject
*o
)
1057 PySequenceMethods
*m
;
1059 if (s
== NULL
|| o
== NULL
)
1060 return null_error();
1062 m
= s
->ob_type
->tp_as_sequence
;
1063 if (m
&& HASINPLACE(s
) && m
->sq_inplace_concat
)
1064 return m
->sq_inplace_concat(s
, o
);
1065 if (m
&& m
->sq_concat
)
1066 return m
->sq_concat(s
, o
);
1068 return type_error("object can't be concatenated");
1072 PySequence_InPlaceRepeat(PyObject
*o
, int count
)
1074 PySequenceMethods
*m
;
1077 return null_error();
1079 m
= o
->ob_type
->tp_as_sequence
;
1080 if (m
&& HASINPLACE(o
) && m
->sq_inplace_repeat
)
1081 return m
->sq_inplace_repeat(o
, count
);
1082 if (m
&& m
->sq_repeat
)
1083 return m
->sq_repeat(o
, count
);
1085 return type_error("object can't be repeated");
1089 PySequence_GetItem(PyObject
*s
, int i
)
1091 PySequenceMethods
*m
;
1094 return null_error();
1096 m
= s
->ob_type
->tp_as_sequence
;
1097 if (m
&& m
->sq_item
) {
1100 int l
= (*m
->sq_length
)(s
);
1106 return m
->sq_item(s
, i
);
1109 return type_error("unindexable object");
1113 sliceobj_from_intint(int i
, int j
)
1115 PyObject
*start
, *end
, *slice
;
1116 start
= PyInt_FromLong((long)i
);
1119 end
= PyInt_FromLong((long)j
);
1124 slice
= PySlice_New(start
, end
, NULL
);
1131 PySequence_GetSlice(PyObject
*s
, int i1
, int i2
)
1133 PySequenceMethods
*m
;
1134 PyMappingMethods
*mp
;
1136 if (!s
) return null_error();
1138 m
= s
->ob_type
->tp_as_sequence
;
1139 if (m
&& m
->sq_slice
) {
1140 if (i1
< 0 || i2
< 0) {
1142 int l
= (*m
->sq_length
)(s
);
1151 return m
->sq_slice(s
, i1
, i2
);
1152 } else if ((mp
= s
->ob_type
->tp_as_mapping
) && mp
->mp_subscript
) {
1154 PyObject
*slice
= sliceobj_from_intint(i1
, i2
);
1157 res
= mp
->mp_subscript(s
, slice
);
1162 return type_error("unsliceable object");
1166 PySequence_SetItem(PyObject
*s
, int i
, PyObject
*o
)
1168 PySequenceMethods
*m
;
1175 m
= s
->ob_type
->tp_as_sequence
;
1176 if (m
&& m
->sq_ass_item
) {
1179 int l
= (*m
->sq_length
)(s
);
1185 return m
->sq_ass_item(s
, i
, o
);
1188 type_error("object doesn't support item assignment");
1193 PySequence_DelItem(PyObject
*s
, int i
)
1195 PySequenceMethods
*m
;
1202 m
= s
->ob_type
->tp_as_sequence
;
1203 if (m
&& m
->sq_ass_item
) {
1206 int l
= (*m
->sq_length
)(s
);
1212 return m
->sq_ass_item(s
, i
, (PyObject
*)NULL
);
1215 type_error("object doesn't support item deletion");
1220 PySequence_SetSlice(PyObject
*s
, int i1
, int i2
, PyObject
*o
)
1222 PySequenceMethods
*m
;
1223 PyMappingMethods
*mp
;
1230 m
= s
->ob_type
->tp_as_sequence
;
1231 if (m
&& m
->sq_ass_slice
) {
1232 if (i1
< 0 || i2
< 0) {
1234 int l
= (*m
->sq_length
)(s
);
1243 return m
->sq_ass_slice(s
, i1
, i2
, o
);
1244 } else if ((mp
= s
->ob_type
->tp_as_mapping
) && mp
->mp_ass_subscript
) {
1246 PyObject
*slice
= sliceobj_from_intint(i1
, i2
);
1249 res
= mp
->mp_ass_subscript(s
, slice
, o
);
1254 type_error("object doesn't support slice assignment");
1259 PySequence_DelSlice(PyObject
*s
, int i1
, int i2
)
1261 PySequenceMethods
*m
;
1268 m
= s
->ob_type
->tp_as_sequence
;
1269 if (m
&& m
->sq_ass_slice
) {
1270 if (i1
< 0 || i2
< 0) {
1272 int l
= (*m
->sq_length
)(s
);
1281 return m
->sq_ass_slice(s
, i1
, i2
, (PyObject
*)NULL
);
1283 type_error("object doesn't support slice deletion");
1288 PySequence_Tuple(PyObject
*v
)
1290 PyObject
*it
; /* iter(v) */
1291 int n
; /* guess for result tuple size */
1296 return null_error();
1298 /* Special-case the common tuple and list cases, for efficiency. */
1299 if (PyTuple_CheckExact(v
)) {
1300 /* Note that we can't know whether it's safe to return
1301 a tuple *subclass* instance as-is, hence the restriction
1302 to exact tuples here. In contrast, lists always make
1303 a copy, so there's no need for exactness below. */
1307 if (PyList_Check(v
))
1308 return PyList_AsTuple(v
);
1311 it
= PyObject_GetIter(v
);
1315 /* Guess result size and allocate space. */
1316 n
= PySequence_Size(v
);
1319 n
= 10; /* arbitrary */
1321 result
= PyTuple_New(n
);
1325 /* Fill the tuple. */
1326 for (j
= 0; ; ++j
) {
1327 PyObject
*item
= PyIter_Next(it
);
1329 if (PyErr_Occurred())
1338 if (_PyTuple_Resize(&result
, n
) != 0) {
1343 PyTuple_SET_ITEM(result
, j
, item
);
1346 /* Cut tuple back if guess was too large. */
1348 _PyTuple_Resize(&result
, j
) != 0)
1361 PySequence_List(PyObject
*v
)
1363 PyObject
*it
; /* iter(v) */
1364 PyObject
*result
; /* result list */
1365 int n
; /* guess for result list size */
1369 return null_error();
1371 /* Special-case list(a_list), for speed. */
1372 if (PyList_Check(v
))
1373 return PyList_GetSlice(v
, 0, PyList_GET_SIZE(v
));
1375 /* Get iterator. There may be some low-level efficiency to be gained
1376 * by caching the tp_iternext slot instead of using PyIter_Next()
1377 * later, but premature optimization is the root etc.
1379 it
= PyObject_GetIter(v
);
1383 /* Guess a result list size. */
1384 n
= -1; /* unknown */
1385 if (PySequence_Check(v
) &&
1386 v
->ob_type
->tp_as_sequence
->sq_length
) {
1387 n
= PySequence_Size(v
);
1392 n
= 8; /* arbitrary */
1393 result
= PyList_New(n
);
1394 if (result
== NULL
) {
1399 /* Run iterator to exhaustion. */
1400 for (i
= 0; ; i
++) {
1401 PyObject
*item
= PyIter_Next(it
);
1403 if (PyErr_Occurred()) {
1410 PyList_SET_ITEM(result
, i
, item
); /* steals ref */
1412 int status
= PyList_Append(result
, item
);
1413 Py_DECREF(item
); /* append creates a new ref */
1422 /* Cut back result list if initial guess was too large. */
1423 if (i
< n
&& result
!= NULL
) {
1424 if (PyList_SetSlice(result
, i
, n
, (PyObject
*)NULL
) != 0) {
1434 PySequence_Fast(PyObject
*v
, const char *m
)
1437 return null_error();
1439 if (PyList_Check(v
) || PyTuple_Check(v
)) {
1444 v
= PySequence_Tuple(v
);
1445 if (v
== NULL
&& PyErr_ExceptionMatches(PyExc_TypeError
))
1446 return type_error(m
);
1451 /* Iterate over seq. Result depends on the operation:
1452 PY_ITERSEARCH_COUNT: -1 if error, else # of times obj appears in seq.
1453 PY_ITERSEARCH_INDEX: 0-based index of first occurence of obj in seq;
1454 set ValueError and return -1 if none found; also return -1 on error.
1455 Py_ITERSEARCH_CONTAINS: return 1 if obj in seq, else 0; -1 on error.
1458 _PySequence_IterSearch(PyObject
*seq
, PyObject
*obj
, int operation
)
1461 int wrapped
; /* for PY_ITERSEARCH_INDEX, true iff n wrapped around */
1462 PyObject
*it
; /* iter(seq) */
1464 if (seq
== NULL
|| obj
== NULL
) {
1469 it
= PyObject_GetIter(seq
);
1471 type_error("iterable argument required");
1478 PyObject
*item
= PyIter_Next(it
);
1480 if (PyErr_Occurred())
1485 cmp
= PyObject_RichCompareBool(obj
, item
, Py_EQ
);
1490 switch (operation
) {
1491 case PY_ITERSEARCH_COUNT
:
1494 PyErr_SetString(PyExc_OverflowError
,
1495 "count exceeds C int size");
1500 case PY_ITERSEARCH_INDEX
:
1502 PyErr_SetString(PyExc_OverflowError
,
1503 "index exceeds C int size");
1508 case PY_ITERSEARCH_CONTAINS
:
1513 assert(!"unknown operation");
1517 if (operation
== PY_ITERSEARCH_INDEX
) {
1524 if (operation
!= PY_ITERSEARCH_INDEX
)
1527 PyErr_SetString(PyExc_ValueError
,
1528 "sequence.index(x): x not in sequence");
1529 /* fall into failure code */
1539 /* Return # of times o appears in s. */
1541 PySequence_Count(PyObject
*s
, PyObject
*o
)
1543 return _PySequence_IterSearch(s
, o
, PY_ITERSEARCH_COUNT
);
1546 /* Return -1 if error; 1 if ob in seq; 0 if ob not in seq.
1547 * Use sq_contains if possible, else defer to _PySequence_IterSearch().
1550 PySequence_Contains(PyObject
*seq
, PyObject
*ob
)
1552 if (PyType_HasFeature(seq
->ob_type
, Py_TPFLAGS_HAVE_SEQUENCE_IN
)) {
1553 PySequenceMethods
*sqm
= seq
->ob_type
->tp_as_sequence
;
1554 if (sqm
!= NULL
&& sqm
->sq_contains
!= NULL
)
1555 return (*sqm
->sq_contains
)(seq
, ob
);
1557 return _PySequence_IterSearch(seq
, ob
, PY_ITERSEARCH_CONTAINS
);
1560 /* Backwards compatibility */
1561 #undef PySequence_In
1563 PySequence_In(PyObject
*w
, PyObject
*v
)
1565 return PySequence_Contains(w
, v
);
1569 PySequence_Index(PyObject
*s
, PyObject
*o
)
1571 return _PySequence_IterSearch(s
, o
, PY_ITERSEARCH_INDEX
);
1574 /* Operations on mappings */
1577 PyMapping_Check(PyObject
*o
)
1579 return o
&& o
->ob_type
->tp_as_mapping
&&
1580 o
->ob_type
->tp_as_mapping
->mp_subscript
;
1584 PyMapping_Size(PyObject
*o
)
1586 PyMappingMethods
*m
;
1593 m
= o
->ob_type
->tp_as_mapping
;
1594 if (m
&& m
->mp_length
)
1595 return m
->mp_length(o
);
1597 type_error("len() of unsized object");
1601 #undef PyMapping_Length
1603 PyMapping_Length(PyObject
*o
)
1605 return PyMapping_Size(o
);
1607 #define PyMapping_Length PyMapping_Size
1610 PyMapping_GetItemString(PyObject
*o
, char *key
)
1615 return null_error();
1617 okey
= PyString_FromString(key
);
1620 r
= PyObject_GetItem(o
, okey
);
1626 PyMapping_SetItemString(PyObject
*o
, char *key
, PyObject
*value
)
1636 okey
= PyString_FromString(key
);
1639 r
= PyObject_SetItem(o
, okey
, value
);
1645 PyMapping_HasKeyString(PyObject
*o
, char *key
)
1649 v
= PyMapping_GetItemString(o
, key
);
1659 PyMapping_HasKey(PyObject
*o
, PyObject
*key
)
1663 v
= PyObject_GetItem(o
, key
);
1672 /* Operations on callable objects */
1674 /* XXX PyCallable_Check() is in object.c */
1677 PyObject_CallObject(PyObject
*o
, PyObject
*a
)
1679 return PyEval_CallObjectWithKeywords(o
, a
, NULL
);
1683 PyObject_Call(PyObject
*func
, PyObject
*arg
, PyObject
*kw
)
1687 if ((call
= func
->ob_type
->tp_call
) != NULL
) {
1688 PyObject
*result
= (*call
)(func
, arg
, kw
);
1689 if (result
== NULL
&& !PyErr_Occurred())
1692 "NULL result without error in PyObject_Call");
1695 PyErr_Format(PyExc_TypeError
, "'%s' object is not callable",
1696 func
->ob_type
->tp_name
);
1701 PyObject_CallFunction(PyObject
*callable
, char *format
, ...)
1704 PyObject
*args
, *retval
;
1706 if (callable
== NULL
)
1707 return null_error();
1709 if (format
&& *format
) {
1710 va_start(va
, format
);
1711 args
= Py_VaBuildValue(format
, va
);
1715 args
= PyTuple_New(0);
1720 if (!PyTuple_Check(args
)) {
1726 if (PyTuple_SetItem(a
, 0, args
) < 0)
1730 retval
= PyObject_Call(callable
, args
, NULL
);
1738 PyObject_CallMethod(PyObject
*o
, char *name
, char *format
, ...)
1741 PyObject
*args
, *func
= 0, *retval
;
1743 if (o
== NULL
|| name
== NULL
)
1744 return null_error();
1746 func
= PyObject_GetAttrString(o
, name
);
1748 PyErr_SetString(PyExc_AttributeError
, name
);
1752 if (!PyCallable_Check(func
))
1753 return type_error("call of non-callable attribute");
1755 if (format
&& *format
) {
1756 va_start(va
, format
);
1757 args
= Py_VaBuildValue(format
, va
);
1761 args
= PyTuple_New(0);
1766 if (!PyTuple_Check(args
)) {
1772 if (PyTuple_SetItem(a
, 0, args
) < 0)
1777 retval
= PyObject_Call(func
, args
, NULL
);
1787 objargs_mktuple(va_list va
)
1791 PyObject
*result
, *tmp
;
1793 #ifdef VA_LIST_IS_ARRAY
1794 memcpy(countva
, va
, sizeof(va_list));
1797 __va_copy(countva
, va
);
1803 while (((PyObject
*)va_arg(countva
, PyObject
*)) != NULL
)
1805 result
= PyTuple_New(n
);
1806 if (result
!= NULL
&& n
> 0) {
1807 for (i
= 0; i
< n
; ++i
) {
1808 tmp
= (PyObject
*)va_arg(va
, PyObject
*);
1809 PyTuple_SET_ITEM(result
, i
, tmp
);
1817 PyObject_CallMethodObjArgs(PyObject
*callable
, PyObject
*name
, ...)
1819 PyObject
*args
, *tmp
;
1822 if (callable
== NULL
|| name
== NULL
)
1823 return null_error();
1825 callable
= PyObject_GetAttr(callable
, name
);
1826 if (callable
== NULL
)
1829 /* count the args */
1830 va_start(vargs
, name
);
1831 args
= objargs_mktuple(vargs
);
1834 Py_DECREF(callable
);
1837 tmp
= PyObject_Call(callable
, args
, NULL
);
1839 Py_DECREF(callable
);
1845 PyObject_CallFunctionObjArgs(PyObject
*callable
, ...)
1847 PyObject
*args
, *tmp
;
1850 if (callable
== NULL
)
1851 return null_error();
1853 /* count the args */
1854 va_start(vargs
, callable
);
1855 args
= objargs_mktuple(vargs
);
1859 tmp
= PyObject_Call(callable
, args
, NULL
);
1866 /* isinstance(), issubclass() */
1868 /* abstract_get_bases() has logically 4 return states, with a sort of 0th
1869 * state that will almost never happen.
1871 * 0. creating the __bases__ static string could get a MemoryError
1872 * 1. getattr(cls, '__bases__') could raise an AttributeError
1873 * 2. getattr(cls, '__bases__') could raise some other exception
1874 * 3. getattr(cls, '__bases__') could return a tuple
1875 * 4. getattr(cls, '__bases__') could return something other than a tuple
1877 * Only state #3 is a non-error state and only it returns a non-NULL object
1878 * (it returns the retrieved tuple).
1880 * Any raised AttributeErrors are masked by clearing the exception and
1881 * returning NULL. If an object other than a tuple comes out of __bases__,
1882 * then again, the return value is NULL. So yes, these two situations
1883 * produce exactly the same results: NULL is returned and no error is set.
1885 * If some exception other than AttributeError is raised, then NULL is also
1886 * returned, but the exception is not cleared. That's because we want the
1887 * exception to be propagated along.
1889 * Callers are expected to test for PyErr_Occurred() when the return value
1890 * is NULL to decide whether a valid exception should be propagated or not.
1891 * When there's no exception to propagate, it's customary for the caller to
1895 abstract_get_bases(PyObject
*cls
)
1897 static PyObject
*__bases__
= NULL
;
1900 if (__bases__
== NULL
) {
1901 __bases__
= PyString_FromString("__bases__");
1902 if (__bases__
== NULL
)
1905 bases
= PyObject_GetAttr(cls
, __bases__
);
1906 if (bases
== NULL
) {
1907 if (PyErr_ExceptionMatches(PyExc_AttributeError
))
1911 if (!PyTuple_Check(bases
)) {
1920 abstract_issubclass(PyObject
*derived
, PyObject
*cls
)
1930 bases
= abstract_get_bases(derived
);
1931 if (bases
== NULL
) {
1932 if (PyErr_Occurred())
1936 n
= PyTuple_GET_SIZE(bases
);
1937 for (i
= 0; i
< n
; i
++) {
1938 r
= abstract_issubclass(PyTuple_GET_ITEM(bases
, i
), cls
);
1949 PyObject_IsInstance(PyObject
*inst
, PyObject
*cls
)
1952 static PyObject
*__class__
= NULL
;
1955 if (PyClass_Check(cls
) && PyInstance_Check(inst
)) {
1957 (PyObject
*)((PyInstanceObject
*)inst
)->in_class
;
1958 retval
= PyClass_IsSubclass(inclass
, cls
);
1960 else if (PyType_Check(cls
)) {
1961 retval
= PyObject_TypeCheck(inst
, (PyTypeObject
*)cls
);
1963 else if (PyTuple_Check(cls
)) {
1964 /* Not a general sequence -- that opens up the road to
1965 recursion and stack overflow. */
1968 n
= PyTuple_GET_SIZE(cls
);
1969 for (i
= 0; i
< n
; i
++) {
1970 retval
= PyObject_IsInstance(
1971 inst
, PyTuple_GET_ITEM(cls
, i
));
1978 PyObject
*cls_bases
= abstract_get_bases(cls
);
1979 if (cls_bases
== NULL
) {
1980 /* Do not mask errors. */
1981 if (!PyErr_Occurred())
1982 PyErr_SetString(PyExc_TypeError
,
1983 "isinstance() arg 2 must be a class, type,"
1984 " or tuple of classes and types");
1987 Py_DECREF(cls_bases
);
1988 if (__class__
== NULL
) {
1989 __class__
= PyString_FromString("__class__");
1990 if (__class__
== NULL
)
1993 icls
= PyObject_GetAttr(inst
, __class__
);
1999 retval
= abstract_issubclass(icls
, cls
);
2008 PyObject_IsSubclass(PyObject
*derived
, PyObject
*cls
)
2012 if (!PyClass_Check(derived
) || !PyClass_Check(cls
)) {
2013 PyObject
*derived_bases
;
2014 PyObject
*cls_bases
;
2016 derived_bases
= abstract_get_bases(derived
);
2017 if (derived_bases
== NULL
) {
2018 /* Do not mask errors */
2019 if (!PyErr_Occurred())
2020 PyErr_SetString(PyExc_TypeError
,
2021 "issubclass() arg 1 must be a class");
2024 Py_DECREF(derived_bases
);
2026 cls_bases
= abstract_get_bases(cls
);
2027 if (cls_bases
== NULL
) {
2028 /* Do not mask errors */
2029 if (!PyErr_Occurred())
2030 PyErr_SetString(PyExc_TypeError
,
2031 "issubclass() arg 2 must be a class");
2034 Py_DECREF(cls_bases
);
2036 retval
= abstract_issubclass(derived
, cls
);
2040 if (!(retval
= (derived
== cls
)))
2041 retval
= PyClass_IsSubclass(derived
, cls
);
2048 PyObject_GetIter(PyObject
*o
)
2050 PyTypeObject
*t
= o
->ob_type
;
2051 getiterfunc f
= NULL
;
2052 if (PyType_HasFeature(t
, Py_TPFLAGS_HAVE_ITER
))
2055 if (PySequence_Check(o
))
2056 return PySeqIter_New(o
);
2057 PyErr_SetString(PyExc_TypeError
,
2058 "iteration over non-sequence");
2062 PyObject
*res
= (*f
)(o
);
2063 if (res
!= NULL
&& !PyIter_Check(res
)) {
2064 PyErr_Format(PyExc_TypeError
,
2065 "iter() returned non-iterator "
2067 res
->ob_type
->tp_name
);
2075 /* Return next item.
2076 * If an error occurs, return NULL. PyErr_Occurred() will be true.
2077 * If the iteration terminates normally, return NULL and clear the
2078 * PyExc_StopIteration exception (if it was set). PyErr_Occurred()
2080 * Else return the next object. PyErr_Occurred() will be false.
2083 PyIter_Next(PyObject
*iter
)
2086 if (!PyIter_Check(iter
)) {
2087 PyErr_Format(PyExc_TypeError
,
2088 "'%.100s' object is not an iterator",
2089 iter
->ob_type
->tp_name
);
2092 result
= (*iter
->ob_type
->tp_iternext
)(iter
);
2093 if (result
== NULL
&&
2095 PyErr_ExceptionMatches(PyExc_StopIteration
))