Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
allendowney
GitHub Repository: allendowney/cpython
Path: blob/main/Objects/abstract.c
12 views
1
/* Abstract Object Interface (many thanks to Jim Fulton) */
2
3
#include "Python.h"
4
#include "pycore_abstract.h" // _PyIndex_Check()
5
#include "pycore_call.h" // _PyObject_CallNoArgs()
6
#include "pycore_ceval.h" // _Py_EnterRecursiveCallTstate()
7
#include "pycore_object.h" // _Py_CheckSlotResult()
8
#include "pycore_long.h" // _Py_IsNegative
9
#include "pycore_pyerrors.h" // _PyErr_Occurred()
10
#include "pycore_pystate.h" // _PyThreadState_GET()
11
#include "pycore_unionobject.h" // _PyUnion_Check()
12
#include <ctype.h>
13
#include <stddef.h> // offsetof()
14
15
16
17
/* Shorthands to return certain errors */
18
19
static PyObject *
20
type_error(const char *msg, PyObject *obj)
21
{
22
PyErr_Format(PyExc_TypeError, msg, Py_TYPE(obj)->tp_name);
23
return NULL;
24
}
25
26
static PyObject *
27
null_error(void)
28
{
29
PyThreadState *tstate = _PyThreadState_GET();
30
if (!_PyErr_Occurred(tstate)) {
31
_PyErr_SetString(tstate, PyExc_SystemError,
32
"null argument to internal routine");
33
}
34
return NULL;
35
}
36
37
/* Operations on any object */
38
39
PyObject *
40
PyObject_Type(PyObject *o)
41
{
42
PyObject *v;
43
44
if (o == NULL) {
45
return null_error();
46
}
47
48
v = (PyObject *)Py_TYPE(o);
49
return Py_NewRef(v);
50
}
51
52
Py_ssize_t
53
PyObject_Size(PyObject *o)
54
{
55
if (o == NULL) {
56
null_error();
57
return -1;
58
}
59
60
PySequenceMethods *m = Py_TYPE(o)->tp_as_sequence;
61
if (m && m->sq_length) {
62
Py_ssize_t len = m->sq_length(o);
63
assert(_Py_CheckSlotResult(o, "__len__", len >= 0));
64
return len;
65
}
66
67
return PyMapping_Size(o);
68
}
69
70
#undef PyObject_Length
71
Py_ssize_t
72
PyObject_Length(PyObject *o)
73
{
74
return PyObject_Size(o);
75
}
76
#define PyObject_Length PyObject_Size
77
78
int
79
_PyObject_HasLen(PyObject *o) {
80
return (Py_TYPE(o)->tp_as_sequence && Py_TYPE(o)->tp_as_sequence->sq_length) ||
81
(Py_TYPE(o)->tp_as_mapping && Py_TYPE(o)->tp_as_mapping->mp_length);
82
}
83
84
/* The length hint function returns a non-negative value from o.__len__()
85
or o.__length_hint__(). If those methods aren't found the defaultvalue is
86
returned. If one of the calls fails with an exception other than TypeError
87
this function returns -1.
88
*/
89
90
Py_ssize_t
91
PyObject_LengthHint(PyObject *o, Py_ssize_t defaultvalue)
92
{
93
PyObject *hint, *result;
94
Py_ssize_t res;
95
if (_PyObject_HasLen(o)) {
96
res = PyObject_Length(o);
97
if (res < 0) {
98
PyThreadState *tstate = _PyThreadState_GET();
99
assert(_PyErr_Occurred(tstate));
100
if (!_PyErr_ExceptionMatches(tstate, PyExc_TypeError)) {
101
return -1;
102
}
103
_PyErr_Clear(tstate);
104
}
105
else {
106
return res;
107
}
108
}
109
hint = _PyObject_LookupSpecial(o, &_Py_ID(__length_hint__));
110
if (hint == NULL) {
111
if (PyErr_Occurred()) {
112
return -1;
113
}
114
return defaultvalue;
115
}
116
result = _PyObject_CallNoArgs(hint);
117
Py_DECREF(hint);
118
if (result == NULL) {
119
PyThreadState *tstate = _PyThreadState_GET();
120
if (_PyErr_ExceptionMatches(tstate, PyExc_TypeError)) {
121
_PyErr_Clear(tstate);
122
return defaultvalue;
123
}
124
return -1;
125
}
126
else if (result == Py_NotImplemented) {
127
Py_DECREF(result);
128
return defaultvalue;
129
}
130
if (!PyLong_Check(result)) {
131
PyErr_Format(PyExc_TypeError, "__length_hint__ must be an integer, not %.100s",
132
Py_TYPE(result)->tp_name);
133
Py_DECREF(result);
134
return -1;
135
}
136
res = PyLong_AsSsize_t(result);
137
Py_DECREF(result);
138
if (res < 0 && PyErr_Occurred()) {
139
return -1;
140
}
141
if (res < 0) {
142
PyErr_Format(PyExc_ValueError, "__length_hint__() should return >= 0");
143
return -1;
144
}
145
return res;
146
}
147
148
PyObject *
149
PyObject_GetItem(PyObject *o, PyObject *key)
150
{
151
if (o == NULL || key == NULL) {
152
return null_error();
153
}
154
155
PyMappingMethods *m = Py_TYPE(o)->tp_as_mapping;
156
if (m && m->mp_subscript) {
157
PyObject *item = m->mp_subscript(o, key);
158
assert(_Py_CheckSlotResult(o, "__getitem__", item != NULL));
159
return item;
160
}
161
162
PySequenceMethods *ms = Py_TYPE(o)->tp_as_sequence;
163
if (ms && ms->sq_item) {
164
if (_PyIndex_Check(key)) {
165
Py_ssize_t key_value;
166
key_value = PyNumber_AsSsize_t(key, PyExc_IndexError);
167
if (key_value == -1 && PyErr_Occurred())
168
return NULL;
169
return PySequence_GetItem(o, key_value);
170
}
171
else {
172
return type_error("sequence index must "
173
"be integer, not '%.200s'", key);
174
}
175
}
176
177
if (PyType_Check(o)) {
178
PyObject *meth, *result;
179
180
// Special case type[int], but disallow other types so str[int] fails
181
if ((PyTypeObject*)o == &PyType_Type) {
182
return Py_GenericAlias(o, key);
183
}
184
185
if (_PyObject_LookupAttr(o, &_Py_ID(__class_getitem__), &meth) < 0) {
186
return NULL;
187
}
188
if (meth && meth != Py_None) {
189
result = PyObject_CallOneArg(meth, key);
190
Py_DECREF(meth);
191
return result;
192
}
193
Py_XDECREF(meth);
194
PyErr_Format(PyExc_TypeError, "type '%.200s' is not subscriptable",
195
((PyTypeObject *)o)->tp_name);
196
return NULL;
197
}
198
199
return type_error("'%.200s' object is not subscriptable", o);
200
}
201
202
int
203
PyObject_SetItem(PyObject *o, PyObject *key, PyObject *value)
204
{
205
if (o == NULL || key == NULL || value == NULL) {
206
null_error();
207
return -1;
208
}
209
210
PyMappingMethods *m = Py_TYPE(o)->tp_as_mapping;
211
if (m && m->mp_ass_subscript) {
212
int res = m->mp_ass_subscript(o, key, value);
213
assert(_Py_CheckSlotResult(o, "__setitem__", res >= 0));
214
return res;
215
}
216
217
if (Py_TYPE(o)->tp_as_sequence) {
218
if (_PyIndex_Check(key)) {
219
Py_ssize_t key_value;
220
key_value = PyNumber_AsSsize_t(key, PyExc_IndexError);
221
if (key_value == -1 && PyErr_Occurred())
222
return -1;
223
return PySequence_SetItem(o, key_value, value);
224
}
225
else if (Py_TYPE(o)->tp_as_sequence->sq_ass_item) {
226
type_error("sequence index must be "
227
"integer, not '%.200s'", key);
228
return -1;
229
}
230
}
231
232
type_error("'%.200s' object does not support item assignment", o);
233
return -1;
234
}
235
236
int
237
PyObject_DelItem(PyObject *o, PyObject *key)
238
{
239
if (o == NULL || key == NULL) {
240
null_error();
241
return -1;
242
}
243
244
PyMappingMethods *m = Py_TYPE(o)->tp_as_mapping;
245
if (m && m->mp_ass_subscript) {
246
int res = m->mp_ass_subscript(o, key, (PyObject*)NULL);
247
assert(_Py_CheckSlotResult(o, "__delitem__", res >= 0));
248
return res;
249
}
250
251
if (Py_TYPE(o)->tp_as_sequence) {
252
if (_PyIndex_Check(key)) {
253
Py_ssize_t key_value;
254
key_value = PyNumber_AsSsize_t(key, PyExc_IndexError);
255
if (key_value == -1 && PyErr_Occurred())
256
return -1;
257
return PySequence_DelItem(o, key_value);
258
}
259
else if (Py_TYPE(o)->tp_as_sequence->sq_ass_item) {
260
type_error("sequence index must be "
261
"integer, not '%.200s'", key);
262
return -1;
263
}
264
}
265
266
type_error("'%.200s' object does not support item deletion", o);
267
return -1;
268
}
269
270
int
271
PyObject_DelItemString(PyObject *o, const char *key)
272
{
273
PyObject *okey;
274
int ret;
275
276
if (o == NULL || key == NULL) {
277
null_error();
278
return -1;
279
}
280
okey = PyUnicode_FromString(key);
281
if (okey == NULL)
282
return -1;
283
ret = PyObject_DelItem(o, okey);
284
Py_DECREF(okey);
285
return ret;
286
}
287
288
289
/* Return 1 if the getbuffer function is available, otherwise return 0. */
290
int
291
PyObject_CheckBuffer(PyObject *obj)
292
{
293
PyBufferProcs *tp_as_buffer = Py_TYPE(obj)->tp_as_buffer;
294
return (tp_as_buffer != NULL && tp_as_buffer->bf_getbuffer != NULL);
295
}
296
297
// Old buffer protocols (deprecated, abi only)
298
299
/* Checks whether an arbitrary object supports the (character, single segment)
300
buffer interface.
301
302
Returns 1 on success, 0 on failure.
303
304
We release the buffer right after use of this function which could
305
cause issues later on. Don't use these functions in new code.
306
*/
307
PyAPI_FUNC(int) /* abi_only */
308
PyObject_CheckReadBuffer(PyObject *obj)
309
{
310
PyBufferProcs *pb = Py_TYPE(obj)->tp_as_buffer;
311
Py_buffer view;
312
313
if (pb == NULL ||
314
pb->bf_getbuffer == NULL)
315
return 0;
316
if ((*pb->bf_getbuffer)(obj, &view, PyBUF_SIMPLE) == -1) {
317
PyErr_Clear();
318
return 0;
319
}
320
PyBuffer_Release(&view);
321
return 1;
322
}
323
324
static int
325
as_read_buffer(PyObject *obj, const void **buffer, Py_ssize_t *buffer_len)
326
{
327
Py_buffer view;
328
329
if (obj == NULL || buffer == NULL || buffer_len == NULL) {
330
null_error();
331
return -1;
332
}
333
if (PyObject_GetBuffer(obj, &view, PyBUF_SIMPLE) != 0)
334
return -1;
335
336
*buffer = view.buf;
337
*buffer_len = view.len;
338
PyBuffer_Release(&view);
339
return 0;
340
}
341
342
/* Takes an arbitrary object which must support the (character, single segment)
343
buffer interface and returns a pointer to a read-only memory location
344
usable as character based input for subsequent processing.
345
346
Return 0 on success. buffer and buffer_len are only set in case no error
347
occurs. Otherwise, -1 is returned and an exception set. */
348
PyAPI_FUNC(int) /* abi_only */
349
PyObject_AsCharBuffer(PyObject *obj,
350
const char **buffer,
351
Py_ssize_t *buffer_len)
352
{
353
return as_read_buffer(obj, (const void **)buffer, buffer_len);
354
}
355
356
/* Same as PyObject_AsCharBuffer() except that this API expects (readable,
357
single segment) buffer interface and returns a pointer to a read-only memory
358
location which can contain arbitrary data.
359
360
0 is returned on success. buffer and buffer_len are only set in case no
361
error occurs. Otherwise, -1 is returned and an exception set. */
362
PyAPI_FUNC(int) /* abi_only */
363
PyObject_AsReadBuffer(PyObject *obj,
364
const void **buffer,
365
Py_ssize_t *buffer_len)
366
{
367
return as_read_buffer(obj, buffer, buffer_len);
368
}
369
370
/* Takes an arbitrary object which must support the (writable, single segment)
371
buffer interface and returns a pointer to a writable memory location in
372
buffer of size 'buffer_len'.
373
374
Return 0 on success. buffer and buffer_len are only set in case no error
375
occurs. Otherwise, -1 is returned and an exception set. */
376
PyAPI_FUNC(int) /* abi_only */
377
PyObject_AsWriteBuffer(PyObject *obj,
378
void **buffer,
379
Py_ssize_t *buffer_len)
380
{
381
PyBufferProcs *pb;
382
Py_buffer view;
383
384
if (obj == NULL || buffer == NULL || buffer_len == NULL) {
385
null_error();
386
return -1;
387
}
388
pb = Py_TYPE(obj)->tp_as_buffer;
389
if (pb == NULL ||
390
pb->bf_getbuffer == NULL ||
391
((*pb->bf_getbuffer)(obj, &view, PyBUF_WRITABLE) != 0)) {
392
PyErr_SetString(PyExc_TypeError,
393
"expected a writable bytes-like object");
394
return -1;
395
}
396
397
*buffer = view.buf;
398
*buffer_len = view.len;
399
PyBuffer_Release(&view);
400
return 0;
401
}
402
403
/* Buffer C-API for Python 3.0 */
404
405
int
406
PyObject_GetBuffer(PyObject *obj, Py_buffer *view, int flags)
407
{
408
PyBufferProcs *pb = Py_TYPE(obj)->tp_as_buffer;
409
410
if (pb == NULL || pb->bf_getbuffer == NULL) {
411
PyErr_Format(PyExc_TypeError,
412
"a bytes-like object is required, not '%.100s'",
413
Py_TYPE(obj)->tp_name);
414
return -1;
415
}
416
int res = (*pb->bf_getbuffer)(obj, view, flags);
417
assert(_Py_CheckSlotResult(obj, "getbuffer", res >= 0));
418
return res;
419
}
420
421
static int
422
_IsFortranContiguous(const Py_buffer *view)
423
{
424
Py_ssize_t sd, dim;
425
int i;
426
427
/* 1) len = product(shape) * itemsize
428
2) itemsize > 0
429
3) len = 0 <==> exists i: shape[i] = 0 */
430
if (view->len == 0) return 1;
431
if (view->strides == NULL) { /* C-contiguous by definition */
432
/* Trivially F-contiguous */
433
if (view->ndim <= 1) return 1;
434
435
/* ndim > 1 implies shape != NULL */
436
assert(view->shape != NULL);
437
438
/* Effectively 1-d */
439
sd = 0;
440
for (i=0; i<view->ndim; i++) {
441
if (view->shape[i] > 1) sd += 1;
442
}
443
return sd <= 1;
444
}
445
446
/* strides != NULL implies both of these */
447
assert(view->ndim > 0);
448
assert(view->shape != NULL);
449
450
sd = view->itemsize;
451
for (i=0; i<view->ndim; i++) {
452
dim = view->shape[i];
453
if (dim > 1 && view->strides[i] != sd) {
454
return 0;
455
}
456
sd *= dim;
457
}
458
return 1;
459
}
460
461
static int
462
_IsCContiguous(const Py_buffer *view)
463
{
464
Py_ssize_t sd, dim;
465
int i;
466
467
/* 1) len = product(shape) * itemsize
468
2) itemsize > 0
469
3) len = 0 <==> exists i: shape[i] = 0 */
470
if (view->len == 0) return 1;
471
if (view->strides == NULL) return 1; /* C-contiguous by definition */
472
473
/* strides != NULL implies both of these */
474
assert(view->ndim > 0);
475
assert(view->shape != NULL);
476
477
sd = view->itemsize;
478
for (i=view->ndim-1; i>=0; i--) {
479
dim = view->shape[i];
480
if (dim > 1 && view->strides[i] != sd) {
481
return 0;
482
}
483
sd *= dim;
484
}
485
return 1;
486
}
487
488
int
489
PyBuffer_IsContiguous(const Py_buffer *view, char order)
490
{
491
492
if (view->suboffsets != NULL) return 0;
493
494
if (order == 'C')
495
return _IsCContiguous(view);
496
else if (order == 'F')
497
return _IsFortranContiguous(view);
498
else if (order == 'A')
499
return (_IsCContiguous(view) || _IsFortranContiguous(view));
500
return 0;
501
}
502
503
504
void*
505
PyBuffer_GetPointer(const Py_buffer *view, const Py_ssize_t *indices)
506
{
507
char* pointer;
508
int i;
509
pointer = (char *)view->buf;
510
for (i = 0; i < view->ndim; i++) {
511
pointer += view->strides[i]*indices[i];
512
if ((view->suboffsets != NULL) && (view->suboffsets[i] >= 0)) {
513
pointer = *((char**)pointer) + view->suboffsets[i];
514
}
515
}
516
return (void*)pointer;
517
}
518
519
520
static void
521
_Py_add_one_to_index_F(int nd, Py_ssize_t *index, const Py_ssize_t *shape)
522
{
523
int k;
524
525
for (k=0; k<nd; k++) {
526
if (index[k] < shape[k]-1) {
527
index[k]++;
528
break;
529
}
530
else {
531
index[k] = 0;
532
}
533
}
534
}
535
536
static void
537
_Py_add_one_to_index_C(int nd, Py_ssize_t *index, const Py_ssize_t *shape)
538
{
539
int k;
540
541
for (k=nd-1; k>=0; k--) {
542
if (index[k] < shape[k]-1) {
543
index[k]++;
544
break;
545
}
546
else {
547
index[k] = 0;
548
}
549
}
550
}
551
552
Py_ssize_t
553
PyBuffer_SizeFromFormat(const char *format)
554
{
555
PyObject *calcsize = NULL;
556
PyObject *res = NULL;
557
PyObject *fmt = NULL;
558
Py_ssize_t itemsize = -1;
559
560
calcsize = _PyImport_GetModuleAttrString("struct", "calcsize");
561
if (calcsize == NULL) {
562
goto done;
563
}
564
565
fmt = PyUnicode_FromString(format);
566
if (fmt == NULL) {
567
goto done;
568
}
569
570
res = PyObject_CallFunctionObjArgs(calcsize, fmt, NULL);
571
if (res == NULL) {
572
goto done;
573
}
574
575
itemsize = PyLong_AsSsize_t(res);
576
if (itemsize < 0) {
577
goto done;
578
}
579
580
done:
581
Py_XDECREF(calcsize);
582
Py_XDECREF(fmt);
583
Py_XDECREF(res);
584
return itemsize;
585
}
586
587
int
588
PyBuffer_FromContiguous(const Py_buffer *view, const void *buf, Py_ssize_t len, char fort)
589
{
590
int k;
591
void (*addone)(int, Py_ssize_t *, const Py_ssize_t *);
592
Py_ssize_t *indices, elements;
593
char *ptr;
594
const char *src;
595
596
if (len > view->len) {
597
len = view->len;
598
}
599
600
if (PyBuffer_IsContiguous(view, fort)) {
601
/* simplest copy is all that is needed */
602
memcpy(view->buf, buf, len);
603
return 0;
604
}
605
606
/* Otherwise a more elaborate scheme is needed */
607
608
/* view->ndim <= 64 */
609
indices = (Py_ssize_t *)PyMem_Malloc(sizeof(Py_ssize_t)*(view->ndim));
610
if (indices == NULL) {
611
PyErr_NoMemory();
612
return -1;
613
}
614
for (k=0; k<view->ndim;k++) {
615
indices[k] = 0;
616
}
617
618
if (fort == 'F') {
619
addone = _Py_add_one_to_index_F;
620
}
621
else {
622
addone = _Py_add_one_to_index_C;
623
}
624
src = buf;
625
/* XXX : This is not going to be the fastest code in the world
626
several optimizations are possible.
627
*/
628
elements = len / view->itemsize;
629
while (elements--) {
630
ptr = PyBuffer_GetPointer(view, indices);
631
memcpy(ptr, src, view->itemsize);
632
src += view->itemsize;
633
addone(view->ndim, indices, view->shape);
634
}
635
636
PyMem_Free(indices);
637
return 0;
638
}
639
640
int PyObject_CopyData(PyObject *dest, PyObject *src)
641
{
642
Py_buffer view_dest, view_src;
643
int k;
644
Py_ssize_t *indices, elements;
645
char *dptr, *sptr;
646
647
if (!PyObject_CheckBuffer(dest) ||
648
!PyObject_CheckBuffer(src)) {
649
PyErr_SetString(PyExc_TypeError,
650
"both destination and source must be "\
651
"bytes-like objects");
652
return -1;
653
}
654
655
if (PyObject_GetBuffer(dest, &view_dest, PyBUF_FULL) != 0) return -1;
656
if (PyObject_GetBuffer(src, &view_src, PyBUF_FULL_RO) != 0) {
657
PyBuffer_Release(&view_dest);
658
return -1;
659
}
660
661
if (view_dest.len < view_src.len) {
662
PyErr_SetString(PyExc_BufferError,
663
"destination is too small to receive data from source");
664
PyBuffer_Release(&view_dest);
665
PyBuffer_Release(&view_src);
666
return -1;
667
}
668
669
if ((PyBuffer_IsContiguous(&view_dest, 'C') &&
670
PyBuffer_IsContiguous(&view_src, 'C')) ||
671
(PyBuffer_IsContiguous(&view_dest, 'F') &&
672
PyBuffer_IsContiguous(&view_src, 'F'))) {
673
/* simplest copy is all that is needed */
674
memcpy(view_dest.buf, view_src.buf, view_src.len);
675
PyBuffer_Release(&view_dest);
676
PyBuffer_Release(&view_src);
677
return 0;
678
}
679
680
/* Otherwise a more elaborate copy scheme is needed */
681
682
/* XXX(nnorwitz): need to check for overflow! */
683
indices = (Py_ssize_t *)PyMem_Malloc(sizeof(Py_ssize_t)*view_src.ndim);
684
if (indices == NULL) {
685
PyErr_NoMemory();
686
PyBuffer_Release(&view_dest);
687
PyBuffer_Release(&view_src);
688
return -1;
689
}
690
for (k=0; k<view_src.ndim;k++) {
691
indices[k] = 0;
692
}
693
elements = 1;
694
for (k=0; k<view_src.ndim; k++) {
695
/* XXX(nnorwitz): can this overflow? */
696
elements *= view_src.shape[k];
697
}
698
while (elements--) {
699
_Py_add_one_to_index_C(view_src.ndim, indices, view_src.shape);
700
dptr = PyBuffer_GetPointer(&view_dest, indices);
701
sptr = PyBuffer_GetPointer(&view_src, indices);
702
memcpy(dptr, sptr, view_src.itemsize);
703
}
704
PyMem_Free(indices);
705
PyBuffer_Release(&view_dest);
706
PyBuffer_Release(&view_src);
707
return 0;
708
}
709
710
void
711
PyBuffer_FillContiguousStrides(int nd, Py_ssize_t *shape,
712
Py_ssize_t *strides, int itemsize,
713
char fort)
714
{
715
int k;
716
Py_ssize_t sd;
717
718
sd = itemsize;
719
if (fort == 'F') {
720
for (k=0; k<nd; k++) {
721
strides[k] = sd;
722
sd *= shape[k];
723
}
724
}
725
else {
726
for (k=nd-1; k>=0; k--) {
727
strides[k] = sd;
728
sd *= shape[k];
729
}
730
}
731
return;
732
}
733
734
int
735
PyBuffer_FillInfo(Py_buffer *view, PyObject *obj, void *buf, Py_ssize_t len,
736
int readonly, int flags)
737
{
738
if (view == NULL) {
739
PyErr_SetString(PyExc_BufferError,
740
"PyBuffer_FillInfo: view==NULL argument is obsolete");
741
return -1;
742
}
743
744
if (((flags & PyBUF_WRITABLE) == PyBUF_WRITABLE) &&
745
(readonly == 1)) {
746
PyErr_SetString(PyExc_BufferError,
747
"Object is not writable.");
748
return -1;
749
}
750
751
view->obj = Py_XNewRef(obj);
752
view->buf = buf;
753
view->len = len;
754
view->readonly = readonly;
755
view->itemsize = 1;
756
view->format = NULL;
757
if ((flags & PyBUF_FORMAT) == PyBUF_FORMAT)
758
view->format = "B";
759
view->ndim = 1;
760
view->shape = NULL;
761
if ((flags & PyBUF_ND) == PyBUF_ND)
762
view->shape = &(view->len);
763
view->strides = NULL;
764
if ((flags & PyBUF_STRIDES) == PyBUF_STRIDES)
765
view->strides = &(view->itemsize);
766
view->suboffsets = NULL;
767
view->internal = NULL;
768
return 0;
769
}
770
771
void
772
PyBuffer_Release(Py_buffer *view)
773
{
774
PyObject *obj = view->obj;
775
PyBufferProcs *pb;
776
if (obj == NULL)
777
return;
778
pb = Py_TYPE(obj)->tp_as_buffer;
779
if (pb && pb->bf_releasebuffer) {
780
pb->bf_releasebuffer(obj, view);
781
}
782
view->obj = NULL;
783
Py_DECREF(obj);
784
}
785
786
PyObject *
787
PyObject_Format(PyObject *obj, PyObject *format_spec)
788
{
789
PyObject *meth;
790
PyObject *empty = NULL;
791
PyObject *result = NULL;
792
793
if (format_spec != NULL && !PyUnicode_Check(format_spec)) {
794
PyErr_Format(PyExc_SystemError,
795
"Format specifier must be a string, not %.200s",
796
Py_TYPE(format_spec)->tp_name);
797
return NULL;
798
}
799
800
/* Fast path for common types. */
801
if (format_spec == NULL || PyUnicode_GET_LENGTH(format_spec) == 0) {
802
if (PyUnicode_CheckExact(obj)) {
803
return Py_NewRef(obj);
804
}
805
if (PyLong_CheckExact(obj)) {
806
return PyObject_Str(obj);
807
}
808
}
809
810
/* If no format_spec is provided, use an empty string */
811
if (format_spec == NULL) {
812
empty = PyUnicode_New(0, 0);
813
format_spec = empty;
814
}
815
816
/* Find the (unbound!) __format__ method */
817
meth = _PyObject_LookupSpecial(obj, &_Py_ID(__format__));
818
if (meth == NULL) {
819
PyThreadState *tstate = _PyThreadState_GET();
820
if (!_PyErr_Occurred(tstate)) {
821
_PyErr_Format(tstate, PyExc_TypeError,
822
"Type %.100s doesn't define __format__",
823
Py_TYPE(obj)->tp_name);
824
}
825
goto done;
826
}
827
828
/* And call it. */
829
result = PyObject_CallOneArg(meth, format_spec);
830
Py_DECREF(meth);
831
832
if (result && !PyUnicode_Check(result)) {
833
PyErr_Format(PyExc_TypeError,
834
"__format__ must return a str, not %.200s",
835
Py_TYPE(result)->tp_name);
836
Py_SETREF(result, NULL);
837
goto done;
838
}
839
840
done:
841
Py_XDECREF(empty);
842
return result;
843
}
844
/* Operations on numbers */
845
846
int
847
PyNumber_Check(PyObject *o)
848
{
849
if (o == NULL)
850
return 0;
851
PyNumberMethods *nb = Py_TYPE(o)->tp_as_number;
852
return nb && (nb->nb_index || nb->nb_int || nb->nb_float || PyComplex_Check(o));
853
}
854
855
/* Binary operators */
856
857
#define NB_SLOT(x) offsetof(PyNumberMethods, x)
858
#define NB_BINOP(nb_methods, slot) \
859
(*(binaryfunc*)(& ((char*)nb_methods)[slot]))
860
#define NB_TERNOP(nb_methods, slot) \
861
(*(ternaryfunc*)(& ((char*)nb_methods)[slot]))
862
863
/*
864
Calling scheme used for binary operations:
865
866
Order operations are tried until either a valid result or error:
867
w.op(v,w)[*], v.op(v,w), w.op(v,w)
868
869
[*] only when Py_TYPE(v) != Py_TYPE(w) && Py_TYPE(w) is a subclass of
870
Py_TYPE(v)
871
*/
872
873
static PyObject *
874
binary_op1(PyObject *v, PyObject *w, const int op_slot
875
#ifndef NDEBUG
876
, const char *op_name
877
#endif
878
)
879
{
880
binaryfunc slotv;
881
if (Py_TYPE(v)->tp_as_number != NULL) {
882
slotv = NB_BINOP(Py_TYPE(v)->tp_as_number, op_slot);
883
}
884
else {
885
slotv = NULL;
886
}
887
888
binaryfunc slotw;
889
if (!Py_IS_TYPE(w, Py_TYPE(v)) && Py_TYPE(w)->tp_as_number != NULL) {
890
slotw = NB_BINOP(Py_TYPE(w)->tp_as_number, op_slot);
891
if (slotw == slotv) {
892
slotw = NULL;
893
}
894
}
895
else {
896
slotw = NULL;
897
}
898
899
if (slotv) {
900
PyObject *x;
901
if (slotw && PyType_IsSubtype(Py_TYPE(w), Py_TYPE(v))) {
902
x = slotw(v, w);
903
if (x != Py_NotImplemented)
904
return x;
905
Py_DECREF(x); /* can't do it */
906
slotw = NULL;
907
}
908
x = slotv(v, w);
909
assert(_Py_CheckSlotResult(v, op_name, x != NULL));
910
if (x != Py_NotImplemented) {
911
return x;
912
}
913
Py_DECREF(x); /* can't do it */
914
}
915
if (slotw) {
916
PyObject *x = slotw(v, w);
917
assert(_Py_CheckSlotResult(w, op_name, x != NULL));
918
if (x != Py_NotImplemented) {
919
return x;
920
}
921
Py_DECREF(x); /* can't do it */
922
}
923
Py_RETURN_NOTIMPLEMENTED;
924
}
925
926
#ifdef NDEBUG
927
# define BINARY_OP1(v, w, op_slot, op_name) binary_op1(v, w, op_slot)
928
#else
929
# define BINARY_OP1(v, w, op_slot, op_name) binary_op1(v, w, op_slot, op_name)
930
#endif
931
932
static PyObject *
933
binop_type_error(PyObject *v, PyObject *w, const char *op_name)
934
{
935
PyErr_Format(PyExc_TypeError,
936
"unsupported operand type(s) for %.100s: "
937
"'%.100s' and '%.100s'",
938
op_name,
939
Py_TYPE(v)->tp_name,
940
Py_TYPE(w)->tp_name);
941
return NULL;
942
}
943
944
static PyObject *
945
binary_op(PyObject *v, PyObject *w, const int op_slot, const char *op_name)
946
{
947
PyObject *result = BINARY_OP1(v, w, op_slot, op_name);
948
if (result == Py_NotImplemented) {
949
Py_DECREF(result);
950
951
if (op_slot == NB_SLOT(nb_rshift) &&
952
PyCFunction_CheckExact(v) &&
953
strcmp(((PyCFunctionObject *)v)->m_ml->ml_name, "print") == 0)
954
{
955
PyErr_Format(PyExc_TypeError,
956
"unsupported operand type(s) for %.100s: "
957
"'%.100s' and '%.100s'. Did you mean \"print(<message>, "
958
"file=<output_stream>)\"?",
959
op_name,
960
Py_TYPE(v)->tp_name,
961
Py_TYPE(w)->tp_name);
962
return NULL;
963
}
964
return binop_type_error(v, w, op_name);
965
}
966
return result;
967
}
968
969
970
/*
971
Calling scheme used for ternary operations:
972
973
Order operations are tried until either a valid result or error:
974
v.op(v,w,z), w.op(v,w,z), z.op(v,w,z)
975
*/
976
977
static PyObject *
978
ternary_op(PyObject *v,
979
PyObject *w,
980
PyObject *z,
981
const int op_slot,
982
const char *op_name
983
)
984
{
985
PyNumberMethods *mv = Py_TYPE(v)->tp_as_number;
986
PyNumberMethods *mw = Py_TYPE(w)->tp_as_number;
987
988
ternaryfunc slotv;
989
if (mv != NULL) {
990
slotv = NB_TERNOP(mv, op_slot);
991
}
992
else {
993
slotv = NULL;
994
}
995
996
ternaryfunc slotw;
997
if (!Py_IS_TYPE(w, Py_TYPE(v)) && mw != NULL) {
998
slotw = NB_TERNOP(mw, op_slot);
999
if (slotw == slotv) {
1000
slotw = NULL;
1001
}
1002
}
1003
else {
1004
slotw = NULL;
1005
}
1006
1007
if (slotv) {
1008
PyObject *x;
1009
if (slotw && PyType_IsSubtype(Py_TYPE(w), Py_TYPE(v))) {
1010
x = slotw(v, w, z);
1011
if (x != Py_NotImplemented) {
1012
return x;
1013
}
1014
Py_DECREF(x); /* can't do it */
1015
slotw = NULL;
1016
}
1017
x = slotv(v, w, z);
1018
assert(_Py_CheckSlotResult(v, op_name, x != NULL));
1019
if (x != Py_NotImplemented) {
1020
return x;
1021
}
1022
Py_DECREF(x); /* can't do it */
1023
}
1024
if (slotw) {
1025
PyObject *x = slotw(v, w, z);
1026
assert(_Py_CheckSlotResult(w, op_name, x != NULL));
1027
if (x != Py_NotImplemented) {
1028
return x;
1029
}
1030
Py_DECREF(x); /* can't do it */
1031
}
1032
1033
PyNumberMethods *mz = Py_TYPE(z)->tp_as_number;
1034
if (mz != NULL) {
1035
ternaryfunc slotz = NB_TERNOP(mz, op_slot);
1036
if (slotz == slotv || slotz == slotw) {
1037
slotz = NULL;
1038
}
1039
if (slotz) {
1040
PyObject *x = slotz(v, w, z);
1041
assert(_Py_CheckSlotResult(z, op_name, x != NULL));
1042
if (x != Py_NotImplemented) {
1043
return x;
1044
}
1045
Py_DECREF(x); /* can't do it */
1046
}
1047
}
1048
1049
if (z == Py_None) {
1050
PyErr_Format(
1051
PyExc_TypeError,
1052
"unsupported operand type(s) for %.100s: "
1053
"'%.100s' and '%.100s'",
1054
op_name,
1055
Py_TYPE(v)->tp_name,
1056
Py_TYPE(w)->tp_name);
1057
}
1058
else {
1059
PyErr_Format(
1060
PyExc_TypeError,
1061
"unsupported operand type(s) for %.100s: "
1062
"'%.100s', '%.100s', '%.100s'",
1063
op_name,
1064
Py_TYPE(v)->tp_name,
1065
Py_TYPE(w)->tp_name,
1066
Py_TYPE(z)->tp_name);
1067
}
1068
return NULL;
1069
}
1070
1071
#define BINARY_FUNC(func, op, op_name) \
1072
PyObject * \
1073
func(PyObject *v, PyObject *w) { \
1074
return binary_op(v, w, NB_SLOT(op), op_name); \
1075
}
1076
1077
BINARY_FUNC(PyNumber_Or, nb_or, "|")
1078
BINARY_FUNC(PyNumber_Xor, nb_xor, "^")
1079
BINARY_FUNC(PyNumber_And, nb_and, "&")
1080
BINARY_FUNC(PyNumber_Lshift, nb_lshift, "<<")
1081
BINARY_FUNC(PyNumber_Rshift, nb_rshift, ">>")
1082
BINARY_FUNC(PyNumber_Subtract, nb_subtract, "-")
1083
BINARY_FUNC(PyNumber_Divmod, nb_divmod, "divmod()")
1084
1085
PyObject *
1086
PyNumber_Add(PyObject *v, PyObject *w)
1087
{
1088
PyObject *result = BINARY_OP1(v, w, NB_SLOT(nb_add), "+");
1089
if (result != Py_NotImplemented) {
1090
return result;
1091
}
1092
Py_DECREF(result);
1093
1094
PySequenceMethods *m = Py_TYPE(v)->tp_as_sequence;
1095
if (m && m->sq_concat) {
1096
result = (*m->sq_concat)(v, w);
1097
assert(_Py_CheckSlotResult(v, "+", result != NULL));
1098
return result;
1099
}
1100
1101
return binop_type_error(v, w, "+");
1102
}
1103
1104
static PyObject *
1105
sequence_repeat(ssizeargfunc repeatfunc, PyObject *seq, PyObject *n)
1106
{
1107
Py_ssize_t count;
1108
if (_PyIndex_Check(n)) {
1109
count = PyNumber_AsSsize_t(n, PyExc_OverflowError);
1110
if (count == -1 && PyErr_Occurred()) {
1111
return NULL;
1112
}
1113
}
1114
else {
1115
return type_error("can't multiply sequence by "
1116
"non-int of type '%.200s'", n);
1117
}
1118
PyObject *res = (*repeatfunc)(seq, count);
1119
assert(_Py_CheckSlotResult(seq, "*", res != NULL));
1120
return res;
1121
}
1122
1123
PyObject *
1124
PyNumber_Multiply(PyObject *v, PyObject *w)
1125
{
1126
PyObject *result = BINARY_OP1(v, w, NB_SLOT(nb_multiply), "*");
1127
if (result == Py_NotImplemented) {
1128
PySequenceMethods *mv = Py_TYPE(v)->tp_as_sequence;
1129
PySequenceMethods *mw = Py_TYPE(w)->tp_as_sequence;
1130
Py_DECREF(result);
1131
if (mv && mv->sq_repeat) {
1132
return sequence_repeat(mv->sq_repeat, v, w);
1133
}
1134
else if (mw && mw->sq_repeat) {
1135
return sequence_repeat(mw->sq_repeat, w, v);
1136
}
1137
result = binop_type_error(v, w, "*");
1138
}
1139
return result;
1140
}
1141
1142
PyObject *
1143
PyNumber_MatrixMultiply(PyObject *v, PyObject *w)
1144
{
1145
return binary_op(v, w, NB_SLOT(nb_matrix_multiply), "@");
1146
}
1147
1148
PyObject *
1149
PyNumber_FloorDivide(PyObject *v, PyObject *w)
1150
{
1151
return binary_op(v, w, NB_SLOT(nb_floor_divide), "//");
1152
}
1153
1154
PyObject *
1155
PyNumber_TrueDivide(PyObject *v, PyObject *w)
1156
{
1157
return binary_op(v, w, NB_SLOT(nb_true_divide), "/");
1158
}
1159
1160
PyObject *
1161
PyNumber_Remainder(PyObject *v, PyObject *w)
1162
{
1163
return binary_op(v, w, NB_SLOT(nb_remainder), "%");
1164
}
1165
1166
PyObject *
1167
PyNumber_Power(PyObject *v, PyObject *w, PyObject *z)
1168
{
1169
return ternary_op(v, w, z, NB_SLOT(nb_power), "** or pow()");
1170
}
1171
1172
PyObject *
1173
_PyNumber_PowerNoMod(PyObject *lhs, PyObject *rhs)
1174
{
1175
return PyNumber_Power(lhs, rhs, Py_None);
1176
}
1177
1178
/* Binary in-place operators */
1179
1180
/* The in-place operators are defined to fall back to the 'normal',
1181
non in-place operations, if the in-place methods are not in place.
1182
1183
- If the left hand object has the appropriate struct members, and
1184
they are filled, call the appropriate function and return the
1185
result. No coercion is done on the arguments; the left-hand object
1186
is the one the operation is performed on, and it's up to the
1187
function to deal with the right-hand object.
1188
1189
- Otherwise, in-place modification is not supported. Handle it exactly as
1190
a non in-place operation of the same kind.
1191
1192
*/
1193
1194
static PyObject *
1195
binary_iop1(PyObject *v, PyObject *w, const int iop_slot, const int op_slot
1196
#ifndef NDEBUG
1197
, const char *op_name
1198
#endif
1199
)
1200
{
1201
PyNumberMethods *mv = Py_TYPE(v)->tp_as_number;
1202
if (mv != NULL) {
1203
binaryfunc slot = NB_BINOP(mv, iop_slot);
1204
if (slot) {
1205
PyObject *x = (slot)(v, w);
1206
assert(_Py_CheckSlotResult(v, op_name, x != NULL));
1207
if (x != Py_NotImplemented) {
1208
return x;
1209
}
1210
Py_DECREF(x);
1211
}
1212
}
1213
#ifdef NDEBUG
1214
return binary_op1(v, w, op_slot);
1215
#else
1216
return binary_op1(v, w, op_slot, op_name);
1217
#endif
1218
}
1219
1220
#ifdef NDEBUG
1221
# define BINARY_IOP1(v, w, iop_slot, op_slot, op_name) binary_iop1(v, w, iop_slot, op_slot)
1222
#else
1223
# define BINARY_IOP1(v, w, iop_slot, op_slot, op_name) binary_iop1(v, w, iop_slot, op_slot, op_name)
1224
#endif
1225
1226
static PyObject *
1227
binary_iop(PyObject *v, PyObject *w, const int iop_slot, const int op_slot,
1228
const char *op_name)
1229
{
1230
PyObject *result = BINARY_IOP1(v, w, iop_slot, op_slot, op_name);
1231
if (result == Py_NotImplemented) {
1232
Py_DECREF(result);
1233
return binop_type_error(v, w, op_name);
1234
}
1235
return result;
1236
}
1237
1238
static PyObject *
1239
ternary_iop(PyObject *v, PyObject *w, PyObject *z, const int iop_slot, const int op_slot,
1240
const char *op_name)
1241
{
1242
PyNumberMethods *mv = Py_TYPE(v)->tp_as_number;
1243
if (mv != NULL) {
1244
ternaryfunc slot = NB_TERNOP(mv, iop_slot);
1245
if (slot) {
1246
PyObject *x = (slot)(v, w, z);
1247
if (x != Py_NotImplemented) {
1248
return x;
1249
}
1250
Py_DECREF(x);
1251
}
1252
}
1253
return ternary_op(v, w, z, op_slot, op_name);
1254
}
1255
1256
#define INPLACE_BINOP(func, iop, op, op_name) \
1257
PyObject * \
1258
func(PyObject *v, PyObject *w) { \
1259
return binary_iop(v, w, NB_SLOT(iop), NB_SLOT(op), op_name); \
1260
}
1261
1262
INPLACE_BINOP(PyNumber_InPlaceOr, nb_inplace_or, nb_or, "|=")
1263
INPLACE_BINOP(PyNumber_InPlaceXor, nb_inplace_xor, nb_xor, "^=")
1264
INPLACE_BINOP(PyNumber_InPlaceAnd, nb_inplace_and, nb_and, "&=")
1265
INPLACE_BINOP(PyNumber_InPlaceLshift, nb_inplace_lshift, nb_lshift, "<<=")
1266
INPLACE_BINOP(PyNumber_InPlaceRshift, nb_inplace_rshift, nb_rshift, ">>=")
1267
INPLACE_BINOP(PyNumber_InPlaceSubtract, nb_inplace_subtract, nb_subtract, "-=")
1268
INPLACE_BINOP(PyNumber_InPlaceMatrixMultiply, nb_inplace_matrix_multiply, nb_matrix_multiply, "@=")
1269
INPLACE_BINOP(PyNumber_InPlaceFloorDivide, nb_inplace_floor_divide, nb_floor_divide, "//=")
1270
INPLACE_BINOP(PyNumber_InPlaceTrueDivide, nb_inplace_true_divide, nb_true_divide, "/=")
1271
INPLACE_BINOP(PyNumber_InPlaceRemainder, nb_inplace_remainder, nb_remainder, "%=")
1272
1273
PyObject *
1274
PyNumber_InPlaceAdd(PyObject *v, PyObject *w)
1275
{
1276
PyObject *result = BINARY_IOP1(v, w, NB_SLOT(nb_inplace_add),
1277
NB_SLOT(nb_add), "+=");
1278
if (result == Py_NotImplemented) {
1279
PySequenceMethods *m = Py_TYPE(v)->tp_as_sequence;
1280
Py_DECREF(result);
1281
if (m != NULL) {
1282
binaryfunc func = m->sq_inplace_concat;
1283
if (func == NULL)
1284
func = m->sq_concat;
1285
if (func != NULL) {
1286
result = func(v, w);
1287
assert(_Py_CheckSlotResult(v, "+=", result != NULL));
1288
return result;
1289
}
1290
}
1291
result = binop_type_error(v, w, "+=");
1292
}
1293
return result;
1294
}
1295
1296
PyObject *
1297
PyNumber_InPlaceMultiply(PyObject *v, PyObject *w)
1298
{
1299
PyObject *result = BINARY_IOP1(v, w, NB_SLOT(nb_inplace_multiply),
1300
NB_SLOT(nb_multiply), "*=");
1301
if (result == Py_NotImplemented) {
1302
ssizeargfunc f = NULL;
1303
PySequenceMethods *mv = Py_TYPE(v)->tp_as_sequence;
1304
PySequenceMethods *mw = Py_TYPE(w)->tp_as_sequence;
1305
Py_DECREF(result);
1306
if (mv != NULL) {
1307
f = mv->sq_inplace_repeat;
1308
if (f == NULL)
1309
f = mv->sq_repeat;
1310
if (f != NULL)
1311
return sequence_repeat(f, v, w);
1312
}
1313
else if (mw != NULL) {
1314
/* Note that the right hand operand should not be
1315
* mutated in this case so sq_inplace_repeat is not
1316
* used. */
1317
if (mw->sq_repeat)
1318
return sequence_repeat(mw->sq_repeat, w, v);
1319
}
1320
result = binop_type_error(v, w, "*=");
1321
}
1322
return result;
1323
}
1324
1325
PyObject *
1326
PyNumber_InPlacePower(PyObject *v, PyObject *w, PyObject *z)
1327
{
1328
return ternary_iop(v, w, z, NB_SLOT(nb_inplace_power),
1329
NB_SLOT(nb_power), "**=");
1330
}
1331
1332
PyObject *
1333
_PyNumber_InPlacePowerNoMod(PyObject *lhs, PyObject *rhs)
1334
{
1335
return PyNumber_InPlacePower(lhs, rhs, Py_None);
1336
}
1337
1338
1339
/* Unary operators and functions */
1340
1341
PyObject *
1342
PyNumber_Negative(PyObject *o)
1343
{
1344
if (o == NULL) {
1345
return null_error();
1346
}
1347
1348
PyNumberMethods *m = Py_TYPE(o)->tp_as_number;
1349
if (m && m->nb_negative) {
1350
PyObject *res = (*m->nb_negative)(o);
1351
assert(_Py_CheckSlotResult(o, "__neg__", res != NULL));
1352
return res;
1353
}
1354
1355
return type_error("bad operand type for unary -: '%.200s'", o);
1356
}
1357
1358
PyObject *
1359
PyNumber_Positive(PyObject *o)
1360
{
1361
if (o == NULL) {
1362
return null_error();
1363
}
1364
1365
PyNumberMethods *m = Py_TYPE(o)->tp_as_number;
1366
if (m && m->nb_positive) {
1367
PyObject *res = (*m->nb_positive)(o);
1368
assert(_Py_CheckSlotResult(o, "__pos__", res != NULL));
1369
return res;
1370
}
1371
1372
return type_error("bad operand type for unary +: '%.200s'", o);
1373
}
1374
1375
PyObject *
1376
PyNumber_Invert(PyObject *o)
1377
{
1378
if (o == NULL) {
1379
return null_error();
1380
}
1381
1382
PyNumberMethods *m = Py_TYPE(o)->tp_as_number;
1383
if (m && m->nb_invert) {
1384
PyObject *res = (*m->nb_invert)(o);
1385
assert(_Py_CheckSlotResult(o, "__invert__", res != NULL));
1386
return res;
1387
}
1388
1389
return type_error("bad operand type for unary ~: '%.200s'", o);
1390
}
1391
1392
PyObject *
1393
PyNumber_Absolute(PyObject *o)
1394
{
1395
if (o == NULL) {
1396
return null_error();
1397
}
1398
1399
PyNumberMethods *m = Py_TYPE(o)->tp_as_number;
1400
if (m && m->nb_absolute) {
1401
PyObject *res = m->nb_absolute(o);
1402
assert(_Py_CheckSlotResult(o, "__abs__", res != NULL));
1403
return res;
1404
}
1405
1406
return type_error("bad operand type for abs(): '%.200s'", o);
1407
}
1408
1409
1410
int
1411
PyIndex_Check(PyObject *obj)
1412
{
1413
return _PyIndex_Check(obj);
1414
}
1415
1416
1417
/* Return a Python int from the object item.
1418
Can return an instance of int subclass.
1419
Raise TypeError if the result is not an int
1420
or if the object cannot be interpreted as an index.
1421
*/
1422
PyObject *
1423
_PyNumber_Index(PyObject *item)
1424
{
1425
if (item == NULL) {
1426
return null_error();
1427
}
1428
1429
if (PyLong_Check(item)) {
1430
return Py_NewRef(item);
1431
}
1432
if (!_PyIndex_Check(item)) {
1433
PyErr_Format(PyExc_TypeError,
1434
"'%.200s' object cannot be interpreted "
1435
"as an integer", Py_TYPE(item)->tp_name);
1436
return NULL;
1437
}
1438
1439
PyObject *result = Py_TYPE(item)->tp_as_number->nb_index(item);
1440
assert(_Py_CheckSlotResult(item, "__index__", result != NULL));
1441
if (!result || PyLong_CheckExact(result)) {
1442
return result;
1443
}
1444
1445
if (!PyLong_Check(result)) {
1446
PyErr_Format(PyExc_TypeError,
1447
"__index__ returned non-int (type %.200s)",
1448
Py_TYPE(result)->tp_name);
1449
Py_DECREF(result);
1450
return NULL;
1451
}
1452
/* Issue #17576: warn if 'result' not of exact type int. */
1453
if (PyErr_WarnFormat(PyExc_DeprecationWarning, 1,
1454
"__index__ returned non-int (type %.200s). "
1455
"The ability to return an instance of a strict subclass of int "
1456
"is deprecated, and may be removed in a future version of Python.",
1457
Py_TYPE(result)->tp_name)) {
1458
Py_DECREF(result);
1459
return NULL;
1460
}
1461
return result;
1462
}
1463
1464
/* Return an exact Python int from the object item.
1465
Raise TypeError if the result is not an int
1466
or if the object cannot be interpreted as an index.
1467
*/
1468
PyObject *
1469
PyNumber_Index(PyObject *item)
1470
{
1471
PyObject *result = _PyNumber_Index(item);
1472
if (result != NULL && !PyLong_CheckExact(result)) {
1473
Py_SETREF(result, _PyLong_Copy((PyLongObject *)result));
1474
}
1475
return result;
1476
}
1477
1478
/* Return an error on Overflow only if err is not NULL*/
1479
1480
Py_ssize_t
1481
PyNumber_AsSsize_t(PyObject *item, PyObject *err)
1482
{
1483
Py_ssize_t result;
1484
PyObject *runerr;
1485
PyObject *value = _PyNumber_Index(item);
1486
if (value == NULL)
1487
return -1;
1488
1489
/* We're done if PyLong_AsSsize_t() returns without error. */
1490
result = PyLong_AsSsize_t(value);
1491
if (result != -1)
1492
goto finish;
1493
1494
PyThreadState *tstate = _PyThreadState_GET();
1495
runerr = _PyErr_Occurred(tstate);
1496
if (!runerr) {
1497
goto finish;
1498
}
1499
1500
/* Error handling code -- only manage OverflowError differently */
1501
if (!PyErr_GivenExceptionMatches(runerr, PyExc_OverflowError)) {
1502
goto finish;
1503
}
1504
_PyErr_Clear(tstate);
1505
1506
/* If no error-handling desired then the default clipping
1507
is sufficient. */
1508
if (!err) {
1509
assert(PyLong_Check(value));
1510
/* Whether or not it is less than or equal to
1511
zero is determined by the sign of ob_size
1512
*/
1513
if (_PyLong_IsNegative((PyLongObject *)value))
1514
result = PY_SSIZE_T_MIN;
1515
else
1516
result = PY_SSIZE_T_MAX;
1517
}
1518
else {
1519
/* Otherwise replace the error with caller's error object. */
1520
_PyErr_Format(tstate, err,
1521
"cannot fit '%.200s' into an index-sized integer",
1522
Py_TYPE(item)->tp_name);
1523
}
1524
1525
finish:
1526
Py_DECREF(value);
1527
return result;
1528
}
1529
1530
1531
PyObject *
1532
PyNumber_Long(PyObject *o)
1533
{
1534
PyObject *result;
1535
PyNumberMethods *m;
1536
PyObject *trunc_func;
1537
Py_buffer view;
1538
1539
if (o == NULL) {
1540
return null_error();
1541
}
1542
1543
if (PyLong_CheckExact(o)) {
1544
return Py_NewRef(o);
1545
}
1546
m = Py_TYPE(o)->tp_as_number;
1547
if (m && m->nb_int) { /* This should include subclasses of int */
1548
/* Convert using the nb_int slot, which should return something
1549
of exact type int. */
1550
result = m->nb_int(o);
1551
assert(_Py_CheckSlotResult(o, "__int__", result != NULL));
1552
if (!result || PyLong_CheckExact(result)) {
1553
return result;
1554
}
1555
1556
if (!PyLong_Check(result)) {
1557
PyErr_Format(PyExc_TypeError,
1558
"__int__ returned non-int (type %.200s)",
1559
Py_TYPE(result)->tp_name);
1560
Py_DECREF(result);
1561
return NULL;
1562
}
1563
/* Issue #17576: warn if 'result' not of exact type int. */
1564
if (PyErr_WarnFormat(PyExc_DeprecationWarning, 1,
1565
"__int__ returned non-int (type %.200s). "
1566
"The ability to return an instance of a strict subclass of int "
1567
"is deprecated, and may be removed in a future version of Python.",
1568
Py_TYPE(result)->tp_name)) {
1569
Py_DECREF(result);
1570
return NULL;
1571
}
1572
Py_SETREF(result, _PyLong_Copy((PyLongObject *)result));
1573
return result;
1574
}
1575
if (m && m->nb_index) {
1576
return PyNumber_Index(o);
1577
}
1578
trunc_func = _PyObject_LookupSpecial(o, &_Py_ID(__trunc__));
1579
if (trunc_func) {
1580
if (PyErr_WarnEx(PyExc_DeprecationWarning,
1581
"The delegation of int() to __trunc__ is deprecated.", 1)) {
1582
Py_DECREF(trunc_func);
1583
return NULL;
1584
}
1585
result = _PyObject_CallNoArgs(trunc_func);
1586
Py_DECREF(trunc_func);
1587
if (result == NULL || PyLong_CheckExact(result)) {
1588
return result;
1589
}
1590
if (PyLong_Check(result)) {
1591
Py_SETREF(result, _PyLong_Copy((PyLongObject *)result));
1592
return result;
1593
}
1594
/* __trunc__ is specified to return an Integral type,
1595
but int() needs to return an int. */
1596
if (!PyIndex_Check(result)) {
1597
PyErr_Format(
1598
PyExc_TypeError,
1599
"__trunc__ returned non-Integral (type %.200s)",
1600
Py_TYPE(result)->tp_name);
1601
Py_DECREF(result);
1602
return NULL;
1603
}
1604
Py_SETREF(result, PyNumber_Index(result));
1605
return result;
1606
}
1607
if (PyErr_Occurred())
1608
return NULL;
1609
1610
if (PyUnicode_Check(o))
1611
/* The below check is done in PyLong_FromUnicodeObject(). */
1612
return PyLong_FromUnicodeObject(o, 10);
1613
1614
if (PyBytes_Check(o))
1615
/* need to do extra error checking that PyLong_FromString()
1616
* doesn't do. In particular int('9\x005') must raise an
1617
* exception, not truncate at the null.
1618
*/
1619
return _PyLong_FromBytes(PyBytes_AS_STRING(o),
1620
PyBytes_GET_SIZE(o), 10);
1621
1622
if (PyByteArray_Check(o))
1623
return _PyLong_FromBytes(PyByteArray_AS_STRING(o),
1624
PyByteArray_GET_SIZE(o), 10);
1625
1626
if (PyObject_GetBuffer(o, &view, PyBUF_SIMPLE) == 0) {
1627
PyObject *bytes;
1628
1629
/* Copy to NUL-terminated buffer. */
1630
bytes = PyBytes_FromStringAndSize((const char *)view.buf, view.len);
1631
if (bytes == NULL) {
1632
PyBuffer_Release(&view);
1633
return NULL;
1634
}
1635
result = _PyLong_FromBytes(PyBytes_AS_STRING(bytes),
1636
PyBytes_GET_SIZE(bytes), 10);
1637
Py_DECREF(bytes);
1638
PyBuffer_Release(&view);
1639
return result;
1640
}
1641
1642
return type_error("int() argument must be a string, a bytes-like object "
1643
"or a real number, not '%.200s'", o);
1644
}
1645
1646
PyObject *
1647
PyNumber_Float(PyObject *o)
1648
{
1649
if (o == NULL) {
1650
return null_error();
1651
}
1652
1653
if (PyFloat_CheckExact(o)) {
1654
return Py_NewRef(o);
1655
}
1656
1657
PyNumberMethods *m = Py_TYPE(o)->tp_as_number;
1658
if (m && m->nb_float) { /* This should include subclasses of float */
1659
PyObject *res = m->nb_float(o);
1660
assert(_Py_CheckSlotResult(o, "__float__", res != NULL));
1661
if (!res || PyFloat_CheckExact(res)) {
1662
return res;
1663
}
1664
1665
if (!PyFloat_Check(res)) {
1666
PyErr_Format(PyExc_TypeError,
1667
"%.50s.__float__ returned non-float (type %.50s)",
1668
Py_TYPE(o)->tp_name, Py_TYPE(res)->tp_name);
1669
Py_DECREF(res);
1670
return NULL;
1671
}
1672
/* Issue #26983: warn if 'res' not of exact type float. */
1673
if (PyErr_WarnFormat(PyExc_DeprecationWarning, 1,
1674
"%.50s.__float__ returned non-float (type %.50s). "
1675
"The ability to return an instance of a strict subclass of float "
1676
"is deprecated, and may be removed in a future version of Python.",
1677
Py_TYPE(o)->tp_name, Py_TYPE(res)->tp_name)) {
1678
Py_DECREF(res);
1679
return NULL;
1680
}
1681
double val = PyFloat_AS_DOUBLE(res);
1682
Py_DECREF(res);
1683
return PyFloat_FromDouble(val);
1684
}
1685
1686
if (m && m->nb_index) {
1687
PyObject *res = _PyNumber_Index(o);
1688
if (!res) {
1689
return NULL;
1690
}
1691
double val = PyLong_AsDouble(res);
1692
Py_DECREF(res);
1693
if (val == -1.0 && PyErr_Occurred()) {
1694
return NULL;
1695
}
1696
return PyFloat_FromDouble(val);
1697
}
1698
1699
/* A float subclass with nb_float == NULL */
1700
if (PyFloat_Check(o)) {
1701
return PyFloat_FromDouble(PyFloat_AS_DOUBLE(o));
1702
}
1703
return PyFloat_FromString(o);
1704
}
1705
1706
1707
PyObject *
1708
PyNumber_ToBase(PyObject *n, int base)
1709
{
1710
if (!(base == 2 || base == 8 || base == 10 || base == 16)) {
1711
PyErr_SetString(PyExc_SystemError,
1712
"PyNumber_ToBase: base must be 2, 8, 10 or 16");
1713
return NULL;
1714
}
1715
PyObject *index = _PyNumber_Index(n);
1716
if (!index)
1717
return NULL;
1718
PyObject *res = _PyLong_Format(index, base);
1719
Py_DECREF(index);
1720
return res;
1721
}
1722
1723
1724
/* Operations on sequences */
1725
1726
int
1727
PySequence_Check(PyObject *s)
1728
{
1729
if (PyDict_Check(s))
1730
return 0;
1731
return Py_TYPE(s)->tp_as_sequence &&
1732
Py_TYPE(s)->tp_as_sequence->sq_item != NULL;
1733
}
1734
1735
Py_ssize_t
1736
PySequence_Size(PyObject *s)
1737
{
1738
if (s == NULL) {
1739
null_error();
1740
return -1;
1741
}
1742
1743
PySequenceMethods *m = Py_TYPE(s)->tp_as_sequence;
1744
if (m && m->sq_length) {
1745
Py_ssize_t len = m->sq_length(s);
1746
assert(_Py_CheckSlotResult(s, "__len__", len >= 0));
1747
return len;
1748
}
1749
1750
if (Py_TYPE(s)->tp_as_mapping && Py_TYPE(s)->tp_as_mapping->mp_length) {
1751
type_error("%.200s is not a sequence", s);
1752
return -1;
1753
}
1754
type_error("object of type '%.200s' has no len()", s);
1755
return -1;
1756
}
1757
1758
#undef PySequence_Length
1759
Py_ssize_t
1760
PySequence_Length(PyObject *s)
1761
{
1762
return PySequence_Size(s);
1763
}
1764
#define PySequence_Length PySequence_Size
1765
1766
PyObject *
1767
PySequence_Concat(PyObject *s, PyObject *o)
1768
{
1769
if (s == NULL || o == NULL) {
1770
return null_error();
1771
}
1772
1773
PySequenceMethods *m = Py_TYPE(s)->tp_as_sequence;
1774
if (m && m->sq_concat) {
1775
PyObject *res = m->sq_concat(s, o);
1776
assert(_Py_CheckSlotResult(s, "+", res != NULL));
1777
return res;
1778
}
1779
1780
/* Instances of user classes defining an __add__() method only
1781
have an nb_add slot, not an sq_concat slot. So we fall back
1782
to nb_add if both arguments appear to be sequences. */
1783
if (PySequence_Check(s) && PySequence_Check(o)) {
1784
PyObject *result = BINARY_OP1(s, o, NB_SLOT(nb_add), "+");
1785
if (result != Py_NotImplemented)
1786
return result;
1787
Py_DECREF(result);
1788
}
1789
return type_error("'%.200s' object can't be concatenated", s);
1790
}
1791
1792
PyObject *
1793
PySequence_Repeat(PyObject *o, Py_ssize_t count)
1794
{
1795
if (o == NULL) {
1796
return null_error();
1797
}
1798
1799
PySequenceMethods *m = Py_TYPE(o)->tp_as_sequence;
1800
if (m && m->sq_repeat) {
1801
PyObject *res = m->sq_repeat(o, count);
1802
assert(_Py_CheckSlotResult(o, "*", res != NULL));
1803
return res;
1804
}
1805
1806
/* Instances of user classes defining a __mul__() method only
1807
have an nb_multiply slot, not an sq_repeat slot. so we fall back
1808
to nb_multiply if o appears to be a sequence. */
1809
if (PySequence_Check(o)) {
1810
PyObject *n, *result;
1811
n = PyLong_FromSsize_t(count);
1812
if (n == NULL)
1813
return NULL;
1814
result = BINARY_OP1(o, n, NB_SLOT(nb_multiply), "*");
1815
Py_DECREF(n);
1816
if (result != Py_NotImplemented)
1817
return result;
1818
Py_DECREF(result);
1819
}
1820
return type_error("'%.200s' object can't be repeated", o);
1821
}
1822
1823
PyObject *
1824
PySequence_InPlaceConcat(PyObject *s, PyObject *o)
1825
{
1826
if (s == NULL || o == NULL) {
1827
return null_error();
1828
}
1829
1830
PySequenceMethods *m = Py_TYPE(s)->tp_as_sequence;
1831
if (m && m->sq_inplace_concat) {
1832
PyObject *res = m->sq_inplace_concat(s, o);
1833
assert(_Py_CheckSlotResult(s, "+=", res != NULL));
1834
return res;
1835
}
1836
if (m && m->sq_concat) {
1837
PyObject *res = m->sq_concat(s, o);
1838
assert(_Py_CheckSlotResult(s, "+", res != NULL));
1839
return res;
1840
}
1841
1842
if (PySequence_Check(s) && PySequence_Check(o)) {
1843
PyObject *result = BINARY_IOP1(s, o, NB_SLOT(nb_inplace_add),
1844
NB_SLOT(nb_add), "+=");
1845
if (result != Py_NotImplemented)
1846
return result;
1847
Py_DECREF(result);
1848
}
1849
return type_error("'%.200s' object can't be concatenated", s);
1850
}
1851
1852
PyObject *
1853
PySequence_InPlaceRepeat(PyObject *o, Py_ssize_t count)
1854
{
1855
if (o == NULL) {
1856
return null_error();
1857
}
1858
1859
PySequenceMethods *m = Py_TYPE(o)->tp_as_sequence;
1860
if (m && m->sq_inplace_repeat) {
1861
PyObject *res = m->sq_inplace_repeat(o, count);
1862
assert(_Py_CheckSlotResult(o, "*=", res != NULL));
1863
return res;
1864
}
1865
if (m && m->sq_repeat) {
1866
PyObject *res = m->sq_repeat(o, count);
1867
assert(_Py_CheckSlotResult(o, "*", res != NULL));
1868
return res;
1869
}
1870
1871
if (PySequence_Check(o)) {
1872
PyObject *n, *result;
1873
n = PyLong_FromSsize_t(count);
1874
if (n == NULL)
1875
return NULL;
1876
result = BINARY_IOP1(o, n, NB_SLOT(nb_inplace_multiply),
1877
NB_SLOT(nb_multiply), "*=");
1878
Py_DECREF(n);
1879
if (result != Py_NotImplemented)
1880
return result;
1881
Py_DECREF(result);
1882
}
1883
return type_error("'%.200s' object can't be repeated", o);
1884
}
1885
1886
PyObject *
1887
PySequence_GetItem(PyObject *s, Py_ssize_t i)
1888
{
1889
if (s == NULL) {
1890
return null_error();
1891
}
1892
1893
PySequenceMethods *m = Py_TYPE(s)->tp_as_sequence;
1894
if (m && m->sq_item) {
1895
if (i < 0) {
1896
if (m->sq_length) {
1897
Py_ssize_t l = (*m->sq_length)(s);
1898
assert(_Py_CheckSlotResult(s, "__len__", l >= 0));
1899
if (l < 0) {
1900
return NULL;
1901
}
1902
i += l;
1903
}
1904
}
1905
PyObject *res = m->sq_item(s, i);
1906
assert(_Py_CheckSlotResult(s, "__getitem__", res != NULL));
1907
return res;
1908
}
1909
1910
if (Py_TYPE(s)->tp_as_mapping && Py_TYPE(s)->tp_as_mapping->mp_subscript) {
1911
return type_error("%.200s is not a sequence", s);
1912
}
1913
return type_error("'%.200s' object does not support indexing", s);
1914
}
1915
1916
PyObject *
1917
PySequence_GetSlice(PyObject *s, Py_ssize_t i1, Py_ssize_t i2)
1918
{
1919
if (!s) {
1920
return null_error();
1921
}
1922
1923
PyMappingMethods *mp = Py_TYPE(s)->tp_as_mapping;
1924
if (mp && mp->mp_subscript) {
1925
PyObject *slice = _PySlice_FromIndices(i1, i2);
1926
if (!slice) {
1927
return NULL;
1928
}
1929
PyObject *res = mp->mp_subscript(s, slice);
1930
assert(_Py_CheckSlotResult(s, "__getitem__", res != NULL));
1931
Py_DECREF(slice);
1932
return res;
1933
}
1934
1935
return type_error("'%.200s' object is unsliceable", s);
1936
}
1937
1938
int
1939
PySequence_SetItem(PyObject *s, Py_ssize_t i, PyObject *o)
1940
{
1941
if (s == NULL) {
1942
null_error();
1943
return -1;
1944
}
1945
1946
PySequenceMethods *m = Py_TYPE(s)->tp_as_sequence;
1947
if (m && m->sq_ass_item) {
1948
if (i < 0) {
1949
if (m->sq_length) {
1950
Py_ssize_t l = (*m->sq_length)(s);
1951
assert(_Py_CheckSlotResult(s, "__len__", l >= 0));
1952
if (l < 0) {
1953
return -1;
1954
}
1955
i += l;
1956
}
1957
}
1958
int res = m->sq_ass_item(s, i, o);
1959
assert(_Py_CheckSlotResult(s, "__setitem__", res >= 0));
1960
return res;
1961
}
1962
1963
if (Py_TYPE(s)->tp_as_mapping && Py_TYPE(s)->tp_as_mapping->mp_ass_subscript) {
1964
type_error("%.200s is not a sequence", s);
1965
return -1;
1966
}
1967
type_error("'%.200s' object does not support item assignment", s);
1968
return -1;
1969
}
1970
1971
int
1972
PySequence_DelItem(PyObject *s, Py_ssize_t i)
1973
{
1974
if (s == NULL) {
1975
null_error();
1976
return -1;
1977
}
1978
1979
PySequenceMethods *m = Py_TYPE(s)->tp_as_sequence;
1980
if (m && m->sq_ass_item) {
1981
if (i < 0) {
1982
if (m->sq_length) {
1983
Py_ssize_t l = (*m->sq_length)(s);
1984
assert(_Py_CheckSlotResult(s, "__len__", l >= 0));
1985
if (l < 0) {
1986
return -1;
1987
}
1988
i += l;
1989
}
1990
}
1991
int res = m->sq_ass_item(s, i, (PyObject *)NULL);
1992
assert(_Py_CheckSlotResult(s, "__delitem__", res >= 0));
1993
return res;
1994
}
1995
1996
if (Py_TYPE(s)->tp_as_mapping && Py_TYPE(s)->tp_as_mapping->mp_ass_subscript) {
1997
type_error("%.200s is not a sequence", s);
1998
return -1;
1999
}
2000
type_error("'%.200s' object doesn't support item deletion", s);
2001
return -1;
2002
}
2003
2004
int
2005
PySequence_SetSlice(PyObject *s, Py_ssize_t i1, Py_ssize_t i2, PyObject *o)
2006
{
2007
if (s == NULL) {
2008
null_error();
2009
return -1;
2010
}
2011
2012
PyMappingMethods *mp = Py_TYPE(s)->tp_as_mapping;
2013
if (mp && mp->mp_ass_subscript) {
2014
PyObject *slice = _PySlice_FromIndices(i1, i2);
2015
if (!slice)
2016
return -1;
2017
int res = mp->mp_ass_subscript(s, slice, o);
2018
assert(_Py_CheckSlotResult(s, "__setitem__", res >= 0));
2019
Py_DECREF(slice);
2020
return res;
2021
}
2022
2023
type_error("'%.200s' object doesn't support slice assignment", s);
2024
return -1;
2025
}
2026
2027
int
2028
PySequence_DelSlice(PyObject *s, Py_ssize_t i1, Py_ssize_t i2)
2029
{
2030
if (s == NULL) {
2031
null_error();
2032
return -1;
2033
}
2034
2035
PyMappingMethods *mp = Py_TYPE(s)->tp_as_mapping;
2036
if (mp && mp->mp_ass_subscript) {
2037
PyObject *slice = _PySlice_FromIndices(i1, i2);
2038
if (!slice) {
2039
return -1;
2040
}
2041
int res = mp->mp_ass_subscript(s, slice, NULL);
2042
assert(_Py_CheckSlotResult(s, "__delitem__", res >= 0));
2043
Py_DECREF(slice);
2044
return res;
2045
}
2046
type_error("'%.200s' object doesn't support slice deletion", s);
2047
return -1;
2048
}
2049
2050
PyObject *
2051
PySequence_Tuple(PyObject *v)
2052
{
2053
PyObject *it; /* iter(v) */
2054
Py_ssize_t n; /* guess for result tuple size */
2055
PyObject *result = NULL;
2056
Py_ssize_t j;
2057
2058
if (v == NULL) {
2059
return null_error();
2060
}
2061
2062
/* Special-case the common tuple and list cases, for efficiency. */
2063
if (PyTuple_CheckExact(v)) {
2064
/* Note that we can't know whether it's safe to return
2065
a tuple *subclass* instance as-is, hence the restriction
2066
to exact tuples here. In contrast, lists always make
2067
a copy, so there's no need for exactness below. */
2068
return Py_NewRef(v);
2069
}
2070
if (PyList_CheckExact(v))
2071
return PyList_AsTuple(v);
2072
2073
/* Get iterator. */
2074
it = PyObject_GetIter(v);
2075
if (it == NULL)
2076
return NULL;
2077
2078
/* Guess result size and allocate space. */
2079
n = PyObject_LengthHint(v, 10);
2080
if (n == -1)
2081
goto Fail;
2082
result = PyTuple_New(n);
2083
if (result == NULL)
2084
goto Fail;
2085
2086
/* Fill the tuple. */
2087
for (j = 0; ; ++j) {
2088
PyObject *item = PyIter_Next(it);
2089
if (item == NULL) {
2090
if (PyErr_Occurred())
2091
goto Fail;
2092
break;
2093
}
2094
if (j >= n) {
2095
size_t newn = (size_t)n;
2096
/* The over-allocation strategy can grow a bit faster
2097
than for lists because unlike lists the
2098
over-allocation isn't permanent -- we reclaim
2099
the excess before the end of this routine.
2100
So, grow by ten and then add 25%.
2101
*/
2102
newn += 10u;
2103
newn += newn >> 2;
2104
if (newn > PY_SSIZE_T_MAX) {
2105
/* Check for overflow */
2106
PyErr_NoMemory();
2107
Py_DECREF(item);
2108
goto Fail;
2109
}
2110
n = (Py_ssize_t)newn;
2111
if (_PyTuple_Resize(&result, n) != 0) {
2112
Py_DECREF(item);
2113
goto Fail;
2114
}
2115
}
2116
PyTuple_SET_ITEM(result, j, item);
2117
}
2118
2119
/* Cut tuple back if guess was too large. */
2120
if (j < n &&
2121
_PyTuple_Resize(&result, j) != 0)
2122
goto Fail;
2123
2124
Py_DECREF(it);
2125
return result;
2126
2127
Fail:
2128
Py_XDECREF(result);
2129
Py_DECREF(it);
2130
return NULL;
2131
}
2132
2133
PyObject *
2134
PySequence_List(PyObject *v)
2135
{
2136
PyObject *result; /* result list */
2137
PyObject *rv; /* return value from PyList_Extend */
2138
2139
if (v == NULL) {
2140
return null_error();
2141
}
2142
2143
result = PyList_New(0);
2144
if (result == NULL)
2145
return NULL;
2146
2147
rv = _PyList_Extend((PyListObject *)result, v);
2148
if (rv == NULL) {
2149
Py_DECREF(result);
2150
return NULL;
2151
}
2152
Py_DECREF(rv);
2153
return result;
2154
}
2155
2156
PyObject *
2157
PySequence_Fast(PyObject *v, const char *m)
2158
{
2159
PyObject *it;
2160
2161
if (v == NULL) {
2162
return null_error();
2163
}
2164
2165
if (PyList_CheckExact(v) || PyTuple_CheckExact(v)) {
2166
return Py_NewRef(v);
2167
}
2168
2169
it = PyObject_GetIter(v);
2170
if (it == NULL) {
2171
PyThreadState *tstate = _PyThreadState_GET();
2172
if (_PyErr_ExceptionMatches(tstate, PyExc_TypeError)) {
2173
_PyErr_SetString(tstate, PyExc_TypeError, m);
2174
}
2175
return NULL;
2176
}
2177
2178
v = PySequence_List(it);
2179
Py_DECREF(it);
2180
2181
return v;
2182
}
2183
2184
/* Iterate over seq. Result depends on the operation:
2185
PY_ITERSEARCH_COUNT: -1 if error, else # of times obj appears in seq.
2186
PY_ITERSEARCH_INDEX: 0-based index of first occurrence of obj in seq;
2187
set ValueError and return -1 if none found; also return -1 on error.
2188
Py_ITERSEARCH_CONTAINS: return 1 if obj in seq, else 0; -1 on error.
2189
*/
2190
Py_ssize_t
2191
_PySequence_IterSearch(PyObject *seq, PyObject *obj, int operation)
2192
{
2193
Py_ssize_t n;
2194
int wrapped; /* for PY_ITERSEARCH_INDEX, true iff n wrapped around */
2195
PyObject *it; /* iter(seq) */
2196
2197
if (seq == NULL || obj == NULL) {
2198
null_error();
2199
return -1;
2200
}
2201
2202
it = PyObject_GetIter(seq);
2203
if (it == NULL) {
2204
if (PyErr_ExceptionMatches(PyExc_TypeError)) {
2205
type_error("argument of type '%.200s' is not iterable", seq);
2206
}
2207
return -1;
2208
}
2209
2210
n = wrapped = 0;
2211
for (;;) {
2212
int cmp;
2213
PyObject *item = PyIter_Next(it);
2214
if (item == NULL) {
2215
if (PyErr_Occurred())
2216
goto Fail;
2217
break;
2218
}
2219
2220
cmp = PyObject_RichCompareBool(item, obj, Py_EQ);
2221
Py_DECREF(item);
2222
if (cmp < 0)
2223
goto Fail;
2224
if (cmp > 0) {
2225
switch (operation) {
2226
case PY_ITERSEARCH_COUNT:
2227
if (n == PY_SSIZE_T_MAX) {
2228
PyErr_SetString(PyExc_OverflowError,
2229
"count exceeds C integer size");
2230
goto Fail;
2231
}
2232
++n;
2233
break;
2234
2235
case PY_ITERSEARCH_INDEX:
2236
if (wrapped) {
2237
PyErr_SetString(PyExc_OverflowError,
2238
"index exceeds C integer size");
2239
goto Fail;
2240
}
2241
goto Done;
2242
2243
case PY_ITERSEARCH_CONTAINS:
2244
n = 1;
2245
goto Done;
2246
2247
default:
2248
Py_UNREACHABLE();
2249
}
2250
}
2251
2252
if (operation == PY_ITERSEARCH_INDEX) {
2253
if (n == PY_SSIZE_T_MAX)
2254
wrapped = 1;
2255
++n;
2256
}
2257
}
2258
2259
if (operation != PY_ITERSEARCH_INDEX)
2260
goto Done;
2261
2262
PyErr_SetString(PyExc_ValueError,
2263
"sequence.index(x): x not in sequence");
2264
/* fall into failure code */
2265
Fail:
2266
n = -1;
2267
/* fall through */
2268
Done:
2269
Py_DECREF(it);
2270
return n;
2271
2272
}
2273
2274
/* Return # of times o appears in s. */
2275
Py_ssize_t
2276
PySequence_Count(PyObject *s, PyObject *o)
2277
{
2278
return _PySequence_IterSearch(s, o, PY_ITERSEARCH_COUNT);
2279
}
2280
2281
/* Return -1 if error; 1 if ob in seq; 0 if ob not in seq.
2282
* Use sq_contains if possible, else defer to _PySequence_IterSearch().
2283
*/
2284
int
2285
PySequence_Contains(PyObject *seq, PyObject *ob)
2286
{
2287
PySequenceMethods *sqm = Py_TYPE(seq)->tp_as_sequence;
2288
if (sqm != NULL && sqm->sq_contains != NULL) {
2289
int res = (*sqm->sq_contains)(seq, ob);
2290
assert(_Py_CheckSlotResult(seq, "__contains__", res >= 0));
2291
return res;
2292
}
2293
Py_ssize_t result = _PySequence_IterSearch(seq, ob, PY_ITERSEARCH_CONTAINS);
2294
return Py_SAFE_DOWNCAST(result, Py_ssize_t, int);
2295
}
2296
2297
/* Backwards compatibility */
2298
#undef PySequence_In
2299
int
2300
PySequence_In(PyObject *w, PyObject *v)
2301
{
2302
return PySequence_Contains(w, v);
2303
}
2304
2305
Py_ssize_t
2306
PySequence_Index(PyObject *s, PyObject *o)
2307
{
2308
return _PySequence_IterSearch(s, o, PY_ITERSEARCH_INDEX);
2309
}
2310
2311
/* Operations on mappings */
2312
2313
int
2314
PyMapping_Check(PyObject *o)
2315
{
2316
return o && Py_TYPE(o)->tp_as_mapping &&
2317
Py_TYPE(o)->tp_as_mapping->mp_subscript;
2318
}
2319
2320
Py_ssize_t
2321
PyMapping_Size(PyObject *o)
2322
{
2323
if (o == NULL) {
2324
null_error();
2325
return -1;
2326
}
2327
2328
PyMappingMethods *m = Py_TYPE(o)->tp_as_mapping;
2329
if (m && m->mp_length) {
2330
Py_ssize_t len = m->mp_length(o);
2331
assert(_Py_CheckSlotResult(o, "__len__", len >= 0));
2332
return len;
2333
}
2334
2335
if (Py_TYPE(o)->tp_as_sequence && Py_TYPE(o)->tp_as_sequence->sq_length) {
2336
type_error("%.200s is not a mapping", o);
2337
return -1;
2338
}
2339
/* PyMapping_Size() can be called from PyObject_Size(). */
2340
type_error("object of type '%.200s' has no len()", o);
2341
return -1;
2342
}
2343
2344
#undef PyMapping_Length
2345
Py_ssize_t
2346
PyMapping_Length(PyObject *o)
2347
{
2348
return PyMapping_Size(o);
2349
}
2350
#define PyMapping_Length PyMapping_Size
2351
2352
PyObject *
2353
PyMapping_GetItemString(PyObject *o, const char *key)
2354
{
2355
PyObject *okey, *r;
2356
2357
if (key == NULL) {
2358
return null_error();
2359
}
2360
2361
okey = PyUnicode_FromString(key);
2362
if (okey == NULL)
2363
return NULL;
2364
r = PyObject_GetItem(o, okey);
2365
Py_DECREF(okey);
2366
return r;
2367
}
2368
2369
int
2370
PyMapping_SetItemString(PyObject *o, const char *key, PyObject *value)
2371
{
2372
PyObject *okey;
2373
int r;
2374
2375
if (key == NULL) {
2376
null_error();
2377
return -1;
2378
}
2379
2380
okey = PyUnicode_FromString(key);
2381
if (okey == NULL)
2382
return -1;
2383
r = PyObject_SetItem(o, okey, value);
2384
Py_DECREF(okey);
2385
return r;
2386
}
2387
2388
int
2389
PyMapping_HasKeyString(PyObject *o, const char *key)
2390
{
2391
PyObject *v;
2392
2393
v = PyMapping_GetItemString(o, key);
2394
if (v) {
2395
Py_DECREF(v);
2396
return 1;
2397
}
2398
PyErr_Clear();
2399
return 0;
2400
}
2401
2402
int
2403
PyMapping_HasKey(PyObject *o, PyObject *key)
2404
{
2405
PyObject *v;
2406
2407
v = PyObject_GetItem(o, key);
2408
if (v) {
2409
Py_DECREF(v);
2410
return 1;
2411
}
2412
PyErr_Clear();
2413
return 0;
2414
}
2415
2416
/* This function is quite similar to PySequence_Fast(), but specialized to be
2417
a helper for PyMapping_Keys(), PyMapping_Items() and PyMapping_Values().
2418
*/
2419
static PyObject *
2420
method_output_as_list(PyObject *o, PyObject *meth)
2421
{
2422
PyObject *it, *result, *meth_output;
2423
2424
assert(o != NULL);
2425
meth_output = PyObject_CallMethodNoArgs(o, meth);
2426
if (meth_output == NULL || PyList_CheckExact(meth_output)) {
2427
return meth_output;
2428
}
2429
it = PyObject_GetIter(meth_output);
2430
if (it == NULL) {
2431
PyThreadState *tstate = _PyThreadState_GET();
2432
if (_PyErr_ExceptionMatches(tstate, PyExc_TypeError)) {
2433
_PyErr_Format(tstate, PyExc_TypeError,
2434
"%.200s.%U() returned a non-iterable (type %.200s)",
2435
Py_TYPE(o)->tp_name,
2436
meth,
2437
Py_TYPE(meth_output)->tp_name);
2438
}
2439
Py_DECREF(meth_output);
2440
return NULL;
2441
}
2442
Py_DECREF(meth_output);
2443
result = PySequence_List(it);
2444
Py_DECREF(it);
2445
return result;
2446
}
2447
2448
PyObject *
2449
PyMapping_Keys(PyObject *o)
2450
{
2451
if (o == NULL) {
2452
return null_error();
2453
}
2454
if (PyDict_CheckExact(o)) {
2455
return PyDict_Keys(o);
2456
}
2457
return method_output_as_list(o, &_Py_ID(keys));
2458
}
2459
2460
PyObject *
2461
PyMapping_Items(PyObject *o)
2462
{
2463
if (o == NULL) {
2464
return null_error();
2465
}
2466
if (PyDict_CheckExact(o)) {
2467
return PyDict_Items(o);
2468
}
2469
return method_output_as_list(o, &_Py_ID(items));
2470
}
2471
2472
PyObject *
2473
PyMapping_Values(PyObject *o)
2474
{
2475
if (o == NULL) {
2476
return null_error();
2477
}
2478
if (PyDict_CheckExact(o)) {
2479
return PyDict_Values(o);
2480
}
2481
return method_output_as_list(o, &_Py_ID(values));
2482
}
2483
2484
/* isinstance(), issubclass() */
2485
2486
/* abstract_get_bases() has logically 4 return states:
2487
*
2488
* 1. getattr(cls, '__bases__') could raise an AttributeError
2489
* 2. getattr(cls, '__bases__') could raise some other exception
2490
* 3. getattr(cls, '__bases__') could return a tuple
2491
* 4. getattr(cls, '__bases__') could return something other than a tuple
2492
*
2493
* Only state #3 is a non-error state and only it returns a non-NULL object
2494
* (it returns the retrieved tuple).
2495
*
2496
* Any raised AttributeErrors are masked by clearing the exception and
2497
* returning NULL. If an object other than a tuple comes out of __bases__,
2498
* then again, the return value is NULL. So yes, these two situations
2499
* produce exactly the same results: NULL is returned and no error is set.
2500
*
2501
* If some exception other than AttributeError is raised, then NULL is also
2502
* returned, but the exception is not cleared. That's because we want the
2503
* exception to be propagated along.
2504
*
2505
* Callers are expected to test for PyErr_Occurred() when the return value
2506
* is NULL to decide whether a valid exception should be propagated or not.
2507
* When there's no exception to propagate, it's customary for the caller to
2508
* set a TypeError.
2509
*/
2510
static PyObject *
2511
abstract_get_bases(PyObject *cls)
2512
{
2513
PyObject *bases;
2514
2515
(void)_PyObject_LookupAttr(cls, &_Py_ID(__bases__), &bases);
2516
if (bases != NULL && !PyTuple_Check(bases)) {
2517
Py_DECREF(bases);
2518
return NULL;
2519
}
2520
return bases;
2521
}
2522
2523
2524
static int
2525
abstract_issubclass(PyObject *derived, PyObject *cls)
2526
{
2527
PyObject *bases = NULL;
2528
Py_ssize_t i, n;
2529
int r = 0;
2530
2531
while (1) {
2532
if (derived == cls) {
2533
Py_XDECREF(bases); /* See below comment */
2534
return 1;
2535
}
2536
/* Use XSETREF to drop bases reference *after* finishing with
2537
derived; bases might be the only reference to it.
2538
XSETREF is used instead of SETREF, because bases is NULL on the
2539
first iteration of the loop.
2540
*/
2541
Py_XSETREF(bases, abstract_get_bases(derived));
2542
if (bases == NULL) {
2543
if (PyErr_Occurred())
2544
return -1;
2545
return 0;
2546
}
2547
n = PyTuple_GET_SIZE(bases);
2548
if (n == 0) {
2549
Py_DECREF(bases);
2550
return 0;
2551
}
2552
/* Avoid recursivity in the single inheritance case */
2553
if (n == 1) {
2554
derived = PyTuple_GET_ITEM(bases, 0);
2555
continue;
2556
}
2557
break;
2558
}
2559
assert(n >= 2);
2560
if (_Py_EnterRecursiveCall(" in __issubclass__")) {
2561
Py_DECREF(bases);
2562
return -1;
2563
}
2564
for (i = 0; i < n; i++) {
2565
r = abstract_issubclass(PyTuple_GET_ITEM(bases, i), cls);
2566
if (r != 0) {
2567
break;
2568
}
2569
}
2570
_Py_LeaveRecursiveCall();
2571
Py_DECREF(bases);
2572
return r;
2573
}
2574
2575
static int
2576
check_class(PyObject *cls, const char *error)
2577
{
2578
PyObject *bases = abstract_get_bases(cls);
2579
if (bases == NULL) {
2580
/* Do not mask errors. */
2581
PyThreadState *tstate = _PyThreadState_GET();
2582
if (!_PyErr_Occurred(tstate)) {
2583
_PyErr_SetString(tstate, PyExc_TypeError, error);
2584
}
2585
return 0;
2586
}
2587
Py_DECREF(bases);
2588
return -1;
2589
}
2590
2591
static int
2592
object_isinstance(PyObject *inst, PyObject *cls)
2593
{
2594
PyObject *icls;
2595
int retval;
2596
if (PyType_Check(cls)) {
2597
retval = PyObject_TypeCheck(inst, (PyTypeObject *)cls);
2598
if (retval == 0) {
2599
retval = _PyObject_LookupAttr(inst, &_Py_ID(__class__), &icls);
2600
if (icls != NULL) {
2601
if (icls != (PyObject *)(Py_TYPE(inst)) && PyType_Check(icls)) {
2602
retval = PyType_IsSubtype(
2603
(PyTypeObject *)icls,
2604
(PyTypeObject *)cls);
2605
}
2606
else {
2607
retval = 0;
2608
}
2609
Py_DECREF(icls);
2610
}
2611
}
2612
}
2613
else {
2614
if (!check_class(cls,
2615
"isinstance() arg 2 must be a type, a tuple of types, or a union"))
2616
return -1;
2617
retval = _PyObject_LookupAttr(inst, &_Py_ID(__class__), &icls);
2618
if (icls != NULL) {
2619
retval = abstract_issubclass(icls, cls);
2620
Py_DECREF(icls);
2621
}
2622
}
2623
2624
return retval;
2625
}
2626
2627
static int
2628
object_recursive_isinstance(PyThreadState *tstate, PyObject *inst, PyObject *cls)
2629
{
2630
/* Quick test for an exact match */
2631
if (Py_IS_TYPE(inst, (PyTypeObject *)cls)) {
2632
return 1;
2633
}
2634
2635
/* We know what type's __instancecheck__ does. */
2636
if (PyType_CheckExact(cls)) {
2637
return object_isinstance(inst, cls);
2638
}
2639
2640
if (_PyUnion_Check(cls)) {
2641
cls = _Py_union_args(cls);
2642
}
2643
2644
if (PyTuple_Check(cls)) {
2645
/* Not a general sequence -- that opens up the road to
2646
recursion and stack overflow. */
2647
if (_Py_EnterRecursiveCallTstate(tstate, " in __instancecheck__")) {
2648
return -1;
2649
}
2650
Py_ssize_t n = PyTuple_GET_SIZE(cls);
2651
int r = 0;
2652
for (Py_ssize_t i = 0; i < n; ++i) {
2653
PyObject *item = PyTuple_GET_ITEM(cls, i);
2654
r = object_recursive_isinstance(tstate, inst, item);
2655
if (r != 0) {
2656
/* either found it, or got an error */
2657
break;
2658
}
2659
}
2660
_Py_LeaveRecursiveCallTstate(tstate);
2661
return r;
2662
}
2663
2664
PyObject *checker = _PyObject_LookupSpecial(cls, &_Py_ID(__instancecheck__));
2665
if (checker != NULL) {
2666
if (_Py_EnterRecursiveCallTstate(tstate, " in __instancecheck__")) {
2667
Py_DECREF(checker);
2668
return -1;
2669
}
2670
2671
PyObject *res = PyObject_CallOneArg(checker, inst);
2672
_Py_LeaveRecursiveCallTstate(tstate);
2673
Py_DECREF(checker);
2674
2675
if (res == NULL) {
2676
return -1;
2677
}
2678
int ok = PyObject_IsTrue(res);
2679
Py_DECREF(res);
2680
2681
return ok;
2682
}
2683
else if (_PyErr_Occurred(tstate)) {
2684
return -1;
2685
}
2686
2687
/* cls has no __instancecheck__() method */
2688
return object_isinstance(inst, cls);
2689
}
2690
2691
2692
int
2693
PyObject_IsInstance(PyObject *inst, PyObject *cls)
2694
{
2695
PyThreadState *tstate = _PyThreadState_GET();
2696
return object_recursive_isinstance(tstate, inst, cls);
2697
}
2698
2699
2700
static int
2701
recursive_issubclass(PyObject *derived, PyObject *cls)
2702
{
2703
if (PyType_Check(cls) && PyType_Check(derived)) {
2704
/* Fast path (non-recursive) */
2705
return PyType_IsSubtype((PyTypeObject *)derived, (PyTypeObject *)cls);
2706
}
2707
if (!check_class(derived,
2708
"issubclass() arg 1 must be a class"))
2709
return -1;
2710
2711
if (!_PyUnion_Check(cls) && !check_class(cls,
2712
"issubclass() arg 2 must be a class,"
2713
" a tuple of classes, or a union")) {
2714
return -1;
2715
}
2716
2717
return abstract_issubclass(derived, cls);
2718
}
2719
2720
static int
2721
object_issubclass(PyThreadState *tstate, PyObject *derived, PyObject *cls)
2722
{
2723
PyObject *checker;
2724
2725
/* We know what type's __subclasscheck__ does. */
2726
if (PyType_CheckExact(cls)) {
2727
/* Quick test for an exact match */
2728
if (derived == cls)
2729
return 1;
2730
return recursive_issubclass(derived, cls);
2731
}
2732
2733
if (_PyUnion_Check(cls)) {
2734
cls = _Py_union_args(cls);
2735
}
2736
2737
if (PyTuple_Check(cls)) {
2738
2739
if (_Py_EnterRecursiveCallTstate(tstate, " in __subclasscheck__")) {
2740
return -1;
2741
}
2742
Py_ssize_t n = PyTuple_GET_SIZE(cls);
2743
int r = 0;
2744
for (Py_ssize_t i = 0; i < n; ++i) {
2745
PyObject *item = PyTuple_GET_ITEM(cls, i);
2746
r = object_issubclass(tstate, derived, item);
2747
if (r != 0)
2748
/* either found it, or got an error */
2749
break;
2750
}
2751
_Py_LeaveRecursiveCallTstate(tstate);
2752
return r;
2753
}
2754
2755
checker = _PyObject_LookupSpecial(cls, &_Py_ID(__subclasscheck__));
2756
if (checker != NULL) {
2757
int ok = -1;
2758
if (_Py_EnterRecursiveCallTstate(tstate, " in __subclasscheck__")) {
2759
Py_DECREF(checker);
2760
return ok;
2761
}
2762
PyObject *res = PyObject_CallOneArg(checker, derived);
2763
_Py_LeaveRecursiveCallTstate(tstate);
2764
Py_DECREF(checker);
2765
if (res != NULL) {
2766
ok = PyObject_IsTrue(res);
2767
Py_DECREF(res);
2768
}
2769
return ok;
2770
}
2771
else if (_PyErr_Occurred(tstate)) {
2772
return -1;
2773
}
2774
2775
/* Probably never reached anymore. */
2776
return recursive_issubclass(derived, cls);
2777
}
2778
2779
2780
int
2781
PyObject_IsSubclass(PyObject *derived, PyObject *cls)
2782
{
2783
PyThreadState *tstate = _PyThreadState_GET();
2784
return object_issubclass(tstate, derived, cls);
2785
}
2786
2787
2788
int
2789
_PyObject_RealIsInstance(PyObject *inst, PyObject *cls)
2790
{
2791
return object_isinstance(inst, cls);
2792
}
2793
2794
int
2795
_PyObject_RealIsSubclass(PyObject *derived, PyObject *cls)
2796
{
2797
return recursive_issubclass(derived, cls);
2798
}
2799
2800
2801
PyObject *
2802
PyObject_GetIter(PyObject *o)
2803
{
2804
PyTypeObject *t = Py_TYPE(o);
2805
getiterfunc f;
2806
2807
f = t->tp_iter;
2808
if (f == NULL) {
2809
if (PySequence_Check(o))
2810
return PySeqIter_New(o);
2811
return type_error("'%.200s' object is not iterable", o);
2812
}
2813
else {
2814
PyObject *res = (*f)(o);
2815
if (res != NULL && !PyIter_Check(res)) {
2816
PyErr_Format(PyExc_TypeError,
2817
"iter() returned non-iterator "
2818
"of type '%.100s'",
2819
Py_TYPE(res)->tp_name);
2820
Py_SETREF(res, NULL);
2821
}
2822
return res;
2823
}
2824
}
2825
2826
PyObject *
2827
PyObject_GetAIter(PyObject *o) {
2828
PyTypeObject *t = Py_TYPE(o);
2829
unaryfunc f;
2830
2831
if (t->tp_as_async == NULL || t->tp_as_async->am_aiter == NULL) {
2832
return type_error("'%.200s' object is not an async iterable", o);
2833
}
2834
f = t->tp_as_async->am_aiter;
2835
PyObject *it = (*f)(o);
2836
if (it != NULL && !PyAIter_Check(it)) {
2837
PyErr_Format(PyExc_TypeError,
2838
"aiter() returned not an async iterator of type '%.100s'",
2839
Py_TYPE(it)->tp_name);
2840
Py_SETREF(it, NULL);
2841
}
2842
return it;
2843
}
2844
2845
int
2846
PyIter_Check(PyObject *obj)
2847
{
2848
PyTypeObject *tp = Py_TYPE(obj);
2849
return (tp->tp_iternext != NULL &&
2850
tp->tp_iternext != &_PyObject_NextNotImplemented);
2851
}
2852
2853
int
2854
PyAIter_Check(PyObject *obj)
2855
{
2856
PyTypeObject *tp = Py_TYPE(obj);
2857
return (tp->tp_as_async != NULL &&
2858
tp->tp_as_async->am_anext != NULL &&
2859
tp->tp_as_async->am_anext != &_PyObject_NextNotImplemented);
2860
}
2861
2862
/* Return next item.
2863
* If an error occurs, return NULL. PyErr_Occurred() will be true.
2864
* If the iteration terminates normally, return NULL and clear the
2865
* PyExc_StopIteration exception (if it was set). PyErr_Occurred()
2866
* will be false.
2867
* Else return the next object. PyErr_Occurred() will be false.
2868
*/
2869
PyObject *
2870
PyIter_Next(PyObject *iter)
2871
{
2872
PyObject *result;
2873
result = (*Py_TYPE(iter)->tp_iternext)(iter);
2874
if (result == NULL) {
2875
PyThreadState *tstate = _PyThreadState_GET();
2876
if (_PyErr_Occurred(tstate)
2877
&& _PyErr_ExceptionMatches(tstate, PyExc_StopIteration))
2878
{
2879
_PyErr_Clear(tstate);
2880
}
2881
}
2882
return result;
2883
}
2884
2885
PySendResult
2886
PyIter_Send(PyObject *iter, PyObject *arg, PyObject **result)
2887
{
2888
assert(arg != NULL);
2889
assert(result != NULL);
2890
if (Py_TYPE(iter)->tp_as_async && Py_TYPE(iter)->tp_as_async->am_send) {
2891
PySendResult res = Py_TYPE(iter)->tp_as_async->am_send(iter, arg, result);
2892
assert(_Py_CheckSlotResult(iter, "am_send", res != PYGEN_ERROR));
2893
return res;
2894
}
2895
if (arg == Py_None && PyIter_Check(iter)) {
2896
*result = Py_TYPE(iter)->tp_iternext(iter);
2897
}
2898
else {
2899
*result = PyObject_CallMethodOneArg(iter, &_Py_ID(send), arg);
2900
}
2901
if (*result != NULL) {
2902
return PYGEN_NEXT;
2903
}
2904
if (_PyGen_FetchStopIterationValue(result) == 0) {
2905
return PYGEN_RETURN;
2906
}
2907
return PYGEN_ERROR;
2908
}
2909
2910