1 /* Abstract Object Interface (many thanks to Jim Fulton) */
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, \
11 #define HASINDEX(o) PyType_HasFeature((o)->ob_type, Py_TPFLAGS_HAVE_INDEX)
14 /* Shorthands to return certain errors */
17 type_error(const char *msg
, PyObject
*obj
)
19 PyErr_Format(PyExc_TypeError
, msg
, obj
->ob_type
->tp_name
);
26 if (!PyErr_Occurred())
27 PyErr_SetString(PyExc_SystemError
,
28 "null argument to internal routine");
32 /* Operations on any object */
35 PyObject_Cmp(PyObject
*o1
, PyObject
*o2
, int *result
)
39 if (o1
== NULL
|| o2
== NULL
) {
43 r
= PyObject_Compare(o1
, o2
);
51 PyObject_Type(PyObject
*o
)
57 v
= (PyObject
*)o
->ob_type
;
63 PyObject_Size(PyObject
*o
)
72 m
= o
->ob_type
->tp_as_sequence
;
73 if (m
&& m
->sq_length
)
74 return m
->sq_length(o
);
76 return PyMapping_Size(o
);
79 #undef PyObject_Length
81 PyObject_Length(PyObject
*o
)
83 return PyObject_Size(o
);
85 #define PyObject_Length PyObject_Size
88 _PyObject_LengthHint(PyObject
*o
)
90 Py_ssize_t rv
= PyObject_Size(o
);
93 if (PyErr_ExceptionMatches(PyExc_TypeError
) ||
94 PyErr_ExceptionMatches(PyExc_AttributeError
)) {
95 PyObject
*err_type
, *err_value
, *err_tb
, *ro
;
97 PyErr_Fetch(&err_type
, &err_value
, &err_tb
);
98 ro
= PyObject_CallMethod(o
, "__length_hint__", NULL
);
100 rv
= PyInt_AsLong(ro
);
102 Py_XDECREF(err_type
);
103 Py_XDECREF(err_value
);
107 PyErr_Restore(err_type
, err_value
, err_tb
);
113 PyObject_GetItem(PyObject
*o
, PyObject
*key
)
117 if (o
== NULL
|| key
== NULL
)
120 m
= o
->ob_type
->tp_as_mapping
;
121 if (m
&& m
->mp_subscript
)
122 return m
->mp_subscript(o
, key
);
124 if (o
->ob_type
->tp_as_sequence
) {
125 PyNumberMethods
*nb
= key
->ob_type
->tp_as_number
;
126 if (nb
!= NULL
&& HASINDEX(key
) && nb
->nb_index
!= NULL
) {
127 Py_ssize_t key_value
= nb
->nb_index(key
);
128 if (key_value
== -1 && PyErr_Occurred())
130 return PySequence_GetItem(o
, key_value
);
132 else if (o
->ob_type
->tp_as_sequence
->sq_item
)
133 return type_error("sequence index must "
134 "be integer, not '%.200s'", key
);
137 return type_error("'%.200s' object is unsubscriptable", o
);
141 PyObject_SetItem(PyObject
*o
, PyObject
*key
, PyObject
*value
)
145 if (o
== NULL
|| key
== NULL
|| value
== NULL
) {
149 m
= o
->ob_type
->tp_as_mapping
;
150 if (m
&& m
->mp_ass_subscript
)
151 return m
->mp_ass_subscript(o
, key
, value
);
153 if (o
->ob_type
->tp_as_sequence
) {
154 PyNumberMethods
*nb
= key
->ob_type
->tp_as_number
;
155 if (nb
!= NULL
&& HASINDEX(key
) && nb
->nb_index
!= NULL
) {
156 Py_ssize_t key_value
= nb
->nb_index(key
);
157 if (key_value
== -1 && PyErr_Occurred())
159 return PySequence_SetItem(o
, key_value
, value
);
161 else if (o
->ob_type
->tp_as_sequence
->sq_ass_item
) {
162 type_error("sequence index must be "
163 "integer, not '%.200s'", key
);
168 type_error("'%.200s' object does not support item assignment", o
);
173 PyObject_DelItem(PyObject
*o
, PyObject
*key
)
177 if (o
== NULL
|| key
== NULL
) {
181 m
= o
->ob_type
->tp_as_mapping
;
182 if (m
&& m
->mp_ass_subscript
)
183 return m
->mp_ass_subscript(o
, key
, (PyObject
*)NULL
);
185 if (o
->ob_type
->tp_as_sequence
) {
186 PyNumberMethods
*nb
= key
->ob_type
->tp_as_number
;
187 if (nb
!= NULL
&& HASINDEX(key
) && nb
->nb_index
!= NULL
) {
188 Py_ssize_t key_value
= nb
->nb_index(key
);
189 if (key_value
== -1 && PyErr_Occurred())
191 return PySequence_DelItem(o
, key_value
);
193 else if (o
->ob_type
->tp_as_sequence
->sq_ass_item
) {
194 type_error("sequence index must be "
195 "integer, not '%.200s'", key
);
200 type_error("'%.200s' object does not support item deletion", o
);
205 PyObject_DelItemString(PyObject
*o
, char *key
)
210 if (o
== NULL
|| key
== NULL
) {
214 okey
= PyString_FromString(key
);
217 ret
= PyObject_DelItem(o
, okey
);
223 PyObject_AsCharBuffer(PyObject
*obj
,
225 Py_ssize_t
*buffer_len
)
231 if (obj
== NULL
|| buffer
== NULL
|| buffer_len
== NULL
) {
235 pb
= obj
->ob_type
->tp_as_buffer
;
237 pb
->bf_getcharbuffer
== NULL
||
238 pb
->bf_getsegcount
== NULL
) {
239 PyErr_SetString(PyExc_TypeError
,
240 "expected a character 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_getcharbuffer
)(obj
, 0, &pp
);
257 PyObject_CheckReadBuffer(PyObject
*obj
)
259 PyBufferProcs
*pb
= obj
->ob_type
->tp_as_buffer
;
262 pb
->bf_getreadbuffer
== NULL
||
263 pb
->bf_getsegcount
== NULL
||
264 (*pb
->bf_getsegcount
)(obj
, NULL
) != 1)
269 int PyObject_AsReadBuffer(PyObject
*obj
,
271 Py_ssize_t
*buffer_len
)
277 if (obj
== NULL
|| buffer
== NULL
|| buffer_len
== NULL
) {
281 pb
= obj
->ob_type
->tp_as_buffer
;
283 pb
->bf_getreadbuffer
== NULL
||
284 pb
->bf_getsegcount
== NULL
) {
285 PyErr_SetString(PyExc_TypeError
,
286 "expected a readable buffer object");
289 if ((*pb
->bf_getsegcount
)(obj
, NULL
) != 1) {
290 PyErr_SetString(PyExc_TypeError
,
291 "expected a single-segment buffer object");
294 len
= (*pb
->bf_getreadbuffer
)(obj
, 0, &pp
);
302 int PyObject_AsWriteBuffer(PyObject
*obj
,
304 Py_ssize_t
*buffer_len
)
310 if (obj
== NULL
|| buffer
== NULL
|| buffer_len
== NULL
) {
314 pb
= obj
->ob_type
->tp_as_buffer
;
316 pb
->bf_getwritebuffer
== NULL
||
317 pb
->bf_getsegcount
== NULL
) {
318 PyErr_SetString(PyExc_TypeError
,
319 "expected a writeable buffer object");
322 if ((*pb
->bf_getsegcount
)(obj
, NULL
) != 1) {
323 PyErr_SetString(PyExc_TypeError
,
324 "expected a single-segment buffer object");
327 len
= (*pb
->bf_getwritebuffer
)(obj
,0,&pp
);
335 /* Operations on numbers */
338 PyNumber_Check(PyObject
*o
)
340 return o
&& o
->ob_type
->tp_as_number
&&
341 (o
->ob_type
->tp_as_number
->nb_int
||
342 o
->ob_type
->tp_as_number
->nb_float
);
345 /* Binary operators */
347 /* New style number protocol support */
349 #define NB_SLOT(x) offsetof(PyNumberMethods, x)
350 #define NB_BINOP(nb_methods, slot) \
351 (*(binaryfunc*)(& ((char*)nb_methods)[slot]))
352 #define NB_TERNOP(nb_methods, slot) \
353 (*(ternaryfunc*)(& ((char*)nb_methods)[slot]))
356 Calling scheme used for binary operations:
359 -------------------------------------------------------------------
360 new new w.op(v,w)[*], v.op(v,w), w.op(v,w)
361 new old v.op(v,w), coerce(v,w), v.op(v,w)
362 old new w.op(v,w), coerce(v,w), v.op(v,w)
363 old old coerce(v,w), v.op(v,w)
365 [*] only when v->ob_type != w->ob_type && w->ob_type is a subclass of
370 * new == new style number
371 * old == old style number
372 * Action indicates the order in which operations are tried until either
373 a valid result is produced or an error occurs.
378 binary_op1(PyObject
*v
, PyObject
*w
, const int op_slot
)
381 binaryfunc slotv
= NULL
;
382 binaryfunc slotw
= NULL
;
384 if (v
->ob_type
->tp_as_number
!= NULL
&& NEW_STYLE_NUMBER(v
))
385 slotv
= NB_BINOP(v
->ob_type
->tp_as_number
, op_slot
);
386 if (w
->ob_type
!= v
->ob_type
&&
387 w
->ob_type
->tp_as_number
!= NULL
&& NEW_STYLE_NUMBER(w
)) {
388 slotw
= NB_BINOP(w
->ob_type
->tp_as_number
, op_slot
);
393 if (slotw
&& PyType_IsSubtype(w
->ob_type
, v
->ob_type
)) {
395 if (x
!= Py_NotImplemented
)
397 Py_DECREF(x
); /* can't do it */
401 if (x
!= Py_NotImplemented
)
403 Py_DECREF(x
); /* can't do it */
407 if (x
!= Py_NotImplemented
)
409 Py_DECREF(x
); /* can't do it */
411 if (!NEW_STYLE_NUMBER(v
) || !NEW_STYLE_NUMBER(w
)) {
412 int err
= PyNumber_CoerceEx(&v
, &w
);
417 PyNumberMethods
*mv
= v
->ob_type
->tp_as_number
;
420 slot
= NB_BINOP(mv
, op_slot
);
428 /* CoerceEx incremented the reference counts */
433 Py_INCREF(Py_NotImplemented
);
434 return Py_NotImplemented
;
438 binop_type_error(PyObject
*v
, PyObject
*w
, const char *op_name
)
440 PyErr_Format(PyExc_TypeError
,
441 "unsupported operand type(s) for %.100s: "
442 "'%.100s' and '%.100s'",
445 w
->ob_type
->tp_name
);
450 binary_op(PyObject
*v
, PyObject
*w
, const int op_slot
, const char *op_name
)
452 PyObject
*result
= binary_op1(v
, w
, op_slot
);
453 if (result
== Py_NotImplemented
) {
455 return binop_type_error(v
, w
, op_name
);
462 Calling scheme used for ternary operations:
464 *** In some cases, w.op is called before v.op; see binary_op1. ***
467 -------------------------------------------------------------------
468 new new new v.op(v,w,z), w.op(v,w,z), z.op(v,w,z)
469 new old new v.op(v,w,z), z.op(v,w,z), coerce(v,w,z), v.op(v,w,z)
470 old new new w.op(v,w,z), z.op(v,w,z), coerce(v,w,z), v.op(v,w,z)
471 old old new z.op(v,w,z), coerce(v,w,z), v.op(v,w,z)
472 new new old v.op(v,w,z), w.op(v,w,z), coerce(v,w,z), v.op(v,w,z)
473 new old old v.op(v,w,z), coerce(v,w,z), v.op(v,w,z)
474 old new old w.op(v,w,z), coerce(v,w,z), v.op(v,w,z)
475 old old old coerce(v,w,z), v.op(v,w,z)
479 * new == new style number
480 * old == old style number
481 * Action indicates the order in which operations are tried until either
482 a valid result is produced or an error occurs.
483 * coerce(v,w,z) actually does: coerce(v,w), coerce(v,z), coerce(w,z) and
484 only if z != Py_None; if z == Py_None, then it is treated as absent
485 variable and only coerce(v,w) is tried.
490 ternary_op(PyObject
*v
,
496 PyNumberMethods
*mv
, *mw
, *mz
;
498 ternaryfunc slotv
= NULL
;
499 ternaryfunc slotw
= NULL
;
500 ternaryfunc slotz
= NULL
;
502 mv
= v
->ob_type
->tp_as_number
;
503 mw
= w
->ob_type
->tp_as_number
;
504 if (mv
!= NULL
&& NEW_STYLE_NUMBER(v
))
505 slotv
= NB_TERNOP(mv
, op_slot
);
506 if (w
->ob_type
!= v
->ob_type
&&
507 mw
!= NULL
&& NEW_STYLE_NUMBER(w
)) {
508 slotw
= NB_TERNOP(mw
, op_slot
);
513 if (slotw
&& PyType_IsSubtype(w
->ob_type
, v
->ob_type
)) {
515 if (x
!= Py_NotImplemented
)
517 Py_DECREF(x
); /* can't do it */
521 if (x
!= Py_NotImplemented
)
523 Py_DECREF(x
); /* can't do it */
527 if (x
!= Py_NotImplemented
)
529 Py_DECREF(x
); /* can't do it */
531 mz
= z
->ob_type
->tp_as_number
;
532 if (mz
!= NULL
&& NEW_STYLE_NUMBER(z
)) {
533 slotz
= NB_TERNOP(mz
, op_slot
);
534 if (slotz
== slotv
|| slotz
== slotw
)
538 if (x
!= Py_NotImplemented
)
540 Py_DECREF(x
); /* can't do it */
544 if (!NEW_STYLE_NUMBER(v
) || !NEW_STYLE_NUMBER(w
) ||
545 (z
!= Py_None
&& !NEW_STYLE_NUMBER(z
))) {
546 /* we have an old style operand, coerce */
547 PyObject
*v1
, *z1
, *w2
, *z2
;
550 c
= PyNumber_Coerce(&v
, &w
);
554 /* Special case: if the third argument is None, it is
555 treated as absent argument and not coerced. */
557 if (v
->ob_type
->tp_as_number
) {
558 slotz
= NB_TERNOP(v
->ob_type
->tp_as_number
,
571 c
= PyNumber_Coerce(&v1
, &z1
);
576 c
= PyNumber_Coerce(&w2
, &z2
);
580 if (v1
->ob_type
->tp_as_number
!= NULL
) {
581 slotv
= NB_TERNOP(v1
->ob_type
->tp_as_number
,
584 x
= slotv(v1
, w2
, z2
);
607 "unsupported operand type(s) for ** or pow(): "
608 "'%.100s' and '%.100s'",
610 w
->ob_type
->tp_name
);
614 "unsupported operand type(s) for pow(): "
615 "'%.100s', '%.100s', '%.100s'",
618 z
->ob_type
->tp_name
);
622 #define BINARY_FUNC(func, op, op_name) \
624 func(PyObject *v, PyObject *w) { \
625 return binary_op(v, w, NB_SLOT(op), op_name); \
628 BINARY_FUNC(PyNumber_Or
, nb_or
, "|")
629 BINARY_FUNC(PyNumber_Xor
, nb_xor
, "^")
630 BINARY_FUNC(PyNumber_And
, nb_and
, "&")
631 BINARY_FUNC(PyNumber_Lshift
, nb_lshift
, "<<")
632 BINARY_FUNC(PyNumber_Rshift
, nb_rshift
, ">>")
633 BINARY_FUNC(PyNumber_Subtract
, nb_subtract
, "-")
634 BINARY_FUNC(PyNumber_Divide
, nb_divide
, "/")
635 BINARY_FUNC(PyNumber_Divmod
, nb_divmod
, "divmod()")
638 PyNumber_Add(PyObject
*v
, PyObject
*w
)
640 PyObject
*result
= binary_op1(v
, w
, NB_SLOT(nb_add
));
641 if (result
== Py_NotImplemented
) {
642 PySequenceMethods
*m
= v
->ob_type
->tp_as_sequence
;
644 if (m
&& m
->sq_concat
) {
645 return (*m
->sq_concat
)(v
, w
);
647 result
= binop_type_error(v
, w
, "+");
653 sequence_repeat(ssizeargfunc repeatfunc
, PyObject
*seq
, PyObject
*n
)
656 PyNumberMethods
*nb
= n
->ob_type
->tp_as_number
;
657 if (nb
!= NULL
&& HASINDEX(n
) && nb
->nb_index
!= NULL
) {
658 count
= nb
->nb_index(n
);
659 if (count
== -1 && PyErr_Occurred())
663 return type_error("can't multiply sequence by "
664 "non-int of type '%.200s'", n
);
666 return (*repeatfunc
)(seq
, count
);
670 PyNumber_Multiply(PyObject
*v
, PyObject
*w
)
672 PyObject
*result
= binary_op1(v
, w
, NB_SLOT(nb_multiply
));
673 if (result
== Py_NotImplemented
) {
674 PySequenceMethods
*mv
= v
->ob_type
->tp_as_sequence
;
675 PySequenceMethods
*mw
= w
->ob_type
->tp_as_sequence
;
677 if (mv
&& mv
->sq_repeat
) {
678 return sequence_repeat(mv
->sq_repeat
, v
, w
);
680 else if (mw
&& mw
->sq_repeat
) {
681 return sequence_repeat(mw
->sq_repeat
, w
, v
);
683 result
= binop_type_error(v
, w
, "*");
689 PyNumber_FloorDivide(PyObject
*v
, PyObject
*w
)
691 /* XXX tp_flags test */
692 return binary_op(v
, w
, NB_SLOT(nb_floor_divide
), "//");
696 PyNumber_TrueDivide(PyObject
*v
, PyObject
*w
)
698 /* XXX tp_flags test */
699 return binary_op(v
, w
, NB_SLOT(nb_true_divide
), "/");
703 PyNumber_Remainder(PyObject
*v
, PyObject
*w
)
705 return binary_op(v
, w
, NB_SLOT(nb_remainder
), "%");
709 PyNumber_Power(PyObject
*v
, PyObject
*w
, PyObject
*z
)
711 return ternary_op(v
, w
, z
, NB_SLOT(nb_power
), "** or pow()");
714 /* Binary in-place operators */
716 /* The in-place operators are defined to fall back to the 'normal',
717 non in-place operations, if the in-place methods are not in place.
719 - If the left hand object has the appropriate struct members, and
720 they are filled, call the appropriate function and return the
721 result. No coercion is done on the arguments; the left-hand object
722 is the one the operation is performed on, and it's up to the
723 function to deal with the right-hand object.
725 - Otherwise, in-place modification is not supported. Handle it exactly as
726 a non in-place operation of the same kind.
730 #define HASINPLACE(t) \
731 PyType_HasFeature((t)->ob_type, Py_TPFLAGS_HAVE_INPLACEOPS)
734 binary_iop1(PyObject
*v
, PyObject
*w
, const int iop_slot
, const int op_slot
)
736 PyNumberMethods
*mv
= v
->ob_type
->tp_as_number
;
737 if (mv
!= NULL
&& HASINPLACE(v
)) {
738 binaryfunc slot
= NB_BINOP(mv
, iop_slot
);
740 PyObject
*x
= (slot
)(v
, w
);
741 if (x
!= Py_NotImplemented
) {
747 return binary_op1(v
, w
, op_slot
);
751 binary_iop(PyObject
*v
, PyObject
*w
, const int iop_slot
, const int op_slot
,
754 PyObject
*result
= binary_iop1(v
, w
, iop_slot
, op_slot
);
755 if (result
== Py_NotImplemented
) {
757 return binop_type_error(v
, w
, op_name
);
762 #define INPLACE_BINOP(func, iop, op, op_name) \
764 func(PyObject *v, PyObject *w) { \
765 return binary_iop(v, w, NB_SLOT(iop), NB_SLOT(op), op_name); \
768 INPLACE_BINOP(PyNumber_InPlaceOr
, nb_inplace_or
, nb_or
, "|=")
769 INPLACE_BINOP(PyNumber_InPlaceXor
, nb_inplace_xor
, nb_xor
, "^=")
770 INPLACE_BINOP(PyNumber_InPlaceAnd
, nb_inplace_and
, nb_and
, "&=")
771 INPLACE_BINOP(PyNumber_InPlaceLshift
, nb_inplace_lshift
, nb_lshift
, "<<=")
772 INPLACE_BINOP(PyNumber_InPlaceRshift
, nb_inplace_rshift
, nb_rshift
, ">>=")
773 INPLACE_BINOP(PyNumber_InPlaceSubtract
, nb_inplace_subtract
, nb_subtract
, "-=")
774 INPLACE_BINOP(PyNumber_InPlaceDivide
, nb_inplace_divide
, nb_divide
, "/=")
777 PyNumber_InPlaceFloorDivide(PyObject
*v
, PyObject
*w
)
779 /* XXX tp_flags test */
780 return binary_iop(v
, w
, NB_SLOT(nb_inplace_floor_divide
),
781 NB_SLOT(nb_floor_divide
), "//=");
785 PyNumber_InPlaceTrueDivide(PyObject
*v
, PyObject
*w
)
787 /* XXX tp_flags test */
788 return binary_iop(v
, w
, NB_SLOT(nb_inplace_true_divide
),
789 NB_SLOT(nb_true_divide
), "/=");
793 PyNumber_InPlaceAdd(PyObject
*v
, PyObject
*w
)
795 PyObject
*result
= binary_iop1(v
, w
, NB_SLOT(nb_inplace_add
),
797 if (result
== Py_NotImplemented
) {
798 PySequenceMethods
*m
= v
->ob_type
->tp_as_sequence
;
803 f
= m
->sq_inplace_concat
;
809 result
= binop_type_error(v
, w
, "+=");
815 PyNumber_InPlaceMultiply(PyObject
*v
, PyObject
*w
)
817 PyObject
*result
= binary_iop1(v
, w
, NB_SLOT(nb_inplace_multiply
),
818 NB_SLOT(nb_multiply
));
819 if (result
== Py_NotImplemented
) {
820 ssizeargfunc f
= NULL
;
821 PySequenceMethods
*mv
= v
->ob_type
->tp_as_sequence
;
822 PySequenceMethods
*mw
= w
->ob_type
->tp_as_sequence
;
826 f
= mv
->sq_inplace_repeat
;
830 return sequence_repeat(f
, v
, w
);
832 else if (mw
!= NULL
) {
833 /* Note that the right hand operand should not be
834 * mutated in this case so sq_inplace_repeat is not
837 return sequence_repeat(mw
->sq_repeat
, w
, v
);
839 result
= binop_type_error(v
, w
, "*=");
845 PyNumber_InPlaceRemainder(PyObject
*v
, PyObject
*w
)
847 return binary_iop(v
, w
, NB_SLOT(nb_inplace_remainder
),
848 NB_SLOT(nb_remainder
), "%=");
852 PyNumber_InPlacePower(PyObject
*v
, PyObject
*w
, PyObject
*z
)
854 if (HASINPLACE(v
) && v
->ob_type
->tp_as_number
&&
855 v
->ob_type
->tp_as_number
->nb_inplace_power
!= NULL
) {
856 return ternary_op(v
, w
, z
, NB_SLOT(nb_inplace_power
), "**=");
859 return ternary_op(v
, w
, z
, NB_SLOT(nb_power
), "**=");
864 /* Unary operators and functions */
867 PyNumber_Negative(PyObject
*o
)
873 m
= o
->ob_type
->tp_as_number
;
874 if (m
&& m
->nb_negative
)
875 return (*m
->nb_negative
)(o
);
877 return type_error("bad operand type for unary -: '%.200s'", o
);
881 PyNumber_Positive(PyObject
*o
)
887 m
= o
->ob_type
->tp_as_number
;
888 if (m
&& m
->nb_positive
)
889 return (*m
->nb_positive
)(o
);
891 return type_error("bad operand type for unary +: '%.200s'", o
);
895 PyNumber_Invert(PyObject
*o
)
901 m
= o
->ob_type
->tp_as_number
;
902 if (m
&& m
->nb_invert
)
903 return (*m
->nb_invert
)(o
);
905 return type_error("bad operand type for unary ~: '%.200s'", o
);
909 PyNumber_Absolute(PyObject
*o
)
915 m
= o
->ob_type
->tp_as_number
;
916 if (m
&& m
->nb_absolute
)
917 return m
->nb_absolute(o
);
919 return type_error("bad operand type for abs(): '%.200s'", o
);
922 /* Add a check for embedded NULL-bytes in the argument. */
924 int_from_string(const char *s
, Py_ssize_t len
)
929 x
= PyInt_FromString((char*)s
, &end
, 10);
932 if (end
!= s
+ len
) {
933 PyErr_SetString(PyExc_ValueError
,
934 "null byte in argument for int()");
941 /* Return a Py_ssize_t integer from the object item */
943 PyNumber_Index(PyObject
*item
)
945 Py_ssize_t value
= -1;
946 PyNumberMethods
*nb
= item
->ob_type
->tp_as_number
;
947 if (nb
!= NULL
&& HASINDEX(item
) && nb
->nb_index
!= NULL
) {
948 value
= nb
->nb_index(item
);
951 PyErr_Format(PyExc_TypeError
,
952 "'%.200s' object cannot be interpreted "
953 "as an index", item
->ob_type
->tp_name
);
959 PyNumber_Int(PyObject
*o
)
963 Py_ssize_t buffer_len
;
967 if (PyInt_CheckExact(o
)) {
971 m
= o
->ob_type
->tp_as_number
;
972 if (m
&& m
->nb_int
) { /* This should include subclasses of int */
973 PyObject
*res
= m
->nb_int(o
);
974 if (res
&& (!PyInt_Check(res
) && !PyLong_Check(res
))) {
975 PyErr_Format(PyExc_TypeError
,
976 "__int__ returned non-int (type %.200s)",
977 res
->ob_type
->tp_name
);
983 if (PyInt_Check(o
)) { /* A int subclass without nb_int */
984 PyIntObject
*io
= (PyIntObject
*)o
;
985 return PyInt_FromLong(io
->ob_ival
);
987 if (PyString_Check(o
))
988 return int_from_string(PyString_AS_STRING(o
),
989 PyString_GET_SIZE(o
));
990 #ifdef Py_USING_UNICODE
991 if (PyUnicode_Check(o
))
992 return PyInt_FromUnicode(PyUnicode_AS_UNICODE(o
),
993 PyUnicode_GET_SIZE(o
),
996 if (!PyObject_AsCharBuffer(o
, &buffer
, &buffer_len
))
997 return int_from_string((char*)buffer
, buffer_len
);
999 return type_error("int() argument must be a string or a "
1000 "number, not '%.200s'", o
);
1003 /* Add a check for embedded NULL-bytes in the argument. */
1005 long_from_string(const char *s
, Py_ssize_t len
)
1010 x
= PyLong_FromString((char*)s
, &end
, 10);
1013 if (end
!= s
+ len
) {
1014 PyErr_SetString(PyExc_ValueError
,
1015 "null byte in argument for long()");
1023 PyNumber_Long(PyObject
*o
)
1027 Py_ssize_t buffer_len
;
1030 return null_error();
1031 m
= o
->ob_type
->tp_as_number
;
1032 if (m
&& m
->nb_long
) { /* This should include subclasses of long */
1033 PyObject
*res
= m
->nb_long(o
);
1034 if (res
&& (!PyInt_Check(res
) && !PyLong_Check(res
))) {
1035 PyErr_Format(PyExc_TypeError
,
1036 "__long__ returned non-long (type %.200s)",
1037 res
->ob_type
->tp_name
);
1043 if (PyLong_Check(o
)) /* A long subclass without nb_long */
1044 return _PyLong_Copy((PyLongObject
*)o
);
1045 if (PyString_Check(o
))
1046 /* need to do extra error checking that PyLong_FromString()
1047 * doesn't do. In particular long('9.5') must raise an
1048 * exception, not truncate the float.
1050 return long_from_string(PyString_AS_STRING(o
),
1051 PyString_GET_SIZE(o
));
1052 #ifdef Py_USING_UNICODE
1053 if (PyUnicode_Check(o
))
1054 /* The above check is done in PyLong_FromUnicode(). */
1055 return PyLong_FromUnicode(PyUnicode_AS_UNICODE(o
),
1056 PyUnicode_GET_SIZE(o
),
1059 if (!PyObject_AsCharBuffer(o
, &buffer
, &buffer_len
))
1060 return long_from_string(buffer
, buffer_len
);
1062 return type_error("long() argument must be a string or a "
1063 "number, not '%.200s'", o
);
1067 PyNumber_Float(PyObject
*o
)
1072 return null_error();
1073 m
= o
->ob_type
->tp_as_number
;
1074 if (m
&& m
->nb_float
) { /* This should include subclasses of float */
1075 PyObject
*res
= m
->nb_float(o
);
1076 if (res
&& !PyFloat_Check(res
)) {
1077 PyErr_Format(PyExc_TypeError
,
1078 "__float__ returned non-float (type %.200s)",
1079 res
->ob_type
->tp_name
);
1085 if (PyFloat_Check(o
)) { /* A float subclass with nb_float == NULL */
1086 PyFloatObject
*po
= (PyFloatObject
*)o
;
1087 return PyFloat_FromDouble(po
->ob_fval
);
1089 return PyFloat_FromString(o
, NULL
);
1092 /* Operations on sequences */
1095 PySequence_Check(PyObject
*s
)
1097 if (s
&& PyInstance_Check(s
))
1098 return PyObject_HasAttrString(s
, "__getitem__");
1099 return s
!= NULL
&& s
->ob_type
->tp_as_sequence
&&
1100 s
->ob_type
->tp_as_sequence
->sq_item
!= NULL
;
1104 PySequence_Size(PyObject
*s
)
1106 PySequenceMethods
*m
;
1113 m
= s
->ob_type
->tp_as_sequence
;
1114 if (m
&& m
->sq_length
)
1115 return m
->sq_length(s
);
1117 type_error("non-sequence object of type '%.200s' has no len()", s
);
1121 #undef PySequence_Length
1123 PySequence_Length(PyObject
*s
)
1125 return PySequence_Size(s
);
1127 #define PySequence_Length PySequence_Size
1130 PySequence_Concat(PyObject
*s
, PyObject
*o
)
1132 PySequenceMethods
*m
;
1134 if (s
== NULL
|| o
== NULL
)
1135 return null_error();
1137 m
= s
->ob_type
->tp_as_sequence
;
1138 if (m
&& m
->sq_concat
)
1139 return m
->sq_concat(s
, o
);
1141 /* Instances of user classes defining an __add__() method only
1142 have an nb_add slot, not an sq_concat slot. So we fall back
1143 to nb_add if both arguments appear to be sequences. */
1144 if (PySequence_Check(s
) && PySequence_Check(o
)) {
1145 PyObject
*result
= binary_op1(s
, o
, NB_SLOT(nb_add
));
1146 if (result
!= Py_NotImplemented
)
1150 return type_error("'%.200s' object can't be concatenated", s
);
1154 PySequence_Repeat(PyObject
*o
, Py_ssize_t count
)
1156 PySequenceMethods
*m
;
1159 return null_error();
1161 m
= o
->ob_type
->tp_as_sequence
;
1162 if (m
&& m
->sq_repeat
)
1163 return m
->sq_repeat(o
, count
);
1165 /* Instances of user classes defining a __mul__() method only
1166 have an nb_multiply slot, not an sq_repeat slot. so we fall back
1167 to nb_multiply if o appears to be a sequence. */
1168 if (PySequence_Check(o
)) {
1169 PyObject
*n
, *result
;
1170 n
= PyInt_FromSsize_t(count
);
1173 result
= binary_op1(o
, n
, NB_SLOT(nb_multiply
));
1175 if (result
!= Py_NotImplemented
)
1179 return type_error("'%.200s' object can't be repeated", o
);
1183 PySequence_InPlaceConcat(PyObject
*s
, PyObject
*o
)
1185 PySequenceMethods
*m
;
1187 if (s
== NULL
|| o
== NULL
)
1188 return null_error();
1190 m
= s
->ob_type
->tp_as_sequence
;
1191 if (m
&& HASINPLACE(s
) && m
->sq_inplace_concat
)
1192 return m
->sq_inplace_concat(s
, o
);
1193 if (m
&& m
->sq_concat
)
1194 return m
->sq_concat(s
, o
);
1196 if (PySequence_Check(s
) && PySequence_Check(o
)) {
1197 PyObject
*result
= binary_iop1(s
, o
, NB_SLOT(nb_inplace_add
),
1199 if (result
!= Py_NotImplemented
)
1203 return type_error("'%.200s' object can't be concatenated", s
);
1207 PySequence_InPlaceRepeat(PyObject
*o
, Py_ssize_t count
)
1209 PySequenceMethods
*m
;
1212 return null_error();
1214 m
= o
->ob_type
->tp_as_sequence
;
1215 if (m
&& HASINPLACE(o
) && m
->sq_inplace_repeat
)
1216 return m
->sq_inplace_repeat(o
, count
);
1217 if (m
&& m
->sq_repeat
)
1218 return m
->sq_repeat(o
, count
);
1220 if (PySequence_Check(o
)) {
1221 PyObject
*n
, *result
;
1222 n
= PyInt_FromSsize_t(count
);
1225 result
= binary_iop1(o
, n
, NB_SLOT(nb_inplace_multiply
),
1226 NB_SLOT(nb_multiply
));
1228 if (result
!= Py_NotImplemented
)
1232 return type_error("'%.200s' object can't be repeated", o
);
1236 PySequence_GetItem(PyObject
*s
, Py_ssize_t i
)
1238 PySequenceMethods
*m
;
1241 return null_error();
1243 m
= s
->ob_type
->tp_as_sequence
;
1244 if (m
&& m
->sq_item
) {
1247 Py_ssize_t l
= (*m
->sq_length
)(s
);
1253 return m
->sq_item(s
, i
);
1256 return type_error("'%.200s' object is unindexable", s
);
1260 PySequence_GetSlice(PyObject
*s
, Py_ssize_t i1
, Py_ssize_t i2
)
1262 PySequenceMethods
*m
;
1263 PyMappingMethods
*mp
;
1265 if (!s
) return null_error();
1267 m
= s
->ob_type
->tp_as_sequence
;
1268 if (m
&& m
->sq_slice
) {
1269 if (i1
< 0 || i2
< 0) {
1271 Py_ssize_t l
= (*m
->sq_length
)(s
);
1280 return m
->sq_slice(s
, i1
, i2
);
1281 } else if ((mp
= s
->ob_type
->tp_as_mapping
) && mp
->mp_subscript
) {
1283 PyObject
*slice
= _PySlice_FromIndices(i1
, i2
);
1286 res
= mp
->mp_subscript(s
, slice
);
1291 return type_error("'%.200s' object is unsliceable", s
);
1295 PySequence_SetItem(PyObject
*s
, Py_ssize_t i
, PyObject
*o
)
1297 PySequenceMethods
*m
;
1304 m
= s
->ob_type
->tp_as_sequence
;
1305 if (m
&& m
->sq_ass_item
) {
1308 Py_ssize_t l
= (*m
->sq_length
)(s
);
1314 return m
->sq_ass_item(s
, i
, o
);
1317 type_error("'%.200s' object does not support item assignment", s
);
1322 PySequence_DelItem(PyObject
*s
, Py_ssize_t i
)
1324 PySequenceMethods
*m
;
1331 m
= s
->ob_type
->tp_as_sequence
;
1332 if (m
&& m
->sq_ass_item
) {
1335 Py_ssize_t l
= (*m
->sq_length
)(s
);
1341 return m
->sq_ass_item(s
, i
, (PyObject
*)NULL
);
1344 type_error("'%.200s' object doesn't support item deletion", s
);
1349 PySequence_SetSlice(PyObject
*s
, Py_ssize_t i1
, Py_ssize_t i2
, PyObject
*o
)
1351 PySequenceMethods
*m
;
1352 PyMappingMethods
*mp
;
1359 m
= s
->ob_type
->tp_as_sequence
;
1360 if (m
&& m
->sq_ass_slice
) {
1361 if (i1
< 0 || i2
< 0) {
1363 Py_ssize_t l
= (*m
->sq_length
)(s
);
1372 return m
->sq_ass_slice(s
, i1
, i2
, o
);
1373 } else if ((mp
= s
->ob_type
->tp_as_mapping
) && mp
->mp_ass_subscript
) {
1375 PyObject
*slice
= _PySlice_FromIndices(i1
, i2
);
1378 res
= mp
->mp_ass_subscript(s
, slice
, o
);
1383 type_error("'%.200s' object doesn't support slice assignment", s
);
1388 PySequence_DelSlice(PyObject
*s
, Py_ssize_t i1
, Py_ssize_t i2
)
1390 PySequenceMethods
*m
;
1397 m
= s
->ob_type
->tp_as_sequence
;
1398 if (m
&& m
->sq_ass_slice
) {
1399 if (i1
< 0 || i2
< 0) {
1401 Py_ssize_t l
= (*m
->sq_length
)(s
);
1410 return m
->sq_ass_slice(s
, i1
, i2
, (PyObject
*)NULL
);
1412 type_error("'%.200s' object doesn't support slice deletion", s
);
1417 PySequence_Tuple(PyObject
*v
)
1419 PyObject
*it
; /* iter(v) */
1420 Py_ssize_t n
; /* guess for result tuple size */
1425 return null_error();
1427 /* Special-case the common tuple and list cases, for efficiency. */
1428 if (PyTuple_CheckExact(v
)) {
1429 /* Note that we can't know whether it's safe to return
1430 a tuple *subclass* instance as-is, hence the restriction
1431 to exact tuples here. In contrast, lists always make
1432 a copy, so there's no need for exactness below. */
1436 if (PyList_Check(v
))
1437 return PyList_AsTuple(v
);
1440 it
= PyObject_GetIter(v
);
1444 /* Guess result size and allocate space. */
1445 n
= _PyObject_LengthHint(v
);
1447 if (!PyErr_ExceptionMatches(PyExc_TypeError
) &&
1448 !PyErr_ExceptionMatches(PyExc_AttributeError
)) {
1453 n
= 10; /* arbitrary */
1455 result
= PyTuple_New(n
);
1459 /* Fill the tuple. */
1460 for (j
= 0; ; ++j
) {
1461 PyObject
*item
= PyIter_Next(it
);
1463 if (PyErr_Occurred())
1468 Py_ssize_t oldn
= n
;
1469 /* The over-allocation strategy can grow a bit faster
1470 than for lists because unlike lists the
1471 over-allocation isn't permanent -- we reclaim
1472 the excess before the end of this routine.
1473 So, grow by ten and then add 25%.
1478 /* Check for overflow */
1483 if (_PyTuple_Resize(&result
, n
) != 0) {
1488 PyTuple_SET_ITEM(result
, j
, item
);
1491 /* Cut tuple back if guess was too large. */
1493 _PyTuple_Resize(&result
, j
) != 0)
1506 PySequence_List(PyObject
*v
)
1508 PyObject
*result
; /* result list */
1509 PyObject
*rv
; /* return value from PyList_Extend */
1512 return null_error();
1514 result
= PyList_New(0);
1518 rv
= _PyList_Extend((PyListObject
*)result
, v
);
1528 PySequence_Fast(PyObject
*v
, const char *m
)
1533 return null_error();
1535 if (PyList_CheckExact(v
) || PyTuple_CheckExact(v
)) {
1540 it
= PyObject_GetIter(v
);
1542 if (PyErr_ExceptionMatches(PyExc_TypeError
))
1543 PyErr_SetString(PyExc_TypeError
, m
);
1547 v
= PySequence_List(it
);
1553 /* Iterate over seq. Result depends on the operation:
1554 PY_ITERSEARCH_COUNT: -1 if error, else # of times obj appears in seq.
1555 PY_ITERSEARCH_INDEX: 0-based index of first occurence of obj in seq;
1556 set ValueError and return -1 if none found; also return -1 on error.
1557 Py_ITERSEARCH_CONTAINS: return 1 if obj in seq, else 0; -1 on error.
1560 _PySequence_IterSearch(PyObject
*seq
, PyObject
*obj
, int operation
)
1563 int wrapped
; /* for PY_ITERSEARCH_INDEX, true iff n wrapped around */
1564 PyObject
*it
; /* iter(seq) */
1566 if (seq
== NULL
|| obj
== NULL
) {
1571 it
= PyObject_GetIter(seq
);
1573 type_error("argument of type '%.200s' is not iterable", seq
);
1580 PyObject
*item
= PyIter_Next(it
);
1582 if (PyErr_Occurred())
1587 cmp
= PyObject_RichCompareBool(obj
, item
, Py_EQ
);
1592 switch (operation
) {
1593 case PY_ITERSEARCH_COUNT
:
1596 /* XXX(nnorwitz): int means ssize_t */
1597 PyErr_SetString(PyExc_OverflowError
,
1598 "count exceeds C int size");
1603 case PY_ITERSEARCH_INDEX
:
1605 /* XXX(nnorwitz): int means ssize_t */
1606 PyErr_SetString(PyExc_OverflowError
,
1607 "index exceeds C int size");
1612 case PY_ITERSEARCH_CONTAINS
:
1617 assert(!"unknown operation");
1621 if (operation
== PY_ITERSEARCH_INDEX
) {
1628 if (operation
!= PY_ITERSEARCH_INDEX
)
1631 PyErr_SetString(PyExc_ValueError
,
1632 "sequence.index(x): x not in sequence");
1633 /* fall into failure code */
1643 /* Return # of times o appears in s. */
1645 PySequence_Count(PyObject
*s
, PyObject
*o
)
1647 return _PySequence_IterSearch(s
, o
, PY_ITERSEARCH_COUNT
);
1650 /* Return -1 if error; 1 if ob in seq; 0 if ob not in seq.
1651 * Use sq_contains if possible, else defer to _PySequence_IterSearch().
1654 PySequence_Contains(PyObject
*seq
, PyObject
*ob
)
1657 if (PyType_HasFeature(seq
->ob_type
, Py_TPFLAGS_HAVE_SEQUENCE_IN
)) {
1658 PySequenceMethods
*sqm
= seq
->ob_type
->tp_as_sequence
;
1659 if (sqm
!= NULL
&& sqm
->sq_contains
!= NULL
)
1660 return (*sqm
->sq_contains
)(seq
, ob
);
1662 result
= _PySequence_IterSearch(seq
, ob
, PY_ITERSEARCH_CONTAINS
);
1663 return Py_SAFE_DOWNCAST(result
, Py_ssize_t
, int);
1666 /* Backwards compatibility */
1667 #undef PySequence_In
1669 PySequence_In(PyObject
*w
, PyObject
*v
)
1671 return PySequence_Contains(w
, v
);
1675 PySequence_Index(PyObject
*s
, PyObject
*o
)
1677 return _PySequence_IterSearch(s
, o
, PY_ITERSEARCH_INDEX
);
1680 /* Operations on mappings */
1683 PyMapping_Check(PyObject
*o
)
1685 if (o
&& PyInstance_Check(o
))
1686 return PyObject_HasAttrString(o
, "__getitem__");
1688 return o
&& o
->ob_type
->tp_as_mapping
&&
1689 o
->ob_type
->tp_as_mapping
->mp_subscript
&&
1690 !(o
->ob_type
->tp_as_sequence
&&
1691 o
->ob_type
->tp_as_sequence
->sq_slice
);
1695 PyMapping_Size(PyObject
*o
)
1697 PyMappingMethods
*m
;
1704 m
= o
->ob_type
->tp_as_mapping
;
1705 if (m
&& m
->mp_length
)
1706 return m
->mp_length(o
);
1708 type_error("non-mapping object of type '%.200s' has no len()", o
);
1712 #undef PyMapping_Length
1714 PyMapping_Length(PyObject
*o
)
1716 return PyMapping_Size(o
);
1718 #define PyMapping_Length PyMapping_Size
1721 PyMapping_GetItemString(PyObject
*o
, char *key
)
1726 return null_error();
1728 okey
= PyString_FromString(key
);
1731 r
= PyObject_GetItem(o
, okey
);
1737 PyMapping_SetItemString(PyObject
*o
, char *key
, PyObject
*value
)
1747 okey
= PyString_FromString(key
);
1750 r
= PyObject_SetItem(o
, okey
, value
);
1756 PyMapping_HasKeyString(PyObject
*o
, char *key
)
1760 v
= PyMapping_GetItemString(o
, key
);
1770 PyMapping_HasKey(PyObject
*o
, PyObject
*key
)
1774 v
= PyObject_GetItem(o
, key
);
1783 /* Operations on callable objects */
1785 /* XXX PyCallable_Check() is in object.c */
1788 PyObject_CallObject(PyObject
*o
, PyObject
*a
)
1790 return PyEval_CallObjectWithKeywords(o
, a
, NULL
);
1794 PyObject_Call(PyObject
*func
, PyObject
*arg
, PyObject
*kw
)
1798 if ((call
= func
->ob_type
->tp_call
) != NULL
) {
1799 PyObject
*result
= NULL
;
1800 /* slot_tp_call() will be called and ends up calling
1801 PyObject_Call() if the object returned for __call__ has
1802 __call__ itself defined upon it. This can be an infinite
1803 recursion if you set __call__ in a class to an instance of
1805 if (Py_EnterRecursiveCall(" in __call__")) {
1808 result
= (*call
)(func
, arg
, kw
);
1809 Py_LeaveRecursiveCall();
1810 if (result
== NULL
&& !PyErr_Occurred())
1813 "NULL result without error in PyObject_Call");
1816 PyErr_Format(PyExc_TypeError
, "'%.200s' object is not callable",
1817 func
->ob_type
->tp_name
);
1822 call_function_tail(PyObject
*callable
, PyObject
*args
)
1829 if (!PyTuple_Check(args
)) {
1837 PyTuple_SET_ITEM(a
, 0, args
);
1840 retval
= PyObject_Call(callable
, args
, NULL
);
1848 PyObject_CallFunction(PyObject
*callable
, char *format
, ...)
1853 if (callable
== NULL
)
1854 return null_error();
1856 if (format
&& *format
) {
1857 va_start(va
, format
);
1858 args
= Py_VaBuildValue(format
, va
);
1862 args
= PyTuple_New(0);
1864 return call_function_tail(callable
, args
);
1868 _PyObject_CallFunction_SizeT(PyObject
*callable
, char *format
, ...)
1873 if (callable
== NULL
)
1874 return null_error();
1876 if (format
&& *format
) {
1877 va_start(va
, format
);
1878 args
= _Py_VaBuildValue_SizeT(format
, va
);
1882 args
= PyTuple_New(0);
1884 return call_function_tail(callable
, args
);
1888 PyObject_CallMethod(PyObject
*o
, char *name
, char *format
, ...)
1892 PyObject
*func
= NULL
;
1893 PyObject
*retval
= NULL
;
1895 if (o
== NULL
|| name
== NULL
)
1896 return null_error();
1898 func
= PyObject_GetAttrString(o
, name
);
1900 PyErr_SetString(PyExc_AttributeError
, name
);
1904 if (!PyCallable_Check(func
)) {
1905 type_error("attribute of type '%.200s' is not callable", func
);
1909 if (format
&& *format
) {
1910 va_start(va
, format
);
1911 args
= Py_VaBuildValue(format
, va
);
1915 args
= PyTuple_New(0);
1917 retval
= call_function_tail(func
, args
);
1920 /* args gets consumed in call_function_tail */
1927 _PyObject_CallMethod_SizeT(PyObject
*o
, char *name
, char *format
, ...)
1931 PyObject
*func
= NULL
;
1932 PyObject
*retval
= NULL
;
1934 if (o
== NULL
|| name
== NULL
)
1935 return null_error();
1937 func
= PyObject_GetAttrString(o
, name
);
1939 PyErr_SetString(PyExc_AttributeError
, name
);
1943 if (!PyCallable_Check(func
)) {
1944 type_error("attribute of type '%.200s' is not callable", func
);
1948 if (format
&& *format
) {
1949 va_start(va
, format
);
1950 args
= _Py_VaBuildValue_SizeT(format
, va
);
1954 args
= PyTuple_New(0);
1956 retval
= call_function_tail(func
, args
);
1959 /* args gets consumed in call_function_tail */
1967 objargs_mktuple(va_list va
)
1971 PyObject
*result
, *tmp
;
1973 #ifdef VA_LIST_IS_ARRAY
1974 memcpy(countva
, va
, sizeof(va_list));
1977 __va_copy(countva
, va
);
1983 while (((PyObject
*)va_arg(countva
, PyObject
*)) != NULL
)
1985 result
= PyTuple_New(n
);
1986 if (result
!= NULL
&& n
> 0) {
1987 for (i
= 0; i
< n
; ++i
) {
1988 tmp
= (PyObject
*)va_arg(va
, PyObject
*);
1989 PyTuple_SET_ITEM(result
, i
, tmp
);
1997 PyObject_CallMethodObjArgs(PyObject
*callable
, PyObject
*name
, ...)
1999 PyObject
*args
, *tmp
;
2002 if (callable
== NULL
|| name
== NULL
)
2003 return null_error();
2005 callable
= PyObject_GetAttr(callable
, name
);
2006 if (callable
== NULL
)
2009 /* count the args */
2010 va_start(vargs
, name
);
2011 args
= objargs_mktuple(vargs
);
2014 Py_DECREF(callable
);
2017 tmp
= PyObject_Call(callable
, args
, NULL
);
2019 Py_DECREF(callable
);
2025 PyObject_CallFunctionObjArgs(PyObject
*callable
, ...)
2027 PyObject
*args
, *tmp
;
2030 if (callable
== NULL
)
2031 return null_error();
2033 /* count the args */
2034 va_start(vargs
, callable
);
2035 args
= objargs_mktuple(vargs
);
2039 tmp
= PyObject_Call(callable
, args
, NULL
);
2046 /* isinstance(), issubclass() */
2048 /* abstract_get_bases() has logically 4 return states, with a sort of 0th
2049 * state that will almost never happen.
2051 * 0. creating the __bases__ static string could get a MemoryError
2052 * 1. getattr(cls, '__bases__') could raise an AttributeError
2053 * 2. getattr(cls, '__bases__') could raise some other exception
2054 * 3. getattr(cls, '__bases__') could return a tuple
2055 * 4. getattr(cls, '__bases__') could return something other than a tuple
2057 * Only state #3 is a non-error state and only it returns a non-NULL object
2058 * (it returns the retrieved tuple).
2060 * Any raised AttributeErrors are masked by clearing the exception and
2061 * returning NULL. If an object other than a tuple comes out of __bases__,
2062 * then again, the return value is NULL. So yes, these two situations
2063 * produce exactly the same results: NULL is returned and no error is set.
2065 * If some exception other than AttributeError is raised, then NULL is also
2066 * returned, but the exception is not cleared. That's because we want the
2067 * exception to be propagated along.
2069 * Callers are expected to test for PyErr_Occurred() when the return value
2070 * is NULL to decide whether a valid exception should be propagated or not.
2071 * When there's no exception to propagate, it's customary for the caller to
2075 abstract_get_bases(PyObject
*cls
)
2077 static PyObject
*__bases__
= NULL
;
2080 if (__bases__
== NULL
) {
2081 __bases__
= PyString_FromString("__bases__");
2082 if (__bases__
== NULL
)
2085 bases
= PyObject_GetAttr(cls
, __bases__
);
2086 if (bases
== NULL
) {
2087 if (PyErr_ExceptionMatches(PyExc_AttributeError
))
2091 if (!PyTuple_Check(bases
)) {
2100 abstract_issubclass(PyObject
*derived
, PyObject
*cls
)
2110 if (PyTuple_Check(cls
)) {
2111 /* Not a general sequence -- that opens up the road to
2112 recursion and stack overflow. */
2113 n
= PyTuple_GET_SIZE(cls
);
2114 for (i
= 0; i
< n
; i
++) {
2115 if (derived
== PyTuple_GET_ITEM(cls
, i
))
2119 bases
= abstract_get_bases(derived
);
2120 if (bases
== NULL
) {
2121 if (PyErr_Occurred())
2125 n
= PyTuple_GET_SIZE(bases
);
2126 for (i
= 0; i
< n
; i
++) {
2127 r
= abstract_issubclass(PyTuple_GET_ITEM(bases
, i
), cls
);
2138 check_class(PyObject
*cls
, const char *error
)
2140 PyObject
*bases
= abstract_get_bases(cls
);
2141 if (bases
== NULL
) {
2142 /* Do not mask errors. */
2143 if (!PyErr_Occurred())
2144 PyErr_SetString(PyExc_TypeError
, error
);
2152 recursive_isinstance(PyObject
*inst
, PyObject
*cls
, int recursion_depth
)
2155 static PyObject
*__class__
= NULL
;
2158 if (__class__
== NULL
) {
2159 __class__
= PyString_FromString("__class__");
2160 if (__class__
== NULL
)
2164 if (PyClass_Check(cls
) && PyInstance_Check(inst
)) {
2166 (PyObject
*)((PyInstanceObject
*)inst
)->in_class
;
2167 retval
= PyClass_IsSubclass(inclass
, cls
);
2169 else if (PyType_Check(cls
)) {
2170 retval
= PyObject_TypeCheck(inst
, (PyTypeObject
*)cls
);
2172 PyObject
*c
= PyObject_GetAttr(inst
, __class__
);
2177 if (c
!= (PyObject
*)(inst
->ob_type
) &&
2179 retval
= PyType_IsSubtype(
2181 (PyTypeObject
*)cls
);
2186 else if (PyTuple_Check(cls
)) {
2189 if (!recursion_depth
) {
2190 PyErr_SetString(PyExc_RuntimeError
,
2191 "nest level of tuple too deep");
2195 n
= PyTuple_GET_SIZE(cls
);
2196 for (i
= 0; i
< n
; i
++) {
2197 retval
= recursive_isinstance(
2199 PyTuple_GET_ITEM(cls
, i
),
2206 if (!check_class(cls
,
2207 "isinstance() arg 2 must be a class, type,"
2208 " or tuple of classes and types"))
2210 icls
= PyObject_GetAttr(inst
, __class__
);
2216 retval
= abstract_issubclass(icls
, cls
);
2225 PyObject_IsInstance(PyObject
*inst
, PyObject
*cls
)
2227 return recursive_isinstance(inst
, cls
, Py_GetRecursionLimit());
2231 recursive_issubclass(PyObject
*derived
, PyObject
*cls
, int recursion_depth
)
2235 if (!PyClass_Check(derived
) || !PyClass_Check(cls
)) {
2236 if (!check_class(derived
,
2237 "issubclass() arg 1 must be a class"))
2240 if (PyTuple_Check(cls
)) {
2242 Py_ssize_t n
= PyTuple_GET_SIZE(cls
);
2244 if (!recursion_depth
) {
2245 PyErr_SetString(PyExc_RuntimeError
,
2246 "nest level of tuple too deep");
2249 for (i
= 0; i
< n
; ++i
) {
2250 retval
= recursive_issubclass(
2252 PyTuple_GET_ITEM(cls
, i
),
2255 /* either found it, or got an error */
2262 if (!check_class(cls
,
2263 "issubclass() arg 2 must be a class"
2264 " or tuple of classes"))
2268 retval
= abstract_issubclass(derived
, cls
);
2272 if (!(retval
= (derived
== cls
)))
2273 retval
= PyClass_IsSubclass(derived
, cls
);
2280 PyObject_IsSubclass(PyObject
*derived
, PyObject
*cls
)
2282 return recursive_issubclass(derived
, cls
, Py_GetRecursionLimit());
2287 PyObject_GetIter(PyObject
*o
)
2289 PyTypeObject
*t
= o
->ob_type
;
2290 getiterfunc f
= NULL
;
2291 if (PyType_HasFeature(t
, Py_TPFLAGS_HAVE_ITER
))
2294 if (PySequence_Check(o
))
2295 return PySeqIter_New(o
);
2296 return type_error("'%.200s' object is not iterable", o
);
2299 PyObject
*res
= (*f
)(o
);
2300 if (res
!= NULL
&& !PyIter_Check(res
)) {
2301 PyErr_Format(PyExc_TypeError
,
2302 "iter() returned non-iterator "
2304 res
->ob_type
->tp_name
);
2312 /* Return next item.
2313 * If an error occurs, return NULL. PyErr_Occurred() will be true.
2314 * If the iteration terminates normally, return NULL and clear the
2315 * PyExc_StopIteration exception (if it was set). PyErr_Occurred()
2317 * Else return the next object. PyErr_Occurred() will be false.
2320 PyIter_Next(PyObject
*iter
)
2323 assert(PyIter_Check(iter
));
2324 result
= (*iter
->ob_type
->tp_iternext
)(iter
);
2325 if (result
== NULL
&&
2327 PyErr_ExceptionMatches(PyExc_StopIteration
))