1 /* Abstract Object Interface (many thanks to Jim Fulton) */
5 #include "structmember.h" /* we need the offsetof() macro from there */
6 #include "longintrepr.h"
10 /* Shorthands to return certain errors */
13 type_error(const char *msg
, PyObject
*obj
)
15 PyErr_Format(PyExc_TypeError
, msg
, obj
->ob_type
->tp_name
);
22 if (!PyErr_Occurred())
23 PyErr_SetString(PyExc_SystemError
,
24 "null argument to internal routine");
28 /* Operations on any object */
31 PyObject_Type(PyObject
*o
)
37 v
= (PyObject
*)o
->ob_type
;
43 PyObject_Size(PyObject
*o
)
52 m
= o
->ob_type
->tp_as_sequence
;
53 if (m
&& m
->sq_length
)
54 return m
->sq_length(o
);
56 return PyMapping_Size(o
);
59 #undef PyObject_Length
61 PyObject_Length(PyObject
*o
)
63 return PyObject_Size(o
);
65 #define PyObject_Length PyObject_Size
68 /* The length hint function returns a non-negative value from o.__len__()
69 or o.__length_hint__(). If those methods aren't found or return a negative
70 value, then the defaultvalue is returned. If one of the calls fails,
71 this function returns -1.
75 _PyObject_LengthHint(PyObject
*o
, Py_ssize_t defaultvalue
)
77 static PyObject
*hintstrobj
= NULL
;
78 PyObject
*ro
, *hintmeth
;
82 rv
= PyObject_Size(o
);
85 if (PyErr_Occurred()) {
86 if (!PyErr_ExceptionMatches(PyExc_TypeError
))
91 /* try o.__length_hint__() */
92 hintmeth
= _PyObject_LookupSpecial(o
, "__length_hint__", &hintstrobj
);
93 if (hintmeth
== NULL
) {
99 ro
= PyObject_CallFunctionObjArgs(hintmeth
, NULL
);
102 if (!PyErr_ExceptionMatches(PyExc_TypeError
))
107 rv
= PyLong_Check(ro
) ? PyLong_AsSsize_t(ro
) : defaultvalue
;
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 if (PyIndex_Check(key
)) {
126 Py_ssize_t key_value
;
127 key_value
= PyNumber_AsSsize_t(key
, PyExc_IndexError
);
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 not subscriptable", 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 if (PyIndex_Check(key
)) {
155 Py_ssize_t key_value
;
156 key_value
= PyNumber_AsSsize_t(key
, PyExc_IndexError
);
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 if (PyIndex_Check(key
)) {
187 Py_ssize_t key_value
;
188 key_value
= PyNumber_AsSsize_t(key
, PyExc_IndexError
);
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
= PyUnicode_FromString(key
);
217 ret
= PyObject_DelItem(o
, okey
);
222 /* We release the buffer right after use of this function which could
223 cause issues later on. Don't use these functions in new code.
226 PyObject_AsCharBuffer(PyObject
*obj
,
228 Py_ssize_t
*buffer_len
)
233 if (obj
== NULL
|| buffer
== NULL
|| buffer_len
== NULL
) {
237 pb
= obj
->ob_type
->tp_as_buffer
;
238 if (pb
== NULL
|| pb
->bf_getbuffer
== NULL
) {
239 PyErr_SetString(PyExc_TypeError
,
240 "expected an object with the buffer interface");
243 if ((*pb
->bf_getbuffer
)(obj
, &view
, PyBUF_SIMPLE
)) return -1;
246 *buffer_len
= view
.len
;
247 if (pb
->bf_releasebuffer
!= NULL
)
248 (*pb
->bf_releasebuffer
)(obj
, &view
);
249 Py_XDECREF(view
.obj
);
254 PyObject_CheckReadBuffer(PyObject
*obj
)
256 PyBufferProcs
*pb
= obj
->ob_type
->tp_as_buffer
;
260 pb
->bf_getbuffer
== NULL
)
262 if ((*pb
->bf_getbuffer
)(obj
, &view
, PyBUF_SIMPLE
) == -1) {
266 PyBuffer_Release(&view
);
270 int PyObject_AsReadBuffer(PyObject
*obj
,
272 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_getbuffer
== NULL
) {
284 PyErr_SetString(PyExc_TypeError
,
285 "expected an object with a buffer interface");
289 if ((*pb
->bf_getbuffer
)(obj
, &view
, PyBUF_SIMPLE
)) return -1;
292 *buffer_len
= view
.len
;
293 if (pb
->bf_releasebuffer
!= NULL
)
294 (*pb
->bf_releasebuffer
)(obj
, &view
);
295 Py_XDECREF(view
.obj
);
299 int PyObject_AsWriteBuffer(PyObject
*obj
,
301 Py_ssize_t
*buffer_len
)
306 if (obj
== NULL
|| buffer
== NULL
|| buffer_len
== NULL
) {
310 pb
= obj
->ob_type
->tp_as_buffer
;
312 pb
->bf_getbuffer
== NULL
||
313 ((*pb
->bf_getbuffer
)(obj
, &view
, PyBUF_WRITABLE
) != 0)) {
314 PyErr_SetString(PyExc_TypeError
,
315 "expected an object with a writable buffer interface");
320 *buffer_len
= view
.len
;
321 if (pb
->bf_releasebuffer
!= NULL
)
322 (*pb
->bf_releasebuffer
)(obj
, &view
);
323 Py_XDECREF(view
.obj
);
327 /* Buffer C-API for Python 3.0 */
330 PyObject_GetBuffer(PyObject
*obj
, Py_buffer
*view
, int flags
)
332 if (!PyObject_CheckBuffer(obj
)) {
333 PyErr_Format(PyExc_TypeError
,
334 "'%100s' does not support the buffer interface",
335 Py_TYPE(obj
)->tp_name
);
338 return (*(obj
->ob_type
->tp_as_buffer
->bf_getbuffer
))(obj
, view
, flags
);
342 _IsFortranContiguous(Py_buffer
*view
)
347 if (view
->ndim
== 0) return 1;
348 if (view
->strides
== NULL
) return (view
->ndim
== 1);
351 if (view
->ndim
== 1) return (view
->shape
[0] == 1 ||
352 sd
== view
->strides
[0]);
353 for (i
=0; i
<view
->ndim
; i
++) {
354 dim
= view
->shape
[i
];
355 if (dim
== 0) return 1;
356 if (view
->strides
[i
] != sd
) return 0;
363 _IsCContiguous(Py_buffer
*view
)
368 if (view
->ndim
== 0) return 1;
369 if (view
->strides
== NULL
) return 1;
372 if (view
->ndim
== 1) return (view
->shape
[0] == 1 ||
373 sd
== view
->strides
[0]);
374 for (i
=view
->ndim
-1; i
>=0; i
--) {
375 dim
= view
->shape
[i
];
376 if (dim
== 0) return 1;
377 if (view
->strides
[i
] != sd
) return 0;
384 PyBuffer_IsContiguous(Py_buffer
*view
, char fort
)
387 if (view
->suboffsets
!= NULL
) return 0;
390 return _IsCContiguous(view
);
391 else if (fort
== 'F')
392 return _IsFortranContiguous(view
);
393 else if (fort
== 'A')
394 return (_IsCContiguous(view
) || _IsFortranContiguous(view
));
400 PyBuffer_GetPointer(Py_buffer
*view
, Py_ssize_t
*indices
)
404 pointer
= (char *)view
->buf
;
405 for (i
= 0; i
< view
->ndim
; i
++) {
406 pointer
+= view
->strides
[i
]*indices
[i
];
407 if ((view
->suboffsets
!= NULL
) && (view
->suboffsets
[i
] >= 0)) {
408 pointer
= *((char**)pointer
) + view
->suboffsets
[i
];
411 return (void*)pointer
;
416 _add_one_to_index_F(int nd
, Py_ssize_t
*index
, Py_ssize_t
*shape
)
420 for (k
=0; k
<nd
; k
++) {
421 if (index
[k
] < shape
[k
]-1) {
432 _add_one_to_index_C(int nd
, Py_ssize_t
*index
, Py_ssize_t
*shape
)
436 for (k
=nd
-1; k
>=0; k
--) {
437 if (index
[k
] < shape
[k
]-1) {
447 /* view is not checked for consistency in either of these. It is
448 assumed that the size of the buffer is view->len in
449 view->len / view->itemsize elements.
453 PyBuffer_ToContiguous(void *buf
, Py_buffer
*view
, Py_ssize_t len
, char fort
)
456 void (*addone
)(int, Py_ssize_t
*, Py_ssize_t
*);
457 Py_ssize_t
*indices
, elements
;
460 if (len
> view
->len
) {
464 if (PyBuffer_IsContiguous(view
, fort
)) {
465 /* simplest copy is all that is needed */
466 memcpy(buf
, view
->buf
, len
);
470 /* Otherwise a more elaborate scheme is needed */
472 /* XXX(nnorwitz): need to check for overflow! */
473 indices
= (Py_ssize_t
*)PyMem_Malloc(sizeof(Py_ssize_t
)*(view
->ndim
));
474 if (indices
== NULL
) {
478 for (k
=0; k
<view
->ndim
;k
++) {
483 addone
= _add_one_to_index_F
;
486 addone
= _add_one_to_index_C
;
489 /* XXX : This is not going to be the fastest code in the world
490 several optimizations are possible.
492 elements
= len
/ view
->itemsize
;
494 addone(view
->ndim
, indices
, view
->shape
);
495 ptr
= PyBuffer_GetPointer(view
, indices
);
496 memcpy(dest
, ptr
, view
->itemsize
);
497 dest
+= view
->itemsize
;
504 PyBuffer_FromContiguous(Py_buffer
*view
, void *buf
, Py_ssize_t len
, char fort
)
507 void (*addone
)(int, Py_ssize_t
*, Py_ssize_t
*);
508 Py_ssize_t
*indices
, elements
;
511 if (len
> view
->len
) {
515 if (PyBuffer_IsContiguous(view
, fort
)) {
516 /* simplest copy is all that is needed */
517 memcpy(view
->buf
, buf
, len
);
521 /* Otherwise a more elaborate scheme is needed */
523 /* XXX(nnorwitz): need to check for overflow! */
524 indices
= (Py_ssize_t
*)PyMem_Malloc(sizeof(Py_ssize_t
)*(view
->ndim
));
525 if (indices
== NULL
) {
529 for (k
=0; k
<view
->ndim
;k
++) {
534 addone
= _add_one_to_index_F
;
537 addone
= _add_one_to_index_C
;
540 /* XXX : This is not going to be the fastest code in the world
541 several optimizations are possible.
543 elements
= len
/ view
->itemsize
;
545 addone(view
->ndim
, indices
, view
->shape
);
546 ptr
= PyBuffer_GetPointer(view
, indices
);
547 memcpy(ptr
, src
, view
->itemsize
);
548 src
+= view
->itemsize
;
555 int PyObject_CopyData(PyObject
*dest
, PyObject
*src
)
557 Py_buffer view_dest
, view_src
;
559 Py_ssize_t
*indices
, elements
;
562 if (!PyObject_CheckBuffer(dest
) ||
563 !PyObject_CheckBuffer(src
)) {
564 PyErr_SetString(PyExc_TypeError
,
565 "both destination and source must have the "\
570 if (PyObject_GetBuffer(dest
, &view_dest
, PyBUF_FULL
) != 0) return -1;
571 if (PyObject_GetBuffer(src
, &view_src
, PyBUF_FULL_RO
) != 0) {
572 PyBuffer_Release(&view_dest
);
576 if (view_dest
.len
< view_src
.len
) {
577 PyErr_SetString(PyExc_BufferError
,
578 "destination is too small to receive data from source");
579 PyBuffer_Release(&view_dest
);
580 PyBuffer_Release(&view_src
);
584 if ((PyBuffer_IsContiguous(&view_dest
, 'C') &&
585 PyBuffer_IsContiguous(&view_src
, 'C')) ||
586 (PyBuffer_IsContiguous(&view_dest
, 'F') &&
587 PyBuffer_IsContiguous(&view_src
, 'F'))) {
588 /* simplest copy is all that is needed */
589 memcpy(view_dest
.buf
, view_src
.buf
, view_src
.len
);
590 PyBuffer_Release(&view_dest
);
591 PyBuffer_Release(&view_src
);
595 /* Otherwise a more elaborate copy scheme is needed */
597 /* XXX(nnorwitz): need to check for overflow! */
598 indices
= (Py_ssize_t
*)PyMem_Malloc(sizeof(Py_ssize_t
)*view_src
.ndim
);
599 if (indices
== NULL
) {
601 PyBuffer_Release(&view_dest
);
602 PyBuffer_Release(&view_src
);
605 for (k
=0; k
<view_src
.ndim
;k
++) {
609 for (k
=0; k
<view_src
.ndim
; k
++) {
610 /* XXX(nnorwitz): can this overflow? */
611 elements
*= view_src
.shape
[k
];
614 _add_one_to_index_C(view_src
.ndim
, indices
, view_src
.shape
);
615 dptr
= PyBuffer_GetPointer(&view_dest
, indices
);
616 sptr
= PyBuffer_GetPointer(&view_src
, indices
);
617 memcpy(dptr
, sptr
, view_src
.itemsize
);
620 PyBuffer_Release(&view_dest
);
621 PyBuffer_Release(&view_src
);
626 PyBuffer_FillContiguousStrides(int nd
, Py_ssize_t
*shape
,
627 Py_ssize_t
*strides
, int itemsize
,
635 for (k
=0; k
<nd
; k
++) {
641 for (k
=nd
-1; k
>=0; k
--) {
650 PyBuffer_FillInfo(Py_buffer
*view
, PyObject
*obj
, void *buf
, Py_ssize_t len
,
651 int readonly
, int flags
)
653 if (view
== NULL
) return 0;
654 if (((flags
& PyBUF_WRITABLE
) == PyBUF_WRITABLE
) &&
656 PyErr_SetString(PyExc_BufferError
,
657 "Object is not writable.");
666 view
->readonly
= readonly
;
669 if ((flags
& PyBUF_FORMAT
) == PyBUF_FORMAT
)
673 if ((flags
& PyBUF_ND
) == PyBUF_ND
)
674 view
->shape
= &(view
->len
);
675 view
->strides
= NULL
;
676 if ((flags
& PyBUF_STRIDES
) == PyBUF_STRIDES
)
677 view
->strides
= &(view
->itemsize
);
678 view
->suboffsets
= NULL
;
679 view
->internal
= NULL
;
684 PyBuffer_Release(Py_buffer
*view
)
686 PyObject
*obj
= view
->obj
;
687 if (obj
&& Py_TYPE(obj
)->tp_as_buffer
&& Py_TYPE(obj
)->tp_as_buffer
->bf_releasebuffer
)
688 Py_TYPE(obj
)->tp_as_buffer
->bf_releasebuffer(obj
, view
);
694 PyObject_Format(PyObject
*obj
, PyObject
*format_spec
)
696 static PyObject
* str__format__
= NULL
;
698 PyObject
*empty
= NULL
;
699 PyObject
*result
= NULL
;
701 /* Initialize cached value */
702 if (str__format__
== NULL
) {
703 /* Initialize static variable needed by _PyType_Lookup */
704 str__format__
= PyUnicode_FromString("__format__");
705 if (str__format__
== NULL
)
709 /* If no format_spec is provided, use an empty string */
710 if (format_spec
== NULL
) {
711 empty
= PyUnicode_FromUnicode(NULL
, 0);
715 /* Make sure the type is initialized. float gets initialized late */
716 if (Py_TYPE(obj
)->tp_dict
== NULL
)
717 if (PyType_Ready(Py_TYPE(obj
)) < 0)
720 /* Find the (unbound!) __format__ method (a borrowed reference) */
721 meth
= _PyType_Lookup(Py_TYPE(obj
), str__format__
);
723 PyErr_Format(PyExc_TypeError
,
724 "Type %.100s doesn't define __format__",
725 Py_TYPE(obj
)->tp_name
);
729 /* And call it, binding it to the value */
730 result
= PyObject_CallFunctionObjArgs(meth
, obj
, format_spec
, NULL
);
732 if (result
&& !PyUnicode_Check(result
)) {
733 PyErr_SetString(PyExc_TypeError
,
734 "__format__ method did not return string");
744 /* Operations on numbers */
747 PyNumber_Check(PyObject
*o
)
749 return o
&& o
->ob_type
->tp_as_number
&&
750 (o
->ob_type
->tp_as_number
->nb_int
||
751 o
->ob_type
->tp_as_number
->nb_float
);
754 /* Binary operators */
756 #define NB_SLOT(x) offsetof(PyNumberMethods, x)
757 #define NB_BINOP(nb_methods, slot) \
758 (*(binaryfunc*)(& ((char*)nb_methods)[slot]))
759 #define NB_TERNOP(nb_methods, slot) \
760 (*(ternaryfunc*)(& ((char*)nb_methods)[slot]))
763 Calling scheme used for binary operations:
765 Order operations are tried until either a valid result or error:
766 w.op(v,w)[*], v.op(v,w), w.op(v,w)
768 [*] only when v->ob_type != w->ob_type && w->ob_type is a subclass of
773 binary_op1(PyObject
*v
, PyObject
*w
, const int op_slot
)
776 binaryfunc slotv
= NULL
;
777 binaryfunc slotw
= NULL
;
779 if (v
->ob_type
->tp_as_number
!= NULL
)
780 slotv
= NB_BINOP(v
->ob_type
->tp_as_number
, op_slot
);
781 if (w
->ob_type
!= v
->ob_type
&&
782 w
->ob_type
->tp_as_number
!= NULL
) {
783 slotw
= NB_BINOP(w
->ob_type
->tp_as_number
, op_slot
);
788 if (slotw
&& PyType_IsSubtype(w
->ob_type
, v
->ob_type
)) {
790 if (x
!= Py_NotImplemented
)
792 Py_DECREF(x
); /* can't do it */
796 if (x
!= Py_NotImplemented
)
798 Py_DECREF(x
); /* can't do it */
802 if (x
!= Py_NotImplemented
)
804 Py_DECREF(x
); /* can't do it */
806 Py_INCREF(Py_NotImplemented
);
807 return Py_NotImplemented
;
811 binop_type_error(PyObject
*v
, PyObject
*w
, const char *op_name
)
813 PyErr_Format(PyExc_TypeError
,
814 "unsupported operand type(s) for %.100s: "
815 "'%.100s' and '%.100s'",
818 w
->ob_type
->tp_name
);
823 binary_op(PyObject
*v
, PyObject
*w
, const int op_slot
, const char *op_name
)
825 PyObject
*result
= binary_op1(v
, w
, op_slot
);
826 if (result
== Py_NotImplemented
) {
828 return binop_type_error(v
, w
, op_name
);
835 Calling scheme used for ternary operations:
837 Order operations are tried until either a valid result or error:
838 v.op(v,w,z), w.op(v,w,z), z.op(v,w,z)
842 ternary_op(PyObject
*v
,
848 PyNumberMethods
*mv
, *mw
, *mz
;
850 ternaryfunc slotv
= NULL
;
851 ternaryfunc slotw
= NULL
;
852 ternaryfunc slotz
= NULL
;
854 mv
= v
->ob_type
->tp_as_number
;
855 mw
= w
->ob_type
->tp_as_number
;
857 slotv
= NB_TERNOP(mv
, op_slot
);
858 if (w
->ob_type
!= v
->ob_type
&&
860 slotw
= NB_TERNOP(mw
, op_slot
);
865 if (slotw
&& PyType_IsSubtype(w
->ob_type
, v
->ob_type
)) {
867 if (x
!= Py_NotImplemented
)
869 Py_DECREF(x
); /* can't do it */
873 if (x
!= Py_NotImplemented
)
875 Py_DECREF(x
); /* can't do it */
879 if (x
!= Py_NotImplemented
)
881 Py_DECREF(x
); /* can't do it */
883 mz
= z
->ob_type
->tp_as_number
;
885 slotz
= NB_TERNOP(mz
, op_slot
);
886 if (slotz
== slotv
|| slotz
== slotw
)
890 if (x
!= Py_NotImplemented
)
892 Py_DECREF(x
); /* can't do it */
899 "unsupported operand type(s) for ** or pow(): "
900 "'%.100s' and '%.100s'",
902 w
->ob_type
->tp_name
);
906 "unsupported operand type(s) for pow(): "
907 "'%.100s', '%.100s', '%.100s'",
910 z
->ob_type
->tp_name
);
914 #define BINARY_FUNC(func, op, op_name) \
916 func(PyObject *v, PyObject *w) { \
917 return binary_op(v, w, NB_SLOT(op), op_name); \
920 BINARY_FUNC(PyNumber_Or
, nb_or
, "|")
921 BINARY_FUNC(PyNumber_Xor
, nb_xor
, "^")
922 BINARY_FUNC(PyNumber_And
, nb_and
, "&")
923 BINARY_FUNC(PyNumber_Lshift
, nb_lshift
, "<<")
924 BINARY_FUNC(PyNumber_Rshift
, nb_rshift
, ">>")
925 BINARY_FUNC(PyNumber_Subtract
, nb_subtract
, "-")
926 BINARY_FUNC(PyNumber_Divmod
, nb_divmod
, "divmod()")
929 PyNumber_Add(PyObject
*v
, PyObject
*w
)
931 PyObject
*result
= binary_op1(v
, w
, NB_SLOT(nb_add
));
932 if (result
== Py_NotImplemented
) {
933 PySequenceMethods
*m
= v
->ob_type
->tp_as_sequence
;
935 if (m
&& m
->sq_concat
) {
936 return (*m
->sq_concat
)(v
, w
);
938 result
= binop_type_error(v
, w
, "+");
944 sequence_repeat(ssizeargfunc repeatfunc
, PyObject
*seq
, PyObject
*n
)
947 if (PyIndex_Check(n
)) {
948 count
= PyNumber_AsSsize_t(n
, PyExc_OverflowError
);
949 if (count
== -1 && PyErr_Occurred())
953 return type_error("can't multiply sequence by "
954 "non-int of type '%.200s'", n
);
956 return (*repeatfunc
)(seq
, count
);
960 PyNumber_Multiply(PyObject
*v
, PyObject
*w
)
962 PyObject
*result
= binary_op1(v
, w
, NB_SLOT(nb_multiply
));
963 if (result
== Py_NotImplemented
) {
964 PySequenceMethods
*mv
= v
->ob_type
->tp_as_sequence
;
965 PySequenceMethods
*mw
= w
->ob_type
->tp_as_sequence
;
967 if (mv
&& mv
->sq_repeat
) {
968 return sequence_repeat(mv
->sq_repeat
, v
, w
);
970 else if (mw
&& mw
->sq_repeat
) {
971 return sequence_repeat(mw
->sq_repeat
, w
, v
);
973 result
= binop_type_error(v
, w
, "*");
979 PyNumber_FloorDivide(PyObject
*v
, PyObject
*w
)
981 return binary_op(v
, w
, NB_SLOT(nb_floor_divide
), "//");
985 PyNumber_TrueDivide(PyObject
*v
, PyObject
*w
)
987 return binary_op(v
, w
, NB_SLOT(nb_true_divide
), "/");
991 PyNumber_Remainder(PyObject
*v
, PyObject
*w
)
993 return binary_op(v
, w
, NB_SLOT(nb_remainder
), "%");
997 PyNumber_Power(PyObject
*v
, PyObject
*w
, PyObject
*z
)
999 return ternary_op(v
, w
, z
, NB_SLOT(nb_power
), "** or pow()");
1002 /* Binary in-place operators */
1004 /* The in-place operators are defined to fall back to the 'normal',
1005 non in-place operations, if the in-place methods are not in place.
1007 - If the left hand object has the appropriate struct members, and
1008 they are filled, call the appropriate function and return the
1009 result. No coercion is done on the arguments; the left-hand object
1010 is the one the operation is performed on, and it's up to the
1011 function to deal with the right-hand object.
1013 - Otherwise, in-place modification is not supported. Handle it exactly as
1014 a non in-place operation of the same kind.
1019 binary_iop1(PyObject
*v
, PyObject
*w
, const int iop_slot
, const int op_slot
)
1021 PyNumberMethods
*mv
= v
->ob_type
->tp_as_number
;
1023 binaryfunc slot
= NB_BINOP(mv
, iop_slot
);
1025 PyObject
*x
= (slot
)(v
, w
);
1026 if (x
!= Py_NotImplemented
) {
1032 return binary_op1(v
, w
, op_slot
);
1036 binary_iop(PyObject
*v
, PyObject
*w
, const int iop_slot
, const int op_slot
,
1037 const char *op_name
)
1039 PyObject
*result
= binary_iop1(v
, w
, iop_slot
, op_slot
);
1040 if (result
== Py_NotImplemented
) {
1042 return binop_type_error(v
, w
, op_name
);
1047 #define INPLACE_BINOP(func, iop, op, op_name) \
1049 func(PyObject *v, PyObject *w) { \
1050 return binary_iop(v, w, NB_SLOT(iop), NB_SLOT(op), op_name); \
1053 INPLACE_BINOP(PyNumber_InPlaceOr
, nb_inplace_or
, nb_or
, "|=")
1054 INPLACE_BINOP(PyNumber_InPlaceXor
, nb_inplace_xor
, nb_xor
, "^=")
1055 INPLACE_BINOP(PyNumber_InPlaceAnd
, nb_inplace_and
, nb_and
, "&=")
1056 INPLACE_BINOP(PyNumber_InPlaceLshift
, nb_inplace_lshift
, nb_lshift
, "<<=")
1057 INPLACE_BINOP(PyNumber_InPlaceRshift
, nb_inplace_rshift
, nb_rshift
, ">>=")
1058 INPLACE_BINOP(PyNumber_InPlaceSubtract
, nb_inplace_subtract
, nb_subtract
, "-=")
1061 PyNumber_InPlaceFloorDivide(PyObject
*v
, PyObject
*w
)
1063 return binary_iop(v
, w
, NB_SLOT(nb_inplace_floor_divide
),
1064 NB_SLOT(nb_floor_divide
), "//=");
1068 PyNumber_InPlaceTrueDivide(PyObject
*v
, PyObject
*w
)
1070 return binary_iop(v
, w
, NB_SLOT(nb_inplace_true_divide
),
1071 NB_SLOT(nb_true_divide
), "/=");
1075 PyNumber_InPlaceAdd(PyObject
*v
, PyObject
*w
)
1077 PyObject
*result
= binary_iop1(v
, w
, NB_SLOT(nb_inplace_add
),
1079 if (result
== Py_NotImplemented
) {
1080 PySequenceMethods
*m
= v
->ob_type
->tp_as_sequence
;
1083 binaryfunc f
= NULL
;
1084 f
= m
->sq_inplace_concat
;
1090 result
= binop_type_error(v
, w
, "+=");
1096 PyNumber_InPlaceMultiply(PyObject
*v
, PyObject
*w
)
1098 PyObject
*result
= binary_iop1(v
, w
, NB_SLOT(nb_inplace_multiply
),
1099 NB_SLOT(nb_multiply
));
1100 if (result
== Py_NotImplemented
) {
1101 ssizeargfunc f
= NULL
;
1102 PySequenceMethods
*mv
= v
->ob_type
->tp_as_sequence
;
1103 PySequenceMethods
*mw
= w
->ob_type
->tp_as_sequence
;
1106 f
= mv
->sq_inplace_repeat
;
1110 return sequence_repeat(f
, v
, w
);
1112 else if (mw
!= NULL
) {
1113 /* Note that the right hand operand should not be
1114 * mutated in this case so sq_inplace_repeat is not
1117 return sequence_repeat(mw
->sq_repeat
, w
, v
);
1119 result
= binop_type_error(v
, w
, "*=");
1125 PyNumber_InPlaceRemainder(PyObject
*v
, PyObject
*w
)
1127 return binary_iop(v
, w
, NB_SLOT(nb_inplace_remainder
),
1128 NB_SLOT(nb_remainder
), "%=");
1132 PyNumber_InPlacePower(PyObject
*v
, PyObject
*w
, PyObject
*z
)
1134 if (v
->ob_type
->tp_as_number
&&
1135 v
->ob_type
->tp_as_number
->nb_inplace_power
!= NULL
) {
1136 return ternary_op(v
, w
, z
, NB_SLOT(nb_inplace_power
), "**=");
1139 return ternary_op(v
, w
, z
, NB_SLOT(nb_power
), "**=");
1144 /* Unary operators and functions */
1147 PyNumber_Negative(PyObject
*o
)
1152 return null_error();
1153 m
= o
->ob_type
->tp_as_number
;
1154 if (m
&& m
->nb_negative
)
1155 return (*m
->nb_negative
)(o
);
1157 return type_error("bad operand type for unary -: '%.200s'", o
);
1161 PyNumber_Positive(PyObject
*o
)
1166 return null_error();
1167 m
= o
->ob_type
->tp_as_number
;
1168 if (m
&& m
->nb_positive
)
1169 return (*m
->nb_positive
)(o
);
1171 return type_error("bad operand type for unary +: '%.200s'", o
);
1175 PyNumber_Invert(PyObject
*o
)
1180 return null_error();
1181 m
= o
->ob_type
->tp_as_number
;
1182 if (m
&& m
->nb_invert
)
1183 return (*m
->nb_invert
)(o
);
1185 return type_error("bad operand type for unary ~: '%.200s'", o
);
1189 PyNumber_Absolute(PyObject
*o
)
1194 return null_error();
1195 m
= o
->ob_type
->tp_as_number
;
1196 if (m
&& m
->nb_absolute
)
1197 return m
->nb_absolute(o
);
1199 return type_error("bad operand type for abs(): '%.200s'", o
);
1202 /* Return a Python Int or Long from the object item
1203 Raise TypeError if the result is not an int-or-long
1204 or if the object cannot be interpreted as an index.
1207 PyNumber_Index(PyObject
*item
)
1209 PyObject
*result
= NULL
;
1211 return null_error();
1212 if (PyLong_Check(item
)) {
1216 if (PyIndex_Check(item
)) {
1217 result
= item
->ob_type
->tp_as_number
->nb_index(item
);
1218 if (result
&& !PyLong_Check(result
)) {
1219 PyErr_Format(PyExc_TypeError
,
1220 "__index__ returned non-int "
1222 result
->ob_type
->tp_name
);
1228 PyErr_Format(PyExc_TypeError
,
1229 "'%.200s' object cannot be interpreted "
1230 "as an integer", item
->ob_type
->tp_name
);
1235 /* Return an error on Overflow only if err is not NULL*/
1238 PyNumber_AsSsize_t(PyObject
*item
, PyObject
*err
)
1242 PyObject
*value
= PyNumber_Index(item
);
1246 /* We're done if PyLong_AsSsize_t() returns without error. */
1247 result
= PyLong_AsSsize_t(value
);
1248 if (result
!= -1 || !(runerr
= PyErr_Occurred()))
1251 /* Error handling code -- only manage OverflowError differently */
1252 if (!PyErr_GivenExceptionMatches(runerr
, PyExc_OverflowError
))
1256 /* If no error-handling desired then the default clipping
1260 assert(PyLong_Check(value
));
1261 /* Whether or not it is less than or equal to
1262 zero is determined by the sign of ob_size
1264 if (_PyLong_Sign(value
) < 0)
1265 result
= PY_SSIZE_T_MIN
;
1267 result
= PY_SSIZE_T_MAX
;
1270 /* Otherwise replace the error with caller's error object. */
1272 "cannot fit '%.200s' into an index-sized integer",
1273 item
->ob_type
->tp_name
);
1283 _PyNumber_ConvertIntegralToInt(PyObject
*integral
, const char* error_format
)
1285 static PyObject
*int_name
= NULL
;
1286 if (int_name
== NULL
) {
1287 int_name
= PyUnicode_InternFromString("__int__");
1288 if (int_name
== NULL
)
1292 if (integral
&& !PyLong_Check(integral
)) {
1293 /* Don't go through tp_as_number->nb_int to avoid
1294 hitting the classic class fallback to __trunc__. */
1295 PyObject
*int_func
= PyObject_GetAttr(integral
, int_name
);
1296 if (int_func
== NULL
) {
1297 PyErr_Clear(); /* Raise a different error. */
1298 goto non_integral_error
;
1300 Py_DECREF(integral
);
1301 integral
= PyEval_CallObject(int_func
, NULL
);
1302 Py_DECREF(int_func
);
1303 if (integral
&& !PyLong_Check(integral
)) {
1304 goto non_integral_error
;
1310 PyErr_Format(PyExc_TypeError
, error_format
, Py_TYPE(integral
)->tp_name
);
1311 Py_DECREF(integral
);
1316 /* Add a check for embedded NULL-bytes in the argument. */
1318 long_from_string(const char *s
, Py_ssize_t len
)
1323 x
= PyLong_FromString((char*)s
, &end
, 10);
1326 if (end
!= s
+ len
) {
1327 PyErr_SetString(PyExc_ValueError
,
1328 "null byte in argument for int()");
1336 PyNumber_Long(PyObject
*o
)
1339 static PyObject
*trunc_name
= NULL
;
1340 PyObject
*trunc_func
;
1342 Py_ssize_t buffer_len
;
1344 if (trunc_name
== NULL
) {
1345 trunc_name
= PyUnicode_InternFromString("__trunc__");
1346 if (trunc_name
== NULL
)
1351 return null_error();
1352 if (PyLong_CheckExact(o
)) {
1356 m
= o
->ob_type
->tp_as_number
;
1357 if (m
&& m
->nb_int
) { /* This should include subclasses of int */
1358 PyObject
*res
= m
->nb_int(o
);
1359 if (res
&& !PyLong_Check(res
)) {
1360 PyErr_Format(PyExc_TypeError
,
1361 "__int__ returned non-int (type %.200s)",
1362 res
->ob_type
->tp_name
);
1368 if (PyLong_Check(o
)) /* An int subclass without nb_int */
1369 return _PyLong_Copy((PyLongObject
*)o
);
1370 trunc_func
= PyObject_GetAttr(o
, trunc_name
);
1372 PyObject
*truncated
= PyEval_CallObject(trunc_func
, NULL
);
1373 PyObject
*int_instance
;
1374 Py_DECREF(trunc_func
);
1375 /* __trunc__ is specified to return an Integral type,
1376 but long() needs to return a long. */
1377 int_instance
= _PyNumber_ConvertIntegralToInt(
1379 "__trunc__ returned non-Integral (type %.200s)");
1380 return int_instance
;
1382 PyErr_Clear(); /* It's not an error if o.__trunc__ doesn't exist. */
1384 if (PyBytes_Check(o
))
1385 /* need to do extra error checking that PyLong_FromString()
1386 * doesn't do. In particular long('9.5') must raise an
1387 * exception, not truncate the float.
1389 return long_from_string(PyBytes_AS_STRING(o
),
1390 PyBytes_GET_SIZE(o
));
1391 if (PyUnicode_Check(o
))
1392 /* The above check is done in PyLong_FromUnicode(). */
1393 return PyLong_FromUnicode(PyUnicode_AS_UNICODE(o
),
1394 PyUnicode_GET_SIZE(o
),
1396 if (!PyObject_AsCharBuffer(o
, &buffer
, &buffer_len
))
1397 return long_from_string(buffer
, buffer_len
);
1399 return type_error("int() argument must be a string or a "
1400 "number, not '%.200s'", o
);
1404 PyNumber_Float(PyObject
*o
)
1409 return null_error();
1410 m
= o
->ob_type
->tp_as_number
;
1411 if (m
&& m
->nb_float
) { /* This should include subclasses of float */
1412 PyObject
*res
= m
->nb_float(o
);
1413 if (res
&& !PyFloat_Check(res
)) {
1414 PyErr_Format(PyExc_TypeError
,
1415 "__float__ returned non-float (type %.200s)",
1416 res
->ob_type
->tp_name
);
1422 if (PyFloat_Check(o
)) { /* A float subclass with nb_float == NULL */
1423 PyFloatObject
*po
= (PyFloatObject
*)o
;
1424 return PyFloat_FromDouble(po
->ob_fval
);
1426 return PyFloat_FromString(o
);
1431 PyNumber_ToBase(PyObject
*n
, int base
)
1433 PyObject
*res
= NULL
;
1434 PyObject
*index
= PyNumber_Index(n
);
1438 if (PyLong_Check(index
))
1439 res
= _PyLong_Format(index
, base
);
1441 /* It should not be possible to get here, as
1442 PyNumber_Index already has a check for the same
1444 PyErr_SetString(PyExc_ValueError
, "PyNumber_ToBase: index not "
1451 /* Operations on sequences */
1454 PySequence_Check(PyObject
*s
)
1456 if (PyObject_IsInstance(s
, (PyObject
*)&PyDict_Type
))
1458 return s
!= NULL
&& s
->ob_type
->tp_as_sequence
&&
1459 s
->ob_type
->tp_as_sequence
->sq_item
!= NULL
;
1463 PySequence_Size(PyObject
*s
)
1465 PySequenceMethods
*m
;
1472 m
= s
->ob_type
->tp_as_sequence
;
1473 if (m
&& m
->sq_length
)
1474 return m
->sq_length(s
);
1476 type_error("object of type '%.200s' has no len()", s
);
1480 #undef PySequence_Length
1482 PySequence_Length(PyObject
*s
)
1484 return PySequence_Size(s
);
1486 #define PySequence_Length PySequence_Size
1489 PySequence_Concat(PyObject
*s
, PyObject
*o
)
1491 PySequenceMethods
*m
;
1493 if (s
== NULL
|| o
== NULL
)
1494 return null_error();
1496 m
= s
->ob_type
->tp_as_sequence
;
1497 if (m
&& m
->sq_concat
)
1498 return m
->sq_concat(s
, o
);
1500 /* Instances of user classes defining an __add__() method only
1501 have an nb_add slot, not an sq_concat slot. So we fall back
1502 to nb_add if both arguments appear to be sequences. */
1503 if (PySequence_Check(s
) && PySequence_Check(o
)) {
1504 PyObject
*result
= binary_op1(s
, o
, NB_SLOT(nb_add
));
1505 if (result
!= Py_NotImplemented
)
1509 return type_error("'%.200s' object can't be concatenated", s
);
1513 PySequence_Repeat(PyObject
*o
, Py_ssize_t count
)
1515 PySequenceMethods
*m
;
1518 return null_error();
1520 m
= o
->ob_type
->tp_as_sequence
;
1521 if (m
&& m
->sq_repeat
)
1522 return m
->sq_repeat(o
, count
);
1524 /* Instances of user classes defining a __mul__() method only
1525 have an nb_multiply slot, not an sq_repeat slot. so we fall back
1526 to nb_multiply if o appears to be a sequence. */
1527 if (PySequence_Check(o
)) {
1528 PyObject
*n
, *result
;
1529 n
= PyLong_FromSsize_t(count
);
1532 result
= binary_op1(o
, n
, NB_SLOT(nb_multiply
));
1534 if (result
!= Py_NotImplemented
)
1538 return type_error("'%.200s' object can't be repeated", o
);
1542 PySequence_InPlaceConcat(PyObject
*s
, PyObject
*o
)
1544 PySequenceMethods
*m
;
1546 if (s
== NULL
|| o
== NULL
)
1547 return null_error();
1549 m
= s
->ob_type
->tp_as_sequence
;
1550 if (m
&& m
->sq_inplace_concat
)
1551 return m
->sq_inplace_concat(s
, o
);
1552 if (m
&& m
->sq_concat
)
1553 return m
->sq_concat(s
, o
);
1555 if (PySequence_Check(s
) && PySequence_Check(o
)) {
1556 PyObject
*result
= binary_iop1(s
, o
, NB_SLOT(nb_inplace_add
),
1558 if (result
!= Py_NotImplemented
)
1562 return type_error("'%.200s' object can't be concatenated", s
);
1566 PySequence_InPlaceRepeat(PyObject
*o
, Py_ssize_t count
)
1568 PySequenceMethods
*m
;
1571 return null_error();
1573 m
= o
->ob_type
->tp_as_sequence
;
1574 if (m
&& m
->sq_inplace_repeat
)
1575 return m
->sq_inplace_repeat(o
, count
);
1576 if (m
&& m
->sq_repeat
)
1577 return m
->sq_repeat(o
, count
);
1579 if (PySequence_Check(o
)) {
1580 PyObject
*n
, *result
;
1581 n
= PyLong_FromSsize_t(count
);
1584 result
= binary_iop1(o
, n
, NB_SLOT(nb_inplace_multiply
),
1585 NB_SLOT(nb_multiply
));
1587 if (result
!= Py_NotImplemented
)
1591 return type_error("'%.200s' object can't be repeated", o
);
1595 PySequence_GetItem(PyObject
*s
, Py_ssize_t i
)
1597 PySequenceMethods
*m
;
1600 return null_error();
1602 m
= s
->ob_type
->tp_as_sequence
;
1603 if (m
&& m
->sq_item
) {
1606 Py_ssize_t l
= (*m
->sq_length
)(s
);
1612 return m
->sq_item(s
, i
);
1615 return type_error("'%.200s' object does not support indexing", s
);
1619 PySequence_GetSlice(PyObject
*s
, Py_ssize_t i1
, Py_ssize_t i2
)
1621 PyMappingMethods
*mp
;
1623 if (!s
) return null_error();
1625 mp
= s
->ob_type
->tp_as_mapping
;
1626 if (mp
->mp_subscript
) {
1628 PyObject
*slice
= _PySlice_FromIndices(i1
, i2
);
1631 res
= mp
->mp_subscript(s
, slice
);
1636 return type_error("'%.200s' object is unsliceable", s
);
1640 PySequence_SetItem(PyObject
*s
, Py_ssize_t i
, PyObject
*o
)
1642 PySequenceMethods
*m
;
1649 m
= s
->ob_type
->tp_as_sequence
;
1650 if (m
&& m
->sq_ass_item
) {
1653 Py_ssize_t l
= (*m
->sq_length
)(s
);
1659 return m
->sq_ass_item(s
, i
, o
);
1662 type_error("'%.200s' object does not support item assignment", s
);
1667 PySequence_DelItem(PyObject
*s
, Py_ssize_t i
)
1669 PySequenceMethods
*m
;
1676 m
= s
->ob_type
->tp_as_sequence
;
1677 if (m
&& m
->sq_ass_item
) {
1680 Py_ssize_t l
= (*m
->sq_length
)(s
);
1686 return m
->sq_ass_item(s
, i
, (PyObject
*)NULL
);
1689 type_error("'%.200s' object doesn't support item deletion", s
);
1694 PySequence_SetSlice(PyObject
*s
, Py_ssize_t i1
, Py_ssize_t i2
, PyObject
*o
)
1696 PyMappingMethods
*mp
;
1703 mp
= s
->ob_type
->tp_as_mapping
;
1704 if (mp
->mp_ass_subscript
) {
1706 PyObject
*slice
= _PySlice_FromIndices(i1
, i2
);
1709 res
= mp
->mp_ass_subscript(s
, slice
, o
);
1714 type_error("'%.200s' object doesn't support slice assignment", s
);
1719 PySequence_DelSlice(PyObject
*s
, Py_ssize_t i1
, Py_ssize_t i2
)
1721 PyMappingMethods
*mp
;
1728 mp
= s
->ob_type
->tp_as_mapping
;
1729 if (mp
->mp_ass_subscript
) {
1731 PyObject
*slice
= _PySlice_FromIndices(i1
, i2
);
1734 res
= mp
->mp_ass_subscript(s
, slice
, NULL
);
1738 type_error("'%.200s' object doesn't support slice deletion", s
);
1743 PySequence_Tuple(PyObject
*v
)
1745 PyObject
*it
; /* iter(v) */
1746 Py_ssize_t n
; /* guess for result tuple size */
1747 PyObject
*result
= NULL
;
1751 return null_error();
1753 /* Special-case the common tuple and list cases, for efficiency. */
1754 if (PyTuple_CheckExact(v
)) {
1755 /* Note that we can't know whether it's safe to return
1756 a tuple *subclass* instance as-is, hence the restriction
1757 to exact tuples here. In contrast, lists always make
1758 a copy, so there's no need for exactness below. */
1762 if (PyList_Check(v
))
1763 return PyList_AsTuple(v
);
1766 it
= PyObject_GetIter(v
);
1770 /* Guess result size and allocate space. */
1771 n
= _PyObject_LengthHint(v
, 10);
1774 result
= PyTuple_New(n
);
1778 /* Fill the tuple. */
1779 for (j
= 0; ; ++j
) {
1780 PyObject
*item
= PyIter_Next(it
);
1782 if (PyErr_Occurred())
1787 Py_ssize_t oldn
= n
;
1788 /* The over-allocation strategy can grow a bit faster
1789 than for lists because unlike lists the
1790 over-allocation isn't permanent -- we reclaim
1791 the excess before the end of this routine.
1792 So, grow by ten and then add 25%.
1797 /* Check for overflow */
1802 if (_PyTuple_Resize(&result
, n
) != 0) {
1807 PyTuple_SET_ITEM(result
, j
, item
);
1810 /* Cut tuple back if guess was too large. */
1812 _PyTuple_Resize(&result
, j
) != 0)
1825 PySequence_List(PyObject
*v
)
1827 PyObject
*result
; /* result list */
1828 PyObject
*rv
; /* return value from PyList_Extend */
1831 return null_error();
1833 result
= PyList_New(0);
1837 rv
= _PyList_Extend((PyListObject
*)result
, v
);
1847 PySequence_Fast(PyObject
*v
, const char *m
)
1852 return null_error();
1854 if (PyList_CheckExact(v
) || PyTuple_CheckExact(v
)) {
1859 it
= PyObject_GetIter(v
);
1861 if (PyErr_ExceptionMatches(PyExc_TypeError
))
1862 PyErr_SetString(PyExc_TypeError
, m
);
1866 v
= PySequence_List(it
);
1872 /* Iterate over seq. Result depends on the operation:
1873 PY_ITERSEARCH_COUNT: -1 if error, else # of times obj appears in seq.
1874 PY_ITERSEARCH_INDEX: 0-based index of first occurrence of obj in seq;
1875 set ValueError and return -1 if none found; also return -1 on error.
1876 Py_ITERSEARCH_CONTAINS: return 1 if obj in seq, else 0; -1 on error.
1879 _PySequence_IterSearch(PyObject
*seq
, PyObject
*obj
, int operation
)
1882 int wrapped
; /* for PY_ITERSEARCH_INDEX, true iff n wrapped around */
1883 PyObject
*it
; /* iter(seq) */
1885 if (seq
== NULL
|| obj
== NULL
) {
1890 it
= PyObject_GetIter(seq
);
1892 type_error("argument of type '%.200s' is not iterable", seq
);
1899 PyObject
*item
= PyIter_Next(it
);
1901 if (PyErr_Occurred())
1906 cmp
= PyObject_RichCompareBool(obj
, item
, Py_EQ
);
1911 switch (operation
) {
1912 case PY_ITERSEARCH_COUNT
:
1913 if (n
== PY_SSIZE_T_MAX
) {
1914 PyErr_SetString(PyExc_OverflowError
,
1915 "count exceeds C integer size");
1921 case PY_ITERSEARCH_INDEX
:
1923 PyErr_SetString(PyExc_OverflowError
,
1924 "index exceeds C integer size");
1929 case PY_ITERSEARCH_CONTAINS
:
1934 assert(!"unknown operation");
1938 if (operation
== PY_ITERSEARCH_INDEX
) {
1939 if (n
== PY_SSIZE_T_MAX
)
1945 if (operation
!= PY_ITERSEARCH_INDEX
)
1948 PyErr_SetString(PyExc_ValueError
,
1949 "sequence.index(x): x not in sequence");
1950 /* fall into failure code */
1960 /* Return # of times o appears in s. */
1962 PySequence_Count(PyObject
*s
, PyObject
*o
)
1964 return _PySequence_IterSearch(s
, o
, PY_ITERSEARCH_COUNT
);
1967 /* Return -1 if error; 1 if ob in seq; 0 if ob not in seq.
1968 * Use sq_contains if possible, else defer to _PySequence_IterSearch().
1971 PySequence_Contains(PyObject
*seq
, PyObject
*ob
)
1974 PySequenceMethods
*sqm
= seq
->ob_type
->tp_as_sequence
;
1975 if (sqm
!= NULL
&& sqm
->sq_contains
!= NULL
)
1976 return (*sqm
->sq_contains
)(seq
, ob
);
1977 result
= _PySequence_IterSearch(seq
, ob
, PY_ITERSEARCH_CONTAINS
);
1978 return Py_SAFE_DOWNCAST(result
, Py_ssize_t
, int);
1981 /* Backwards compatibility */
1982 #undef PySequence_In
1984 PySequence_In(PyObject
*w
, PyObject
*v
)
1986 return PySequence_Contains(w
, v
);
1990 PySequence_Index(PyObject
*s
, PyObject
*o
)
1992 return _PySequence_IterSearch(s
, o
, PY_ITERSEARCH_INDEX
);
1995 /* Operations on mappings */
1998 PyMapping_Check(PyObject
*o
)
2000 return o
&& o
->ob_type
->tp_as_mapping
&&
2001 o
->ob_type
->tp_as_mapping
->mp_subscript
;
2005 PyMapping_Size(PyObject
*o
)
2007 PyMappingMethods
*m
;
2014 m
= o
->ob_type
->tp_as_mapping
;
2015 if (m
&& m
->mp_length
)
2016 return m
->mp_length(o
);
2018 type_error("object of type '%.200s' has no len()", o
);
2022 #undef PyMapping_Length
2024 PyMapping_Length(PyObject
*o
)
2026 return PyMapping_Size(o
);
2028 #define PyMapping_Length PyMapping_Size
2031 PyMapping_GetItemString(PyObject
*o
, char *key
)
2036 return null_error();
2038 okey
= PyUnicode_FromString(key
);
2041 r
= PyObject_GetItem(o
, okey
);
2047 PyMapping_SetItemString(PyObject
*o
, char *key
, PyObject
*value
)
2057 okey
= PyUnicode_FromString(key
);
2060 r
= PyObject_SetItem(o
, okey
, value
);
2066 PyMapping_HasKeyString(PyObject
*o
, char *key
)
2070 v
= PyMapping_GetItemString(o
, key
);
2080 PyMapping_HasKey(PyObject
*o
, PyObject
*key
)
2084 v
= PyObject_GetItem(o
, key
);
2094 PyMapping_Keys(PyObject
*o
)
2099 if (PyDict_CheckExact(o
))
2100 return PyDict_Keys(o
);
2101 keys
= PyObject_CallMethod(o
, "keys", NULL
);
2104 fast
= PySequence_Fast(keys
, "o.keys() are not iterable");
2110 PyMapping_Items(PyObject
*o
)
2115 if (PyDict_CheckExact(o
))
2116 return PyDict_Items(o
);
2117 items
= PyObject_CallMethod(o
, "items", NULL
);
2120 fast
= PySequence_Fast(items
, "o.items() are not iterable");
2126 PyMapping_Values(PyObject
*o
)
2131 if (PyDict_CheckExact(o
))
2132 return PyDict_Values(o
);
2133 values
= PyObject_CallMethod(o
, "values", NULL
);
2136 fast
= PySequence_Fast(values
, "o.values() are not iterable");
2141 /* Operations on callable objects */
2143 /* XXX PyCallable_Check() is in object.c */
2146 PyObject_CallObject(PyObject
*o
, PyObject
*a
)
2148 return PyEval_CallObjectWithKeywords(o
, a
, NULL
);
2152 PyObject_Call(PyObject
*func
, PyObject
*arg
, PyObject
*kw
)
2156 if ((call
= func
->ob_type
->tp_call
) != NULL
) {
2158 if (Py_EnterRecursiveCall(" while calling a Python object"))
2160 result
= (*call
)(func
, arg
, kw
);
2161 Py_LeaveRecursiveCall();
2162 if (result
== NULL
&& !PyErr_Occurred())
2165 "NULL result without error in PyObject_Call");
2168 PyErr_Format(PyExc_TypeError
, "'%.200s' object is not callable",
2169 func
->ob_type
->tp_name
);
2174 call_function_tail(PyObject
*callable
, PyObject
*args
)
2181 if (!PyTuple_Check(args
)) {
2189 PyTuple_SET_ITEM(a
, 0, args
);
2192 retval
= PyObject_Call(callable
, args
, NULL
);
2200 PyObject_CallFunction(PyObject
*callable
, char *format
, ...)
2205 if (callable
== NULL
)
2206 return null_error();
2208 if (format
&& *format
) {
2209 va_start(va
, format
);
2210 args
= Py_VaBuildValue(format
, va
);
2214 args
= PyTuple_New(0);
2216 return call_function_tail(callable
, args
);
2220 _PyObject_CallFunction_SizeT(PyObject
*callable
, char *format
, ...)
2225 if (callable
== NULL
)
2226 return null_error();
2228 if (format
&& *format
) {
2229 va_start(va
, format
);
2230 args
= _Py_VaBuildValue_SizeT(format
, va
);
2234 args
= PyTuple_New(0);
2236 return call_function_tail(callable
, args
);
2240 PyObject_CallMethod(PyObject
*o
, char *name
, char *format
, ...)
2244 PyObject
*func
= NULL
;
2245 PyObject
*retval
= NULL
;
2247 if (o
== NULL
|| name
== NULL
)
2248 return null_error();
2250 func
= PyObject_GetAttrString(o
, name
);
2252 PyErr_SetString(PyExc_AttributeError
, name
);
2256 if (!PyCallable_Check(func
)) {
2257 type_error("attribute of type '%.200s' is not callable", func
);
2261 if (format
&& *format
) {
2262 va_start(va
, format
);
2263 args
= Py_VaBuildValue(format
, va
);
2267 args
= PyTuple_New(0);
2269 retval
= call_function_tail(func
, args
);
2272 /* args gets consumed in call_function_tail */
2279 _PyObject_CallMethod_SizeT(PyObject
*o
, char *name
, char *format
, ...)
2283 PyObject
*func
= NULL
;
2284 PyObject
*retval
= NULL
;
2286 if (o
== NULL
|| name
== NULL
)
2287 return null_error();
2289 func
= PyObject_GetAttrString(o
, name
);
2291 PyErr_SetString(PyExc_AttributeError
, name
);
2295 if (!PyCallable_Check(func
)) {
2296 type_error("attribute of type '%.200s' is not callable", func
);
2300 if (format
&& *format
) {
2301 va_start(va
, format
);
2302 args
= _Py_VaBuildValue_SizeT(format
, va
);
2306 args
= PyTuple_New(0);
2308 retval
= call_function_tail(func
, args
);
2311 /* args gets consumed in call_function_tail */
2319 objargs_mktuple(va_list va
)
2323 PyObject
*result
, *tmp
;
2325 #ifdef VA_LIST_IS_ARRAY
2326 memcpy(countva
, va
, sizeof(va_list));
2329 __va_copy(countva
, va
);
2335 while (((PyObject
*)va_arg(countva
, PyObject
*)) != NULL
)
2337 result
= PyTuple_New(n
);
2338 if (result
!= NULL
&& n
> 0) {
2339 for (i
= 0; i
< n
; ++i
) {
2340 tmp
= (PyObject
*)va_arg(va
, PyObject
*);
2341 PyTuple_SET_ITEM(result
, i
, tmp
);
2349 PyObject_CallMethodObjArgs(PyObject
*callable
, PyObject
*name
, ...)
2351 PyObject
*args
, *tmp
;
2354 if (callable
== NULL
|| name
== NULL
)
2355 return null_error();
2357 callable
= PyObject_GetAttr(callable
, name
);
2358 if (callable
== NULL
)
2361 /* count the args */
2362 va_start(vargs
, name
);
2363 args
= objargs_mktuple(vargs
);
2366 Py_DECREF(callable
);
2369 tmp
= PyObject_Call(callable
, args
, NULL
);
2371 Py_DECREF(callable
);
2377 PyObject_CallFunctionObjArgs(PyObject
*callable
, ...)
2379 PyObject
*args
, *tmp
;
2382 if (callable
== NULL
)
2383 return null_error();
2385 /* count the args */
2386 va_start(vargs
, callable
);
2387 args
= objargs_mktuple(vargs
);
2391 tmp
= PyObject_Call(callable
, args
, NULL
);
2398 /* isinstance(), issubclass() */
2400 /* abstract_get_bases() has logically 4 return states, with a sort of 0th
2401 * state that will almost never happen.
2403 * 0. creating the __bases__ static string could get a MemoryError
2404 * 1. getattr(cls, '__bases__') could raise an AttributeError
2405 * 2. getattr(cls, '__bases__') could raise some other exception
2406 * 3. getattr(cls, '__bases__') could return a tuple
2407 * 4. getattr(cls, '__bases__') could return something other than a tuple
2409 * Only state #3 is a non-error state and only it returns a non-NULL object
2410 * (it returns the retrieved tuple).
2412 * Any raised AttributeErrors are masked by clearing the exception and
2413 * returning NULL. If an object other than a tuple comes out of __bases__,
2414 * then again, the return value is NULL. So yes, these two situations
2415 * produce exactly the same results: NULL is returned and no error is set.
2417 * If some exception other than AttributeError is raised, then NULL is also
2418 * returned, but the exception is not cleared. That's because we want the
2419 * exception to be propagated along.
2421 * Callers are expected to test for PyErr_Occurred() when the return value
2422 * is NULL to decide whether a valid exception should be propagated or not.
2423 * When there's no exception to propagate, it's customary for the caller to
2427 abstract_get_bases(PyObject
*cls
)
2429 static PyObject
*__bases__
= NULL
;
2432 if (__bases__
== NULL
) {
2433 __bases__
= PyUnicode_InternFromString("__bases__");
2434 if (__bases__
== NULL
)
2438 bases
= PyObject_GetAttr(cls
, __bases__
);
2439 Py_END_ALLOW_RECURSION
2440 if (bases
== NULL
) {
2441 if (PyErr_ExceptionMatches(PyExc_AttributeError
))
2445 if (!PyTuple_Check(bases
)) {
2454 abstract_issubclass(PyObject
*derived
, PyObject
*cls
)
2456 PyObject
*bases
= NULL
;
2463 bases
= abstract_get_bases(derived
);
2464 if (bases
== NULL
) {
2465 if (PyErr_Occurred())
2469 n
= PyTuple_GET_SIZE(bases
);
2474 /* Avoid recursivity in the single inheritance case */
2476 derived
= PyTuple_GET_ITEM(bases
, 0);
2480 for (i
= 0; i
< n
; i
++) {
2481 r
= abstract_issubclass(PyTuple_GET_ITEM(bases
, i
), cls
);
2491 check_class(PyObject
*cls
, const char *error
)
2493 PyObject
*bases
= abstract_get_bases(cls
);
2494 if (bases
== NULL
) {
2495 /* Do not mask errors. */
2496 if (!PyErr_Occurred())
2497 PyErr_SetString(PyExc_TypeError
, error
);
2505 recursive_isinstance(PyObject
*inst
, PyObject
*cls
)
2508 static PyObject
*__class__
= NULL
;
2511 if (__class__
== NULL
) {
2512 __class__
= PyUnicode_InternFromString("__class__");
2513 if (__class__
== NULL
)
2517 if (PyType_Check(cls
)) {
2518 retval
= PyObject_TypeCheck(inst
, (PyTypeObject
*)cls
);
2520 PyObject
*c
= PyObject_GetAttr(inst
, __class__
);
2525 if (c
!= (PyObject
*)(inst
->ob_type
) &&
2527 retval
= PyType_IsSubtype(
2529 (PyTypeObject
*)cls
);
2535 if (!check_class(cls
,
2536 "isinstance() arg 2 must be a class, type,"
2537 " or tuple of classes and types"))
2539 icls
= PyObject_GetAttr(inst
, __class__
);
2545 retval
= abstract_issubclass(icls
, cls
);
2554 PyObject_IsInstance(PyObject
*inst
, PyObject
*cls
)
2556 static PyObject
*name
= NULL
;
2559 /* Quick test for an exact match */
2560 if (Py_TYPE(inst
) == (PyTypeObject
*)cls
)
2563 if (PyTuple_Check(cls
)) {
2568 if (Py_EnterRecursiveCall(" in __instancecheck__"))
2570 n
= PyTuple_GET_SIZE(cls
);
2571 for (i
= 0; i
< n
; ++i
) {
2572 PyObject
*item
= PyTuple_GET_ITEM(cls
, i
);
2573 r
= PyObject_IsInstance(inst
, item
);
2575 /* either found it, or got an error */
2578 Py_LeaveRecursiveCall();
2582 checker
= _PyObject_LookupSpecial(cls
, "__instancecheck__", &name
);
2583 if (checker
!= NULL
) {
2586 if (Py_EnterRecursiveCall(" in __instancecheck__")) {
2590 res
= PyObject_CallFunctionObjArgs(checker
, inst
, NULL
);
2591 Py_LeaveRecursiveCall();
2594 ok
= PyObject_IsTrue(res
);
2599 else if (PyErr_Occurred())
2601 return recursive_isinstance(inst
, cls
);
2605 recursive_issubclass(PyObject
*derived
, PyObject
*cls
)
2607 if (PyType_Check(cls
) && PyType_Check(derived
)) {
2608 /* Fast path (non-recursive) */
2609 return PyType_IsSubtype((PyTypeObject
*)derived
, (PyTypeObject
*)cls
);
2611 if (!check_class(derived
,
2612 "issubclass() arg 1 must be a class"))
2614 if (!check_class(cls
,
2615 "issubclass() arg 2 must be a class"
2616 " or tuple of classes"))
2619 return abstract_issubclass(derived
, cls
);
2623 PyObject_IsSubclass(PyObject
*derived
, PyObject
*cls
)
2625 static PyObject
*name
= NULL
;
2628 if (PyTuple_Check(cls
)) {
2633 if (Py_EnterRecursiveCall(" in __subclasscheck__"))
2635 n
= PyTuple_GET_SIZE(cls
);
2636 for (i
= 0; i
< n
; ++i
) {
2637 PyObject
*item
= PyTuple_GET_ITEM(cls
, i
);
2638 r
= PyObject_IsSubclass(derived
, item
);
2640 /* either found it, or got an error */
2643 Py_LeaveRecursiveCall();
2647 checker
= _PyObject_LookupSpecial(cls
, "__subclasscheck__", &name
);
2648 if (checker
!= NULL
) {
2651 if (Py_EnterRecursiveCall(" in __subclasscheck__")) {
2655 res
= PyObject_CallFunctionObjArgs(checker
, derived
, NULL
);
2656 Py_LeaveRecursiveCall();
2659 ok
= PyObject_IsTrue(res
);
2664 else if (PyErr_Occurred())
2666 return recursive_issubclass(derived
, cls
);
2670 _PyObject_RealIsInstance(PyObject
*inst
, PyObject
*cls
)
2672 return recursive_isinstance(inst
, cls
);
2676 _PyObject_RealIsSubclass(PyObject
*derived
, PyObject
*cls
)
2678 return recursive_issubclass(derived
, cls
);
2683 PyObject_GetIter(PyObject
*o
)
2685 PyTypeObject
*t
= o
->ob_type
;
2686 getiterfunc f
= NULL
;
2689 if (PySequence_Check(o
))
2690 return PySeqIter_New(o
);
2691 return type_error("'%.200s' object is not iterable", o
);
2694 PyObject
*res
= (*f
)(o
);
2695 if (res
!= NULL
&& !PyIter_Check(res
)) {
2696 PyErr_Format(PyExc_TypeError
,
2697 "iter() returned non-iterator "
2699 res
->ob_type
->tp_name
);
2707 /* Return next item.
2708 * If an error occurs, return NULL. PyErr_Occurred() will be true.
2709 * If the iteration terminates normally, return NULL and clear the
2710 * PyExc_StopIteration exception (if it was set). PyErr_Occurred()
2712 * Else return the next object. PyErr_Occurred() will be false.
2715 PyIter_Next(PyObject
*iter
)
2718 result
= (*iter
->ob_type
->tp_iternext
)(iter
);
2719 if (result
== NULL
&&
2721 PyErr_ExceptionMatches(PyExc_StopIteration
))