Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
allendowney
GitHub Repository: allendowney/cpython
Path: blob/main/Python/bltinmodule.c
12 views
1
/* Built-in functions */
2
3
#include "Python.h"
4
#include <ctype.h>
5
#include "pycore_ast.h" // _PyAST_Validate()
6
#include "pycore_call.h" // _PyObject_CallNoArgs()
7
#include "pycore_compile.h" // _PyAST_Compile()
8
#include "pycore_long.h" // _PyLong_CompactValue
9
#include "pycore_object.h" // _Py_AddToAllObjects()
10
#include "pycore_pyerrors.h" // _PyErr_NoMemory()
11
#include "pycore_pystate.h" // _PyThreadState_GET()
12
#include "pycore_tuple.h" // _PyTuple_FromArray()
13
#include "pycore_ceval.h" // _PyEval_Vector()
14
15
#include "clinic/bltinmodule.c.h"
16
17
static PyObject*
18
update_bases(PyObject *bases, PyObject *const *args, Py_ssize_t nargs)
19
{
20
Py_ssize_t i, j;
21
PyObject *base, *meth, *new_base, *result, *new_bases = NULL;
22
assert(PyTuple_Check(bases));
23
24
for (i = 0; i < nargs; i++) {
25
base = args[i];
26
if (PyType_Check(base)) {
27
if (new_bases) {
28
/* If we already have made a replacement, then we append every normal base,
29
otherwise just skip it. */
30
if (PyList_Append(new_bases, base) < 0) {
31
goto error;
32
}
33
}
34
continue;
35
}
36
if (_PyObject_LookupAttr(base, &_Py_ID(__mro_entries__), &meth) < 0) {
37
goto error;
38
}
39
if (!meth) {
40
if (new_bases) {
41
if (PyList_Append(new_bases, base) < 0) {
42
goto error;
43
}
44
}
45
continue;
46
}
47
new_base = PyObject_CallOneArg(meth, bases);
48
Py_DECREF(meth);
49
if (!new_base) {
50
goto error;
51
}
52
if (!PyTuple_Check(new_base)) {
53
PyErr_SetString(PyExc_TypeError,
54
"__mro_entries__ must return a tuple");
55
Py_DECREF(new_base);
56
goto error;
57
}
58
if (!new_bases) {
59
/* If this is a first successful replacement, create new_bases list and
60
copy previously encountered bases. */
61
if (!(new_bases = PyList_New(i))) {
62
Py_DECREF(new_base);
63
goto error;
64
}
65
for (j = 0; j < i; j++) {
66
base = args[j];
67
PyList_SET_ITEM(new_bases, j, Py_NewRef(base));
68
}
69
}
70
j = PyList_GET_SIZE(new_bases);
71
if (PyList_SetSlice(new_bases, j, j, new_base) < 0) {
72
Py_DECREF(new_base);
73
goto error;
74
}
75
Py_DECREF(new_base);
76
}
77
if (!new_bases) {
78
return bases;
79
}
80
result = PyList_AsTuple(new_bases);
81
Py_DECREF(new_bases);
82
return result;
83
84
error:
85
Py_XDECREF(new_bases);
86
return NULL;
87
}
88
89
/* AC: cannot convert yet, waiting for *args support */
90
static PyObject *
91
builtin___build_class__(PyObject *self, PyObject *const *args, Py_ssize_t nargs,
92
PyObject *kwnames)
93
{
94
PyObject *func, *name, *winner, *prep;
95
PyObject *cls = NULL, *cell = NULL, *ns = NULL, *meta = NULL, *orig_bases = NULL;
96
PyObject *mkw = NULL, *bases = NULL;
97
int isclass = 0; /* initialize to prevent gcc warning */
98
99
if (nargs < 2) {
100
PyErr_SetString(PyExc_TypeError,
101
"__build_class__: not enough arguments");
102
return NULL;
103
}
104
func = args[0]; /* Better be callable */
105
if (!PyFunction_Check(func)) {
106
PyErr_SetString(PyExc_TypeError,
107
"__build_class__: func must be a function");
108
return NULL;
109
}
110
name = args[1];
111
if (!PyUnicode_Check(name)) {
112
PyErr_SetString(PyExc_TypeError,
113
"__build_class__: name is not a string");
114
return NULL;
115
}
116
orig_bases = _PyTuple_FromArray(args + 2, nargs - 2);
117
if (orig_bases == NULL)
118
return NULL;
119
120
bases = update_bases(orig_bases, args + 2, nargs - 2);
121
if (bases == NULL) {
122
Py_DECREF(orig_bases);
123
return NULL;
124
}
125
126
if (kwnames == NULL) {
127
meta = NULL;
128
mkw = NULL;
129
}
130
else {
131
mkw = _PyStack_AsDict(args + nargs, kwnames);
132
if (mkw == NULL) {
133
goto error;
134
}
135
136
meta = _PyDict_GetItemWithError(mkw, &_Py_ID(metaclass));
137
if (meta != NULL) {
138
Py_INCREF(meta);
139
if (PyDict_DelItem(mkw, &_Py_ID(metaclass)) < 0) {
140
goto error;
141
}
142
/* metaclass is explicitly given, check if it's indeed a class */
143
isclass = PyType_Check(meta);
144
}
145
else if (PyErr_Occurred()) {
146
goto error;
147
}
148
}
149
if (meta == NULL) {
150
/* if there are no bases, use type: */
151
if (PyTuple_GET_SIZE(bases) == 0) {
152
meta = (PyObject *) (&PyType_Type);
153
}
154
/* else get the type of the first base */
155
else {
156
PyObject *base0 = PyTuple_GET_ITEM(bases, 0);
157
meta = (PyObject *)Py_TYPE(base0);
158
}
159
Py_INCREF(meta);
160
isclass = 1; /* meta is really a class */
161
}
162
163
if (isclass) {
164
/* meta is really a class, so check for a more derived
165
metaclass, or possible metaclass conflicts: */
166
winner = (PyObject *)_PyType_CalculateMetaclass((PyTypeObject *)meta,
167
bases);
168
if (winner == NULL) {
169
goto error;
170
}
171
if (winner != meta) {
172
Py_SETREF(meta, Py_NewRef(winner));
173
}
174
}
175
/* else: meta is not a class, so we cannot do the metaclass
176
calculation, so we will use the explicitly given object as it is */
177
if (_PyObject_LookupAttr(meta, &_Py_ID(__prepare__), &prep) < 0) {
178
ns = NULL;
179
}
180
else if (prep == NULL) {
181
ns = PyDict_New();
182
}
183
else {
184
PyObject *pargs[2] = {name, bases};
185
ns = PyObject_VectorcallDict(prep, pargs, 2, mkw);
186
Py_DECREF(prep);
187
}
188
if (ns == NULL) {
189
goto error;
190
}
191
if (!PyMapping_Check(ns)) {
192
PyErr_Format(PyExc_TypeError,
193
"%.200s.__prepare__() must return a mapping, not %.200s",
194
isclass ? ((PyTypeObject *)meta)->tp_name : "<metaclass>",
195
Py_TYPE(ns)->tp_name);
196
goto error;
197
}
198
PyThreadState *tstate = _PyThreadState_GET();
199
EVAL_CALL_STAT_INC(EVAL_CALL_BUILD_CLASS);
200
cell = _PyEval_Vector(tstate, (PyFunctionObject *)func, ns, NULL, 0, NULL);
201
if (cell != NULL) {
202
if (bases != orig_bases) {
203
if (PyMapping_SetItemString(ns, "__orig_bases__", orig_bases) < 0) {
204
goto error;
205
}
206
}
207
PyObject *margs[3] = {name, bases, ns};
208
cls = PyObject_VectorcallDict(meta, margs, 3, mkw);
209
if (cls != NULL && PyType_Check(cls) && PyCell_Check(cell)) {
210
PyObject *cell_cls = PyCell_GET(cell);
211
if (cell_cls != cls) {
212
if (cell_cls == NULL) {
213
const char *msg =
214
"__class__ not set defining %.200R as %.200R. "
215
"Was __classcell__ propagated to type.__new__?";
216
PyErr_Format(PyExc_RuntimeError, msg, name, cls);
217
} else {
218
const char *msg =
219
"__class__ set to %.200R defining %.200R as %.200R";
220
PyErr_Format(PyExc_TypeError, msg, cell_cls, name, cls);
221
}
222
Py_SETREF(cls, NULL);
223
goto error;
224
}
225
}
226
}
227
error:
228
Py_XDECREF(cell);
229
Py_XDECREF(ns);
230
Py_XDECREF(meta);
231
Py_XDECREF(mkw);
232
if (bases != orig_bases) {
233
Py_DECREF(orig_bases);
234
}
235
Py_DECREF(bases);
236
return cls;
237
}
238
239
PyDoc_STRVAR(build_class_doc,
240
"__build_class__(func, name, /, *bases, [metaclass], **kwds) -> class\n\
241
\n\
242
Internal helper function used by the class statement.");
243
244
/*[clinic input]
245
__import__ as builtin___import__
246
247
name: object
248
globals: object(c_default="NULL") = None
249
locals: object(c_default="NULL") = None
250
fromlist: object(c_default="NULL") = ()
251
level: int = 0
252
253
Import a module.
254
255
Because this function is meant for use by the Python
256
interpreter and not for general use, it is better to use
257
importlib.import_module() to programmatically import a module.
258
259
The globals argument is only used to determine the context;
260
they are not modified. The locals argument is unused. The fromlist
261
should be a list of names to emulate ``from name import ...``, or an
262
empty list to emulate ``import name``.
263
When importing a module from a package, note that __import__('A.B', ...)
264
returns package A when fromlist is empty, but its submodule B when
265
fromlist is not empty. The level argument is used to determine whether to
266
perform absolute or relative imports: 0 is absolute, while a positive number
267
is the number of parent directories to search relative to the current module.
268
[clinic start generated code]*/
269
270
static PyObject *
271
builtin___import___impl(PyObject *module, PyObject *name, PyObject *globals,
272
PyObject *locals, PyObject *fromlist, int level)
273
/*[clinic end generated code: output=4febeda88a0cd245 input=73f4b960ea5b9dd6]*/
274
{
275
return PyImport_ImportModuleLevelObject(name, globals, locals,
276
fromlist, level);
277
}
278
279
280
/*[clinic input]
281
abs as builtin_abs
282
283
x: object
284
/
285
286
Return the absolute value of the argument.
287
[clinic start generated code]*/
288
289
static PyObject *
290
builtin_abs(PyObject *module, PyObject *x)
291
/*[clinic end generated code: output=b1b433b9e51356f5 input=bed4ca14e29c20d1]*/
292
{
293
return PyNumber_Absolute(x);
294
}
295
296
/*[clinic input]
297
all as builtin_all
298
299
iterable: object
300
/
301
302
Return True if bool(x) is True for all values x in the iterable.
303
304
If the iterable is empty, return True.
305
[clinic start generated code]*/
306
307
static PyObject *
308
builtin_all(PyObject *module, PyObject *iterable)
309
/*[clinic end generated code: output=ca2a7127276f79b3 input=1a7c5d1bc3438a21]*/
310
{
311
PyObject *it, *item;
312
PyObject *(*iternext)(PyObject *);
313
int cmp;
314
315
it = PyObject_GetIter(iterable);
316
if (it == NULL)
317
return NULL;
318
iternext = *Py_TYPE(it)->tp_iternext;
319
320
for (;;) {
321
item = iternext(it);
322
if (item == NULL)
323
break;
324
cmp = PyObject_IsTrue(item);
325
Py_DECREF(item);
326
if (cmp < 0) {
327
Py_DECREF(it);
328
return NULL;
329
}
330
if (cmp == 0) {
331
Py_DECREF(it);
332
Py_RETURN_FALSE;
333
}
334
}
335
Py_DECREF(it);
336
if (PyErr_Occurred()) {
337
if (PyErr_ExceptionMatches(PyExc_StopIteration))
338
PyErr_Clear();
339
else
340
return NULL;
341
}
342
Py_RETURN_TRUE;
343
}
344
345
/*[clinic input]
346
any as builtin_any
347
348
iterable: object
349
/
350
351
Return True if bool(x) is True for any x in the iterable.
352
353
If the iterable is empty, return False.
354
[clinic start generated code]*/
355
356
static PyObject *
357
builtin_any(PyObject *module, PyObject *iterable)
358
/*[clinic end generated code: output=fa65684748caa60e input=41d7451c23384f24]*/
359
{
360
PyObject *it, *item;
361
PyObject *(*iternext)(PyObject *);
362
int cmp;
363
364
it = PyObject_GetIter(iterable);
365
if (it == NULL)
366
return NULL;
367
iternext = *Py_TYPE(it)->tp_iternext;
368
369
for (;;) {
370
item = iternext(it);
371
if (item == NULL)
372
break;
373
cmp = PyObject_IsTrue(item);
374
Py_DECREF(item);
375
if (cmp < 0) {
376
Py_DECREF(it);
377
return NULL;
378
}
379
if (cmp > 0) {
380
Py_DECREF(it);
381
Py_RETURN_TRUE;
382
}
383
}
384
Py_DECREF(it);
385
if (PyErr_Occurred()) {
386
if (PyErr_ExceptionMatches(PyExc_StopIteration))
387
PyErr_Clear();
388
else
389
return NULL;
390
}
391
Py_RETURN_FALSE;
392
}
393
394
/*[clinic input]
395
ascii as builtin_ascii
396
397
obj: object
398
/
399
400
Return an ASCII-only representation of an object.
401
402
As repr(), return a string containing a printable representation of an
403
object, but escape the non-ASCII characters in the string returned by
404
repr() using \\x, \\u or \\U escapes. This generates a string similar
405
to that returned by repr() in Python 2.
406
[clinic start generated code]*/
407
408
static PyObject *
409
builtin_ascii(PyObject *module, PyObject *obj)
410
/*[clinic end generated code: output=6d37b3f0984c7eb9 input=4c62732e1b3a3cc9]*/
411
{
412
return PyObject_ASCII(obj);
413
}
414
415
416
/*[clinic input]
417
bin as builtin_bin
418
419
number: object
420
/
421
422
Return the binary representation of an integer.
423
424
>>> bin(2796202)
425
'0b1010101010101010101010'
426
[clinic start generated code]*/
427
428
static PyObject *
429
builtin_bin(PyObject *module, PyObject *number)
430
/*[clinic end generated code: output=b6fc4ad5e649f4f7 input=53f8a0264bacaf90]*/
431
{
432
return PyNumber_ToBase(number, 2);
433
}
434
435
436
/*[clinic input]
437
callable as builtin_callable
438
439
obj: object
440
/
441
442
Return whether the object is callable (i.e., some kind of function).
443
444
Note that classes are callable, as are instances of classes with a
445
__call__() method.
446
[clinic start generated code]*/
447
448
static PyObject *
449
builtin_callable(PyObject *module, PyObject *obj)
450
/*[clinic end generated code: output=2b095d59d934cb7e input=1423bab99cc41f58]*/
451
{
452
return PyBool_FromLong((long)PyCallable_Check(obj));
453
}
454
455
static PyObject *
456
builtin_breakpoint(PyObject *self, PyObject *const *args, Py_ssize_t nargs, PyObject *keywords)
457
{
458
PyObject *hook = PySys_GetObject("breakpointhook");
459
460
if (hook == NULL) {
461
PyErr_SetString(PyExc_RuntimeError, "lost sys.breakpointhook");
462
return NULL;
463
}
464
465
if (PySys_Audit("builtins.breakpoint", "O", hook) < 0) {
466
return NULL;
467
}
468
469
Py_INCREF(hook);
470
PyObject *retval = PyObject_Vectorcall(hook, args, nargs, keywords);
471
Py_DECREF(hook);
472
return retval;
473
}
474
475
PyDoc_STRVAR(breakpoint_doc,
476
"breakpoint(*args, **kws)\n\
477
\n\
478
Call sys.breakpointhook(*args, **kws). sys.breakpointhook() must accept\n\
479
whatever arguments are passed.\n\
480
\n\
481
By default, this drops you into the pdb debugger.");
482
483
typedef struct {
484
PyObject_HEAD
485
PyObject *func;
486
PyObject *it;
487
} filterobject;
488
489
static PyObject *
490
filter_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
491
{
492
PyObject *func, *seq;
493
PyObject *it;
494
filterobject *lz;
495
496
if ((type == &PyFilter_Type || type->tp_init == PyFilter_Type.tp_init) &&
497
!_PyArg_NoKeywords("filter", kwds))
498
return NULL;
499
500
if (!PyArg_UnpackTuple(args, "filter", 2, 2, &func, &seq))
501
return NULL;
502
503
/* Get iterator. */
504
it = PyObject_GetIter(seq);
505
if (it == NULL)
506
return NULL;
507
508
/* create filterobject structure */
509
lz = (filterobject *)type->tp_alloc(type, 0);
510
if (lz == NULL) {
511
Py_DECREF(it);
512
return NULL;
513
}
514
515
lz->func = Py_NewRef(func);
516
lz->it = it;
517
518
return (PyObject *)lz;
519
}
520
521
static PyObject *
522
filter_vectorcall(PyObject *type, PyObject * const*args,
523
size_t nargsf, PyObject *kwnames)
524
{
525
PyTypeObject *tp = _PyType_CAST(type);
526
if (tp == &PyFilter_Type && !_PyArg_NoKwnames("filter", kwnames)) {
527
return NULL;
528
}
529
530
Py_ssize_t nargs = PyVectorcall_NARGS(nargsf);
531
if (!_PyArg_CheckPositional("filter", nargs, 2, 2)) {
532
return NULL;
533
}
534
535
PyObject *it = PyObject_GetIter(args[1]);
536
if (it == NULL) {
537
return NULL;
538
}
539
540
filterobject *lz = (filterobject *)tp->tp_alloc(tp, 0);
541
542
if (lz == NULL) {
543
Py_DECREF(it);
544
return NULL;
545
}
546
547
lz->func = Py_NewRef(args[0]);
548
lz->it = it;
549
550
return (PyObject *)lz;
551
}
552
553
static void
554
filter_dealloc(filterobject *lz)
555
{
556
PyObject_GC_UnTrack(lz);
557
Py_TRASHCAN_BEGIN(lz, filter_dealloc)
558
Py_XDECREF(lz->func);
559
Py_XDECREF(lz->it);
560
Py_TYPE(lz)->tp_free(lz);
561
Py_TRASHCAN_END
562
}
563
564
static int
565
filter_traverse(filterobject *lz, visitproc visit, void *arg)
566
{
567
Py_VISIT(lz->it);
568
Py_VISIT(lz->func);
569
return 0;
570
}
571
572
static PyObject *
573
filter_next(filterobject *lz)
574
{
575
PyObject *item;
576
PyObject *it = lz->it;
577
long ok;
578
PyObject *(*iternext)(PyObject *);
579
int checktrue = lz->func == Py_None || lz->func == (PyObject *)&PyBool_Type;
580
581
iternext = *Py_TYPE(it)->tp_iternext;
582
for (;;) {
583
item = iternext(it);
584
if (item == NULL)
585
return NULL;
586
587
if (checktrue) {
588
ok = PyObject_IsTrue(item);
589
} else {
590
PyObject *good;
591
good = PyObject_CallOneArg(lz->func, item);
592
if (good == NULL) {
593
Py_DECREF(item);
594
return NULL;
595
}
596
ok = PyObject_IsTrue(good);
597
Py_DECREF(good);
598
}
599
if (ok > 0)
600
return item;
601
Py_DECREF(item);
602
if (ok < 0)
603
return NULL;
604
}
605
}
606
607
static PyObject *
608
filter_reduce(filterobject *lz, PyObject *Py_UNUSED(ignored))
609
{
610
return Py_BuildValue("O(OO)", Py_TYPE(lz), lz->func, lz->it);
611
}
612
613
PyDoc_STRVAR(reduce_doc, "Return state information for pickling.");
614
615
static PyMethodDef filter_methods[] = {
616
{"__reduce__", _PyCFunction_CAST(filter_reduce), METH_NOARGS, reduce_doc},
617
{NULL, NULL} /* sentinel */
618
};
619
620
PyDoc_STRVAR(filter_doc,
621
"filter(function or None, iterable) --> filter object\n\
622
\n\
623
Return an iterator yielding those items of iterable for which function(item)\n\
624
is true. If function is None, return the items that are true.");
625
626
PyTypeObject PyFilter_Type = {
627
PyVarObject_HEAD_INIT(&PyType_Type, 0)
628
"filter", /* tp_name */
629
sizeof(filterobject), /* tp_basicsize */
630
0, /* tp_itemsize */
631
/* methods */
632
(destructor)filter_dealloc, /* tp_dealloc */
633
0, /* tp_vectorcall_offset */
634
0, /* tp_getattr */
635
0, /* tp_setattr */
636
0, /* tp_as_async */
637
0, /* tp_repr */
638
0, /* tp_as_number */
639
0, /* tp_as_sequence */
640
0, /* tp_as_mapping */
641
0, /* tp_hash */
642
0, /* tp_call */
643
0, /* tp_str */
644
PyObject_GenericGetAttr, /* tp_getattro */
645
0, /* tp_setattro */
646
0, /* tp_as_buffer */
647
Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
648
Py_TPFLAGS_BASETYPE, /* tp_flags */
649
filter_doc, /* tp_doc */
650
(traverseproc)filter_traverse, /* tp_traverse */
651
0, /* tp_clear */
652
0, /* tp_richcompare */
653
0, /* tp_weaklistoffset */
654
PyObject_SelfIter, /* tp_iter */
655
(iternextfunc)filter_next, /* tp_iternext */
656
filter_methods, /* tp_methods */
657
0, /* tp_members */
658
0, /* tp_getset */
659
0, /* tp_base */
660
0, /* tp_dict */
661
0, /* tp_descr_get */
662
0, /* tp_descr_set */
663
0, /* tp_dictoffset */
664
0, /* tp_init */
665
PyType_GenericAlloc, /* tp_alloc */
666
filter_new, /* tp_new */
667
PyObject_GC_Del, /* tp_free */
668
.tp_vectorcall = (vectorcallfunc)filter_vectorcall
669
};
670
671
672
/*[clinic input]
673
format as builtin_format
674
675
value: object
676
format_spec: unicode(c_default="NULL") = ''
677
/
678
679
Return type(value).__format__(value, format_spec)
680
681
Many built-in types implement format_spec according to the
682
Format Specification Mini-language. See help('FORMATTING').
683
684
If type(value) does not supply a method named __format__
685
and format_spec is empty, then str(value) is returned.
686
See also help('SPECIALMETHODS').
687
[clinic start generated code]*/
688
689
static PyObject *
690
builtin_format_impl(PyObject *module, PyObject *value, PyObject *format_spec)
691
/*[clinic end generated code: output=2f40bdfa4954b077 input=45ef3934b86d5624]*/
692
{
693
return PyObject_Format(value, format_spec);
694
}
695
696
/*[clinic input]
697
chr as builtin_chr
698
699
i: int
700
/
701
702
Return a Unicode string of one character with ordinal i; 0 <= i <= 0x10ffff.
703
[clinic start generated code]*/
704
705
static PyObject *
706
builtin_chr_impl(PyObject *module, int i)
707
/*[clinic end generated code: output=c733afcd200afcb7 input=3f604ef45a70750d]*/
708
{
709
return PyUnicode_FromOrdinal(i);
710
}
711
712
713
/*[clinic input]
714
compile as builtin_compile
715
716
source: object
717
filename: object(converter="PyUnicode_FSDecoder")
718
mode: str
719
flags: int = 0
720
dont_inherit: bool = False
721
optimize: int = -1
722
*
723
_feature_version as feature_version: int = -1
724
725
Compile source into a code object that can be executed by exec() or eval().
726
727
The source code may represent a Python module, statement or expression.
728
The filename will be used for run-time error messages.
729
The mode must be 'exec' to compile a module, 'single' to compile a
730
single (interactive) statement, or 'eval' to compile an expression.
731
The flags argument, if present, controls which future statements influence
732
the compilation of the code.
733
The dont_inherit argument, if true, stops the compilation inheriting
734
the effects of any future statements in effect in the code calling
735
compile; if absent or false these statements do influence the compilation,
736
in addition to any features explicitly specified.
737
[clinic start generated code]*/
738
739
static PyObject *
740
builtin_compile_impl(PyObject *module, PyObject *source, PyObject *filename,
741
const char *mode, int flags, int dont_inherit,
742
int optimize, int feature_version)
743
/*[clinic end generated code: output=b0c09c84f116d3d7 input=cc78e20e7c7682ba]*/
744
{
745
PyObject *source_copy;
746
const char *str;
747
int compile_mode = -1;
748
int is_ast;
749
int start[] = {Py_file_input, Py_eval_input, Py_single_input, Py_func_type_input};
750
PyObject *result;
751
752
PyCompilerFlags cf = _PyCompilerFlags_INIT;
753
cf.cf_flags = flags | PyCF_SOURCE_IS_UTF8;
754
if (feature_version >= 0 && (flags & PyCF_ONLY_AST)) {
755
cf.cf_feature_version = feature_version;
756
}
757
758
if (flags &
759
~(PyCF_MASK | PyCF_MASK_OBSOLETE | PyCF_COMPILE_MASK))
760
{
761
PyErr_SetString(PyExc_ValueError,
762
"compile(): unrecognised flags");
763
goto error;
764
}
765
/* XXX Warn if (supplied_flags & PyCF_MASK_OBSOLETE) != 0? */
766
767
if (optimize < -1 || optimize > 2) {
768
PyErr_SetString(PyExc_ValueError,
769
"compile(): invalid optimize value");
770
goto error;
771
}
772
773
if (!dont_inherit) {
774
PyEval_MergeCompilerFlags(&cf);
775
}
776
777
if (strcmp(mode, "exec") == 0)
778
compile_mode = 0;
779
else if (strcmp(mode, "eval") == 0)
780
compile_mode = 1;
781
else if (strcmp(mode, "single") == 0)
782
compile_mode = 2;
783
else if (strcmp(mode, "func_type") == 0) {
784
if (!(flags & PyCF_ONLY_AST)) {
785
PyErr_SetString(PyExc_ValueError,
786
"compile() mode 'func_type' requires flag PyCF_ONLY_AST");
787
goto error;
788
}
789
compile_mode = 3;
790
}
791
else {
792
const char *msg;
793
if (flags & PyCF_ONLY_AST)
794
msg = "compile() mode must be 'exec', 'eval', 'single' or 'func_type'";
795
else
796
msg = "compile() mode must be 'exec', 'eval' or 'single'";
797
PyErr_SetString(PyExc_ValueError, msg);
798
goto error;
799
}
800
801
is_ast = PyAST_Check(source);
802
if (is_ast == -1)
803
goto error;
804
if (is_ast) {
805
if (flags & PyCF_ONLY_AST) {
806
result = Py_NewRef(source);
807
}
808
else {
809
PyArena *arena;
810
mod_ty mod;
811
812
arena = _PyArena_New();
813
if (arena == NULL)
814
goto error;
815
mod = PyAST_obj2mod(source, arena, compile_mode);
816
if (mod == NULL || !_PyAST_Validate(mod)) {
817
_PyArena_Free(arena);
818
goto error;
819
}
820
result = (PyObject*)_PyAST_Compile(mod, filename,
821
&cf, optimize, arena);
822
_PyArena_Free(arena);
823
}
824
goto finally;
825
}
826
827
str = _Py_SourceAsString(source, "compile", "string, bytes or AST", &cf, &source_copy);
828
if (str == NULL)
829
goto error;
830
831
result = Py_CompileStringObject(str, filename, start[compile_mode], &cf, optimize);
832
833
Py_XDECREF(source_copy);
834
goto finally;
835
836
error:
837
result = NULL;
838
finally:
839
Py_DECREF(filename);
840
return result;
841
}
842
843
/*[clinic input]
844
dir as builtin_dir
845
846
arg: object = NULL
847
/
848
849
Show attributes of an object.
850
851
If called without an argument, return the names in the current scope.
852
Else, return an alphabetized list of names comprising (some of) the attributes
853
of the given object, and of attributes reachable from it.
854
If the object supplies a method named __dir__, it will be used; otherwise
855
the default dir() logic is used and returns:
856
for a module object: the module's attributes.
857
for a class object: its attributes, and recursively the attributes
858
of its bases.
859
for any other object: its attributes, its class's attributes, and
860
recursively the attributes of its class's base classes.
861
[clinic start generated code]*/
862
863
static PyObject *
864
builtin_dir_impl(PyObject *module, PyObject *arg)
865
/*[clinic end generated code: output=24f2c7a52c1e3b08 input=ed6d6ccb13d52251]*/
866
{
867
return PyObject_Dir(arg);
868
}
869
870
/*[clinic input]
871
divmod as builtin_divmod
872
873
x: object
874
y: object
875
/
876
877
Return the tuple (x//y, x%y). Invariant: div*y + mod == x.
878
[clinic start generated code]*/
879
880
static PyObject *
881
builtin_divmod_impl(PyObject *module, PyObject *x, PyObject *y)
882
/*[clinic end generated code: output=b06d8a5f6e0c745e input=175ad9c84ff41a85]*/
883
{
884
return PyNumber_Divmod(x, y);
885
}
886
887
888
/*[clinic input]
889
eval as builtin_eval
890
891
source: object
892
globals: object = None
893
locals: object = None
894
/
895
896
Evaluate the given source in the context of globals and locals.
897
898
The source may be a string representing a Python expression
899
or a code object as returned by compile().
900
The globals must be a dictionary and locals can be any mapping,
901
defaulting to the current globals and locals.
902
If only globals is given, locals defaults to it.
903
[clinic start generated code]*/
904
905
static PyObject *
906
builtin_eval_impl(PyObject *module, PyObject *source, PyObject *globals,
907
PyObject *locals)
908
/*[clinic end generated code: output=0a0824aa70093116 input=11ee718a8640e527]*/
909
{
910
PyObject *result, *source_copy;
911
const char *str;
912
913
if (locals != Py_None && !PyMapping_Check(locals)) {
914
PyErr_SetString(PyExc_TypeError, "locals must be a mapping");
915
return NULL;
916
}
917
if (globals != Py_None && !PyDict_Check(globals)) {
918
PyErr_SetString(PyExc_TypeError, PyMapping_Check(globals) ?
919
"globals must be a real dict; try eval(expr, {}, mapping)"
920
: "globals must be a dict");
921
return NULL;
922
}
923
if (globals == Py_None) {
924
globals = PyEval_GetGlobals();
925
if (locals == Py_None) {
926
locals = PyEval_GetLocals();
927
if (locals == NULL)
928
return NULL;
929
}
930
}
931
else if (locals == Py_None)
932
locals = globals;
933
934
if (globals == NULL || locals == NULL) {
935
PyErr_SetString(PyExc_TypeError,
936
"eval must be given globals and locals "
937
"when called without a frame");
938
return NULL;
939
}
940
941
int r = PyDict_Contains(globals, &_Py_ID(__builtins__));
942
if (r == 0) {
943
r = PyDict_SetItem(globals, &_Py_ID(__builtins__), PyEval_GetBuiltins());
944
}
945
if (r < 0) {
946
return NULL;
947
}
948
949
if (PyCode_Check(source)) {
950
if (PySys_Audit("exec", "O", source) < 0) {
951
return NULL;
952
}
953
954
if (PyCode_GetNumFree((PyCodeObject *)source) > 0) {
955
PyErr_SetString(PyExc_TypeError,
956
"code object passed to eval() may not contain free variables");
957
return NULL;
958
}
959
return PyEval_EvalCode(source, globals, locals);
960
}
961
962
PyCompilerFlags cf = _PyCompilerFlags_INIT;
963
cf.cf_flags = PyCF_SOURCE_IS_UTF8;
964
str = _Py_SourceAsString(source, "eval", "string, bytes or code", &cf, &source_copy);
965
if (str == NULL)
966
return NULL;
967
968
while (*str == ' ' || *str == '\t')
969
str++;
970
971
(void)PyEval_MergeCompilerFlags(&cf);
972
result = PyRun_StringFlags(str, Py_eval_input, globals, locals, &cf);
973
Py_XDECREF(source_copy);
974
return result;
975
}
976
977
/*[clinic input]
978
exec as builtin_exec
979
980
source: object
981
globals: object = None
982
locals: object = None
983
/
984
*
985
closure: object(c_default="NULL") = None
986
987
Execute the given source in the context of globals and locals.
988
989
The source may be a string representing one or more Python statements
990
or a code object as returned by compile().
991
The globals must be a dictionary and locals can be any mapping,
992
defaulting to the current globals and locals.
993
If only globals is given, locals defaults to it.
994
The closure must be a tuple of cellvars, and can only be used
995
when source is a code object requiring exactly that many cellvars.
996
[clinic start generated code]*/
997
998
static PyObject *
999
builtin_exec_impl(PyObject *module, PyObject *source, PyObject *globals,
1000
PyObject *locals, PyObject *closure)
1001
/*[clinic end generated code: output=7579eb4e7646743d input=f13a7e2b503d1d9a]*/
1002
{
1003
PyObject *v;
1004
1005
if (globals == Py_None) {
1006
globals = PyEval_GetGlobals();
1007
if (locals == Py_None) {
1008
locals = PyEval_GetLocals();
1009
if (locals == NULL)
1010
return NULL;
1011
}
1012
if (!globals || !locals) {
1013
PyErr_SetString(PyExc_SystemError,
1014
"globals and locals cannot be NULL");
1015
return NULL;
1016
}
1017
}
1018
else if (locals == Py_None)
1019
locals = globals;
1020
1021
if (!PyDict_Check(globals)) {
1022
PyErr_Format(PyExc_TypeError, "exec() globals must be a dict, not %.100s",
1023
Py_TYPE(globals)->tp_name);
1024
return NULL;
1025
}
1026
if (!PyMapping_Check(locals)) {
1027
PyErr_Format(PyExc_TypeError,
1028
"locals must be a mapping or None, not %.100s",
1029
Py_TYPE(locals)->tp_name);
1030
return NULL;
1031
}
1032
int r = PyDict_Contains(globals, &_Py_ID(__builtins__));
1033
if (r == 0) {
1034
r = PyDict_SetItem(globals, &_Py_ID(__builtins__), PyEval_GetBuiltins());
1035
}
1036
if (r < 0) {
1037
return NULL;
1038
}
1039
1040
if (closure == Py_None) {
1041
closure = NULL;
1042
}
1043
1044
if (PyCode_Check(source)) {
1045
Py_ssize_t num_free = PyCode_GetNumFree((PyCodeObject *)source);
1046
if (num_free == 0) {
1047
if (closure) {
1048
PyErr_SetString(PyExc_TypeError,
1049
"cannot use a closure with this code object");
1050
return NULL;
1051
}
1052
} else {
1053
int closure_is_ok =
1054
closure
1055
&& PyTuple_CheckExact(closure)
1056
&& (PyTuple_GET_SIZE(closure) == num_free);
1057
if (closure_is_ok) {
1058
for (Py_ssize_t i = 0; i < num_free; i++) {
1059
PyObject *cell = PyTuple_GET_ITEM(closure, i);
1060
if (!PyCell_Check(cell)) {
1061
closure_is_ok = 0;
1062
break;
1063
}
1064
}
1065
}
1066
if (!closure_is_ok) {
1067
PyErr_Format(PyExc_TypeError,
1068
"code object requires a closure of exactly length %zd",
1069
num_free);
1070
return NULL;
1071
}
1072
}
1073
1074
if (PySys_Audit("exec", "O", source) < 0) {
1075
return NULL;
1076
}
1077
1078
if (!closure) {
1079
v = PyEval_EvalCode(source, globals, locals);
1080
} else {
1081
v = PyEval_EvalCodeEx(source, globals, locals,
1082
NULL, 0,
1083
NULL, 0,
1084
NULL, 0,
1085
NULL,
1086
closure);
1087
}
1088
}
1089
else {
1090
if (closure != NULL) {
1091
PyErr_SetString(PyExc_TypeError,
1092
"closure can only be used when source is a code object");
1093
}
1094
PyObject *source_copy;
1095
const char *str;
1096
PyCompilerFlags cf = _PyCompilerFlags_INIT;
1097
cf.cf_flags = PyCF_SOURCE_IS_UTF8;
1098
str = _Py_SourceAsString(source, "exec",
1099
"string, bytes or code", &cf,
1100
&source_copy);
1101
if (str == NULL)
1102
return NULL;
1103
if (PyEval_MergeCompilerFlags(&cf))
1104
v = PyRun_StringFlags(str, Py_file_input, globals,
1105
locals, &cf);
1106
else
1107
v = PyRun_String(str, Py_file_input, globals, locals);
1108
Py_XDECREF(source_copy);
1109
}
1110
if (v == NULL)
1111
return NULL;
1112
Py_DECREF(v);
1113
Py_RETURN_NONE;
1114
}
1115
1116
1117
/*[clinic input]
1118
getattr as builtin_getattr
1119
1120
object: object
1121
name: object
1122
default: object = NULL
1123
/
1124
1125
Get a named attribute from an object.
1126
1127
getattr(x, 'y') is equivalent to x.y
1128
When a default argument is given, it is returned when the attribute doesn't
1129
exist; without it, an exception is raised in that case.
1130
[clinic start generated code]*/
1131
1132
static PyObject *
1133
builtin_getattr_impl(PyObject *module, PyObject *object, PyObject *name,
1134
PyObject *default_value)
1135
/*[clinic end generated code: output=74ad0e225e3f701c input=d7562cd4c3556171]*/
1136
{
1137
PyObject *result;
1138
1139
if (default_value != NULL) {
1140
if (_PyObject_LookupAttr(object, name, &result) == 0) {
1141
return Py_NewRef(default_value);
1142
}
1143
}
1144
else {
1145
result = PyObject_GetAttr(object, name);
1146
}
1147
return result;
1148
}
1149
1150
1151
/*[clinic input]
1152
globals as builtin_globals
1153
1154
Return the dictionary containing the current scope's global variables.
1155
1156
NOTE: Updates to this dictionary *will* affect name lookups in the current
1157
global scope and vice-versa.
1158
[clinic start generated code]*/
1159
1160
static PyObject *
1161
builtin_globals_impl(PyObject *module)
1162
/*[clinic end generated code: output=e5dd1527067b94d2 input=9327576f92bb48ba]*/
1163
{
1164
PyObject *d;
1165
1166
d = PyEval_GetGlobals();
1167
return Py_XNewRef(d);
1168
}
1169
1170
1171
/*[clinic input]
1172
hasattr as builtin_hasattr
1173
1174
obj: object
1175
name: object
1176
/
1177
1178
Return whether the object has an attribute with the given name.
1179
1180
This is done by calling getattr(obj, name) and catching AttributeError.
1181
[clinic start generated code]*/
1182
1183
static PyObject *
1184
builtin_hasattr_impl(PyObject *module, PyObject *obj, PyObject *name)
1185
/*[clinic end generated code: output=a7aff2090a4151e5 input=0faec9787d979542]*/
1186
{
1187
PyObject *v;
1188
1189
if (_PyObject_LookupAttr(obj, name, &v) < 0) {
1190
return NULL;
1191
}
1192
if (v == NULL) {
1193
Py_RETURN_FALSE;
1194
}
1195
Py_DECREF(v);
1196
Py_RETURN_TRUE;
1197
}
1198
1199
1200
/* AC: gdb's integration with CPython relies on builtin_id having
1201
* the *exact* parameter names of "self" and "v", so we ensure we
1202
* preserve those name rather than using the AC defaults.
1203
*/
1204
/*[clinic input]
1205
id as builtin_id
1206
1207
self: self(type="PyModuleDef *")
1208
obj as v: object
1209
/
1210
1211
Return the identity of an object.
1212
1213
This is guaranteed to be unique among simultaneously existing objects.
1214
(CPython uses the object's memory address.)
1215
[clinic start generated code]*/
1216
1217
static PyObject *
1218
builtin_id(PyModuleDef *self, PyObject *v)
1219
/*[clinic end generated code: output=0aa640785f697f65 input=5a534136419631f4]*/
1220
{
1221
PyObject *id = PyLong_FromVoidPtr(v);
1222
1223
if (id && PySys_Audit("builtins.id", "O", id) < 0) {
1224
Py_DECREF(id);
1225
return NULL;
1226
}
1227
1228
return id;
1229
}
1230
1231
1232
/* map object ************************************************************/
1233
1234
typedef struct {
1235
PyObject_HEAD
1236
PyObject *iters;
1237
PyObject *func;
1238
} mapobject;
1239
1240
static PyObject *
1241
map_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1242
{
1243
PyObject *it, *iters, *func;
1244
mapobject *lz;
1245
Py_ssize_t numargs, i;
1246
1247
if ((type == &PyMap_Type || type->tp_init == PyMap_Type.tp_init) &&
1248
!_PyArg_NoKeywords("map", kwds))
1249
return NULL;
1250
1251
numargs = PyTuple_Size(args);
1252
if (numargs < 2) {
1253
PyErr_SetString(PyExc_TypeError,
1254
"map() must have at least two arguments.");
1255
return NULL;
1256
}
1257
1258
iters = PyTuple_New(numargs-1);
1259
if (iters == NULL)
1260
return NULL;
1261
1262
for (i=1 ; i<numargs ; i++) {
1263
/* Get iterator. */
1264
it = PyObject_GetIter(PyTuple_GET_ITEM(args, i));
1265
if (it == NULL) {
1266
Py_DECREF(iters);
1267
return NULL;
1268
}
1269
PyTuple_SET_ITEM(iters, i-1, it);
1270
}
1271
1272
/* create mapobject structure */
1273
lz = (mapobject *)type->tp_alloc(type, 0);
1274
if (lz == NULL) {
1275
Py_DECREF(iters);
1276
return NULL;
1277
}
1278
lz->iters = iters;
1279
func = PyTuple_GET_ITEM(args, 0);
1280
lz->func = Py_NewRef(func);
1281
1282
return (PyObject *)lz;
1283
}
1284
1285
static PyObject *
1286
map_vectorcall(PyObject *type, PyObject * const*args,
1287
size_t nargsf, PyObject *kwnames)
1288
{
1289
PyTypeObject *tp = _PyType_CAST(type);
1290
if (tp == &PyMap_Type && !_PyArg_NoKwnames("map", kwnames)) {
1291
return NULL;
1292
}
1293
1294
Py_ssize_t nargs = PyVectorcall_NARGS(nargsf);
1295
if (nargs < 2) {
1296
PyErr_SetString(PyExc_TypeError,
1297
"map() must have at least two arguments.");
1298
return NULL;
1299
}
1300
1301
PyObject *iters = PyTuple_New(nargs-1);
1302
if (iters == NULL) {
1303
return NULL;
1304
}
1305
1306
for (int i=1; i<nargs; i++) {
1307
PyObject *it = PyObject_GetIter(args[i]);
1308
if (it == NULL) {
1309
Py_DECREF(iters);
1310
return NULL;
1311
}
1312
PyTuple_SET_ITEM(iters, i-1, it);
1313
}
1314
1315
mapobject *lz = (mapobject *)tp->tp_alloc(tp, 0);
1316
if (lz == NULL) {
1317
Py_DECREF(iters);
1318
return NULL;
1319
}
1320
lz->iters = iters;
1321
lz->func = Py_NewRef(args[0]);
1322
1323
return (PyObject *)lz;
1324
}
1325
1326
static void
1327
map_dealloc(mapobject *lz)
1328
{
1329
PyObject_GC_UnTrack(lz);
1330
Py_XDECREF(lz->iters);
1331
Py_XDECREF(lz->func);
1332
Py_TYPE(lz)->tp_free(lz);
1333
}
1334
1335
static int
1336
map_traverse(mapobject *lz, visitproc visit, void *arg)
1337
{
1338
Py_VISIT(lz->iters);
1339
Py_VISIT(lz->func);
1340
return 0;
1341
}
1342
1343
static PyObject *
1344
map_next(mapobject *lz)
1345
{
1346
PyObject *small_stack[_PY_FASTCALL_SMALL_STACK];
1347
PyObject **stack;
1348
PyObject *result = NULL;
1349
PyThreadState *tstate = _PyThreadState_GET();
1350
1351
const Py_ssize_t niters = PyTuple_GET_SIZE(lz->iters);
1352
if (niters <= (Py_ssize_t)Py_ARRAY_LENGTH(small_stack)) {
1353
stack = small_stack;
1354
}
1355
else {
1356
stack = PyMem_Malloc(niters * sizeof(stack[0]));
1357
if (stack == NULL) {
1358
_PyErr_NoMemory(tstate);
1359
return NULL;
1360
}
1361
}
1362
1363
Py_ssize_t nargs = 0;
1364
for (Py_ssize_t i=0; i < niters; i++) {
1365
PyObject *it = PyTuple_GET_ITEM(lz->iters, i);
1366
PyObject *val = Py_TYPE(it)->tp_iternext(it);
1367
if (val == NULL) {
1368
goto exit;
1369
}
1370
stack[i] = val;
1371
nargs++;
1372
}
1373
1374
result = _PyObject_VectorcallTstate(tstate, lz->func, stack, nargs, NULL);
1375
1376
exit:
1377
for (Py_ssize_t i=0; i < nargs; i++) {
1378
Py_DECREF(stack[i]);
1379
}
1380
if (stack != small_stack) {
1381
PyMem_Free(stack);
1382
}
1383
return result;
1384
}
1385
1386
static PyObject *
1387
map_reduce(mapobject *lz, PyObject *Py_UNUSED(ignored))
1388
{
1389
Py_ssize_t numargs = PyTuple_GET_SIZE(lz->iters);
1390
PyObject *args = PyTuple_New(numargs+1);
1391
Py_ssize_t i;
1392
if (args == NULL)
1393
return NULL;
1394
PyTuple_SET_ITEM(args, 0, Py_NewRef(lz->func));
1395
for (i = 0; i<numargs; i++){
1396
PyObject *it = PyTuple_GET_ITEM(lz->iters, i);
1397
PyTuple_SET_ITEM(args, i+1, Py_NewRef(it));
1398
}
1399
1400
return Py_BuildValue("ON", Py_TYPE(lz), args);
1401
}
1402
1403
static PyMethodDef map_methods[] = {
1404
{"__reduce__", _PyCFunction_CAST(map_reduce), METH_NOARGS, reduce_doc},
1405
{NULL, NULL} /* sentinel */
1406
};
1407
1408
1409
PyDoc_STRVAR(map_doc,
1410
"map(func, *iterables) --> map object\n\
1411
\n\
1412
Make an iterator that computes the function using arguments from\n\
1413
each of the iterables. Stops when the shortest iterable is exhausted.");
1414
1415
PyTypeObject PyMap_Type = {
1416
PyVarObject_HEAD_INIT(&PyType_Type, 0)
1417
"map", /* tp_name */
1418
sizeof(mapobject), /* tp_basicsize */
1419
0, /* tp_itemsize */
1420
/* methods */
1421
(destructor)map_dealloc, /* tp_dealloc */
1422
0, /* tp_vectorcall_offset */
1423
0, /* tp_getattr */
1424
0, /* tp_setattr */
1425
0, /* tp_as_async */
1426
0, /* tp_repr */
1427
0, /* tp_as_number */
1428
0, /* tp_as_sequence */
1429
0, /* tp_as_mapping */
1430
0, /* tp_hash */
1431
0, /* tp_call */
1432
0, /* tp_str */
1433
PyObject_GenericGetAttr, /* tp_getattro */
1434
0, /* tp_setattro */
1435
0, /* tp_as_buffer */
1436
Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
1437
Py_TPFLAGS_BASETYPE, /* tp_flags */
1438
map_doc, /* tp_doc */
1439
(traverseproc)map_traverse, /* tp_traverse */
1440
0, /* tp_clear */
1441
0, /* tp_richcompare */
1442
0, /* tp_weaklistoffset */
1443
PyObject_SelfIter, /* tp_iter */
1444
(iternextfunc)map_next, /* tp_iternext */
1445
map_methods, /* tp_methods */
1446
0, /* tp_members */
1447
0, /* tp_getset */
1448
0, /* tp_base */
1449
0, /* tp_dict */
1450
0, /* tp_descr_get */
1451
0, /* tp_descr_set */
1452
0, /* tp_dictoffset */
1453
0, /* tp_init */
1454
PyType_GenericAlloc, /* tp_alloc */
1455
map_new, /* tp_new */
1456
PyObject_GC_Del, /* tp_free */
1457
.tp_vectorcall = (vectorcallfunc)map_vectorcall
1458
};
1459
1460
1461
/*[clinic input]
1462
next as builtin_next
1463
1464
iterator: object
1465
default: object = NULL
1466
/
1467
1468
Return the next item from the iterator.
1469
1470
If default is given and the iterator is exhausted,
1471
it is returned instead of raising StopIteration.
1472
[clinic start generated code]*/
1473
1474
static PyObject *
1475
builtin_next_impl(PyObject *module, PyObject *iterator,
1476
PyObject *default_value)
1477
/*[clinic end generated code: output=a38a94eeb447fef9 input=180f9984f182020f]*/
1478
{
1479
PyObject *res;
1480
1481
if (!PyIter_Check(iterator)) {
1482
PyErr_Format(PyExc_TypeError,
1483
"'%.200s' object is not an iterator",
1484
Py_TYPE(iterator)->tp_name);
1485
return NULL;
1486
}
1487
1488
res = (*Py_TYPE(iterator)->tp_iternext)(iterator);
1489
if (res != NULL) {
1490
return res;
1491
} else if (default_value != NULL) {
1492
if (PyErr_Occurred()) {
1493
if(!PyErr_ExceptionMatches(PyExc_StopIteration))
1494
return NULL;
1495
PyErr_Clear();
1496
}
1497
return Py_NewRef(default_value);
1498
} else if (PyErr_Occurred()) {
1499
return NULL;
1500
} else {
1501
PyErr_SetNone(PyExc_StopIteration);
1502
return NULL;
1503
}
1504
}
1505
1506
1507
/*[clinic input]
1508
setattr as builtin_setattr
1509
1510
obj: object
1511
name: object
1512
value: object
1513
/
1514
1515
Sets the named attribute on the given object to the specified value.
1516
1517
setattr(x, 'y', v) is equivalent to ``x.y = v``
1518
[clinic start generated code]*/
1519
1520
static PyObject *
1521
builtin_setattr_impl(PyObject *module, PyObject *obj, PyObject *name,
1522
PyObject *value)
1523
/*[clinic end generated code: output=dc2ce1d1add9acb4 input=5e26417f2e8598d4]*/
1524
{
1525
if (PyObject_SetAttr(obj, name, value) != 0)
1526
return NULL;
1527
Py_RETURN_NONE;
1528
}
1529
1530
1531
/*[clinic input]
1532
delattr as builtin_delattr
1533
1534
obj: object
1535
name: object
1536
/
1537
1538
Deletes the named attribute from the given object.
1539
1540
delattr(x, 'y') is equivalent to ``del x.y``
1541
[clinic start generated code]*/
1542
1543
static PyObject *
1544
builtin_delattr_impl(PyObject *module, PyObject *obj, PyObject *name)
1545
/*[clinic end generated code: output=85134bc58dff79fa input=164865623abe7216]*/
1546
{
1547
if (PyObject_SetAttr(obj, name, (PyObject *)NULL) != 0)
1548
return NULL;
1549
Py_RETURN_NONE;
1550
}
1551
1552
1553
/*[clinic input]
1554
hash as builtin_hash
1555
1556
obj: object
1557
/
1558
1559
Return the hash value for the given object.
1560
1561
Two objects that compare equal must also have the same hash value, but the
1562
reverse is not necessarily true.
1563
[clinic start generated code]*/
1564
1565
static PyObject *
1566
builtin_hash(PyObject *module, PyObject *obj)
1567
/*[clinic end generated code: output=237668e9d7688db7 input=58c48be822bf9c54]*/
1568
{
1569
Py_hash_t x;
1570
1571
x = PyObject_Hash(obj);
1572
if (x == -1)
1573
return NULL;
1574
return PyLong_FromSsize_t(x);
1575
}
1576
1577
1578
/*[clinic input]
1579
hex as builtin_hex
1580
1581
number: object
1582
/
1583
1584
Return the hexadecimal representation of an integer.
1585
1586
>>> hex(12648430)
1587
'0xc0ffee'
1588
[clinic start generated code]*/
1589
1590
static PyObject *
1591
builtin_hex(PyObject *module, PyObject *number)
1592
/*[clinic end generated code: output=e46b612169099408 input=e645aff5fc7d540e]*/
1593
{
1594
return PyNumber_ToBase(number, 16);
1595
}
1596
1597
1598
/*[clinic input]
1599
iter as builtin_iter
1600
1601
object: object
1602
sentinel: object = NULL
1603
/
1604
1605
Get an iterator from an object.
1606
1607
In the first form, the argument must supply its own iterator, or be a sequence.
1608
In the second form, the callable is called until it returns the sentinel.
1609
[clinic start generated code]*/
1610
1611
static PyObject *
1612
builtin_iter_impl(PyObject *module, PyObject *object, PyObject *sentinel)
1613
/*[clinic end generated code: output=12cf64203c195a94 input=a5d64d9d81880ba6]*/
1614
{
1615
if (sentinel == NULL)
1616
return PyObject_GetIter(object);
1617
if (!PyCallable_Check(object)) {
1618
PyErr_SetString(PyExc_TypeError,
1619
"iter(object, sentinel): object must be callable");
1620
return NULL;
1621
}
1622
return PyCallIter_New(object, sentinel);
1623
}
1624
1625
1626
/*[clinic input]
1627
aiter as builtin_aiter
1628
1629
async_iterable: object
1630
/
1631
1632
Return an AsyncIterator for an AsyncIterable object.
1633
[clinic start generated code]*/
1634
1635
static PyObject *
1636
builtin_aiter(PyObject *module, PyObject *async_iterable)
1637
/*[clinic end generated code: output=1bae108d86f7960e input=473993d0cacc7d23]*/
1638
{
1639
return PyObject_GetAIter(async_iterable);
1640
}
1641
1642
PyObject *PyAnextAwaitable_New(PyObject *, PyObject *);
1643
1644
/*[clinic input]
1645
anext as builtin_anext
1646
1647
aiterator: object
1648
default: object = NULL
1649
/
1650
1651
async anext(aiterator[, default])
1652
1653
Return the next item from the async iterator. If default is given and the async
1654
iterator is exhausted, it is returned instead of raising StopAsyncIteration.
1655
[clinic start generated code]*/
1656
1657
static PyObject *
1658
builtin_anext_impl(PyObject *module, PyObject *aiterator,
1659
PyObject *default_value)
1660
/*[clinic end generated code: output=f02c060c163a81fa input=8f63f4f78590bb4c]*/
1661
{
1662
PyTypeObject *t;
1663
PyObject *awaitable;
1664
1665
t = Py_TYPE(aiterator);
1666
if (t->tp_as_async == NULL || t->tp_as_async->am_anext == NULL) {
1667
PyErr_Format(PyExc_TypeError,
1668
"'%.200s' object is not an async iterator",
1669
t->tp_name);
1670
return NULL;
1671
}
1672
1673
awaitable = (*t->tp_as_async->am_anext)(aiterator);
1674
if (default_value == NULL) {
1675
return awaitable;
1676
}
1677
1678
PyObject* new_awaitable = PyAnextAwaitable_New(
1679
awaitable, default_value);
1680
Py_DECREF(awaitable);
1681
return new_awaitable;
1682
}
1683
1684
1685
/*[clinic input]
1686
len as builtin_len
1687
1688
obj: object
1689
/
1690
1691
Return the number of items in a container.
1692
[clinic start generated code]*/
1693
1694
static PyObject *
1695
builtin_len(PyObject *module, PyObject *obj)
1696
/*[clinic end generated code: output=fa7a270d314dfb6c input=bc55598da9e9c9b5]*/
1697
{
1698
Py_ssize_t res;
1699
1700
res = PyObject_Size(obj);
1701
if (res < 0) {
1702
assert(PyErr_Occurred());
1703
return NULL;
1704
}
1705
return PyLong_FromSsize_t(res);
1706
}
1707
1708
1709
/*[clinic input]
1710
locals as builtin_locals
1711
1712
Return a dictionary containing the current scope's local variables.
1713
1714
NOTE: Whether or not updates to this dictionary will affect name lookups in
1715
the local scope and vice-versa is *implementation dependent* and not
1716
covered by any backwards compatibility guarantees.
1717
[clinic start generated code]*/
1718
1719
static PyObject *
1720
builtin_locals_impl(PyObject *module)
1721
/*[clinic end generated code: output=b46c94015ce11448 input=7874018d478d5c4b]*/
1722
{
1723
PyObject *d;
1724
1725
d = PyEval_GetLocals();
1726
return Py_XNewRef(d);
1727
}
1728
1729
1730
static PyObject *
1731
min_max(PyObject *args, PyObject *kwds, int op)
1732
{
1733
PyObject *v, *it, *item, *val, *maxitem, *maxval, *keyfunc=NULL;
1734
PyObject *emptytuple, *defaultval = NULL;
1735
static char *kwlist[] = {"key", "default", NULL};
1736
const char *name = op == Py_LT ? "min" : "max";
1737
const int positional = PyTuple_Size(args) > 1;
1738
int ret;
1739
1740
if (positional) {
1741
v = args;
1742
}
1743
else if (!PyArg_UnpackTuple(args, name, 1, 1, &v)) {
1744
if (PyExceptionClass_Check(PyExc_TypeError)) {
1745
PyErr_Format(PyExc_TypeError, "%s expected at least 1 argument, got 0", name);
1746
}
1747
return NULL;
1748
}
1749
1750
emptytuple = PyTuple_New(0);
1751
if (emptytuple == NULL)
1752
return NULL;
1753
ret = PyArg_ParseTupleAndKeywords(emptytuple, kwds,
1754
(op == Py_LT) ? "|$OO:min" : "|$OO:max",
1755
kwlist, &keyfunc, &defaultval);
1756
Py_DECREF(emptytuple);
1757
if (!ret)
1758
return NULL;
1759
1760
if (positional && defaultval != NULL) {
1761
PyErr_Format(PyExc_TypeError,
1762
"Cannot specify a default for %s() with multiple "
1763
"positional arguments", name);
1764
return NULL;
1765
}
1766
1767
it = PyObject_GetIter(v);
1768
if (it == NULL) {
1769
return NULL;
1770
}
1771
1772
if (keyfunc == Py_None) {
1773
keyfunc = NULL;
1774
}
1775
1776
maxitem = NULL; /* the result */
1777
maxval = NULL; /* the value associated with the result */
1778
while (( item = PyIter_Next(it) )) {
1779
/* get the value from the key function */
1780
if (keyfunc != NULL) {
1781
val = PyObject_CallOneArg(keyfunc, item);
1782
if (val == NULL)
1783
goto Fail_it_item;
1784
}
1785
/* no key function; the value is the item */
1786
else {
1787
val = Py_NewRef(item);
1788
}
1789
1790
/* maximum value and item are unset; set them */
1791
if (maxval == NULL) {
1792
maxitem = item;
1793
maxval = val;
1794
}
1795
/* maximum value and item are set; update them as necessary */
1796
else {
1797
int cmp = PyObject_RichCompareBool(val, maxval, op);
1798
if (cmp < 0)
1799
goto Fail_it_item_and_val;
1800
else if (cmp > 0) {
1801
Py_DECREF(maxval);
1802
Py_DECREF(maxitem);
1803
maxval = val;
1804
maxitem = item;
1805
}
1806
else {
1807
Py_DECREF(item);
1808
Py_DECREF(val);
1809
}
1810
}
1811
}
1812
if (PyErr_Occurred())
1813
goto Fail_it;
1814
if (maxval == NULL) {
1815
assert(maxitem == NULL);
1816
if (defaultval != NULL) {
1817
maxitem = Py_NewRef(defaultval);
1818
} else {
1819
PyErr_Format(PyExc_ValueError,
1820
"%s() iterable argument is empty", name);
1821
}
1822
}
1823
else
1824
Py_DECREF(maxval);
1825
Py_DECREF(it);
1826
return maxitem;
1827
1828
Fail_it_item_and_val:
1829
Py_DECREF(val);
1830
Fail_it_item:
1831
Py_DECREF(item);
1832
Fail_it:
1833
Py_XDECREF(maxval);
1834
Py_XDECREF(maxitem);
1835
Py_DECREF(it);
1836
return NULL;
1837
}
1838
1839
/* AC: cannot convert yet, waiting for *args support */
1840
static PyObject *
1841
builtin_min(PyObject *self, PyObject *args, PyObject *kwds)
1842
{
1843
return min_max(args, kwds, Py_LT);
1844
}
1845
1846
PyDoc_STRVAR(min_doc,
1847
"min(iterable, *[, default=obj, key=func]) -> value\n\
1848
min(arg1, arg2, *args, *[, key=func]) -> value\n\
1849
\n\
1850
With a single iterable argument, return its smallest item. The\n\
1851
default keyword-only argument specifies an object to return if\n\
1852
the provided iterable is empty.\n\
1853
With two or more arguments, return the smallest argument.");
1854
1855
1856
/* AC: cannot convert yet, waiting for *args support */
1857
static PyObject *
1858
builtin_max(PyObject *self, PyObject *args, PyObject *kwds)
1859
{
1860
return min_max(args, kwds, Py_GT);
1861
}
1862
1863
PyDoc_STRVAR(max_doc,
1864
"max(iterable, *[, default=obj, key=func]) -> value\n\
1865
max(arg1, arg2, *args, *[, key=func]) -> value\n\
1866
\n\
1867
With a single iterable argument, return its biggest item. The\n\
1868
default keyword-only argument specifies an object to return if\n\
1869
the provided iterable is empty.\n\
1870
With two or more arguments, return the largest argument.");
1871
1872
1873
/*[clinic input]
1874
oct as builtin_oct
1875
1876
number: object
1877
/
1878
1879
Return the octal representation of an integer.
1880
1881
>>> oct(342391)
1882
'0o1234567'
1883
[clinic start generated code]*/
1884
1885
static PyObject *
1886
builtin_oct(PyObject *module, PyObject *number)
1887
/*[clinic end generated code: output=40a34656b6875352 input=ad6b274af4016c72]*/
1888
{
1889
return PyNumber_ToBase(number, 8);
1890
}
1891
1892
1893
/*[clinic input]
1894
ord as builtin_ord
1895
1896
c: object
1897
/
1898
1899
Return the Unicode code point for a one-character string.
1900
[clinic start generated code]*/
1901
1902
static PyObject *
1903
builtin_ord(PyObject *module, PyObject *c)
1904
/*[clinic end generated code: output=4fa5e87a323bae71 input=3064e5d6203ad012]*/
1905
{
1906
long ord;
1907
Py_ssize_t size;
1908
1909
if (PyBytes_Check(c)) {
1910
size = PyBytes_GET_SIZE(c);
1911
if (size == 1) {
1912
ord = (long)((unsigned char)*PyBytes_AS_STRING(c));
1913
return PyLong_FromLong(ord);
1914
}
1915
}
1916
else if (PyUnicode_Check(c)) {
1917
size = PyUnicode_GET_LENGTH(c);
1918
if (size == 1) {
1919
ord = (long)PyUnicode_READ_CHAR(c, 0);
1920
return PyLong_FromLong(ord);
1921
}
1922
}
1923
else if (PyByteArray_Check(c)) {
1924
/* XXX Hopefully this is temporary */
1925
size = PyByteArray_GET_SIZE(c);
1926
if (size == 1) {
1927
ord = (long)((unsigned char)*PyByteArray_AS_STRING(c));
1928
return PyLong_FromLong(ord);
1929
}
1930
}
1931
else {
1932
PyErr_Format(PyExc_TypeError,
1933
"ord() expected string of length 1, but " \
1934
"%.200s found", Py_TYPE(c)->tp_name);
1935
return NULL;
1936
}
1937
1938
PyErr_Format(PyExc_TypeError,
1939
"ord() expected a character, "
1940
"but string of length %zd found",
1941
size);
1942
return NULL;
1943
}
1944
1945
1946
/*[clinic input]
1947
pow as builtin_pow
1948
1949
base: object
1950
exp: object
1951
mod: object = None
1952
1953
Equivalent to base**exp with 2 arguments or base**exp % mod with 3 arguments
1954
1955
Some types, such as ints, are able to use a more efficient algorithm when
1956
invoked using the three argument form.
1957
[clinic start generated code]*/
1958
1959
static PyObject *
1960
builtin_pow_impl(PyObject *module, PyObject *base, PyObject *exp,
1961
PyObject *mod)
1962
/*[clinic end generated code: output=3ca1538221bbf15f input=435dbd48a12efb23]*/
1963
{
1964
return PyNumber_Power(base, exp, mod);
1965
}
1966
1967
/*[clinic input]
1968
print as builtin_print
1969
1970
*args: object
1971
sep: object(c_default="Py_None") = ' '
1972
string inserted between values, default a space.
1973
end: object(c_default="Py_None") = '\n'
1974
string appended after the last value, default a newline.
1975
file: object = None
1976
a file-like object (stream); defaults to the current sys.stdout.
1977
flush: bool = False
1978
whether to forcibly flush the stream.
1979
1980
Prints the values to a stream, or to sys.stdout by default.
1981
1982
[clinic start generated code]*/
1983
1984
static PyObject *
1985
builtin_print_impl(PyObject *module, PyObject *args, PyObject *sep,
1986
PyObject *end, PyObject *file, int flush)
1987
/*[clinic end generated code: output=3cfc0940f5bc237b input=c143c575d24fe665]*/
1988
{
1989
int i, err;
1990
1991
if (file == Py_None) {
1992
PyThreadState *tstate = _PyThreadState_GET();
1993
file = _PySys_GetAttr(tstate, &_Py_ID(stdout));
1994
if (file == NULL) {
1995
PyErr_SetString(PyExc_RuntimeError, "lost sys.stdout");
1996
return NULL;
1997
}
1998
1999
/* sys.stdout may be None when FILE* stdout isn't connected */
2000
if (file == Py_None) {
2001
Py_RETURN_NONE;
2002
}
2003
}
2004
2005
if (sep == Py_None) {
2006
sep = NULL;
2007
}
2008
else if (sep && !PyUnicode_Check(sep)) {
2009
PyErr_Format(PyExc_TypeError,
2010
"sep must be None or a string, not %.200s",
2011
Py_TYPE(sep)->tp_name);
2012
return NULL;
2013
}
2014
if (end == Py_None) {
2015
end = NULL;
2016
}
2017
else if (end && !PyUnicode_Check(end)) {
2018
PyErr_Format(PyExc_TypeError,
2019
"end must be None or a string, not %.200s",
2020
Py_TYPE(end)->tp_name);
2021
return NULL;
2022
}
2023
2024
for (i = 0; i < PyTuple_GET_SIZE(args); i++) {
2025
if (i > 0) {
2026
if (sep == NULL) {
2027
err = PyFile_WriteString(" ", file);
2028
}
2029
else {
2030
err = PyFile_WriteObject(sep, file, Py_PRINT_RAW);
2031
}
2032
if (err) {
2033
return NULL;
2034
}
2035
}
2036
err = PyFile_WriteObject(PyTuple_GET_ITEM(args, i), file, Py_PRINT_RAW);
2037
if (err) {
2038
return NULL;
2039
}
2040
}
2041
2042
if (end == NULL) {
2043
err = PyFile_WriteString("\n", file);
2044
}
2045
else {
2046
err = PyFile_WriteObject(end, file, Py_PRINT_RAW);
2047
}
2048
if (err) {
2049
return NULL;
2050
}
2051
2052
if (flush) {
2053
PyObject *tmp = PyObject_CallMethodNoArgs(file, &_Py_ID(flush));
2054
if (tmp == NULL) {
2055
return NULL;
2056
}
2057
Py_DECREF(tmp);
2058
}
2059
2060
Py_RETURN_NONE;
2061
}
2062
2063
2064
/*[clinic input]
2065
input as builtin_input
2066
2067
prompt: object(c_default="NULL") = ""
2068
/
2069
2070
Read a string from standard input. The trailing newline is stripped.
2071
2072
The prompt string, if given, is printed to standard output without a
2073
trailing newline before reading input.
2074
2075
If the user hits EOF (*nix: Ctrl-D, Windows: Ctrl-Z+Return), raise EOFError.
2076
On *nix systems, readline is used if available.
2077
[clinic start generated code]*/
2078
2079
static PyObject *
2080
builtin_input_impl(PyObject *module, PyObject *prompt)
2081
/*[clinic end generated code: output=83db5a191e7a0d60 input=159c46d4ae40977e]*/
2082
{
2083
PyThreadState *tstate = _PyThreadState_GET();
2084
PyObject *fin = _PySys_GetAttr(
2085
tstate, &_Py_ID(stdin));
2086
PyObject *fout = _PySys_GetAttr(
2087
tstate, &_Py_ID(stdout));
2088
PyObject *ferr = _PySys_GetAttr(
2089
tstate, &_Py_ID(stderr));
2090
PyObject *tmp;
2091
long fd;
2092
int tty;
2093
2094
/* Check that stdin/out/err are intact */
2095
if (fin == NULL || fin == Py_None) {
2096
PyErr_SetString(PyExc_RuntimeError,
2097
"input(): lost sys.stdin");
2098
return NULL;
2099
}
2100
if (fout == NULL || fout == Py_None) {
2101
PyErr_SetString(PyExc_RuntimeError,
2102
"input(): lost sys.stdout");
2103
return NULL;
2104
}
2105
if (ferr == NULL || ferr == Py_None) {
2106
PyErr_SetString(PyExc_RuntimeError,
2107
"input(): lost sys.stderr");
2108
return NULL;
2109
}
2110
2111
if (PySys_Audit("builtins.input", "O", prompt ? prompt : Py_None) < 0) {
2112
return NULL;
2113
}
2114
2115
/* First of all, flush stderr */
2116
tmp = PyObject_CallMethodNoArgs(ferr, &_Py_ID(flush));
2117
if (tmp == NULL)
2118
PyErr_Clear();
2119
else
2120
Py_DECREF(tmp);
2121
2122
/* We should only use (GNU) readline if Python's sys.stdin and
2123
sys.stdout are the same as C's stdin and stdout, because we
2124
need to pass it those. */
2125
tmp = PyObject_CallMethodNoArgs(fin, &_Py_ID(fileno));
2126
if (tmp == NULL) {
2127
PyErr_Clear();
2128
tty = 0;
2129
}
2130
else {
2131
fd = PyLong_AsLong(tmp);
2132
Py_DECREF(tmp);
2133
if (fd < 0 && PyErr_Occurred())
2134
return NULL;
2135
tty = fd == fileno(stdin) && isatty(fd);
2136
}
2137
if (tty) {
2138
tmp = PyObject_CallMethodNoArgs(fout, &_Py_ID(fileno));
2139
if (tmp == NULL) {
2140
PyErr_Clear();
2141
tty = 0;
2142
}
2143
else {
2144
fd = PyLong_AsLong(tmp);
2145
Py_DECREF(tmp);
2146
if (fd < 0 && PyErr_Occurred())
2147
return NULL;
2148
tty = fd == fileno(stdout) && isatty(fd);
2149
}
2150
}
2151
2152
/* If we're interactive, use (GNU) readline */
2153
if (tty) {
2154
PyObject *po = NULL;
2155
const char *promptstr;
2156
char *s = NULL;
2157
PyObject *stdin_encoding = NULL, *stdin_errors = NULL;
2158
PyObject *stdout_encoding = NULL, *stdout_errors = NULL;
2159
const char *stdin_encoding_str, *stdin_errors_str;
2160
PyObject *result;
2161
size_t len;
2162
2163
/* stdin is a text stream, so it must have an encoding. */
2164
stdin_encoding = PyObject_GetAttr(fin, &_Py_ID(encoding));
2165
if (stdin_encoding == NULL) {
2166
tty = 0;
2167
goto _readline_errors;
2168
}
2169
stdin_errors = PyObject_GetAttr(fin, &_Py_ID(errors));
2170
if (stdin_errors == NULL) {
2171
tty = 0;
2172
goto _readline_errors;
2173
}
2174
if (!PyUnicode_Check(stdin_encoding) ||
2175
!PyUnicode_Check(stdin_errors))
2176
{
2177
tty = 0;
2178
goto _readline_errors;
2179
}
2180
stdin_encoding_str = PyUnicode_AsUTF8(stdin_encoding);
2181
if (stdin_encoding_str == NULL) {
2182
goto _readline_errors;
2183
}
2184
stdin_errors_str = PyUnicode_AsUTF8(stdin_errors);
2185
if (stdin_errors_str == NULL) {
2186
goto _readline_errors;
2187
}
2188
tmp = PyObject_CallMethodNoArgs(fout, &_Py_ID(flush));
2189
if (tmp == NULL)
2190
PyErr_Clear();
2191
else
2192
Py_DECREF(tmp);
2193
if (prompt != NULL) {
2194
/* We have a prompt, encode it as stdout would */
2195
const char *stdout_encoding_str, *stdout_errors_str;
2196
PyObject *stringpo;
2197
stdout_encoding = PyObject_GetAttr(fout, &_Py_ID(encoding));
2198
if (stdout_encoding == NULL) {
2199
tty = 0;
2200
goto _readline_errors;
2201
}
2202
stdout_errors = PyObject_GetAttr(fout, &_Py_ID(errors));
2203
if (stdout_errors == NULL) {
2204
tty = 0;
2205
goto _readline_errors;
2206
}
2207
if (!PyUnicode_Check(stdout_encoding) ||
2208
!PyUnicode_Check(stdout_errors))
2209
{
2210
tty = 0;
2211
goto _readline_errors;
2212
}
2213
stdout_encoding_str = PyUnicode_AsUTF8(stdout_encoding);
2214
if (stdout_encoding_str == NULL) {
2215
goto _readline_errors;
2216
}
2217
stdout_errors_str = PyUnicode_AsUTF8(stdout_errors);
2218
if (stdout_errors_str == NULL) {
2219
goto _readline_errors;
2220
}
2221
stringpo = PyObject_Str(prompt);
2222
if (stringpo == NULL)
2223
goto _readline_errors;
2224
po = PyUnicode_AsEncodedString(stringpo,
2225
stdout_encoding_str, stdout_errors_str);
2226
Py_CLEAR(stdout_encoding);
2227
Py_CLEAR(stdout_errors);
2228
Py_CLEAR(stringpo);
2229
if (po == NULL)
2230
goto _readline_errors;
2231
assert(PyBytes_Check(po));
2232
promptstr = PyBytes_AS_STRING(po);
2233
}
2234
else {
2235
po = NULL;
2236
promptstr = "";
2237
}
2238
s = PyOS_Readline(stdin, stdout, promptstr);
2239
if (s == NULL) {
2240
PyErr_CheckSignals();
2241
if (!PyErr_Occurred())
2242
PyErr_SetNone(PyExc_KeyboardInterrupt);
2243
goto _readline_errors;
2244
}
2245
2246
len = strlen(s);
2247
if (len == 0) {
2248
PyErr_SetNone(PyExc_EOFError);
2249
result = NULL;
2250
}
2251
else {
2252
if (len > PY_SSIZE_T_MAX) {
2253
PyErr_SetString(PyExc_OverflowError,
2254
"input: input too long");
2255
result = NULL;
2256
}
2257
else {
2258
len--; /* strip trailing '\n' */
2259
if (len != 0 && s[len-1] == '\r')
2260
len--; /* strip trailing '\r' */
2261
result = PyUnicode_Decode(s, len, stdin_encoding_str,
2262
stdin_errors_str);
2263
}
2264
}
2265
Py_DECREF(stdin_encoding);
2266
Py_DECREF(stdin_errors);
2267
Py_XDECREF(po);
2268
PyMem_Free(s);
2269
2270
if (result != NULL) {
2271
if (PySys_Audit("builtins.input/result", "O", result) < 0) {
2272
return NULL;
2273
}
2274
}
2275
2276
return result;
2277
2278
_readline_errors:
2279
Py_XDECREF(stdin_encoding);
2280
Py_XDECREF(stdout_encoding);
2281
Py_XDECREF(stdin_errors);
2282
Py_XDECREF(stdout_errors);
2283
Py_XDECREF(po);
2284
if (tty)
2285
return NULL;
2286
2287
PyErr_Clear();
2288
}
2289
2290
/* Fallback if we're not interactive */
2291
if (prompt != NULL) {
2292
if (PyFile_WriteObject(prompt, fout, Py_PRINT_RAW) != 0)
2293
return NULL;
2294
}
2295
tmp = PyObject_CallMethodNoArgs(fout, &_Py_ID(flush));
2296
if (tmp == NULL)
2297
PyErr_Clear();
2298
else
2299
Py_DECREF(tmp);
2300
return PyFile_GetLine(fin, -1);
2301
}
2302
2303
2304
/*[clinic input]
2305
repr as builtin_repr
2306
2307
obj: object
2308
/
2309
2310
Return the canonical string representation of the object.
2311
2312
For many object types, including most builtins, eval(repr(obj)) == obj.
2313
[clinic start generated code]*/
2314
2315
static PyObject *
2316
builtin_repr(PyObject *module, PyObject *obj)
2317
/*[clinic end generated code: output=7ed3778c44fd0194 input=1c9e6d66d3e3be04]*/
2318
{
2319
return PyObject_Repr(obj);
2320
}
2321
2322
2323
/*[clinic input]
2324
round as builtin_round
2325
2326
number: object
2327
ndigits: object = None
2328
2329
Round a number to a given precision in decimal digits.
2330
2331
The return value is an integer if ndigits is omitted or None. Otherwise
2332
the return value has the same type as the number. ndigits may be negative.
2333
[clinic start generated code]*/
2334
2335
static PyObject *
2336
builtin_round_impl(PyObject *module, PyObject *number, PyObject *ndigits)
2337
/*[clinic end generated code: output=ff0d9dd176c02ede input=275678471d7aca15]*/
2338
{
2339
PyObject *round, *result;
2340
2341
if (!_PyType_IsReady(Py_TYPE(number))) {
2342
if (PyType_Ready(Py_TYPE(number)) < 0)
2343
return NULL;
2344
}
2345
2346
round = _PyObject_LookupSpecial(number, &_Py_ID(__round__));
2347
if (round == NULL) {
2348
if (!PyErr_Occurred())
2349
PyErr_Format(PyExc_TypeError,
2350
"type %.100s doesn't define __round__ method",
2351
Py_TYPE(number)->tp_name);
2352
return NULL;
2353
}
2354
2355
if (ndigits == Py_None)
2356
result = _PyObject_CallNoArgs(round);
2357
else
2358
result = PyObject_CallOneArg(round, ndigits);
2359
Py_DECREF(round);
2360
return result;
2361
}
2362
2363
2364
/*AC: we need to keep the kwds dict intact to easily call into the
2365
* list.sort method, which isn't currently supported in AC. So we just use
2366
* the initially generated signature with a custom implementation.
2367
*/
2368
/* [disabled clinic input]
2369
sorted as builtin_sorted
2370
2371
iterable as seq: object
2372
key as keyfunc: object = None
2373
reverse: object = False
2374
2375
Return a new list containing all items from the iterable in ascending order.
2376
2377
A custom key function can be supplied to customize the sort order, and the
2378
reverse flag can be set to request the result in descending order.
2379
[end disabled clinic input]*/
2380
2381
PyDoc_STRVAR(builtin_sorted__doc__,
2382
"sorted($module, iterable, /, *, key=None, reverse=False)\n"
2383
"--\n"
2384
"\n"
2385
"Return a new list containing all items from the iterable in ascending order.\n"
2386
"\n"
2387
"A custom key function can be supplied to customize the sort order, and the\n"
2388
"reverse flag can be set to request the result in descending order.");
2389
2390
#define BUILTIN_SORTED_METHODDEF \
2391
{"sorted", _PyCFunction_CAST(builtin_sorted), METH_FASTCALL | METH_KEYWORDS, builtin_sorted__doc__},
2392
2393
static PyObject *
2394
builtin_sorted(PyObject *self, PyObject *const *args, Py_ssize_t nargs, PyObject *kwnames)
2395
{
2396
PyObject *newlist, *v, *seq, *callable;
2397
2398
/* Keyword arguments are passed through list.sort() which will check
2399
them. */
2400
if (!_PyArg_UnpackStack(args, nargs, "sorted", 1, 1, &seq))
2401
return NULL;
2402
2403
newlist = PySequence_List(seq);
2404
if (newlist == NULL)
2405
return NULL;
2406
2407
callable = PyObject_GetAttr(newlist, &_Py_ID(sort));
2408
if (callable == NULL) {
2409
Py_DECREF(newlist);
2410
return NULL;
2411
}
2412
2413
assert(nargs >= 1);
2414
v = PyObject_Vectorcall(callable, args + 1, nargs - 1, kwnames);
2415
Py_DECREF(callable);
2416
if (v == NULL) {
2417
Py_DECREF(newlist);
2418
return NULL;
2419
}
2420
Py_DECREF(v);
2421
return newlist;
2422
}
2423
2424
2425
/*[clinic input]
2426
vars as builtin_vars
2427
2428
object: object = NULL
2429
/
2430
2431
Show vars.
2432
2433
Without arguments, equivalent to locals().
2434
With an argument, equivalent to object.__dict__.
2435
[clinic start generated code]*/
2436
2437
static PyObject *
2438
builtin_vars_impl(PyObject *module, PyObject *object)
2439
/*[clinic end generated code: output=840a7f64007a3e0a input=80cbdef9182c4ba3]*/
2440
{
2441
PyObject *d;
2442
2443
if (object == NULL) {
2444
d = Py_XNewRef(PyEval_GetLocals());
2445
}
2446
else {
2447
if (_PyObject_LookupAttr(object, &_Py_ID(__dict__), &d) == 0) {
2448
PyErr_SetString(PyExc_TypeError,
2449
"vars() argument must have __dict__ attribute");
2450
}
2451
}
2452
return d;
2453
}
2454
2455
2456
/*[clinic input]
2457
sum as builtin_sum
2458
2459
iterable: object
2460
/
2461
start: object(c_default="NULL") = 0
2462
2463
Return the sum of a 'start' value (default: 0) plus an iterable of numbers
2464
2465
When the iterable is empty, return the start value.
2466
This function is intended specifically for use with numeric values and may
2467
reject non-numeric types.
2468
[clinic start generated code]*/
2469
2470
static PyObject *
2471
builtin_sum_impl(PyObject *module, PyObject *iterable, PyObject *start)
2472
/*[clinic end generated code: output=df758cec7d1d302f input=162b50765250d222]*/
2473
{
2474
PyObject *result = start;
2475
PyObject *temp, *item, *iter;
2476
2477
iter = PyObject_GetIter(iterable);
2478
if (iter == NULL)
2479
return NULL;
2480
2481
if (result == NULL) {
2482
result = PyLong_FromLong(0);
2483
if (result == NULL) {
2484
Py_DECREF(iter);
2485
return NULL;
2486
}
2487
} else {
2488
/* reject string values for 'start' parameter */
2489
if (PyUnicode_Check(result)) {
2490
PyErr_SetString(PyExc_TypeError,
2491
"sum() can't sum strings [use ''.join(seq) instead]");
2492
Py_DECREF(iter);
2493
return NULL;
2494
}
2495
if (PyBytes_Check(result)) {
2496
PyErr_SetString(PyExc_TypeError,
2497
"sum() can't sum bytes [use b''.join(seq) instead]");
2498
Py_DECREF(iter);
2499
return NULL;
2500
}
2501
if (PyByteArray_Check(result)) {
2502
PyErr_SetString(PyExc_TypeError,
2503
"sum() can't sum bytearray [use b''.join(seq) instead]");
2504
Py_DECREF(iter);
2505
return NULL;
2506
}
2507
Py_INCREF(result);
2508
}
2509
2510
#ifndef SLOW_SUM
2511
/* Fast addition by keeping temporary sums in C instead of new Python objects.
2512
Assumes all inputs are the same type. If the assumption fails, default
2513
to the more general routine.
2514
*/
2515
if (PyLong_CheckExact(result)) {
2516
int overflow;
2517
Py_ssize_t i_result = PyLong_AsLongAndOverflow(result, &overflow);
2518
/* If this already overflowed, don't even enter the loop. */
2519
if (overflow == 0) {
2520
Py_SETREF(result, NULL);
2521
}
2522
while(result == NULL) {
2523
item = PyIter_Next(iter);
2524
if (item == NULL) {
2525
Py_DECREF(iter);
2526
if (PyErr_Occurred())
2527
return NULL;
2528
return PyLong_FromSsize_t(i_result);
2529
}
2530
if (PyLong_CheckExact(item) || PyBool_Check(item)) {
2531
Py_ssize_t b;
2532
overflow = 0;
2533
/* Single digits are common, fast, and cannot overflow on unpacking. */
2534
if (_PyLong_IsCompact((PyLongObject *)item)) {
2535
b = _PyLong_CompactValue((PyLongObject *)item);
2536
}
2537
else {
2538
b = PyLong_AsLongAndOverflow(item, &overflow);
2539
}
2540
if (overflow == 0 &&
2541
(i_result >= 0 ? (b <= LONG_MAX - i_result)
2542
: (b >= LONG_MIN - i_result)))
2543
{
2544
i_result += b;
2545
Py_DECREF(item);
2546
continue;
2547
}
2548
}
2549
/* Either overflowed or is not an int. Restore real objects and process normally */
2550
result = PyLong_FromSsize_t(i_result);
2551
if (result == NULL) {
2552
Py_DECREF(item);
2553
Py_DECREF(iter);
2554
return NULL;
2555
}
2556
temp = PyNumber_Add(result, item);
2557
Py_DECREF(result);
2558
Py_DECREF(item);
2559
result = temp;
2560
if (result == NULL) {
2561
Py_DECREF(iter);
2562
return NULL;
2563
}
2564
}
2565
}
2566
2567
if (PyFloat_CheckExact(result)) {
2568
double f_result = PyFloat_AS_DOUBLE(result);
2569
double c = 0.0;
2570
Py_SETREF(result, NULL);
2571
while(result == NULL) {
2572
item = PyIter_Next(iter);
2573
if (item == NULL) {
2574
Py_DECREF(iter);
2575
if (PyErr_Occurred())
2576
return NULL;
2577
/* Avoid losing the sign on a negative result,
2578
and don't let adding the compensation convert
2579
an infinite or overflowed sum to a NaN. */
2580
if (c && Py_IS_FINITE(c)) {
2581
f_result += c;
2582
}
2583
return PyFloat_FromDouble(f_result);
2584
}
2585
if (PyFloat_CheckExact(item)) {
2586
// Improved Kahan–Babuška algorithm by Arnold Neumaier
2587
// https://www.mat.univie.ac.at/~neum/scan/01.pdf
2588
double x = PyFloat_AS_DOUBLE(item);
2589
double t = f_result + x;
2590
if (fabs(f_result) >= fabs(x)) {
2591
c += (f_result - t) + x;
2592
} else {
2593
c += (x - t) + f_result;
2594
}
2595
f_result = t;
2596
_Py_DECREF_SPECIALIZED(item, _PyFloat_ExactDealloc);
2597
continue;
2598
}
2599
if (PyLong_Check(item)) {
2600
long value;
2601
int overflow;
2602
value = PyLong_AsLongAndOverflow(item, &overflow);
2603
if (!overflow) {
2604
f_result += (double)value;
2605
Py_DECREF(item);
2606
continue;
2607
}
2608
}
2609
if (c && Py_IS_FINITE(c)) {
2610
f_result += c;
2611
}
2612
result = PyFloat_FromDouble(f_result);
2613
if (result == NULL) {
2614
Py_DECREF(item);
2615
Py_DECREF(iter);
2616
return NULL;
2617
}
2618
temp = PyNumber_Add(result, item);
2619
Py_DECREF(result);
2620
Py_DECREF(item);
2621
result = temp;
2622
if (result == NULL) {
2623
Py_DECREF(iter);
2624
return NULL;
2625
}
2626
}
2627
}
2628
#endif
2629
2630
for(;;) {
2631
item = PyIter_Next(iter);
2632
if (item == NULL) {
2633
/* error, or end-of-sequence */
2634
if (PyErr_Occurred()) {
2635
Py_SETREF(result, NULL);
2636
}
2637
break;
2638
}
2639
/* It's tempting to use PyNumber_InPlaceAdd instead of
2640
PyNumber_Add here, to avoid quadratic running time
2641
when doing 'sum(list_of_lists, [])'. However, this
2642
would produce a change in behaviour: a snippet like
2643
2644
empty = []
2645
sum([[x] for x in range(10)], empty)
2646
2647
would change the value of empty. In fact, using
2648
in-place addition rather that binary addition for
2649
any of the steps introduces subtle behavior changes:
2650
2651
https://bugs.python.org/issue18305 */
2652
temp = PyNumber_Add(result, item);
2653
Py_DECREF(result);
2654
Py_DECREF(item);
2655
result = temp;
2656
if (result == NULL)
2657
break;
2658
}
2659
Py_DECREF(iter);
2660
return result;
2661
}
2662
2663
2664
/*[clinic input]
2665
isinstance as builtin_isinstance
2666
2667
obj: object
2668
class_or_tuple: object
2669
/
2670
2671
Return whether an object is an instance of a class or of a subclass thereof.
2672
2673
A tuple, as in ``isinstance(x, (A, B, ...))``, may be given as the target to
2674
check against. This is equivalent to ``isinstance(x, A) or isinstance(x, B)
2675
or ...`` etc.
2676
[clinic start generated code]*/
2677
2678
static PyObject *
2679
builtin_isinstance_impl(PyObject *module, PyObject *obj,
2680
PyObject *class_or_tuple)
2681
/*[clinic end generated code: output=6faf01472c13b003 input=ffa743db1daf7549]*/
2682
{
2683
int retval;
2684
2685
retval = PyObject_IsInstance(obj, class_or_tuple);
2686
if (retval < 0)
2687
return NULL;
2688
return PyBool_FromLong(retval);
2689
}
2690
2691
2692
/*[clinic input]
2693
issubclass as builtin_issubclass
2694
2695
cls: object
2696
class_or_tuple: object
2697
/
2698
2699
Return whether 'cls' is derived from another class or is the same class.
2700
2701
A tuple, as in ``issubclass(x, (A, B, ...))``, may be given as the target to
2702
check against. This is equivalent to ``issubclass(x, A) or issubclass(x, B)
2703
or ...``.
2704
[clinic start generated code]*/
2705
2706
static PyObject *
2707
builtin_issubclass_impl(PyObject *module, PyObject *cls,
2708
PyObject *class_or_tuple)
2709
/*[clinic end generated code: output=358412410cd7a250 input=a24b9f3d58c370d6]*/
2710
{
2711
int retval;
2712
2713
retval = PyObject_IsSubclass(cls, class_or_tuple);
2714
if (retval < 0)
2715
return NULL;
2716
return PyBool_FromLong(retval);
2717
}
2718
2719
typedef struct {
2720
PyObject_HEAD
2721
Py_ssize_t tuplesize;
2722
PyObject *ittuple; /* tuple of iterators */
2723
PyObject *result;
2724
int strict;
2725
} zipobject;
2726
2727
static PyObject *
2728
zip_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
2729
{
2730
zipobject *lz;
2731
Py_ssize_t i;
2732
PyObject *ittuple; /* tuple of iterators */
2733
PyObject *result;
2734
Py_ssize_t tuplesize;
2735
int strict = 0;
2736
2737
if (kwds) {
2738
PyObject *empty = PyTuple_New(0);
2739
if (empty == NULL) {
2740
return NULL;
2741
}
2742
static char *kwlist[] = {"strict", NULL};
2743
int parsed = PyArg_ParseTupleAndKeywords(
2744
empty, kwds, "|$p:zip", kwlist, &strict);
2745
Py_DECREF(empty);
2746
if (!parsed) {
2747
return NULL;
2748
}
2749
}
2750
2751
/* args must be a tuple */
2752
assert(PyTuple_Check(args));
2753
tuplesize = PyTuple_GET_SIZE(args);
2754
2755
/* obtain iterators */
2756
ittuple = PyTuple_New(tuplesize);
2757
if (ittuple == NULL)
2758
return NULL;
2759
for (i=0; i < tuplesize; ++i) {
2760
PyObject *item = PyTuple_GET_ITEM(args, i);
2761
PyObject *it = PyObject_GetIter(item);
2762
if (it == NULL) {
2763
Py_DECREF(ittuple);
2764
return NULL;
2765
}
2766
PyTuple_SET_ITEM(ittuple, i, it);
2767
}
2768
2769
/* create a result holder */
2770
result = PyTuple_New(tuplesize);
2771
if (result == NULL) {
2772
Py_DECREF(ittuple);
2773
return NULL;
2774
}
2775
for (i=0 ; i < tuplesize ; i++) {
2776
PyTuple_SET_ITEM(result, i, Py_NewRef(Py_None));
2777
}
2778
2779
/* create zipobject structure */
2780
lz = (zipobject *)type->tp_alloc(type, 0);
2781
if (lz == NULL) {
2782
Py_DECREF(ittuple);
2783
Py_DECREF(result);
2784
return NULL;
2785
}
2786
lz->ittuple = ittuple;
2787
lz->tuplesize = tuplesize;
2788
lz->result = result;
2789
lz->strict = strict;
2790
2791
return (PyObject *)lz;
2792
}
2793
2794
static void
2795
zip_dealloc(zipobject *lz)
2796
{
2797
PyObject_GC_UnTrack(lz);
2798
Py_XDECREF(lz->ittuple);
2799
Py_XDECREF(lz->result);
2800
Py_TYPE(lz)->tp_free(lz);
2801
}
2802
2803
static int
2804
zip_traverse(zipobject *lz, visitproc visit, void *arg)
2805
{
2806
Py_VISIT(lz->ittuple);
2807
Py_VISIT(lz->result);
2808
return 0;
2809
}
2810
2811
static PyObject *
2812
zip_next(zipobject *lz)
2813
{
2814
Py_ssize_t i;
2815
Py_ssize_t tuplesize = lz->tuplesize;
2816
PyObject *result = lz->result;
2817
PyObject *it;
2818
PyObject *item;
2819
PyObject *olditem;
2820
2821
if (tuplesize == 0)
2822
return NULL;
2823
if (Py_REFCNT(result) == 1) {
2824
Py_INCREF(result);
2825
for (i=0 ; i < tuplesize ; i++) {
2826
it = PyTuple_GET_ITEM(lz->ittuple, i);
2827
item = (*Py_TYPE(it)->tp_iternext)(it);
2828
if (item == NULL) {
2829
Py_DECREF(result);
2830
if (lz->strict) {
2831
goto check;
2832
}
2833
return NULL;
2834
}
2835
olditem = PyTuple_GET_ITEM(result, i);
2836
PyTuple_SET_ITEM(result, i, item);
2837
Py_DECREF(olditem);
2838
}
2839
// bpo-42536: The GC may have untracked this result tuple. Since we're
2840
// recycling it, make sure it's tracked again:
2841
if (!_PyObject_GC_IS_TRACKED(result)) {
2842
_PyObject_GC_TRACK(result);
2843
}
2844
} else {
2845
result = PyTuple_New(tuplesize);
2846
if (result == NULL)
2847
return NULL;
2848
for (i=0 ; i < tuplesize ; i++) {
2849
it = PyTuple_GET_ITEM(lz->ittuple, i);
2850
item = (*Py_TYPE(it)->tp_iternext)(it);
2851
if (item == NULL) {
2852
Py_DECREF(result);
2853
if (lz->strict) {
2854
goto check;
2855
}
2856
return NULL;
2857
}
2858
PyTuple_SET_ITEM(result, i, item);
2859
}
2860
}
2861
return result;
2862
check:
2863
if (PyErr_Occurred()) {
2864
if (!PyErr_ExceptionMatches(PyExc_StopIteration)) {
2865
// next() on argument i raised an exception (not StopIteration)
2866
return NULL;
2867
}
2868
PyErr_Clear();
2869
}
2870
if (i) {
2871
// ValueError: zip() argument 2 is shorter than argument 1
2872
// ValueError: zip() argument 3 is shorter than arguments 1-2
2873
const char* plural = i == 1 ? " " : "s 1-";
2874
return PyErr_Format(PyExc_ValueError,
2875
"zip() argument %d is shorter than argument%s%d",
2876
i + 1, plural, i);
2877
}
2878
for (i = 1; i < tuplesize; i++) {
2879
it = PyTuple_GET_ITEM(lz->ittuple, i);
2880
item = (*Py_TYPE(it)->tp_iternext)(it);
2881
if (item) {
2882
Py_DECREF(item);
2883
const char* plural = i == 1 ? " " : "s 1-";
2884
return PyErr_Format(PyExc_ValueError,
2885
"zip() argument %d is longer than argument%s%d",
2886
i + 1, plural, i);
2887
}
2888
if (PyErr_Occurred()) {
2889
if (!PyErr_ExceptionMatches(PyExc_StopIteration)) {
2890
// next() on argument i raised an exception (not StopIteration)
2891
return NULL;
2892
}
2893
PyErr_Clear();
2894
}
2895
// Argument i is exhausted. So far so good...
2896
}
2897
// All arguments are exhausted. Success!
2898
return NULL;
2899
}
2900
2901
static PyObject *
2902
zip_reduce(zipobject *lz, PyObject *Py_UNUSED(ignored))
2903
{
2904
/* Just recreate the zip with the internal iterator tuple */
2905
if (lz->strict) {
2906
return PyTuple_Pack(3, Py_TYPE(lz), lz->ittuple, Py_True);
2907
}
2908
return PyTuple_Pack(2, Py_TYPE(lz), lz->ittuple);
2909
}
2910
2911
PyDoc_STRVAR(setstate_doc, "Set state information for unpickling.");
2912
2913
static PyObject *
2914
zip_setstate(zipobject *lz, PyObject *state)
2915
{
2916
int strict = PyObject_IsTrue(state);
2917
if (strict < 0) {
2918
return NULL;
2919
}
2920
lz->strict = strict;
2921
Py_RETURN_NONE;
2922
}
2923
2924
static PyMethodDef zip_methods[] = {
2925
{"__reduce__", _PyCFunction_CAST(zip_reduce), METH_NOARGS, reduce_doc},
2926
{"__setstate__", _PyCFunction_CAST(zip_setstate), METH_O, setstate_doc},
2927
{NULL} /* sentinel */
2928
};
2929
2930
PyDoc_STRVAR(zip_doc,
2931
"zip(*iterables, strict=False) --> Yield tuples until an input is exhausted.\n\
2932
\n\
2933
>>> list(zip('abcdefg', range(3), range(4)))\n\
2934
[('a', 0, 0), ('b', 1, 1), ('c', 2, 2)]\n\
2935
\n\
2936
The zip object yields n-length tuples, where n is the number of iterables\n\
2937
passed as positional arguments to zip(). The i-th element in every tuple\n\
2938
comes from the i-th iterable argument to zip(). This continues until the\n\
2939
shortest argument is exhausted.\n\
2940
\n\
2941
If strict is true and one of the arguments is exhausted before the others,\n\
2942
raise a ValueError.");
2943
2944
PyTypeObject PyZip_Type = {
2945
PyVarObject_HEAD_INIT(&PyType_Type, 0)
2946
"zip", /* tp_name */
2947
sizeof(zipobject), /* tp_basicsize */
2948
0, /* tp_itemsize */
2949
/* methods */
2950
(destructor)zip_dealloc, /* tp_dealloc */
2951
0, /* tp_vectorcall_offset */
2952
0, /* tp_getattr */
2953
0, /* tp_setattr */
2954
0, /* tp_as_async */
2955
0, /* tp_repr */
2956
0, /* tp_as_number */
2957
0, /* tp_as_sequence */
2958
0, /* tp_as_mapping */
2959
0, /* tp_hash */
2960
0, /* tp_call */
2961
0, /* tp_str */
2962
PyObject_GenericGetAttr, /* tp_getattro */
2963
0, /* tp_setattro */
2964
0, /* tp_as_buffer */
2965
Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
2966
Py_TPFLAGS_BASETYPE, /* tp_flags */
2967
zip_doc, /* tp_doc */
2968
(traverseproc)zip_traverse, /* tp_traverse */
2969
0, /* tp_clear */
2970
0, /* tp_richcompare */
2971
0, /* tp_weaklistoffset */
2972
PyObject_SelfIter, /* tp_iter */
2973
(iternextfunc)zip_next, /* tp_iternext */
2974
zip_methods, /* tp_methods */
2975
0, /* tp_members */
2976
0, /* tp_getset */
2977
0, /* tp_base */
2978
0, /* tp_dict */
2979
0, /* tp_descr_get */
2980
0, /* tp_descr_set */
2981
0, /* tp_dictoffset */
2982
0, /* tp_init */
2983
PyType_GenericAlloc, /* tp_alloc */
2984
zip_new, /* tp_new */
2985
PyObject_GC_Del, /* tp_free */
2986
};
2987
2988
2989
static PyMethodDef builtin_methods[] = {
2990
{"__build_class__", _PyCFunction_CAST(builtin___build_class__),
2991
METH_FASTCALL | METH_KEYWORDS, build_class_doc},
2992
BUILTIN___IMPORT___METHODDEF
2993
BUILTIN_ABS_METHODDEF
2994
BUILTIN_ALL_METHODDEF
2995
BUILTIN_ANY_METHODDEF
2996
BUILTIN_ASCII_METHODDEF
2997
BUILTIN_BIN_METHODDEF
2998
{"breakpoint", _PyCFunction_CAST(builtin_breakpoint), METH_FASTCALL | METH_KEYWORDS, breakpoint_doc},
2999
BUILTIN_CALLABLE_METHODDEF
3000
BUILTIN_CHR_METHODDEF
3001
BUILTIN_COMPILE_METHODDEF
3002
BUILTIN_DELATTR_METHODDEF
3003
BUILTIN_DIR_METHODDEF
3004
BUILTIN_DIVMOD_METHODDEF
3005
BUILTIN_EVAL_METHODDEF
3006
BUILTIN_EXEC_METHODDEF
3007
BUILTIN_FORMAT_METHODDEF
3008
BUILTIN_GETATTR_METHODDEF
3009
BUILTIN_GLOBALS_METHODDEF
3010
BUILTIN_HASATTR_METHODDEF
3011
BUILTIN_HASH_METHODDEF
3012
BUILTIN_HEX_METHODDEF
3013
BUILTIN_ID_METHODDEF
3014
BUILTIN_INPUT_METHODDEF
3015
BUILTIN_ISINSTANCE_METHODDEF
3016
BUILTIN_ISSUBCLASS_METHODDEF
3017
BUILTIN_ITER_METHODDEF
3018
BUILTIN_AITER_METHODDEF
3019
BUILTIN_LEN_METHODDEF
3020
BUILTIN_LOCALS_METHODDEF
3021
{"max", _PyCFunction_CAST(builtin_max), METH_VARARGS | METH_KEYWORDS, max_doc},
3022
{"min", _PyCFunction_CAST(builtin_min), METH_VARARGS | METH_KEYWORDS, min_doc},
3023
BUILTIN_NEXT_METHODDEF
3024
BUILTIN_ANEXT_METHODDEF
3025
BUILTIN_OCT_METHODDEF
3026
BUILTIN_ORD_METHODDEF
3027
BUILTIN_POW_METHODDEF
3028
BUILTIN_PRINT_METHODDEF
3029
BUILTIN_REPR_METHODDEF
3030
BUILTIN_ROUND_METHODDEF
3031
BUILTIN_SETATTR_METHODDEF
3032
BUILTIN_SORTED_METHODDEF
3033
BUILTIN_SUM_METHODDEF
3034
BUILTIN_VARS_METHODDEF
3035
{NULL, NULL},
3036
};
3037
3038
PyDoc_STRVAR(builtin_doc,
3039
"Built-in functions, types, exceptions, and other objects.\n\
3040
\n\
3041
This module provides direct access to all 'built-in'\n\
3042
identifiers of Python; for example, builtins.len is\n\
3043
the full name for the built-in function len().\n\
3044
\n\
3045
This module is not normally accessed explicitly by most\n\
3046
applications, but can be useful in modules that provide\n\
3047
objects with the same name as a built-in value, but in\n\
3048
which the built-in of that name is also needed.");
3049
3050
static struct PyModuleDef builtinsmodule = {
3051
PyModuleDef_HEAD_INIT,
3052
"builtins",
3053
builtin_doc,
3054
-1, /* multiple "initialization" just copies the module dict. */
3055
builtin_methods,
3056
NULL,
3057
NULL,
3058
NULL,
3059
NULL
3060
};
3061
3062
3063
PyObject *
3064
_PyBuiltin_Init(PyInterpreterState *interp)
3065
{
3066
PyObject *mod, *dict, *debug;
3067
3068
const PyConfig *config = _PyInterpreterState_GetConfig(interp);
3069
3070
mod = _PyModule_CreateInitialized(&builtinsmodule, PYTHON_API_VERSION);
3071
if (mod == NULL)
3072
return NULL;
3073
dict = PyModule_GetDict(mod);
3074
3075
#ifdef Py_TRACE_REFS
3076
/* "builtins" exposes a number of statically allocated objects
3077
* that, before this code was added in 2.3, never showed up in
3078
* the list of "all objects" maintained by Py_TRACE_REFS. As a
3079
* result, programs leaking references to None and False (etc)
3080
* couldn't be diagnosed by examining sys.getobjects(0).
3081
*/
3082
#define ADD_TO_ALL(OBJECT) _Py_AddToAllObjects((PyObject *)(OBJECT), 0)
3083
#else
3084
#define ADD_TO_ALL(OBJECT) (void)0
3085
#endif
3086
3087
#define SETBUILTIN(NAME, OBJECT) \
3088
if (PyDict_SetItemString(dict, NAME, (PyObject *)OBJECT) < 0) \
3089
return NULL; \
3090
ADD_TO_ALL(OBJECT)
3091
3092
SETBUILTIN("None", Py_None);
3093
SETBUILTIN("Ellipsis", Py_Ellipsis);
3094
SETBUILTIN("NotImplemented", Py_NotImplemented);
3095
SETBUILTIN("False", Py_False);
3096
SETBUILTIN("True", Py_True);
3097
SETBUILTIN("bool", &PyBool_Type);
3098
SETBUILTIN("memoryview", &PyMemoryView_Type);
3099
SETBUILTIN("bytearray", &PyByteArray_Type);
3100
SETBUILTIN("bytes", &PyBytes_Type);
3101
SETBUILTIN("classmethod", &PyClassMethod_Type);
3102
SETBUILTIN("complex", &PyComplex_Type);
3103
SETBUILTIN("dict", &PyDict_Type);
3104
SETBUILTIN("enumerate", &PyEnum_Type);
3105
SETBUILTIN("filter", &PyFilter_Type);
3106
SETBUILTIN("float", &PyFloat_Type);
3107
SETBUILTIN("frozenset", &PyFrozenSet_Type);
3108
SETBUILTIN("property", &PyProperty_Type);
3109
SETBUILTIN("int", &PyLong_Type);
3110
SETBUILTIN("list", &PyList_Type);
3111
SETBUILTIN("map", &PyMap_Type);
3112
SETBUILTIN("object", &PyBaseObject_Type);
3113
SETBUILTIN("range", &PyRange_Type);
3114
SETBUILTIN("reversed", &PyReversed_Type);
3115
SETBUILTIN("set", &PySet_Type);
3116
SETBUILTIN("slice", &PySlice_Type);
3117
SETBUILTIN("staticmethod", &PyStaticMethod_Type);
3118
SETBUILTIN("str", &PyUnicode_Type);
3119
SETBUILTIN("super", &PySuper_Type);
3120
SETBUILTIN("tuple", &PyTuple_Type);
3121
SETBUILTIN("type", &PyType_Type);
3122
SETBUILTIN("zip", &PyZip_Type);
3123
debug = PyBool_FromLong(config->optimization_level == 0);
3124
if (PyDict_SetItemString(dict, "__debug__", debug) < 0) {
3125
Py_DECREF(debug);
3126
return NULL;
3127
}
3128
Py_DECREF(debug);
3129
3130
return mod;
3131
#undef ADD_TO_ALL
3132
#undef SETBUILTIN
3133
}
3134
3135