blob: 52591c4a46f3dbbd41206814172d6ff0db34e39d [file] [log] [blame]
Guido van Rossum3f5da241990-12-20 15:06:42 +00001/* Built-in functions */
2
Guido van Rossum79f25d91997-04-29 20:08:16 +00003#include "Python.h"
Guido van Rossum6bf62da1997-04-11 20:37:35 +00004#include <ctype.h>
Victor Stinner5f2df882018-11-12 00:56:19 +01005#include "ast.h"
Victor Stinner3bb183d2018-11-22 18:38:38 +01006#undef Yield /* undefine macro conflicting with <winbase.h> */
Victor Stinnerc96d00e2020-06-22 18:02:49 +02007#include "pycore_object.h" // _Py_AddToAllObjects()
Victor Stinner384621c2020-06-22 17:27:35 +02008#include "pycore_pyerrors.h" // _PyErr_NoMemory()
9#include "pycore_pystate.h" // _PyThreadState_GET()
10#include "pycore_tuple.h" // _PyTuple_FromArray()
Mark Shannon0332e562021-02-01 10:42:03 +000011#include "pycore_ceval.h" // _PyEval_Vector()
Guido van Rossum6bf62da1997-04-11 20:37:35 +000012
Victor Stinnerbd303c12013-11-07 23:07:29 +010013_Py_IDENTIFIER(__builtins__);
14_Py_IDENTIFIER(__dict__);
15_Py_IDENTIFIER(__prepare__);
16_Py_IDENTIFIER(__round__);
Ivan Levkivskyi2b5fd1e2017-12-14 23:32:56 +010017_Py_IDENTIFIER(__mro_entries__);
Victor Stinnerbd303c12013-11-07 23:07:29 +010018_Py_IDENTIFIER(encoding);
19_Py_IDENTIFIER(errors);
Martin v. Löwisbd928fe2011-10-14 10:20:37 +020020_Py_IDENTIFIER(fileno);
21_Py_IDENTIFIER(flush);
Victor Stinnerbd303c12013-11-07 23:07:29 +010022_Py_IDENTIFIER(metaclass);
23_Py_IDENTIFIER(sort);
24_Py_IDENTIFIER(stdin);
25_Py_IDENTIFIER(stdout);
26_Py_IDENTIFIER(stderr);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +020027
Serhiy Storchaka1009bf12015-04-03 23:53:51 +030028#include "clinic/bltinmodule.c.h"
29
Ivan Levkivskyi2b5fd1e2017-12-14 23:32:56 +010030static PyObject*
Victor Stinner05d68a82018-01-18 11:15:25 +010031update_bases(PyObject *bases, PyObject *const *args, Py_ssize_t nargs)
Ivan Levkivskyi2b5fd1e2017-12-14 23:32:56 +010032{
Victor Stinner05d68a82018-01-18 11:15:25 +010033 Py_ssize_t i, j;
Ivan Levkivskyi2b5fd1e2017-12-14 23:32:56 +010034 PyObject *base, *meth, *new_base, *result, *new_bases = NULL;
Ivan Levkivskyi2b5fd1e2017-12-14 23:32:56 +010035 assert(PyTuple_Check(bases));
36
37 for (i = 0; i < nargs; i++) {
38 base = args[i];
39 if (PyType_Check(base)) {
40 if (new_bases) {
41 /* If we already have made a replacement, then we append every normal base,
42 otherwise just skip it. */
43 if (PyList_Append(new_bases, base) < 0) {
44 goto error;
45 }
46 }
47 continue;
48 }
Serhiy Storchakaf320be72018-01-25 10:49:40 +020049 if (_PyObject_LookupAttrId(base, &PyId___mro_entries__, &meth) < 0) {
50 goto error;
51 }
Ivan Levkivskyi2b5fd1e2017-12-14 23:32:56 +010052 if (!meth) {
Ivan Levkivskyi2b5fd1e2017-12-14 23:32:56 +010053 if (new_bases) {
54 if (PyList_Append(new_bases, base) < 0) {
55 goto error;
56 }
57 }
58 continue;
59 }
Petr Viktorinffd97532020-02-11 17:46:57 +010060 new_base = PyObject_CallOneArg(meth, bases);
Ivan Levkivskyi2b5fd1e2017-12-14 23:32:56 +010061 Py_DECREF(meth);
62 if (!new_base) {
63 goto error;
64 }
65 if (!PyTuple_Check(new_base)) {
66 PyErr_SetString(PyExc_TypeError,
67 "__mro_entries__ must return a tuple");
68 Py_DECREF(new_base);
69 goto error;
70 }
71 if (!new_bases) {
72 /* If this is a first successful replacement, create new_bases list and
73 copy previously encountered bases. */
74 if (!(new_bases = PyList_New(i))) {
75 goto error;
76 }
77 for (j = 0; j < i; j++) {
78 base = args[j];
79 PyList_SET_ITEM(new_bases, j, base);
80 Py_INCREF(base);
81 }
82 }
83 j = PyList_GET_SIZE(new_bases);
84 if (PyList_SetSlice(new_bases, j, j, new_base) < 0) {
85 goto error;
86 }
87 Py_DECREF(new_base);
88 }
89 if (!new_bases) {
90 return bases;
91 }
92 result = PyList_AsTuple(new_bases);
93 Py_DECREF(new_bases);
94 return result;
95
96error:
97 Py_XDECREF(new_bases);
98 return NULL;
99}
100
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000101/* AC: cannot convert yet, waiting for *args support */
Guido van Rossum79f25d91997-04-29 20:08:16 +0000102static PyObject *
Serhiy Storchakaa5552f02017-12-15 13:11:11 +0200103builtin___build_class__(PyObject *self, PyObject *const *args, Py_ssize_t nargs,
Victor Stinner773dc6d2017-01-16 23:46:26 +0100104 PyObject *kwnames)
Guido van Rossum52cc1d82007-03-18 15:41:51 +0000105{
Ivan Levkivskyi2b5fd1e2017-12-14 23:32:56 +0100106 PyObject *func, *name, *bases, *mkw, *meta, *winner, *prep, *ns, *orig_bases;
Nick Coghlan19d24672016-12-05 16:47:55 +1000107 PyObject *cls = NULL, *cell = NULL;
Victor Stinner0c39b1b2015-03-18 15:02:06 +0100108 int isclass = 0; /* initialize to prevent gcc warning */
Guido van Rossum52cc1d82007-03-18 15:41:51 +0000109
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000110 if (nargs < 2) {
111 PyErr_SetString(PyExc_TypeError,
112 "__build_class__: not enough arguments");
113 return NULL;
114 }
Victor Stinner773dc6d2017-01-16 23:46:26 +0100115 func = args[0]; /* Better be callable */
Benjamin Petersone8e14592013-05-16 14:37:25 -0500116 if (!PyFunction_Check(func)) {
117 PyErr_SetString(PyExc_TypeError,
Zachary Ware9b338722014-08-05 14:01:10 -0500118 "__build_class__: func must be a function");
Benjamin Petersone8e14592013-05-16 14:37:25 -0500119 return NULL;
120 }
Victor Stinner773dc6d2017-01-16 23:46:26 +0100121 name = args[1];
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000122 if (!PyUnicode_Check(name)) {
123 PyErr_SetString(PyExc_TypeError,
124 "__build_class__: name is not a string");
125 return NULL;
126 }
Sergey Fedoseevf1b9abe2019-02-26 02:37:26 +0500127 orig_bases = _PyTuple_FromArray(args + 2, nargs - 2);
Ivan Levkivskyi2b5fd1e2017-12-14 23:32:56 +0100128 if (orig_bases == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000129 return NULL;
Guido van Rossum52cc1d82007-03-18 15:41:51 +0000130
Ivan Levkivskyi2b5fd1e2017-12-14 23:32:56 +0100131 bases = update_bases(orig_bases, args + 2, nargs - 2);
132 if (bases == NULL) {
133 Py_DECREF(orig_bases);
134 return NULL;
135 }
136
Victor Stinner773dc6d2017-01-16 23:46:26 +0100137 if (kwnames == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000138 meta = NULL;
139 mkw = NULL;
140 }
141 else {
Victor Stinner773dc6d2017-01-16 23:46:26 +0100142 mkw = _PyStack_AsDict(args + nargs, kwnames);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000143 if (mkw == NULL) {
144 Py_DECREF(bases);
145 return NULL;
Guido van Rossum52cc1d82007-03-18 15:41:51 +0000146 }
Victor Stinner773dc6d2017-01-16 23:46:26 +0100147
Serhiy Storchakaa24107b2019-02-25 17:59:46 +0200148 meta = _PyDict_GetItemIdWithError(mkw, &PyId_metaclass);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000149 if (meta != NULL) {
150 Py_INCREF(meta);
Victor Stinnerae9f1612013-11-06 22:46:51 +0100151 if (_PyDict_DelItemId(mkw, &PyId_metaclass) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000152 Py_DECREF(meta);
153 Py_DECREF(mkw);
154 Py_DECREF(bases);
155 return NULL;
156 }
Nick Coghlande31b192011-10-23 22:04:16 +1000157 /* metaclass is explicitly given, check if it's indeed a class */
158 isclass = PyType_Check(meta);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000159 }
Serhiy Storchakaa24107b2019-02-25 17:59:46 +0200160 else if (PyErr_Occurred()) {
161 Py_DECREF(mkw);
162 Py_DECREF(bases);
163 return NULL;
164 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000165 }
166 if (meta == NULL) {
Nick Coghlande31b192011-10-23 22:04:16 +1000167 /* if there are no bases, use type: */
168 if (PyTuple_GET_SIZE(bases) == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000169 meta = (PyObject *) (&PyType_Type);
Nick Coghlande31b192011-10-23 22:04:16 +1000170 }
171 /* else get the type of the first base */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000172 else {
173 PyObject *base0 = PyTuple_GET_ITEM(bases, 0);
Victor Stinnera102ed72020-02-07 02:24:48 +0100174 meta = (PyObject *)Py_TYPE(base0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000175 }
176 Py_INCREF(meta);
Nick Coghlande31b192011-10-23 22:04:16 +1000177 isclass = 1; /* meta is really a class */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000178 }
Nick Coghlan9715d262011-10-23 22:36:42 +1000179
Nick Coghlande31b192011-10-23 22:04:16 +1000180 if (isclass) {
181 /* meta is really a class, so check for a more derived
182 metaclass, or possible metaclass conflicts: */
183 winner = (PyObject *)_PyType_CalculateMetaclass((PyTypeObject *)meta,
184 bases);
185 if (winner == NULL) {
186 Py_DECREF(meta);
187 Py_XDECREF(mkw);
188 Py_DECREF(bases);
189 return NULL;
190 }
191 if (winner != meta) {
192 Py_DECREF(meta);
193 meta = winner;
194 Py_INCREF(meta);
195 }
196 }
197 /* else: meta is not a class, so we cannot do the metaclass
198 calculation, so we will use the explicitly given object as it is */
Serhiy Storchakaf320be72018-01-25 10:49:40 +0200199 if (_PyObject_LookupAttrId(meta, &PyId___prepare__, &prep) < 0) {
200 ns = NULL;
201 }
202 else if (prep == NULL) {
203 ns = PyDict_New();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000204 }
205 else {
Victor Stinner463b86a2016-08-22 23:33:13 +0200206 PyObject *pargs[2] = {name, bases};
Petr Viktorinffd97532020-02-11 17:46:57 +0100207 ns = PyObject_VectorcallDict(prep, pargs, 2, mkw);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000208 Py_DECREF(prep);
209 }
210 if (ns == NULL) {
211 Py_DECREF(meta);
212 Py_XDECREF(mkw);
213 Py_DECREF(bases);
214 return NULL;
215 }
Oren Milman5837d042017-09-27 17:04:37 +0300216 if (!PyMapping_Check(ns)) {
217 PyErr_Format(PyExc_TypeError,
218 "%.200s.__prepare__() must return a mapping, not %.200s",
219 isclass ? ((PyTypeObject *)meta)->tp_name : "<metaclass>",
220 Py_TYPE(ns)->tp_name);
221 goto error;
222 }
Mark Shannon0332e562021-02-01 10:42:03 +0000223 PyFrameConstructor *f = PyFunction_AS_FRAME_CONSTRUCTOR(func);
224 PyThreadState *tstate = PyThreadState_GET();
225 cell = _PyEval_Vector(tstate, f, ns, NULL, 0, NULL);
Nick Coghlan19d24672016-12-05 16:47:55 +1000226 if (cell != NULL) {
Ivan Levkivskyi2b5fd1e2017-12-14 23:32:56 +0100227 if (bases != orig_bases) {
228 if (PyMapping_SetItemString(ns, "__orig_bases__", orig_bases) < 0) {
229 goto error;
230 }
231 }
Victor Stinnerd1c2a8e2016-08-23 01:34:35 +0200232 PyObject *margs[3] = {name, bases, ns};
Petr Viktorinffd97532020-02-11 17:46:57 +0100233 cls = PyObject_VectorcallDict(meta, margs, 3, mkw);
Nick Coghlan19d24672016-12-05 16:47:55 +1000234 if (cls != NULL && PyType_Check(cls) && PyCell_Check(cell)) {
235 PyObject *cell_cls = PyCell_GET(cell);
236 if (cell_cls != cls) {
Nick Coghlan19d24672016-12-05 16:47:55 +1000237 if (cell_cls == NULL) {
238 const char *msg =
239 "__class__ not set defining %.200R as %.200R. "
240 "Was __classcell__ propagated to type.__new__?";
Serhiy Storchakaf5e7b192018-05-20 08:48:12 +0300241 PyErr_Format(PyExc_RuntimeError, msg, name, cls);
Nick Coghlan19d24672016-12-05 16:47:55 +1000242 } else {
243 const char *msg =
244 "__class__ set to %.200R defining %.200R as %.200R";
245 PyErr_Format(PyExc_TypeError, msg, cell_cls, name, cls);
Nick Coghlan19d24672016-12-05 16:47:55 +1000246 }
Serhiy Storchakaf5e7b192018-05-20 08:48:12 +0300247 Py_DECREF(cls);
248 cls = NULL;
249 goto error;
Nick Coghlan19d24672016-12-05 16:47:55 +1000250 }
251 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000252 }
Nick Coghlan19d24672016-12-05 16:47:55 +1000253error:
254 Py_XDECREF(cell);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000255 Py_DECREF(ns);
256 Py_DECREF(meta);
257 Py_XDECREF(mkw);
258 Py_DECREF(bases);
Ivan Levkivskyi2b5fd1e2017-12-14 23:32:56 +0100259 if (bases != orig_bases) {
260 Py_DECREF(orig_bases);
261 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000262 return cls;
Guido van Rossum52cc1d82007-03-18 15:41:51 +0000263}
264
265PyDoc_STRVAR(build_class_doc,
Pablo Galindoe3babbd2019-10-13 16:35:41 +0100266"__build_class__(func, name, /, *bases, [metaclass], **kwds) -> class\n\
Guido van Rossum52cc1d82007-03-18 15:41:51 +0000267\n\
268Internal helper function used by the class statement.");
269
270static PyObject *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000271builtin___import__(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000272{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000273 static char *kwlist[] = {"name", "globals", "locals", "fromlist",
274 "level", 0};
Victor Stinnerfe93faf2011-03-14 15:54:52 -0400275 PyObject *name, *globals = NULL, *locals = NULL, *fromlist = NULL;
Brett Cannonfd074152012-04-14 14:10:13 -0400276 int level = 0;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000277
Victor Stinnerfe93faf2011-03-14 15:54:52 -0400278 if (!PyArg_ParseTupleAndKeywords(args, kwds, "U|OOOi:__import__",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000279 kwlist, &name, &globals, &locals, &fromlist, &level))
280 return NULL;
Victor Stinnerfe93faf2011-03-14 15:54:52 -0400281 return PyImport_ImportModuleLevelObject(name, globals, locals,
282 fromlist, level);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000283}
284
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000285PyDoc_STRVAR(import_doc,
Brett Cannoncb4996a2012-08-06 16:34:44 -0400286"__import__(name, globals=None, locals=None, fromlist=(), level=0) -> module\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000287\n\
Brett Cannon5305a992010-09-27 21:08:38 +0000288Import a module. Because this function is meant for use by the Python\n\
oldk461d2252018-02-02 12:20:00 +0800289interpreter and not for general use, it is better to use\n\
Brett Cannon5305a992010-09-27 21:08:38 +0000290importlib.import_module() to programmatically import a module.\n\
291\n\
292The globals argument is only used to determine the context;\n\
293they are not modified. The locals argument is unused. The fromlist\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000294should be a list of names to emulate ``from name import ...'', or an\n\
295empty list to emulate ``import name''.\n\
296When importing a module from a package, note that __import__('A.B', ...)\n\
297returns package A when fromlist is empty, but its submodule B when\n\
oldk461d2252018-02-02 12:20:00 +0800298fromlist is not empty. The level argument is used to determine whether to\n\
299perform absolute or relative imports: 0 is absolute, while a positive number\n\
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000300is the number of parent directories to search relative to the current module.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000301
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000302
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000303/*[clinic input]
304abs as builtin_abs
305
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300306 x: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000307 /
308
309Return the absolute value of the argument.
310[clinic start generated code]*/
311
Guido van Rossum79f25d91997-04-29 20:08:16 +0000312static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300313builtin_abs(PyObject *module, PyObject *x)
314/*[clinic end generated code: output=b1b433b9e51356f5 input=bed4ca14e29c20d1]*/
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000315{
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000316 return PyNumber_Absolute(x);
Guido van Rossum3f5da241990-12-20 15:06:42 +0000317}
318
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000319/*[clinic input]
320all as builtin_all
321
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300322 iterable: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000323 /
324
325Return True if bool(x) is True for all values x in the iterable.
326
327If the iterable is empty, return True.
328[clinic start generated code]*/
329
Raymond Hettinger96229b12005-03-11 06:49:40 +0000330static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300331builtin_all(PyObject *module, PyObject *iterable)
332/*[clinic end generated code: output=ca2a7127276f79b3 input=1a7c5d1bc3438a21]*/
Raymond Hettinger96229b12005-03-11 06:49:40 +0000333{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000334 PyObject *it, *item;
335 PyObject *(*iternext)(PyObject *);
336 int cmp;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000337
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000338 it = PyObject_GetIter(iterable);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000339 if (it == NULL)
340 return NULL;
341 iternext = *Py_TYPE(it)->tp_iternext;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000342
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000343 for (;;) {
344 item = iternext(it);
345 if (item == NULL)
346 break;
347 cmp = PyObject_IsTrue(item);
348 Py_DECREF(item);
349 if (cmp < 0) {
350 Py_DECREF(it);
351 return NULL;
352 }
353 if (cmp == 0) {
354 Py_DECREF(it);
355 Py_RETURN_FALSE;
356 }
357 }
358 Py_DECREF(it);
359 if (PyErr_Occurred()) {
360 if (PyErr_ExceptionMatches(PyExc_StopIteration))
361 PyErr_Clear();
362 else
363 return NULL;
364 }
365 Py_RETURN_TRUE;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000366}
367
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000368/*[clinic input]
369any as builtin_any
370
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300371 iterable: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000372 /
373
374Return True if bool(x) is True for any x in the iterable.
375
376If the iterable is empty, return False.
377[clinic start generated code]*/
378
Raymond Hettinger96229b12005-03-11 06:49:40 +0000379static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300380builtin_any(PyObject *module, PyObject *iterable)
381/*[clinic end generated code: output=fa65684748caa60e input=41d7451c23384f24]*/
Raymond Hettinger96229b12005-03-11 06:49:40 +0000382{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000383 PyObject *it, *item;
384 PyObject *(*iternext)(PyObject *);
385 int cmp;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000386
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000387 it = PyObject_GetIter(iterable);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000388 if (it == NULL)
389 return NULL;
390 iternext = *Py_TYPE(it)->tp_iternext;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000391
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000392 for (;;) {
393 item = iternext(it);
394 if (item == NULL)
395 break;
396 cmp = PyObject_IsTrue(item);
397 Py_DECREF(item);
398 if (cmp < 0) {
399 Py_DECREF(it);
400 return NULL;
401 }
Raymond Hettinger5098b582015-10-09 00:42:47 -0400402 if (cmp > 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000403 Py_DECREF(it);
404 Py_RETURN_TRUE;
405 }
406 }
407 Py_DECREF(it);
408 if (PyErr_Occurred()) {
409 if (PyErr_ExceptionMatches(PyExc_StopIteration))
410 PyErr_Clear();
411 else
412 return NULL;
413 }
414 Py_RETURN_FALSE;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000415}
416
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000417/*[clinic input]
418ascii as builtin_ascii
419
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300420 obj: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000421 /
422
423Return an ASCII-only representation of an object.
424
425As repr(), return a string containing a printable representation of an
426object, but escape the non-ASCII characters in the string returned by
427repr() using \\x, \\u or \\U escapes. This generates a string similar
428to that returned by repr() in Python 2.
429[clinic start generated code]*/
430
Georg Brandl559e5d72008-06-11 18:37:52 +0000431static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300432builtin_ascii(PyObject *module, PyObject *obj)
433/*[clinic end generated code: output=6d37b3f0984c7eb9 input=4c62732e1b3a3cc9]*/
Georg Brandl559e5d72008-06-11 18:37:52 +0000434{
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000435 return PyObject_ASCII(obj);
Georg Brandl559e5d72008-06-11 18:37:52 +0000436}
437
Georg Brandl559e5d72008-06-11 18:37:52 +0000438
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000439/*[clinic input]
440bin as builtin_bin
441
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300442 number: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000443 /
444
445Return the binary representation of an integer.
446
447 >>> bin(2796202)
448 '0b1010101010101010101010'
449[clinic start generated code]*/
450
Guido van Rossum79f25d91997-04-29 20:08:16 +0000451static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300452builtin_bin(PyObject *module, PyObject *number)
453/*[clinic end generated code: output=b6fc4ad5e649f4f7 input=53f8a0264bacaf90]*/
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000454{
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000455 return PyNumber_ToBase(number, 2);
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000456}
457
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000458
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000459/*[clinic input]
460callable as builtin_callable
461
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300462 obj: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000463 /
464
465Return whether the object is callable (i.e., some kind of function).
466
467Note that classes are callable, as are instances of classes with a
468__call__() method.
469[clinic start generated code]*/
470
Antoine Pitroue71362d2010-11-27 22:00:11 +0000471static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300472builtin_callable(PyObject *module, PyObject *obj)
473/*[clinic end generated code: output=2b095d59d934cb7e input=1423bab99cc41f58]*/
Antoine Pitroue71362d2010-11-27 22:00:11 +0000474{
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000475 return PyBool_FromLong((long)PyCallable_Check(obj));
Antoine Pitroue71362d2010-11-27 22:00:11 +0000476}
477
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400478static PyObject *
Serhiy Storchakaa5552f02017-12-15 13:11:11 +0200479builtin_breakpoint(PyObject *self, PyObject *const *args, Py_ssize_t nargs, PyObject *keywords)
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400480{
481 PyObject *hook = PySys_GetObject("breakpointhook");
482
483 if (hook == NULL) {
484 PyErr_SetString(PyExc_RuntimeError, "lost sys.breakpointhook");
485 return NULL;
486 }
Steve Dower60419a72019-06-24 08:42:54 -0700487
488 if (PySys_Audit("builtins.breakpoint", "O", hook) < 0) {
489 return NULL;
490 }
491
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400492 Py_INCREF(hook);
Petr Viktorinffd97532020-02-11 17:46:57 +0100493 PyObject *retval = PyObject_Vectorcall(hook, args, nargs, keywords);
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400494 Py_DECREF(hook);
495 return retval;
496}
497
498PyDoc_STRVAR(breakpoint_doc,
499"breakpoint(*args, **kws)\n\
500\n\
501Call sys.breakpointhook(*args, **kws). sys.breakpointhook() must accept\n\
502whatever arguments are passed.\n\
503\n\
504By default, this drops you into the pdb debugger.");
Antoine Pitroue71362d2010-11-27 22:00:11 +0000505
Raymond Hettinger17301e92008-03-13 00:19:26 +0000506typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000507 PyObject_HEAD
508 PyObject *func;
509 PyObject *it;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000510} filterobject;
511
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000512static PyObject *
Raymond Hettinger17301e92008-03-13 00:19:26 +0000513filter_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
Guido van Rossum12d12c51993-10-26 17:58:25 +0000514{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000515 PyObject *func, *seq;
516 PyObject *it;
517 filterobject *lz;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000518
Serhiy Storchaka6cca5c82017-06-08 14:41:19 +0300519 if (type == &PyFilter_Type && !_PyArg_NoKeywords("filter", kwds))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000520 return NULL;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000521
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000522 if (!PyArg_UnpackTuple(args, "filter", 2, 2, &func, &seq))
523 return NULL;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000524
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000525 /* Get iterator. */
526 it = PyObject_GetIter(seq);
527 if (it == NULL)
528 return NULL;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000529
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000530 /* create filterobject structure */
531 lz = (filterobject *)type->tp_alloc(type, 0);
532 if (lz == NULL) {
533 Py_DECREF(it);
534 return NULL;
535 }
Dong-hee Na9a9c11a2021-03-11 01:39:52 +0900536
537 lz->func = Py_NewRef(func);
538 lz->it = it;
539
540 return (PyObject *)lz;
541}
542
543static PyObject *
544filter_vectorcall(PyObject *type, PyObject * const*args,
545 size_t nargsf, PyObject *kwnames)
546{
547 PyTypeObject *tp = (PyTypeObject *)type;
548 if (tp == &PyFilter_Type && !_PyArg_NoKwnames("filter", kwnames)) {
549 return NULL;
550 }
551
552 Py_ssize_t nargs = PyVectorcall_NARGS(nargsf);
553 if (!_PyArg_CheckPositional("filter", nargs, 2, 2)) {
554 return NULL;
555 }
556
557 PyObject *it = PyObject_GetIter(args[1]);
558 if (it == NULL) {
559 return NULL;
560 }
561
562 filterobject *lz = (filterobject *)tp->tp_alloc(tp, 0);
563
564 if (lz == NULL) {
565 Py_DECREF(it);
566 return NULL;
567 }
568
569 lz->func = Py_NewRef(args[0]);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000570 lz->it = it;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000571
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000572 return (PyObject *)lz;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000573}
574
575static void
576filter_dealloc(filterobject *lz)
577{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000578 PyObject_GC_UnTrack(lz);
579 Py_XDECREF(lz->func);
580 Py_XDECREF(lz->it);
581 Py_TYPE(lz)->tp_free(lz);
Raymond Hettinger17301e92008-03-13 00:19:26 +0000582}
583
584static int
585filter_traverse(filterobject *lz, visitproc visit, void *arg)
586{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000587 Py_VISIT(lz->it);
588 Py_VISIT(lz->func);
589 return 0;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000590}
591
592static PyObject *
593filter_next(filterobject *lz)
594{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000595 PyObject *item;
596 PyObject *it = lz->it;
597 long ok;
598 PyObject *(*iternext)(PyObject *);
Raymond Hettingerbd5f0e82015-10-09 01:34:08 -0400599 int checktrue = lz->func == Py_None || lz->func == (PyObject *)&PyBool_Type;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000600
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000601 iternext = *Py_TYPE(it)->tp_iternext;
602 for (;;) {
603 item = iternext(it);
604 if (item == NULL)
605 return NULL;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000606
Raymond Hettingerbd5f0e82015-10-09 01:34:08 -0400607 if (checktrue) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000608 ok = PyObject_IsTrue(item);
609 } else {
610 PyObject *good;
Petr Viktorinffd97532020-02-11 17:46:57 +0100611 good = PyObject_CallOneArg(lz->func, item);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000612 if (good == NULL) {
613 Py_DECREF(item);
614 return NULL;
615 }
616 ok = PyObject_IsTrue(good);
617 Py_DECREF(good);
618 }
Antoine Pitrou6f430e42012-08-15 23:18:25 +0200619 if (ok > 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000620 return item;
621 Py_DECREF(item);
Antoine Pitrou6f430e42012-08-15 23:18:25 +0200622 if (ok < 0)
623 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000624 }
Guido van Rossum12d12c51993-10-26 17:58:25 +0000625}
626
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +0000627static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +0530628filter_reduce(filterobject *lz, PyObject *Py_UNUSED(ignored))
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +0000629{
630 return Py_BuildValue("O(OO)", Py_TYPE(lz), lz->func, lz->it);
631}
632
633PyDoc_STRVAR(reduce_doc, "Return state information for pickling.");
634
635static PyMethodDef filter_methods[] = {
636 {"__reduce__", (PyCFunction)filter_reduce, METH_NOARGS, reduce_doc},
637 {NULL, NULL} /* sentinel */
638};
639
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000640PyDoc_STRVAR(filter_doc,
Georg Brandld11ae5d2008-05-16 13:27:32 +0000641"filter(function or None, iterable) --> filter object\n\
Guido van Rossumc1f779c2007-07-03 08:25:58 +0000642\n\
Georg Brandld11ae5d2008-05-16 13:27:32 +0000643Return an iterator yielding those items of iterable for which function(item)\n\
Raymond Hettinger17301e92008-03-13 00:19:26 +0000644is true. If function is None, return the items that are true.");
645
646PyTypeObject PyFilter_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000647 PyVarObject_HEAD_INIT(&PyType_Type, 0)
648 "filter", /* tp_name */
649 sizeof(filterobject), /* tp_basicsize */
650 0, /* tp_itemsize */
651 /* methods */
652 (destructor)filter_dealloc, /* tp_dealloc */
Jeroen Demeyer530f5062019-05-31 04:13:39 +0200653 0, /* tp_vectorcall_offset */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000654 0, /* tp_getattr */
655 0, /* tp_setattr */
Jeroen Demeyer530f5062019-05-31 04:13:39 +0200656 0, /* tp_as_async */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000657 0, /* tp_repr */
658 0, /* tp_as_number */
659 0, /* tp_as_sequence */
660 0, /* tp_as_mapping */
661 0, /* tp_hash */
662 0, /* tp_call */
663 0, /* tp_str */
664 PyObject_GenericGetAttr, /* tp_getattro */
665 0, /* tp_setattro */
666 0, /* tp_as_buffer */
667 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
668 Py_TPFLAGS_BASETYPE, /* tp_flags */
669 filter_doc, /* tp_doc */
670 (traverseproc)filter_traverse, /* tp_traverse */
671 0, /* tp_clear */
672 0, /* tp_richcompare */
673 0, /* tp_weaklistoffset */
674 PyObject_SelfIter, /* tp_iter */
675 (iternextfunc)filter_next, /* tp_iternext */
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +0000676 filter_methods, /* tp_methods */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000677 0, /* tp_members */
678 0, /* tp_getset */
679 0, /* tp_base */
680 0, /* tp_dict */
681 0, /* tp_descr_get */
682 0, /* tp_descr_set */
683 0, /* tp_dictoffset */
684 0, /* tp_init */
685 PyType_GenericAlloc, /* tp_alloc */
686 filter_new, /* tp_new */
687 PyObject_GC_Del, /* tp_free */
Dong-hee Na9a9c11a2021-03-11 01:39:52 +0900688 .tp_vectorcall = (vectorcallfunc)filter_vectorcall
Raymond Hettinger17301e92008-03-13 00:19:26 +0000689};
690
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000691
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000692/*[clinic input]
693format as builtin_format
694
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300695 value: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000696 format_spec: unicode(c_default="NULL") = ''
697 /
698
699Return value.__format__(format_spec)
700
Amit Kumar2e6bb442017-05-29 06:32:26 +0530701format_spec defaults to the empty string.
702See the Format Specification Mini-Language section of help('FORMATTING') for
703details.
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000704[clinic start generated code]*/
705
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000706static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300707builtin_format_impl(PyObject *module, PyObject *value, PyObject *format_spec)
Amit Kumar2e6bb442017-05-29 06:32:26 +0530708/*[clinic end generated code: output=2f40bdfa4954b077 input=88339c93ea522b33]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000709{
Eric Smith8fd3eba2008-02-17 19:48:00 +0000710 return PyObject_Format(value, format_spec);
Eric Smith8c663262007-08-25 02:26:07 +0000711}
712
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000713/*[clinic input]
714chr as builtin_chr
715
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300716 i: int
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000717 /
718
719Return a Unicode string of one character with ordinal i; 0 <= i <= 0x10ffff.
720[clinic start generated code]*/
721
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000722static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300723builtin_chr_impl(PyObject *module, int i)
724/*[clinic end generated code: output=c733afcd200afcb7 input=3f604ef45a70750d]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000725{
726 return PyUnicode_FromOrdinal(i);
727}
Guido van Rossum09095f32000-03-10 23:00:52 +0000728
729
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000730/*[clinic input]
731compile as builtin_compile
732
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300733 source: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000734 filename: object(converter="PyUnicode_FSDecoder")
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300735 mode: str
736 flags: int = 0
Serhiy Storchaka202fda52017-03-12 10:10:47 +0200737 dont_inherit: bool(accept={int}) = False
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300738 optimize: int = -1
Victor Stinnerefdf6ca2019-06-12 02:52:16 +0200739 *
740 _feature_version as feature_version: int = -1
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000741
742Compile source into a code object that can be executed by exec() or eval().
743
744The source code may represent a Python module, statement or expression.
745The filename will be used for run-time error messages.
746The mode must be 'exec' to compile a module, 'single' to compile a
747single (interactive) statement, or 'eval' to compile an expression.
748The flags argument, if present, controls which future statements influence
749the compilation of the code.
Serhiy Storchaka8b2e8b62015-05-30 11:30:39 +0300750The dont_inherit argument, if true, stops the compilation inheriting
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000751the effects of any future statements in effect in the code calling
Serhiy Storchaka8b2e8b62015-05-30 11:30:39 +0300752compile; if absent or false these statements do influence the compilation,
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000753in addition to any features explicitly specified.
754[clinic start generated code]*/
755
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000756static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300757builtin_compile_impl(PyObject *module, PyObject *source, PyObject *filename,
758 const char *mode, int flags, int dont_inherit,
Guido van Rossum495da292019-03-07 12:38:08 -0800759 int optimize, int feature_version)
Victor Stinnerefdf6ca2019-06-12 02:52:16 +0200760/*[clinic end generated code: output=b0c09c84f116d3d7 input=40171fb92c1d580d]*/
Guido van Rossum5b722181993-03-30 17:46:03 +0000761{
Martin Panter61d6e4a2015-11-07 02:56:11 +0000762 PyObject *source_copy;
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +0200763 const char *str;
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000764 int compile_mode = -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000765 int is_ast;
Guido van Rossumdcfcd142019-01-31 03:40:27 -0800766 int start[] = {Py_file_input, Py_eval_input, Py_single_input, Py_func_type_input};
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000767 PyObject *result;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000768
Victor Stinner37d66d72019-06-13 02:16:41 +0200769 PyCompilerFlags cf = _PyCompilerFlags_INIT;
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000770 cf.cf_flags = flags | PyCF_SOURCE_IS_UTF8;
Guido van Rossum495da292019-03-07 12:38:08 -0800771 if (feature_version >= 0 && (flags & PyCF_ONLY_AST)) {
772 cf.cf_feature_version = feature_version;
773 }
Tim Peters6cd6a822001-08-17 22:11:27 +0000774
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000775 if (flags &
Batuhan Taşkaya44540572020-04-22 19:09:03 +0300776 ~(PyCF_MASK | PyCF_MASK_OBSOLETE | PyCF_COMPILE_MASK))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000777 {
778 PyErr_SetString(PyExc_ValueError,
779 "compile(): unrecognised flags");
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000780 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000781 }
782 /* XXX Warn if (supplied_flags & PyCF_MASK_OBSOLETE) != 0? */
Tim Peters6cd6a822001-08-17 22:11:27 +0000783
Georg Brandl8334fd92010-12-04 10:26:46 +0000784 if (optimize < -1 || optimize > 2) {
785 PyErr_SetString(PyExc_ValueError,
786 "compile(): invalid optimize value");
787 goto error;
788 }
789
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000790 if (!dont_inherit) {
791 PyEval_MergeCompilerFlags(&cf);
792 }
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000793
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000794 if (strcmp(mode, "exec") == 0)
795 compile_mode = 0;
796 else if (strcmp(mode, "eval") == 0)
797 compile_mode = 1;
798 else if (strcmp(mode, "single") == 0)
799 compile_mode = 2;
Guido van Rossumdcfcd142019-01-31 03:40:27 -0800800 else if (strcmp(mode, "func_type") == 0) {
801 if (!(flags & PyCF_ONLY_AST)) {
802 PyErr_SetString(PyExc_ValueError,
803 "compile() mode 'func_type' requires flag PyCF_ONLY_AST");
804 goto error;
805 }
806 compile_mode = 3;
807 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000808 else {
Guido van Rossumdcfcd142019-01-31 03:40:27 -0800809 const char *msg;
810 if (flags & PyCF_ONLY_AST)
811 msg = "compile() mode must be 'exec', 'eval', 'single' or 'func_type'";
812 else
813 msg = "compile() mode must be 'exec', 'eval' or 'single'";
814 PyErr_SetString(PyExc_ValueError, msg);
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000815 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000816 }
Neal Norwitzdb4115f2008-03-31 04:20:05 +0000817
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000818 is_ast = PyAST_Check(source);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000819 if (is_ast == -1)
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000820 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000821 if (is_ast) {
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000822 if (flags & PyCF_ONLY_AST) {
823 Py_INCREF(source);
824 result = source;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000825 }
826 else {
827 PyArena *arena;
828 mod_ty mod;
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000829
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000830 arena = PyArena_New();
Stefan Krah07795df2012-08-20 17:19:50 +0200831 if (arena == NULL)
832 goto error;
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000833 mod = PyAST_obj2mod(source, arena, compile_mode);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000834 if (mod == NULL) {
835 PyArena_Free(arena);
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000836 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000837 }
Benjamin Peterson832bfe22011-08-09 16:15:04 -0500838 if (!PyAST_Validate(mod)) {
839 PyArena_Free(arena);
840 goto error;
841 }
Victor Stinner14e461d2013-08-26 22:28:21 +0200842 result = (PyObject*)PyAST_CompileObject(mod, filename,
843 &cf, optimize, arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000844 PyArena_Free(arena);
845 }
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000846 goto finally;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000847 }
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000848
Dino Viehland41540692019-05-28 16:21:17 -0700849 str = _Py_SourceAsString(source, "compile", "string, bytes or AST", &cf, &source_copy);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000850 if (str == NULL)
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000851 goto error;
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000852
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000853 result = Py_CompileStringObject(str, filename, start[compile_mode], &cf, optimize);
Guido van Rossumc001c092020-04-30 12:12:19 -0700854
Martin Panter61d6e4a2015-11-07 02:56:11 +0000855 Py_XDECREF(source_copy);
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000856 goto finally;
857
858error:
859 result = NULL;
860finally:
Victor Stinner14e461d2013-08-26 22:28:21 +0200861 Py_DECREF(filename);
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000862 return result;
Guido van Rossum5b722181993-03-30 17:46:03 +0000863}
864
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000865/* AC: cannot convert yet, as needs PEP 457 group support in inspect */
Guido van Rossum79f25d91997-04-29 20:08:16 +0000866static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000867builtin_dir(PyObject *self, PyObject *args)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000868{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000869 PyObject *arg = NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000870
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000871 if (!PyArg_UnpackTuple(args, "dir", 0, 1, &arg))
872 return NULL;
873 return PyObject_Dir(arg);
Guido van Rossum3f5da241990-12-20 15:06:42 +0000874}
875
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000876PyDoc_STRVAR(dir_doc,
Tim Peters5d2b77c2001-09-03 05:47:38 +0000877"dir([object]) -> list of strings\n"
878"\n"
Georg Brandle32b4222007-03-10 22:13:27 +0000879"If called without an argument, return the names in the current scope.\n"
880"Else, return an alphabetized list of names comprising (some of) the attributes\n"
881"of the given object, and of attributes reachable from it.\n"
882"If the object supplies a method named __dir__, it will be used; otherwise\n"
883"the default dir() logic is used and returns:\n"
884" for a module object: the module's attributes.\n"
885" for a class object: its attributes, and recursively the attributes\n"
886" of its bases.\n"
Guido van Rossumd8faa362007-04-27 19:54:29 +0000887" for any other object: its attributes, its class's attributes, and\n"
Georg Brandle32b4222007-03-10 22:13:27 +0000888" recursively the attributes of its class's base classes.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000889
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000890/*[clinic input]
891divmod as builtin_divmod
Guido van Rossum6a00cd81995-01-07 12:39:01 +0000892
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300893 x: object
894 y: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000895 /
896
Zachary Ware7f227d92016-04-28 14:39:50 -0500897Return the tuple (x//y, x%y). Invariant: div*y + mod == x.
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000898[clinic start generated code]*/
899
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000900static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300901builtin_divmod_impl(PyObject *module, PyObject *x, PyObject *y)
902/*[clinic end generated code: output=b06d8a5f6e0c745e input=175ad9c84ff41a85]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000903{
904 return PyNumber_Divmod(x, y);
905}
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000906
907
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000908/*[clinic input]
909eval as builtin_eval
910
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300911 source: object
912 globals: object = None
913 locals: object = None
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000914 /
915
916Evaluate the given source in the context of globals and locals.
917
918The source may be a string representing a Python expression
919or a code object as returned by compile().
920The globals must be a dictionary and locals can be any mapping,
921defaulting to the current globals and locals.
922If only globals is given, locals defaults to it.
923[clinic start generated code]*/
924
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000925static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300926builtin_eval_impl(PyObject *module, PyObject *source, PyObject *globals,
Larry Hastings89964c42015-04-14 18:07:59 -0400927 PyObject *locals)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300928/*[clinic end generated code: output=0a0824aa70093116 input=11ee718a8640e527]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000929{
Martin Panter61d6e4a2015-11-07 02:56:11 +0000930 PyObject *result, *source_copy;
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +0200931 const char *str;
Guido van Rossum590baa41993-11-30 13:40:46 +0000932
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000933 if (locals != Py_None && !PyMapping_Check(locals)) {
934 PyErr_SetString(PyExc_TypeError, "locals must be a mapping");
935 return NULL;
936 }
937 if (globals != Py_None && !PyDict_Check(globals)) {
938 PyErr_SetString(PyExc_TypeError, PyMapping_Check(globals) ?
939 "globals must be a real dict; try eval(expr, {}, mapping)"
940 : "globals must be a dict");
941 return NULL;
942 }
943 if (globals == Py_None) {
944 globals = PyEval_GetGlobals();
Victor Stinner41bb43a2013-10-29 01:19:37 +0100945 if (locals == Py_None) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000946 locals = PyEval_GetLocals();
Victor Stinner41bb43a2013-10-29 01:19:37 +0100947 if (locals == NULL)
948 return NULL;
949 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000950 }
951 else if (locals == Py_None)
952 locals = globals;
Tim Peters9fa96be2001-08-17 23:04:59 +0000953
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000954 if (globals == NULL || locals == NULL) {
955 PyErr_SetString(PyExc_TypeError,
956 "eval must be given globals and locals "
957 "when called without a frame");
958 return NULL;
959 }
Georg Brandl77c85e62005-09-15 10:46:13 +0000960
Serhiy Storchakab510e102020-10-26 12:47:57 +0200961 int r = _PyDict_ContainsId(globals, &PyId___builtins__);
962 if (r == 0) {
963 r = _PyDict_SetItemId(globals, &PyId___builtins__,
964 PyEval_GetBuiltins());
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000965 }
Serhiy Storchakab510e102020-10-26 12:47:57 +0200966 if (r < 0) {
Serhiy Storchakaa24107b2019-02-25 17:59:46 +0200967 return NULL;
968 }
Tim Peters9fa96be2001-08-17 23:04:59 +0000969
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000970 if (PyCode_Check(source)) {
Steve Dowerb82e17e2019-05-23 08:45:22 -0700971 if (PySys_Audit("exec", "O", source) < 0) {
972 return NULL;
973 }
974
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000975 if (PyCode_GetNumFree((PyCodeObject *)source) > 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000976 PyErr_SetString(PyExc_TypeError,
Steve Dowerb82e17e2019-05-23 08:45:22 -0700977 "code object passed to eval() may not contain free variables");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000978 return NULL;
979 }
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000980 return PyEval_EvalCode(source, globals, locals);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000981 }
Tim Peters9fa96be2001-08-17 23:04:59 +0000982
Victor Stinner37d66d72019-06-13 02:16:41 +0200983 PyCompilerFlags cf = _PyCompilerFlags_INIT;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000984 cf.cf_flags = PyCF_SOURCE_IS_UTF8;
Dino Viehland41540692019-05-28 16:21:17 -0700985 str = _Py_SourceAsString(source, "eval", "string, bytes or code", &cf, &source_copy);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000986 if (str == NULL)
987 return NULL;
Just van Rossum3aaf42c2003-02-10 08:21:10 +0000988
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000989 while (*str == ' ' || *str == '\t')
990 str++;
Tim Peters9fa96be2001-08-17 23:04:59 +0000991
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000992 (void)PyEval_MergeCompilerFlags(&cf);
993 result = PyRun_StringFlags(str, Py_eval_input, globals, locals, &cf);
Martin Panter61d6e4a2015-11-07 02:56:11 +0000994 Py_XDECREF(source_copy);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000995 return result;
Guido van Rossum3f5da241990-12-20 15:06:42 +0000996}
997
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000998/*[clinic input]
999exec as builtin_exec
1000
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001001 source: object
1002 globals: object = None
1003 locals: object = None
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001004 /
1005
1006Execute the given source in the context of globals and locals.
1007
1008The source may be a string representing one or more Python statements
1009or a code object as returned by compile().
1010The globals must be a dictionary and locals can be any mapping,
1011defaulting to the current globals and locals.
1012If only globals is given, locals defaults to it.
1013[clinic start generated code]*/
1014
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001015static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001016builtin_exec_impl(PyObject *module, PyObject *source, PyObject *globals,
Larry Hastings89964c42015-04-14 18:07:59 -04001017 PyObject *locals)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001018/*[clinic end generated code: output=3c90efc6ab68ef5d input=01ca3e1c01692829]*/
Georg Brandl7cae87c2006-09-06 06:51:57 +00001019{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001020 PyObject *v;
Georg Brandl2cabc562008-08-28 07:57:16 +00001021
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001022 if (globals == Py_None) {
1023 globals = PyEval_GetGlobals();
1024 if (locals == Py_None) {
1025 locals = PyEval_GetLocals();
Victor Stinner41bb43a2013-10-29 01:19:37 +01001026 if (locals == NULL)
1027 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001028 }
1029 if (!globals || !locals) {
1030 PyErr_SetString(PyExc_SystemError,
1031 "globals and locals cannot be NULL");
1032 return NULL;
1033 }
1034 }
1035 else if (locals == Py_None)
1036 locals = globals;
Georg Brandl7cae87c2006-09-06 06:51:57 +00001037
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001038 if (!PyDict_Check(globals)) {
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001039 PyErr_Format(PyExc_TypeError, "exec() globals must be a dict, not %.100s",
Victor Stinnera102ed72020-02-07 02:24:48 +01001040 Py_TYPE(globals)->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001041 return NULL;
1042 }
1043 if (!PyMapping_Check(locals)) {
1044 PyErr_Format(PyExc_TypeError,
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001045 "locals must be a mapping or None, not %.100s",
Victor Stinnera102ed72020-02-07 02:24:48 +01001046 Py_TYPE(locals)->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001047 return NULL;
1048 }
Serhiy Storchakab510e102020-10-26 12:47:57 +02001049 int r = _PyDict_ContainsId(globals, &PyId___builtins__);
1050 if (r == 0) {
1051 r = _PyDict_SetItemId(globals, &PyId___builtins__,
1052 PyEval_GetBuiltins());
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001053 }
Serhiy Storchakab510e102020-10-26 12:47:57 +02001054 if (r < 0) {
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02001055 return NULL;
1056 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001057
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001058 if (PyCode_Check(source)) {
Steve Dowerb82e17e2019-05-23 08:45:22 -07001059 if (PySys_Audit("exec", "O", source) < 0) {
1060 return NULL;
1061 }
1062
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001063 if (PyCode_GetNumFree((PyCodeObject *)source) > 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001064 PyErr_SetString(PyExc_TypeError,
1065 "code object passed to exec() may not "
1066 "contain free variables");
1067 return NULL;
1068 }
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001069 v = PyEval_EvalCode(source, globals, locals);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001070 }
1071 else {
Martin Panter61d6e4a2015-11-07 02:56:11 +00001072 PyObject *source_copy;
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +02001073 const char *str;
Victor Stinner37d66d72019-06-13 02:16:41 +02001074 PyCompilerFlags cf = _PyCompilerFlags_INIT;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001075 cf.cf_flags = PyCF_SOURCE_IS_UTF8;
Dino Viehland41540692019-05-28 16:21:17 -07001076 str = _Py_SourceAsString(source, "exec",
Martin Panter61d6e4a2015-11-07 02:56:11 +00001077 "string, bytes or code", &cf,
1078 &source_copy);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001079 if (str == NULL)
1080 return NULL;
1081 if (PyEval_MergeCompilerFlags(&cf))
1082 v = PyRun_StringFlags(str, Py_file_input, globals,
1083 locals, &cf);
1084 else
1085 v = PyRun_String(str, Py_file_input, globals, locals);
Martin Panter61d6e4a2015-11-07 02:56:11 +00001086 Py_XDECREF(source_copy);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001087 }
1088 if (v == NULL)
1089 return NULL;
1090 Py_DECREF(v);
1091 Py_RETURN_NONE;
Georg Brandl7cae87c2006-09-06 06:51:57 +00001092}
1093
Georg Brandl7cae87c2006-09-06 06:51:57 +00001094
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001095/* AC: cannot convert yet, as needs PEP 457 group support in inspect */
Guido van Rossum79f25d91997-04-29 20:08:16 +00001096static PyObject *
Serhiy Storchakaa5552f02017-12-15 13:11:11 +02001097builtin_getattr(PyObject *self, PyObject *const *args, Py_ssize_t nargs)
Guido van Rossum33894be1992-01-27 16:53:09 +00001098{
Serhiy Storchaka79342662019-01-12 08:25:41 +02001099 PyObject *v, *name, *result;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001100
Serhiy Storchaka79342662019-01-12 08:25:41 +02001101 if (!_PyArg_CheckPositional("getattr", nargs, 2, 3))
Sylvain96c7c062017-06-15 17:05:23 +02001102 return NULL;
1103
Serhiy Storchaka79342662019-01-12 08:25:41 +02001104 v = args[0];
1105 name = args[1];
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001106 if (!PyUnicode_Check(name)) {
1107 PyErr_SetString(PyExc_TypeError,
1108 "getattr(): attribute name must be string");
1109 return NULL;
1110 }
Serhiy Storchaka79342662019-01-12 08:25:41 +02001111 if (nargs > 2) {
Serhiy Storchakaf320be72018-01-25 10:49:40 +02001112 if (_PyObject_LookupAttr(v, name, &result) == 0) {
Serhiy Storchaka79342662019-01-12 08:25:41 +02001113 PyObject *dflt = args[2];
INADA Naoki378edee2018-01-16 20:52:41 +09001114 Py_INCREF(dflt);
1115 return dflt;
1116 }
1117 }
1118 else {
1119 result = PyObject_GetAttr(v, name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001120 }
1121 return result;
Guido van Rossum9bfef441993-03-29 10:43:31 +00001122}
1123
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001124PyDoc_STRVAR(getattr_doc,
Guido van Rossum950ff291998-06-29 13:38:57 +00001125"getattr(object, name[, default]) -> value\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001126\n\
Guido van Rossum950ff291998-06-29 13:38:57 +00001127Get a named attribute from an object; getattr(x, 'y') is equivalent to x.y.\n\
1128When a default argument is given, it is returned when the attribute doesn't\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001129exist; without it, an exception is raised in that case.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001130
1131
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001132/*[clinic input]
1133globals as builtin_globals
1134
1135Return the dictionary containing the current scope's global variables.
1136
1137NOTE: Updates to this dictionary *will* affect name lookups in the current
1138global scope and vice-versa.
1139[clinic start generated code]*/
1140
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001141static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001142builtin_globals_impl(PyObject *module)
1143/*[clinic end generated code: output=e5dd1527067b94d2 input=9327576f92bb48ba]*/
Guido van Rossum872537c1995-07-07 22:43:42 +00001144{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001145 PyObject *d;
Guido van Rossum872537c1995-07-07 22:43:42 +00001146
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001147 d = PyEval_GetGlobals();
1148 Py_XINCREF(d);
1149 return d;
Guido van Rossum872537c1995-07-07 22:43:42 +00001150}
1151
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001152
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001153/*[clinic input]
1154hasattr as builtin_hasattr
1155
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001156 obj: object
1157 name: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001158 /
1159
1160Return whether the object has an attribute with the given name.
1161
1162This is done by calling getattr(obj, name) and catching AttributeError.
1163[clinic start generated code]*/
1164
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001165static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001166builtin_hasattr_impl(PyObject *module, PyObject *obj, PyObject *name)
1167/*[clinic end generated code: output=a7aff2090a4151e5 input=0faec9787d979542]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001168{
1169 PyObject *v;
1170
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001171 if (!PyUnicode_Check(name)) {
1172 PyErr_SetString(PyExc_TypeError,
1173 "hasattr(): attribute name must be string");
1174 return NULL;
1175 }
Serhiy Storchakaf320be72018-01-25 10:49:40 +02001176 if (_PyObject_LookupAttr(obj, name, &v) < 0) {
Benjamin Peterson17689992010-08-24 03:26:23 +00001177 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001178 }
Serhiy Storchakaf320be72018-01-25 10:49:40 +02001179 if (v == NULL) {
1180 Py_RETURN_FALSE;
1181 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001182 Py_DECREF(v);
Benjamin Peterson17689992010-08-24 03:26:23 +00001183 Py_RETURN_TRUE;
Guido van Rossum33894be1992-01-27 16:53:09 +00001184}
1185
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001186
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001187/* AC: gdb's integration with CPython relies on builtin_id having
1188 * the *exact* parameter names of "self" and "v", so we ensure we
1189 * preserve those name rather than using the AC defaults.
1190 */
1191/*[clinic input]
1192id as builtin_id
1193
Serhiy Storchaka24182a32016-05-05 16:21:35 +03001194 self: self(type="PyModuleDef *")
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001195 obj as v: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001196 /
1197
1198Return the identity of an object.
1199
1200This is guaranteed to be unique among simultaneously existing objects.
1201(CPython uses the object's memory address.)
1202[clinic start generated code]*/
1203
Guido van Rossum79f25d91997-04-29 20:08:16 +00001204static PyObject *
Serhiy Storchaka24182a32016-05-05 16:21:35 +03001205builtin_id(PyModuleDef *self, PyObject *v)
1206/*[clinic end generated code: output=0aa640785f697f65 input=5a534136419631f4]*/
Guido van Rossum5b722181993-03-30 17:46:03 +00001207{
Steve Dowerb82e17e2019-05-23 08:45:22 -07001208 PyObject *id = PyLong_FromVoidPtr(v);
1209
1210 if (id && PySys_Audit("builtins.id", "O", id) < 0) {
1211 Py_DECREF(id);
1212 return NULL;
1213 }
1214
1215 return id;
Guido van Rossum5b722181993-03-30 17:46:03 +00001216}
1217
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001218
Raymond Hettingera6c60372008-03-13 01:26:19 +00001219/* map object ************************************************************/
1220
1221typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001222 PyObject_HEAD
1223 PyObject *iters;
1224 PyObject *func;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001225} mapobject;
1226
Guido van Rossum79f25d91997-04-29 20:08:16 +00001227static PyObject *
Raymond Hettingera6c60372008-03-13 01:26:19 +00001228map_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
Guido van Rossum12d12c51993-10-26 17:58:25 +00001229{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001230 PyObject *it, *iters, *func;
1231 mapobject *lz;
1232 Py_ssize_t numargs, i;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001233
Serhiy Storchaka6cca5c82017-06-08 14:41:19 +03001234 if (type == &PyMap_Type && !_PyArg_NoKeywords("map", kwds))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001235 return NULL;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001236
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001237 numargs = PyTuple_Size(args);
1238 if (numargs < 2) {
1239 PyErr_SetString(PyExc_TypeError,
1240 "map() must have at least two arguments.");
1241 return NULL;
1242 }
Raymond Hettingera6c60372008-03-13 01:26:19 +00001243
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001244 iters = PyTuple_New(numargs-1);
1245 if (iters == NULL)
1246 return NULL;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001247
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001248 for (i=1 ; i<numargs ; i++) {
1249 /* Get iterator. */
1250 it = PyObject_GetIter(PyTuple_GET_ITEM(args, i));
1251 if (it == NULL) {
1252 Py_DECREF(iters);
1253 return NULL;
1254 }
1255 PyTuple_SET_ITEM(iters, i-1, it);
1256 }
Raymond Hettingera6c60372008-03-13 01:26:19 +00001257
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001258 /* create mapobject structure */
1259 lz = (mapobject *)type->tp_alloc(type, 0);
1260 if (lz == NULL) {
1261 Py_DECREF(iters);
1262 return NULL;
1263 }
1264 lz->iters = iters;
1265 func = PyTuple_GET_ITEM(args, 0);
1266 Py_INCREF(func);
1267 lz->func = func;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001268
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001269 return (PyObject *)lz;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001270}
1271
1272static void
1273map_dealloc(mapobject *lz)
1274{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001275 PyObject_GC_UnTrack(lz);
1276 Py_XDECREF(lz->iters);
1277 Py_XDECREF(lz->func);
1278 Py_TYPE(lz)->tp_free(lz);
Raymond Hettingera6c60372008-03-13 01:26:19 +00001279}
1280
1281static int
1282map_traverse(mapobject *lz, visitproc visit, void *arg)
1283{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001284 Py_VISIT(lz->iters);
1285 Py_VISIT(lz->func);
1286 return 0;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001287}
1288
1289static PyObject *
1290map_next(mapobject *lz)
1291{
Victor Stinnerbc08ab42016-12-15 12:40:53 +01001292 PyObject *small_stack[_PY_FASTCALL_SMALL_STACK];
Victor Stinnercdb5cee2016-08-24 01:45:13 +02001293 PyObject **stack;
Victor Stinnercdb5cee2016-08-24 01:45:13 +02001294 PyObject *result = NULL;
Victor Stinner4d231bc2019-11-14 13:36:21 +01001295 PyThreadState *tstate = _PyThreadState_GET();
Raymond Hettingera6c60372008-03-13 01:26:19 +00001296
Victor Stinner4d231bc2019-11-14 13:36:21 +01001297 const Py_ssize_t niters = PyTuple_GET_SIZE(lz->iters);
Victor Stinnercdb5cee2016-08-24 01:45:13 +02001298 if (niters <= (Py_ssize_t)Py_ARRAY_LENGTH(small_stack)) {
1299 stack = small_stack;
1300 }
1301 else {
1302 stack = PyMem_Malloc(niters * sizeof(stack[0]));
1303 if (stack == NULL) {
Victor Stinner4d231bc2019-11-14 13:36:21 +01001304 _PyErr_NoMemory(tstate);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001305 return NULL;
1306 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001307 }
Victor Stinnercdb5cee2016-08-24 01:45:13 +02001308
Victor Stinner4d231bc2019-11-14 13:36:21 +01001309 Py_ssize_t nargs = 0;
1310 for (Py_ssize_t i=0; i < niters; i++) {
Victor Stinnercdb5cee2016-08-24 01:45:13 +02001311 PyObject *it = PyTuple_GET_ITEM(lz->iters, i);
1312 PyObject *val = Py_TYPE(it)->tp_iternext(it);
1313 if (val == NULL) {
1314 goto exit;
1315 }
1316 stack[i] = val;
1317 nargs++;
1318 }
1319
Victor Stinner4d231bc2019-11-14 13:36:21 +01001320 result = _PyObject_VectorcallTstate(tstate, lz->func, stack, nargs, NULL);
Victor Stinnercdb5cee2016-08-24 01:45:13 +02001321
1322exit:
Victor Stinner4d231bc2019-11-14 13:36:21 +01001323 for (Py_ssize_t i=0; i < nargs; i++) {
Victor Stinnercdb5cee2016-08-24 01:45:13 +02001324 Py_DECREF(stack[i]);
1325 }
1326 if (stack != small_stack) {
1327 PyMem_Free(stack);
1328 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001329 return result;
Guido van Rossum12d12c51993-10-26 17:58:25 +00001330}
1331
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001332static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05301333map_reduce(mapobject *lz, PyObject *Py_UNUSED(ignored))
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001334{
1335 Py_ssize_t numargs = PyTuple_GET_SIZE(lz->iters);
1336 PyObject *args = PyTuple_New(numargs+1);
1337 Py_ssize_t i;
1338 if (args == NULL)
1339 return NULL;
1340 Py_INCREF(lz->func);
1341 PyTuple_SET_ITEM(args, 0, lz->func);
1342 for (i = 0; i<numargs; i++){
1343 PyObject *it = PyTuple_GET_ITEM(lz->iters, i);
1344 Py_INCREF(it);
1345 PyTuple_SET_ITEM(args, i+1, it);
1346 }
1347
1348 return Py_BuildValue("ON", Py_TYPE(lz), args);
1349}
1350
1351static PyMethodDef map_methods[] = {
1352 {"__reduce__", (PyCFunction)map_reduce, METH_NOARGS, reduce_doc},
1353 {NULL, NULL} /* sentinel */
1354};
1355
1356
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001357PyDoc_STRVAR(map_doc,
Raymond Hettingera6c60372008-03-13 01:26:19 +00001358"map(func, *iterables) --> map object\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001359\n\
Raymond Hettingera6c60372008-03-13 01:26:19 +00001360Make an iterator that computes the function using arguments from\n\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001361each of the iterables. Stops when the shortest iterable is exhausted.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001362
Raymond Hettingera6c60372008-03-13 01:26:19 +00001363PyTypeObject PyMap_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001364 PyVarObject_HEAD_INIT(&PyType_Type, 0)
1365 "map", /* tp_name */
1366 sizeof(mapobject), /* tp_basicsize */
1367 0, /* tp_itemsize */
1368 /* methods */
1369 (destructor)map_dealloc, /* tp_dealloc */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02001370 0, /* tp_vectorcall_offset */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001371 0, /* tp_getattr */
1372 0, /* tp_setattr */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02001373 0, /* tp_as_async */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001374 0, /* tp_repr */
1375 0, /* tp_as_number */
1376 0, /* tp_as_sequence */
1377 0, /* tp_as_mapping */
1378 0, /* tp_hash */
1379 0, /* tp_call */
1380 0, /* tp_str */
1381 PyObject_GenericGetAttr, /* tp_getattro */
1382 0, /* tp_setattro */
1383 0, /* tp_as_buffer */
1384 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
1385 Py_TPFLAGS_BASETYPE, /* tp_flags */
1386 map_doc, /* tp_doc */
1387 (traverseproc)map_traverse, /* tp_traverse */
1388 0, /* tp_clear */
1389 0, /* tp_richcompare */
1390 0, /* tp_weaklistoffset */
1391 PyObject_SelfIter, /* tp_iter */
1392 (iternextfunc)map_next, /* tp_iternext */
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001393 map_methods, /* tp_methods */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001394 0, /* tp_members */
1395 0, /* tp_getset */
1396 0, /* tp_base */
1397 0, /* tp_dict */
1398 0, /* tp_descr_get */
1399 0, /* tp_descr_set */
1400 0, /* tp_dictoffset */
1401 0, /* tp_init */
1402 PyType_GenericAlloc, /* tp_alloc */
1403 map_new, /* tp_new */
1404 PyObject_GC_Del, /* tp_free */
Raymond Hettingera6c60372008-03-13 01:26:19 +00001405};
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001406
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001407
1408/* AC: cannot convert yet, as needs PEP 457 group support in inspect */
Guido van Rossum79f25d91997-04-29 20:08:16 +00001409static PyObject *
Serhiy Storchakaa5552f02017-12-15 13:11:11 +02001410builtin_next(PyObject *self, PyObject *const *args, Py_ssize_t nargs)
Georg Brandla18af4e2007-04-21 15:47:16 +00001411{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001412 PyObject *it, *res;
Georg Brandla18af4e2007-04-21 15:47:16 +00001413
Serhiy Storchaka79342662019-01-12 08:25:41 +02001414 if (!_PyArg_CheckPositional("next", nargs, 1, 2))
Sylvain96c7c062017-06-15 17:05:23 +02001415 return NULL;
1416
Serhiy Storchaka79342662019-01-12 08:25:41 +02001417 it = args[0];
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001418 if (!PyIter_Check(it)) {
1419 PyErr_Format(PyExc_TypeError,
Philip Jenvey50add042011-11-06 16:37:52 -08001420 "'%.200s' object is not an iterator",
Victor Stinnera102ed72020-02-07 02:24:48 +01001421 Py_TYPE(it)->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001422 return NULL;
1423 }
1424
Victor Stinnera102ed72020-02-07 02:24:48 +01001425 res = (*Py_TYPE(it)->tp_iternext)(it);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001426 if (res != NULL) {
1427 return res;
Serhiy Storchaka79342662019-01-12 08:25:41 +02001428 } else if (nargs > 1) {
1429 PyObject *def = args[1];
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001430 if (PyErr_Occurred()) {
1431 if(!PyErr_ExceptionMatches(PyExc_StopIteration))
1432 return NULL;
1433 PyErr_Clear();
1434 }
1435 Py_INCREF(def);
1436 return def;
1437 } else if (PyErr_Occurred()) {
1438 return NULL;
1439 } else {
1440 PyErr_SetNone(PyExc_StopIteration);
1441 return NULL;
1442 }
Georg Brandla18af4e2007-04-21 15:47:16 +00001443}
1444
1445PyDoc_STRVAR(next_doc,
1446"next(iterator[, default])\n\
1447\n\
1448Return the next item from the iterator. If default is given and the iterator\n\
1449is exhausted, it is returned instead of raising StopIteration.");
1450
1451
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001452/*[clinic input]
1453setattr as builtin_setattr
1454
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001455 obj: object
1456 name: object
1457 value: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001458 /
1459
1460Sets the named attribute on the given object to the specified value.
1461
1462setattr(x, 'y', v) is equivalent to ``x.y = v''
1463[clinic start generated code]*/
1464
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001465static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001466builtin_setattr_impl(PyObject *module, PyObject *obj, PyObject *name,
Larry Hastings89964c42015-04-14 18:07:59 -04001467 PyObject *value)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001468/*[clinic end generated code: output=dc2ce1d1add9acb4 input=bd2b7ca6875a1899]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001469{
1470 if (PyObject_SetAttr(obj, name, value) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001471 return NULL;
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02001472 Py_RETURN_NONE;
Guido van Rossum33894be1992-01-27 16:53:09 +00001473}
1474
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001475
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001476/*[clinic input]
1477delattr as builtin_delattr
1478
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001479 obj: object
1480 name: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001481 /
1482
1483Deletes the named attribute from the given object.
1484
1485delattr(x, 'y') is equivalent to ``del x.y''
1486[clinic start generated code]*/
1487
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001488static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001489builtin_delattr_impl(PyObject *module, PyObject *obj, PyObject *name)
1490/*[clinic end generated code: output=85134bc58dff79fa input=db16685d6b4b9410]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001491{
1492 if (PyObject_SetAttr(obj, name, (PyObject *)NULL) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001493 return NULL;
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02001494 Py_RETURN_NONE;
Guido van Rossum14144fc1994-08-29 12:53:40 +00001495}
1496
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001497
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001498/*[clinic input]
1499hash as builtin_hash
1500
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001501 obj: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001502 /
1503
1504Return the hash value for the given object.
1505
1506Two objects that compare equal must also have the same hash value, but the
1507reverse is not necessarily true.
1508[clinic start generated code]*/
1509
Guido van Rossum79f25d91997-04-29 20:08:16 +00001510static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001511builtin_hash(PyObject *module, PyObject *obj)
1512/*[clinic end generated code: output=237668e9d7688db7 input=58c48be822bf9c54]*/
Guido van Rossum9bfef441993-03-29 10:43:31 +00001513{
Benjamin Peterson8f67d082010-10-17 20:54:53 +00001514 Py_hash_t x;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001515
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001516 x = PyObject_Hash(obj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001517 if (x == -1)
1518 return NULL;
Benjamin Peterson8f67d082010-10-17 20:54:53 +00001519 return PyLong_FromSsize_t(x);
Guido van Rossum9bfef441993-03-29 10:43:31 +00001520}
1521
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001522
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001523/*[clinic input]
1524hex as builtin_hex
1525
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001526 number: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001527 /
1528
1529Return the hexadecimal representation of an integer.
1530
1531 >>> hex(12648430)
1532 '0xc0ffee'
1533[clinic start generated code]*/
1534
Guido van Rossum79f25d91997-04-29 20:08:16 +00001535static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001536builtin_hex(PyObject *module, PyObject *number)
1537/*[clinic end generated code: output=e46b612169099408 input=e645aff5fc7d540e]*/
Guido van Rossum006bcd41991-10-24 14:54:44 +00001538{
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001539 return PyNumber_ToBase(number, 16);
Guido van Rossum006bcd41991-10-24 14:54:44 +00001540}
1541
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001542
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001543/* AC: cannot convert yet, as needs PEP 457 group support in inspect */
Guido van Rossum79f25d91997-04-29 20:08:16 +00001544static PyObject *
Serhiy Storchaka79342662019-01-12 08:25:41 +02001545builtin_iter(PyObject *self, PyObject *const *args, Py_ssize_t nargs)
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001546{
Serhiy Storchaka79342662019-01-12 08:25:41 +02001547 PyObject *v;
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001548
Serhiy Storchaka79342662019-01-12 08:25:41 +02001549 if (!_PyArg_CheckPositional("iter", nargs, 1, 2))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001550 return NULL;
Serhiy Storchaka79342662019-01-12 08:25:41 +02001551 v = args[0];
1552 if (nargs == 1)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001553 return PyObject_GetIter(v);
1554 if (!PyCallable_Check(v)) {
1555 PyErr_SetString(PyExc_TypeError,
1556 "iter(v, w): v must be callable");
1557 return NULL;
1558 }
Serhiy Storchaka79342662019-01-12 08:25:41 +02001559 PyObject *sentinel = args[1];
1560 return PyCallIter_New(v, sentinel);
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001561}
1562
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001563PyDoc_STRVAR(iter_doc,
Georg Brandld11ae5d2008-05-16 13:27:32 +00001564"iter(iterable) -> iterator\n\
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001565iter(callable, sentinel) -> iterator\n\
1566\n\
1567Get an iterator from an object. In the first form, the argument must\n\
1568supply its own iterator, or be a sequence.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001569In the second form, the callable is called until it returns the sentinel.");
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001570
1571
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001572/*[clinic input]
1573len as builtin_len
1574
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001575 obj: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001576 /
1577
1578Return the number of items in a container.
1579[clinic start generated code]*/
1580
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001581static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001582builtin_len(PyObject *module, PyObject *obj)
1583/*[clinic end generated code: output=fa7a270d314dfb6c input=bc55598da9e9c9b5]*/
Guido van Rossum3f5da241990-12-20 15:06:42 +00001584{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001585 Py_ssize_t res;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001586
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001587 res = PyObject_Size(obj);
Serhiy Storchaka813f9432017-04-16 09:21:44 +03001588 if (res < 0) {
1589 assert(PyErr_Occurred());
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001590 return NULL;
Serhiy Storchaka813f9432017-04-16 09:21:44 +03001591 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001592 return PyLong_FromSsize_t(res);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001593}
1594
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001595
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001596/*[clinic input]
1597locals as builtin_locals
1598
1599Return a dictionary containing the current scope's local variables.
1600
1601NOTE: Whether or not updates to this dictionary will affect name lookups in
1602the local scope and vice-versa is *implementation dependent* and not
1603covered by any backwards compatibility guarantees.
1604[clinic start generated code]*/
1605
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001606static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001607builtin_locals_impl(PyObject *module)
1608/*[clinic end generated code: output=b46c94015ce11448 input=7874018d478d5c4b]*/
Guido van Rossum872537c1995-07-07 22:43:42 +00001609{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001610 PyObject *d;
Guido van Rossum872537c1995-07-07 22:43:42 +00001611
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001612 d = PyEval_GetLocals();
1613 Py_XINCREF(d);
1614 return d;
Guido van Rossum872537c1995-07-07 22:43:42 +00001615}
1616
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001617
Guido van Rossum79f25d91997-04-29 20:08:16 +00001618static PyObject *
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001619min_max(PyObject *args, PyObject *kwds, int op)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001620{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001621 PyObject *v, *it, *item, *val, *maxitem, *maxval, *keyfunc=NULL;
Raymond Hettinger4d6018f2013-06-24 22:43:02 -07001622 PyObject *emptytuple, *defaultval = NULL;
1623 static char *kwlist[] = {"key", "default", NULL};
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001624 const char *name = op == Py_LT ? "min" : "max";
Raymond Hettinger4d6018f2013-06-24 22:43:02 -07001625 const int positional = PyTuple_Size(args) > 1;
1626 int ret;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001627
Dong-hee Naabdc6342020-01-11 01:31:43 +09001628 if (positional) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001629 v = args;
Dong-hee Naabdc6342020-01-11 01:31:43 +09001630 }
1631 else if (!PyArg_UnpackTuple(args, name, 1, 1, &v)) {
1632 if (PyExceptionClass_Check(PyExc_TypeError)) {
1633 PyErr_Format(PyExc_TypeError, "%s expected at least 1 argument, got 0", name);
1634 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001635 return NULL;
Dong-hee Naabdc6342020-01-11 01:31:43 +09001636 }
Tim Peters67d687a2002-04-29 21:27:32 +00001637
Raymond Hettinger4d6018f2013-06-24 22:43:02 -07001638 emptytuple = PyTuple_New(0);
1639 if (emptytuple == NULL)
1640 return NULL;
Oren Milman58cf7482017-08-21 20:19:07 +03001641 ret = PyArg_ParseTupleAndKeywords(emptytuple, kwds,
1642 (op == Py_LT) ? "|$OO:min" : "|$OO:max",
1643 kwlist, &keyfunc, &defaultval);
Raymond Hettinger4d6018f2013-06-24 22:43:02 -07001644 Py_DECREF(emptytuple);
1645 if (!ret)
1646 return NULL;
1647
1648 if (positional && defaultval != NULL) {
1649 PyErr_Format(PyExc_TypeError,
1650 "Cannot specify a default for %s() with multiple "
1651 "positional arguments", name);
1652 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001653 }
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001654
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001655 it = PyObject_GetIter(v);
1656 if (it == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001657 return NULL;
1658 }
Tim Petersc3074532001-05-03 07:00:32 +00001659
Alexander Marshalove22072f2018-07-24 10:58:21 +07001660 if (keyfunc == Py_None) {
1661 keyfunc = NULL;
1662 }
1663
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001664 maxitem = NULL; /* the result */
1665 maxval = NULL; /* the value associated with the result */
1666 while (( item = PyIter_Next(it) )) {
1667 /* get the value from the key function */
1668 if (keyfunc != NULL) {
Petr Viktorinffd97532020-02-11 17:46:57 +01001669 val = PyObject_CallOneArg(keyfunc, item);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001670 if (val == NULL)
1671 goto Fail_it_item;
1672 }
1673 /* no key function; the value is the item */
1674 else {
1675 val = item;
1676 Py_INCREF(val);
1677 }
Tim Petersc3074532001-05-03 07:00:32 +00001678
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001679 /* maximum value and item are unset; set them */
1680 if (maxval == NULL) {
1681 maxitem = item;
1682 maxval = val;
1683 }
1684 /* maximum value and item are set; update them as necessary */
1685 else {
1686 int cmp = PyObject_RichCompareBool(val, maxval, op);
1687 if (cmp < 0)
1688 goto Fail_it_item_and_val;
1689 else if (cmp > 0) {
1690 Py_DECREF(maxval);
1691 Py_DECREF(maxitem);
1692 maxval = val;
1693 maxitem = item;
1694 }
1695 else {
1696 Py_DECREF(item);
1697 Py_DECREF(val);
1698 }
1699 }
1700 }
1701 if (PyErr_Occurred())
1702 goto Fail_it;
1703 if (maxval == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001704 assert(maxitem == NULL);
Raymond Hettinger4d6018f2013-06-24 22:43:02 -07001705 if (defaultval != NULL) {
1706 Py_INCREF(defaultval);
1707 maxitem = defaultval;
1708 } else {
1709 PyErr_Format(PyExc_ValueError,
1710 "%s() arg is an empty sequence", name);
1711 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001712 }
1713 else
1714 Py_DECREF(maxval);
1715 Py_DECREF(it);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001716 return maxitem;
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001717
1718Fail_it_item_and_val:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001719 Py_DECREF(val);
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001720Fail_it_item:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001721 Py_DECREF(item);
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001722Fail_it:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001723 Py_XDECREF(maxval);
1724 Py_XDECREF(maxitem);
1725 Py_DECREF(it);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001726 return NULL;
Guido van Rossum3f5da241990-12-20 15:06:42 +00001727}
1728
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001729/* AC: cannot convert yet, waiting for *args support */
Guido van Rossum79f25d91997-04-29 20:08:16 +00001730static PyObject *
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001731builtin_min(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001732{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001733 return min_max(args, kwds, Py_LT);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001734}
1735
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001736PyDoc_STRVAR(min_doc,
Raymond Hettinger2a545822014-05-19 22:20:52 +01001737"min(iterable, *[, default=obj, key=func]) -> value\n\
1738min(arg1, arg2, *args, *[, key=func]) -> value\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001739\n\
Raymond Hettinger2a545822014-05-19 22:20:52 +01001740With a single iterable argument, return its smallest item. The\n\
1741default keyword-only argument specifies an object to return if\n\
1742the provided iterable is empty.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001743With two or more arguments, return the smallest argument.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001744
1745
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001746/* AC: cannot convert yet, waiting for *args support */
Guido van Rossum79f25d91997-04-29 20:08:16 +00001747static PyObject *
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001748builtin_max(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001749{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001750 return min_max(args, kwds, Py_GT);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001751}
1752
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001753PyDoc_STRVAR(max_doc,
Raymond Hettinger2a545822014-05-19 22:20:52 +01001754"max(iterable, *[, default=obj, key=func]) -> value\n\
1755max(arg1, arg2, *args, *[, key=func]) -> value\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001756\n\
Raymond Hettinger2a545822014-05-19 22:20:52 +01001757With a single iterable argument, return its biggest item. The\n\
1758default keyword-only argument specifies an object to return if\n\
1759the provided iterable is empty.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001760With two or more arguments, return the largest argument.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001761
1762
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001763/*[clinic input]
1764oct as builtin_oct
1765
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001766 number: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001767 /
1768
1769Return the octal representation of an integer.
1770
1771 >>> oct(342391)
1772 '0o1234567'
1773[clinic start generated code]*/
1774
Guido van Rossum79f25d91997-04-29 20:08:16 +00001775static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001776builtin_oct(PyObject *module, PyObject *number)
1777/*[clinic end generated code: output=40a34656b6875352 input=ad6b274af4016c72]*/
Guido van Rossum006bcd41991-10-24 14:54:44 +00001778{
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001779 return PyNumber_ToBase(number, 8);
Guido van Rossum006bcd41991-10-24 14:54:44 +00001780}
1781
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001782
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001783/*[clinic input]
1784ord as builtin_ord
1785
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001786 c: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001787 /
1788
1789Return the Unicode code point for a one-character string.
1790[clinic start generated code]*/
1791
Guido van Rossum79f25d91997-04-29 20:08:16 +00001792static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001793builtin_ord(PyObject *module, PyObject *c)
1794/*[clinic end generated code: output=4fa5e87a323bae71 input=3064e5d6203ad012]*/
Guido van Rossum3f5da241990-12-20 15:06:42 +00001795{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001796 long ord;
1797 Py_ssize_t size;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001798
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001799 if (PyBytes_Check(c)) {
1800 size = PyBytes_GET_SIZE(c);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001801 if (size == 1) {
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001802 ord = (long)((unsigned char)*PyBytes_AS_STRING(c));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001803 return PyLong_FromLong(ord);
1804 }
1805 }
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001806 else if (PyUnicode_Check(c)) {
1807 if (PyUnicode_READY(c) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001808 return NULL;
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001809 size = PyUnicode_GET_LENGTH(c);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001810 if (size == 1) {
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001811 ord = (long)PyUnicode_READ_CHAR(c, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001812 return PyLong_FromLong(ord);
1813 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001814 }
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001815 else if (PyByteArray_Check(c)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001816 /* XXX Hopefully this is temporary */
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001817 size = PyByteArray_GET_SIZE(c);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001818 if (size == 1) {
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001819 ord = (long)((unsigned char)*PyByteArray_AS_STRING(c));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001820 return PyLong_FromLong(ord);
1821 }
1822 }
1823 else {
1824 PyErr_Format(PyExc_TypeError,
1825 "ord() expected string of length 1, but " \
Victor Stinnera102ed72020-02-07 02:24:48 +01001826 "%.200s found", Py_TYPE(c)->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001827 return NULL;
1828 }
Guido van Rossum09095f32000-03-10 23:00:52 +00001829
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001830 PyErr_Format(PyExc_TypeError,
1831 "ord() expected a character, "
1832 "but string of length %zd found",
1833 size);
1834 return NULL;
Guido van Rossum3f5da241990-12-20 15:06:42 +00001835}
1836
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001837
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001838/*[clinic input]
1839pow as builtin_pow
1840
Ammar Askar87d6cd32019-09-21 00:28:49 -04001841 base: object
1842 exp: object
1843 mod: object = None
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001844
Raymond Hettingerb104ecb2019-09-21 12:57:44 -07001845Equivalent to base**exp with 2 arguments or base**exp % mod with 3 arguments
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001846
1847Some types, such as ints, are able to use a more efficient algorithm when
1848invoked using the three argument form.
1849[clinic start generated code]*/
1850
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001851static PyObject *
Ammar Askar87d6cd32019-09-21 00:28:49 -04001852builtin_pow_impl(PyObject *module, PyObject *base, PyObject *exp,
1853 PyObject *mod)
Raymond Hettingerb104ecb2019-09-21 12:57:44 -07001854/*[clinic end generated code: output=3ca1538221bbf15f input=435dbd48a12efb23]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001855{
Ammar Askar87d6cd32019-09-21 00:28:49 -04001856 return PyNumber_Power(base, exp, mod);
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001857}
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001858
1859
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001860/* AC: cannot convert yet, waiting for *args support */
Guido van Rossum34343512006-11-30 22:13:52 +00001861static PyObject *
Serhiy Storchakaa5552f02017-12-15 13:11:11 +02001862builtin_print(PyObject *self, PyObject *const *args, Py_ssize_t nargs, PyObject *kwnames)
Guido van Rossum34343512006-11-30 22:13:52 +00001863{
INADA Naokibd584f12017-01-19 12:50:34 +01001864 static const char * const _keywords[] = {"sep", "end", "file", "flush", 0};
Serhiy Storchaka1f21eaa2019-09-01 12:16:51 +03001865 static struct _PyArg_Parser _parser = {"|OOOp:print", _keywords, 0};
1866 PyObject *sep = NULL, *end = NULL, *file = NULL;
1867 int flush = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001868 int i, err;
Guido van Rossum34343512006-11-30 22:13:52 +00001869
INADA Naokibd584f12017-01-19 12:50:34 +01001870 if (kwnames != NULL &&
1871 !_PyArg_ParseStackAndKeywords(args + nargs, 0, kwnames, &_parser,
1872 &sep, &end, &file, &flush)) {
Georg Brandlbc3b6822012-01-13 19:41:25 +01001873 return NULL;
INADA Naokibd584f12017-01-19 12:50:34 +01001874 }
1875
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001876 if (file == NULL || file == Py_None) {
Victor Stinnerbd303c12013-11-07 23:07:29 +01001877 file = _PySys_GetObjectId(&PyId_stdout);
Victor Stinner1e53bba2013-07-16 22:26:05 +02001878 if (file == NULL) {
1879 PyErr_SetString(PyExc_RuntimeError, "lost sys.stdout");
1880 return NULL;
1881 }
1882
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001883 /* sys.stdout may be None when FILE* stdout isn't connected */
1884 if (file == Py_None)
1885 Py_RETURN_NONE;
1886 }
Guido van Rossum34343512006-11-30 22:13:52 +00001887
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001888 if (sep == Py_None) {
1889 sep = NULL;
1890 }
1891 else if (sep && !PyUnicode_Check(sep)) {
1892 PyErr_Format(PyExc_TypeError,
1893 "sep must be None or a string, not %.200s",
Victor Stinnera102ed72020-02-07 02:24:48 +01001894 Py_TYPE(sep)->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001895 return NULL;
1896 }
1897 if (end == Py_None) {
1898 end = NULL;
1899 }
1900 else if (end && !PyUnicode_Check(end)) {
1901 PyErr_Format(PyExc_TypeError,
1902 "end must be None or a string, not %.200s",
Victor Stinnera102ed72020-02-07 02:24:48 +01001903 Py_TYPE(end)->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001904 return NULL;
1905 }
Guido van Rossum34343512006-11-30 22:13:52 +00001906
INADA Naokibd584f12017-01-19 12:50:34 +01001907 for (i = 0; i < nargs; i++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001908 if (i > 0) {
1909 if (sep == NULL)
1910 err = PyFile_WriteString(" ", file);
1911 else
1912 err = PyFile_WriteObject(sep, file,
1913 Py_PRINT_RAW);
1914 if (err)
1915 return NULL;
1916 }
INADA Naokibd584f12017-01-19 12:50:34 +01001917 err = PyFile_WriteObject(args[i], file, Py_PRINT_RAW);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001918 if (err)
1919 return NULL;
1920 }
Guido van Rossum34343512006-11-30 22:13:52 +00001921
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001922 if (end == NULL)
1923 err = PyFile_WriteString("\n", file);
1924 else
1925 err = PyFile_WriteObject(end, file, Py_PRINT_RAW);
1926 if (err)
1927 return NULL;
Guido van Rossum34343512006-11-30 22:13:52 +00001928
Serhiy Storchaka1f21eaa2019-09-01 12:16:51 +03001929 if (flush) {
1930 PyObject *tmp = _PyObject_CallMethodIdNoArgs(file, &PyId_flush);
1931 if (tmp == NULL)
Georg Brandlbc3b6822012-01-13 19:41:25 +01001932 return NULL;
Serhiy Storchaka1f21eaa2019-09-01 12:16:51 +03001933 Py_DECREF(tmp);
Georg Brandlbc3b6822012-01-13 19:41:25 +01001934 }
1935
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001936 Py_RETURN_NONE;
Guido van Rossum34343512006-11-30 22:13:52 +00001937}
1938
1939PyDoc_STRVAR(print_doc,
Senthil Kumarane9175bd2012-08-10 13:53:45 -07001940"print(value, ..., sep=' ', end='\\n', file=sys.stdout, flush=False)\n\
Guido van Rossum34343512006-11-30 22:13:52 +00001941\n\
1942Prints the values to a stream, or to sys.stdout by default.\n\
1943Optional keyword arguments:\n\
Senthil Kumarane9175bd2012-08-10 13:53:45 -07001944file: a file-like object (stream); defaults to the current sys.stdout.\n\
1945sep: string inserted between values, default a space.\n\
1946end: string appended after the last value, default a newline.\n\
1947flush: whether to forcibly flush the stream.");
Guido van Rossum34343512006-11-30 22:13:52 +00001948
1949
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001950/*[clinic input]
1951input as builtin_input
1952
1953 prompt: object(c_default="NULL") = None
1954 /
1955
1956Read a string from standard input. The trailing newline is stripped.
1957
1958The prompt string, if given, is printed to standard output without a
1959trailing newline before reading input.
1960
1961If the user hits EOF (*nix: Ctrl-D, Windows: Ctrl-Z+Return), raise EOFError.
1962On *nix systems, readline is used if available.
1963[clinic start generated code]*/
1964
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001965static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001966builtin_input_impl(PyObject *module, PyObject *prompt)
1967/*[clinic end generated code: output=83db5a191e7a0d60 input=5e8bb70c2908fe3c]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001968{
Victor Stinnerbd303c12013-11-07 23:07:29 +01001969 PyObject *fin = _PySys_GetObjectId(&PyId_stdin);
1970 PyObject *fout = _PySys_GetObjectId(&PyId_stdout);
1971 PyObject *ferr = _PySys_GetObjectId(&PyId_stderr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001972 PyObject *tmp;
1973 long fd;
1974 int tty;
Guido van Rossuma88a0332007-02-26 16:59:55 +00001975
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001976 /* Check that stdin/out/err are intact */
1977 if (fin == NULL || fin == Py_None) {
1978 PyErr_SetString(PyExc_RuntimeError,
1979 "input(): lost sys.stdin");
1980 return NULL;
1981 }
1982 if (fout == NULL || fout == Py_None) {
1983 PyErr_SetString(PyExc_RuntimeError,
1984 "input(): lost sys.stdout");
1985 return NULL;
1986 }
1987 if (ferr == NULL || ferr == Py_None) {
1988 PyErr_SetString(PyExc_RuntimeError,
1989 "input(): lost sys.stderr");
1990 return NULL;
1991 }
Guido van Rossumeba76962007-05-27 09:13:28 +00001992
Steve Dowerb82e17e2019-05-23 08:45:22 -07001993 if (PySys_Audit("builtins.input", "O", prompt ? prompt : Py_None) < 0) {
1994 return NULL;
1995 }
1996
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001997 /* First of all, flush stderr */
Jeroen Demeyer762f93f2019-07-08 10:19:25 +02001998 tmp = _PyObject_CallMethodIdNoArgs(ferr, &PyId_flush);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001999 if (tmp == NULL)
2000 PyErr_Clear();
2001 else
2002 Py_DECREF(tmp);
Guido van Rossumeba76962007-05-27 09:13:28 +00002003
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002004 /* We should only use (GNU) readline if Python's sys.stdin and
2005 sys.stdout are the same as C's stdin and stdout, because we
2006 need to pass it those. */
Jeroen Demeyer762f93f2019-07-08 10:19:25 +02002007 tmp = _PyObject_CallMethodIdNoArgs(fin, &PyId_fileno);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002008 if (tmp == NULL) {
2009 PyErr_Clear();
2010 tty = 0;
2011 }
2012 else {
2013 fd = PyLong_AsLong(tmp);
2014 Py_DECREF(tmp);
2015 if (fd < 0 && PyErr_Occurred())
2016 return NULL;
2017 tty = fd == fileno(stdin) && isatty(fd);
2018 }
2019 if (tty) {
Jeroen Demeyer762f93f2019-07-08 10:19:25 +02002020 tmp = _PyObject_CallMethodIdNoArgs(fout, &PyId_fileno);
Martin Panterc9a6ab52015-10-10 01:25:38 +00002021 if (tmp == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002022 PyErr_Clear();
Martin Panterc9a6ab52015-10-10 01:25:38 +00002023 tty = 0;
2024 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002025 else {
2026 fd = PyLong_AsLong(tmp);
2027 Py_DECREF(tmp);
2028 if (fd < 0 && PyErr_Occurred())
2029 return NULL;
2030 tty = fd == fileno(stdout) && isatty(fd);
2031 }
2032 }
Guido van Rossumeba76962007-05-27 09:13:28 +00002033
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002034 /* If we're interactive, use (GNU) readline */
2035 if (tty) {
Antoine Pitrou0d776b12011-11-06 00:34:26 +01002036 PyObject *po = NULL;
Serhiy Storchakae2f92de2017-11-11 13:06:26 +02002037 const char *promptstr;
Antoine Pitrou0d776b12011-11-06 00:34:26 +01002038 char *s = NULL;
2039 PyObject *stdin_encoding = NULL, *stdin_errors = NULL;
2040 PyObject *stdout_encoding = NULL, *stdout_errors = NULL;
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +02002041 const char *stdin_encoding_str, *stdin_errors_str;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002042 PyObject *result;
Victor Stinnerc0f1a1a2011-02-23 12:07:37 +00002043 size_t len;
Martin v. Löwis4a7b5d52007-09-04 05:24:49 +00002044
Serhiy Storchakac2cf1282017-03-12 13:50:36 +02002045 /* stdin is a text stream, so it must have an encoding. */
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02002046 stdin_encoding = _PyObject_GetAttrId(fin, &PyId_encoding);
Antoine Pitrou5ee9d8a2011-11-06 00:38:45 +01002047 stdin_errors = _PyObject_GetAttrId(fin, &PyId_errors);
Serhiy Storchakac2cf1282017-03-12 13:50:36 +02002048 if (!stdin_encoding || !stdin_errors ||
2049 !PyUnicode_Check(stdin_encoding) ||
2050 !PyUnicode_Check(stdin_errors)) {
2051 tty = 0;
Antoine Pitrou0d776b12011-11-06 00:34:26 +01002052 goto _readline_errors;
Serhiy Storchakac2cf1282017-03-12 13:50:36 +02002053 }
Serhiy Storchaka06515832016-11-20 09:13:07 +02002054 stdin_encoding_str = PyUnicode_AsUTF8(stdin_encoding);
2055 stdin_errors_str = PyUnicode_AsUTF8(stdin_errors);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01002056 if (!stdin_encoding_str || !stdin_errors_str)
2057 goto _readline_errors;
Jeroen Demeyer762f93f2019-07-08 10:19:25 +02002058 tmp = _PyObject_CallMethodIdNoArgs(fout, &PyId_flush);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002059 if (tmp == NULL)
2060 PyErr_Clear();
2061 else
2062 Py_DECREF(tmp);
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002063 if (prompt != NULL) {
Antoine Pitrou0d776b12011-11-06 00:34:26 +01002064 /* We have a prompt, encode it as stdout would */
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +02002065 const char *stdout_encoding_str, *stdout_errors_str;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002066 PyObject *stringpo;
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02002067 stdout_encoding = _PyObject_GetAttrId(fout, &PyId_encoding);
Antoine Pitrou5ee9d8a2011-11-06 00:38:45 +01002068 stdout_errors = _PyObject_GetAttrId(fout, &PyId_errors);
Serhiy Storchakac2cf1282017-03-12 13:50:36 +02002069 if (!stdout_encoding || !stdout_errors ||
2070 !PyUnicode_Check(stdout_encoding) ||
2071 !PyUnicode_Check(stdout_errors)) {
2072 tty = 0;
Antoine Pitrou0d776b12011-11-06 00:34:26 +01002073 goto _readline_errors;
Serhiy Storchakac2cf1282017-03-12 13:50:36 +02002074 }
Serhiy Storchaka06515832016-11-20 09:13:07 +02002075 stdout_encoding_str = PyUnicode_AsUTF8(stdout_encoding);
2076 stdout_errors_str = PyUnicode_AsUTF8(stdout_errors);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01002077 if (!stdout_encoding_str || !stdout_errors_str)
2078 goto _readline_errors;
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002079 stringpo = PyObject_Str(prompt);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01002080 if (stringpo == NULL)
2081 goto _readline_errors;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002082 po = PyUnicode_AsEncodedString(stringpo,
Antoine Pitrou0d776b12011-11-06 00:34:26 +01002083 stdout_encoding_str, stdout_errors_str);
2084 Py_CLEAR(stdout_encoding);
2085 Py_CLEAR(stdout_errors);
2086 Py_CLEAR(stringpo);
2087 if (po == NULL)
2088 goto _readline_errors;
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03002089 assert(PyBytes_Check(po));
2090 promptstr = PyBytes_AS_STRING(po);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002091 }
2092 else {
2093 po = NULL;
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002094 promptstr = "";
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002095 }
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002096 s = PyOS_Readline(stdin, stdout, promptstr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002097 if (s == NULL) {
Richard Oudkerk614c5782013-04-03 13:44:50 +01002098 PyErr_CheckSignals();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002099 if (!PyErr_Occurred())
2100 PyErr_SetNone(PyExc_KeyboardInterrupt);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01002101 goto _readline_errors;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002102 }
Victor Stinnerc0f1a1a2011-02-23 12:07:37 +00002103
2104 len = strlen(s);
2105 if (len == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002106 PyErr_SetNone(PyExc_EOFError);
2107 result = NULL;
2108 }
Victor Stinnerc0f1a1a2011-02-23 12:07:37 +00002109 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002110 if (len > PY_SSIZE_T_MAX) {
2111 PyErr_SetString(PyExc_OverflowError,
2112 "input: input too long");
2113 result = NULL;
2114 }
2115 else {
Victor Stinnerc0f1a1a2011-02-23 12:07:37 +00002116 len--; /* strip trailing '\n' */
2117 if (len != 0 && s[len-1] == '\r')
2118 len--; /* strip trailing '\r' */
Antoine Pitrou0d776b12011-11-06 00:34:26 +01002119 result = PyUnicode_Decode(s, len, stdin_encoding_str,
2120 stdin_errors_str);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002121 }
2122 }
2123 Py_DECREF(stdin_encoding);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01002124 Py_DECREF(stdin_errors);
2125 Py_XDECREF(po);
Victor Stinner00d7abd2020-12-01 09:56:42 +01002126 PyMem_Free(s);
Steve Dowerb82e17e2019-05-23 08:45:22 -07002127
2128 if (result != NULL) {
2129 if (PySys_Audit("builtins.input/result", "O", result) < 0) {
2130 return NULL;
2131 }
2132 }
2133
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002134 return result;
Serhiy Storchakac2cf1282017-03-12 13:50:36 +02002135
Antoine Pitrou0d776b12011-11-06 00:34:26 +01002136 _readline_errors:
2137 Py_XDECREF(stdin_encoding);
2138 Py_XDECREF(stdout_encoding);
2139 Py_XDECREF(stdin_errors);
2140 Py_XDECREF(stdout_errors);
2141 Py_XDECREF(po);
Serhiy Storchakac2cf1282017-03-12 13:50:36 +02002142 if (tty)
2143 return NULL;
2144
2145 PyErr_Clear();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002146 }
Guido van Rossumeba76962007-05-27 09:13:28 +00002147
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002148 /* Fallback if we're not interactive */
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002149 if (prompt != NULL) {
2150 if (PyFile_WriteObject(prompt, fout, Py_PRINT_RAW) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002151 return NULL;
2152 }
Jeroen Demeyer762f93f2019-07-08 10:19:25 +02002153 tmp = _PyObject_CallMethodIdNoArgs(fout, &PyId_flush);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002154 if (tmp == NULL)
2155 PyErr_Clear();
2156 else
2157 Py_DECREF(tmp);
2158 return PyFile_GetLine(fin, -1);
Guido van Rossuma88a0332007-02-26 16:59:55 +00002159}
2160
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002161
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002162/*[clinic input]
2163repr as builtin_repr
2164
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03002165 obj: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002166 /
2167
2168Return the canonical string representation of the object.
2169
2170For many object types, including most builtins, eval(repr(obj)) == obj.
2171[clinic start generated code]*/
2172
Guido van Rossum79f25d91997-04-29 20:08:16 +00002173static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002174builtin_repr(PyObject *module, PyObject *obj)
2175/*[clinic end generated code: output=7ed3778c44fd0194 input=1c9e6d66d3e3be04]*/
Guido van Rossumc89705d1992-11-26 08:54:07 +00002176{
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002177 return PyObject_Repr(obj);
Guido van Rossumc89705d1992-11-26 08:54:07 +00002178}
2179
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002180
Serhiy Storchakaaca7f572017-11-15 17:51:14 +02002181/*[clinic input]
2182round as builtin_round
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002183
Serhiy Storchakaaca7f572017-11-15 17:51:14 +02002184 number: object
Serhiy Storchaka279f4462019-09-14 12:24:05 +03002185 ndigits: object = None
Serhiy Storchakaaca7f572017-11-15 17:51:14 +02002186
2187Round a number to a given precision in decimal digits.
2188
2189The return value is an integer if ndigits is omitted or None. Otherwise
2190the return value has the same type as the number. ndigits may be negative.
2191[clinic start generated code]*/
2192
2193static PyObject *
2194builtin_round_impl(PyObject *module, PyObject *number, PyObject *ndigits)
Serhiy Storchaka279f4462019-09-14 12:24:05 +03002195/*[clinic end generated code: output=ff0d9dd176c02ede input=275678471d7aca15]*/
Serhiy Storchakaaca7f572017-11-15 17:51:14 +02002196{
2197 PyObject *round, *result;
Alex Martelliae211f92007-08-22 23:21:33 +00002198
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002199 if (Py_TYPE(number)->tp_dict == NULL) {
2200 if (PyType_Ready(Py_TYPE(number)) < 0)
2201 return NULL;
2202 }
Guido van Rossum15d3d042007-08-24 02:02:45 +00002203
Benjamin Peterson214a7d22013-04-13 17:19:01 -04002204 round = _PyObject_LookupSpecial(number, &PyId___round__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002205 if (round == NULL) {
Benjamin Peterson214a7d22013-04-13 17:19:01 -04002206 if (!PyErr_Occurred())
2207 PyErr_Format(PyExc_TypeError,
2208 "type %.100s doesn't define __round__ method",
2209 Py_TYPE(number)->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002210 return NULL;
2211 }
Alex Martelliae211f92007-08-22 23:21:33 +00002212
Serhiy Storchaka279f4462019-09-14 12:24:05 +03002213 if (ndigits == Py_None)
Victor Stinnerf17c3de2016-12-06 18:46:19 +01002214 result = _PyObject_CallNoArg(round);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002215 else
Petr Viktorinffd97532020-02-11 17:46:57 +01002216 result = PyObject_CallOneArg(round, ndigits);
Benjamin Peterson214a7d22013-04-13 17:19:01 -04002217 Py_DECREF(round);
2218 return result;
Guido van Rossum9e51f9b1993-02-12 16:29:05 +00002219}
2220
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002221
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002222/*AC: we need to keep the kwds dict intact to easily call into the
2223 * list.sort method, which isn't currently supported in AC. So we just use
2224 * the initially generated signature with a custom implementation.
2225 */
2226/* [disabled clinic input]
2227sorted as builtin_sorted
2228
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03002229 iterable as seq: object
2230 key as keyfunc: object = None
2231 reverse: object = False
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002232
2233Return a new list containing all items from the iterable in ascending order.
2234
Raymond Hettinger7ea386e2016-08-25 21:11:50 -07002235A custom key function can be supplied to customize the sort order, and the
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002236reverse flag can be set to request the result in descending order.
2237[end disabled clinic input]*/
2238
2239PyDoc_STRVAR(builtin_sorted__doc__,
Serhiy Storchaka3a104252017-01-23 12:29:47 +02002240"sorted($module, iterable, /, *, key=None, reverse=False)\n"
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002241"--\n"
2242"\n"
2243"Return a new list containing all items from the iterable in ascending order.\n"
2244"\n"
Raymond Hettinger7ea386e2016-08-25 21:11:50 -07002245"A custom key function can be supplied to customize the sort order, and the\n"
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002246"reverse flag can be set to request the result in descending order.");
2247
2248#define BUILTIN_SORTED_METHODDEF \
Serhiy Storchaka62be7422018-11-27 13:27:31 +02002249 {"sorted", (PyCFunction)(void(*)(void))builtin_sorted, METH_FASTCALL | METH_KEYWORDS, builtin_sorted__doc__},
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002250
Raymond Hettinger64958a12003-12-17 20:43:33 +00002251static PyObject *
Serhiy Storchakaa5552f02017-12-15 13:11:11 +02002252builtin_sorted(PyObject *self, PyObject *const *args, Py_ssize_t nargs, PyObject *kwnames)
Raymond Hettinger64958a12003-12-17 20:43:33 +00002253{
Serhiy Storchaka7cf8beb2017-01-21 23:05:00 +02002254 PyObject *newlist, *v, *seq, *callable;
Victor Stinner5a60eca2017-01-17 15:17:49 +01002255
Serhiy Storchaka7cf8beb2017-01-21 23:05:00 +02002256 /* Keyword arguments are passed through list.sort() which will check
2257 them. */
2258 if (!_PyArg_UnpackStack(args, nargs, "sorted", 1, 1, &seq))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002259 return NULL;
Raymond Hettinger64958a12003-12-17 20:43:33 +00002260
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002261 newlist = PySequence_List(seq);
2262 if (newlist == NULL)
2263 return NULL;
Raymond Hettinger64958a12003-12-17 20:43:33 +00002264
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02002265 callable = _PyObject_GetAttrId(newlist, &PyId_sort);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002266 if (callable == NULL) {
2267 Py_DECREF(newlist);
2268 return NULL;
2269 }
Georg Brandl99d7e4e2005-08-31 22:21:15 +00002270
Serhiy Storchaka299dc232017-01-20 08:35:18 +02002271 assert(nargs >= 1);
Petr Viktorinffd97532020-02-11 17:46:57 +01002272 v = PyObject_Vectorcall(callable, args + 1, nargs - 1, kwnames);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002273 Py_DECREF(callable);
2274 if (v == NULL) {
2275 Py_DECREF(newlist);
2276 return NULL;
2277 }
2278 Py_DECREF(v);
2279 return newlist;
Raymond Hettinger64958a12003-12-17 20:43:33 +00002280}
2281
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002282
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002283/* AC: cannot convert yet, as needs PEP 457 group support in inspect */
Guido van Rossum79f25d91997-04-29 20:08:16 +00002284static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002285builtin_vars(PyObject *self, PyObject *args)
Guido van Rossum2d951851994-08-29 12:52:16 +00002286{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002287 PyObject *v = NULL;
2288 PyObject *d;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002289
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002290 if (!PyArg_UnpackTuple(args, "vars", 0, 1, &v))
2291 return NULL;
2292 if (v == NULL) {
2293 d = PyEval_GetLocals();
Serhiy Storchaka41c57b32019-09-01 12:03:39 +03002294 Py_XINCREF(d);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002295 }
2296 else {
Serhiy Storchaka41c57b32019-09-01 12:03:39 +03002297 if (_PyObject_LookupAttrId(v, &PyId___dict__, &d) == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002298 PyErr_SetString(PyExc_TypeError,
2299 "vars() argument must have __dict__ attribute");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002300 }
2301 }
2302 return d;
Guido van Rossum2d951851994-08-29 12:52:16 +00002303}
2304
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002305PyDoc_STRVAR(vars_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002306"vars([object]) -> dictionary\n\
2307\n\
2308Without arguments, equivalent to locals().\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002309With an argument, equivalent to object.__dict__.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002310
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002311
2312/*[clinic input]
2313sum as builtin_sum
2314
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03002315 iterable: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002316 /
Raymond Hettinger9dfa0fe2018-09-12 10:54:06 -07002317 start: object(c_default="NULL") = 0
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002318
2319Return the sum of a 'start' value (default: 0) plus an iterable of numbers
2320
2321When the iterable is empty, return the start value.
2322This function is intended specifically for use with numeric values and may
2323reject non-numeric types.
2324[clinic start generated code]*/
2325
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002326static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002327builtin_sum_impl(PyObject *module, PyObject *iterable, PyObject *start)
Raymond Hettinger9dfa0fe2018-09-12 10:54:06 -07002328/*[clinic end generated code: output=df758cec7d1d302f input=162b50765250d222]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002329{
2330 PyObject *result = start;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002331 PyObject *temp, *item, *iter;
Alex Martellia70b1912003-04-22 08:12:33 +00002332
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002333 iter = PyObject_GetIter(iterable);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002334 if (iter == NULL)
2335 return NULL;
Alex Martellia70b1912003-04-22 08:12:33 +00002336
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002337 if (result == NULL) {
2338 result = PyLong_FromLong(0);
2339 if (result == NULL) {
2340 Py_DECREF(iter);
2341 return NULL;
2342 }
2343 } else {
2344 /* reject string values for 'start' parameter */
2345 if (PyUnicode_Check(result)) {
2346 PyErr_SetString(PyExc_TypeError,
2347 "sum() can't sum strings [use ''.join(seq) instead]");
2348 Py_DECREF(iter);
2349 return NULL;
2350 }
Benjamin Petersonce071ca2011-07-29 14:23:47 -05002351 if (PyBytes_Check(result)) {
2352 PyErr_SetString(PyExc_TypeError,
2353 "sum() can't sum bytes [use b''.join(seq) instead]");
Benjamin Peterson405f32c2011-07-29 22:43:45 -05002354 Py_DECREF(iter);
Benjamin Petersonce071ca2011-07-29 14:23:47 -05002355 return NULL;
2356 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002357 if (PyByteArray_Check(result)) {
2358 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson4f921c22011-07-29 14:24:29 -05002359 "sum() can't sum bytearray [use b''.join(seq) instead]");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002360 Py_DECREF(iter);
2361 return NULL;
2362 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002363 Py_INCREF(result);
2364 }
Alex Martellia70b1912003-04-22 08:12:33 +00002365
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002366#ifndef SLOW_SUM
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002367 /* Fast addition by keeping temporary sums in C instead of new Python objects.
2368 Assumes all inputs are the same type. If the assumption fails, default
2369 to the more general routine.
2370 */
2371 if (PyLong_CheckExact(result)) {
2372 int overflow;
2373 long i_result = PyLong_AsLongAndOverflow(result, &overflow);
2374 /* If this already overflowed, don't even enter the loop. */
2375 if (overflow == 0) {
2376 Py_DECREF(result);
2377 result = NULL;
2378 }
2379 while(result == NULL) {
2380 item = PyIter_Next(iter);
2381 if (item == NULL) {
2382 Py_DECREF(iter);
2383 if (PyErr_Occurred())
2384 return NULL;
2385 return PyLong_FromLong(i_result);
2386 }
Serhiy Storchaka88bdb922019-09-10 16:31:01 +03002387 if (PyLong_CheckExact(item) || PyBool_Check(item)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002388 long b = PyLong_AsLongAndOverflow(item, &overflow);
Serhiy Storchaka29500732019-05-05 14:26:23 +03002389 if (overflow == 0 &&
2390 (i_result >= 0 ? (b <= LONG_MAX - i_result)
2391 : (b >= LONG_MIN - i_result)))
2392 {
2393 i_result += b;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002394 Py_DECREF(item);
2395 continue;
2396 }
2397 }
2398 /* Either overflowed or is not an int. Restore real objects and process normally */
2399 result = PyLong_FromLong(i_result);
Christian Heimes704e2d32013-07-26 22:49:26 +02002400 if (result == NULL) {
2401 Py_DECREF(item);
2402 Py_DECREF(iter);
2403 return NULL;
2404 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002405 temp = PyNumber_Add(result, item);
2406 Py_DECREF(result);
2407 Py_DECREF(item);
2408 result = temp;
2409 if (result == NULL) {
2410 Py_DECREF(iter);
2411 return NULL;
2412 }
2413 }
2414 }
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002415
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002416 if (PyFloat_CheckExact(result)) {
2417 double f_result = PyFloat_AS_DOUBLE(result);
2418 Py_DECREF(result);
2419 result = NULL;
2420 while(result == NULL) {
2421 item = PyIter_Next(iter);
2422 if (item == NULL) {
2423 Py_DECREF(iter);
2424 if (PyErr_Occurred())
2425 return NULL;
2426 return PyFloat_FromDouble(f_result);
2427 }
2428 if (PyFloat_CheckExact(item)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002429 f_result += PyFloat_AS_DOUBLE(item);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002430 Py_DECREF(item);
2431 continue;
2432 }
Serhiy Storchaka88bdb922019-09-10 16:31:01 +03002433 if (PyLong_Check(item)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002434 long value;
2435 int overflow;
2436 value = PyLong_AsLongAndOverflow(item, &overflow);
2437 if (!overflow) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002438 f_result += (double)value;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002439 Py_DECREF(item);
2440 continue;
2441 }
2442 }
2443 result = PyFloat_FromDouble(f_result);
Alexey Izbyshev2b824b22018-08-24 07:27:52 +03002444 if (result == NULL) {
2445 Py_DECREF(item);
2446 Py_DECREF(iter);
2447 return NULL;
2448 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002449 temp = PyNumber_Add(result, item);
2450 Py_DECREF(result);
2451 Py_DECREF(item);
2452 result = temp;
2453 if (result == NULL) {
2454 Py_DECREF(iter);
2455 return NULL;
2456 }
2457 }
2458 }
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002459#endif
2460
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002461 for(;;) {
2462 item = PyIter_Next(iter);
2463 if (item == NULL) {
2464 /* error, or end-of-sequence */
2465 if (PyErr_Occurred()) {
2466 Py_DECREF(result);
2467 result = NULL;
2468 }
2469 break;
2470 }
2471 /* It's tempting to use PyNumber_InPlaceAdd instead of
2472 PyNumber_Add here, to avoid quadratic running time
2473 when doing 'sum(list_of_lists, [])'. However, this
2474 would produce a change in behaviour: a snippet like
Mark Dickinson9acadc52009-10-26 14:19:42 +00002475
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002476 empty = []
2477 sum([[x] for x in range(10)], empty)
Mark Dickinson9acadc52009-10-26 14:19:42 +00002478
Brandt Bucherabb9a442020-02-01 03:08:34 -08002479 would change the value of empty. In fact, using
2480 in-place addition rather that binary addition for
2481 any of the steps introduces subtle behavior changes:
Victor Stinner58f4e1a2020-02-05 18:24:33 +01002482
Brandt Bucherabb9a442020-02-01 03:08:34 -08002483 https://bugs.python.org/issue18305 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002484 temp = PyNumber_Add(result, item);
2485 Py_DECREF(result);
2486 Py_DECREF(item);
2487 result = temp;
2488 if (result == NULL)
2489 break;
2490 }
2491 Py_DECREF(iter);
2492 return result;
Alex Martellia70b1912003-04-22 08:12:33 +00002493}
2494
Alex Martellia70b1912003-04-22 08:12:33 +00002495
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002496/*[clinic input]
2497isinstance as builtin_isinstance
2498
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03002499 obj: object
2500 class_or_tuple: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002501 /
2502
2503Return whether an object is an instance of a class or of a subclass thereof.
2504
2505A tuple, as in ``isinstance(x, (A, B, ...))``, may be given as the target to
2506check against. This is equivalent to ``isinstance(x, A) or isinstance(x, B)
2507or ...`` etc.
2508[clinic start generated code]*/
2509
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002510static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002511builtin_isinstance_impl(PyObject *module, PyObject *obj,
Larry Hastings89964c42015-04-14 18:07:59 -04002512 PyObject *class_or_tuple)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002513/*[clinic end generated code: output=6faf01472c13b003 input=ffa743db1daf7549]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002514{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002515 int retval;
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002516
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002517 retval = PyObject_IsInstance(obj, class_or_tuple);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002518 if (retval < 0)
2519 return NULL;
2520 return PyBool_FromLong(retval);
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002521}
2522
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002523
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002524/*[clinic input]
2525issubclass as builtin_issubclass
2526
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03002527 cls: object
2528 class_or_tuple: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002529 /
2530
Alex Poveldf773f82020-06-03 15:19:45 +02002531Return whether 'cls' is derived from another class or is the same class.
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002532
2533A tuple, as in ``issubclass(x, (A, B, ...))``, may be given as the target to
2534check against. This is equivalent to ``issubclass(x, A) or issubclass(x, B)
Alex Poveldf773f82020-06-03 15:19:45 +02002535or ...``.
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002536[clinic start generated code]*/
2537
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002538static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002539builtin_issubclass_impl(PyObject *module, PyObject *cls,
Larry Hastings89964c42015-04-14 18:07:59 -04002540 PyObject *class_or_tuple)
Alex Poveldf773f82020-06-03 15:19:45 +02002541/*[clinic end generated code: output=358412410cd7a250 input=a24b9f3d58c370d6]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002542{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002543 int retval;
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002544
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002545 retval = PyObject_IsSubclass(cls, class_or_tuple);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002546 if (retval < 0)
2547 return NULL;
2548 return PyBool_FromLong(retval);
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002549}
2550
2551
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002552typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002553 PyObject_HEAD
Guido van Rossum310f6aa2020-06-19 03:16:57 -07002554 Py_ssize_t tuplesize;
2555 PyObject *ittuple; /* tuple of iterators */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002556 PyObject *result;
Guido van Rossum310f6aa2020-06-19 03:16:57 -07002557 int strict;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002558} zipobject;
2559
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002560static PyObject *
2561zip_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
Barry Warsawbd599b52000-08-03 15:45:29 +00002562{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002563 zipobject *lz;
2564 Py_ssize_t i;
2565 PyObject *ittuple; /* tuple of iterators */
2566 PyObject *result;
Serhiy Storchakabf623ae2017-04-19 20:03:52 +03002567 Py_ssize_t tuplesize;
Guido van Rossum310f6aa2020-06-19 03:16:57 -07002568 int strict = 0;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002569
Guido van Rossum310f6aa2020-06-19 03:16:57 -07002570 if (kwds) {
2571 PyObject *empty = PyTuple_New(0);
2572 if (empty == NULL) {
2573 return NULL;
2574 }
2575 static char *kwlist[] = {"strict", NULL};
2576 int parsed = PyArg_ParseTupleAndKeywords(
2577 empty, kwds, "|$p:zip", kwlist, &strict);
2578 Py_DECREF(empty);
2579 if (!parsed) {
2580 return NULL;
2581 }
2582 }
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002583
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002584 /* args must be a tuple */
2585 assert(PyTuple_Check(args));
Serhiy Storchakabf623ae2017-04-19 20:03:52 +03002586 tuplesize = PyTuple_GET_SIZE(args);
Barry Warsawbd599b52000-08-03 15:45:29 +00002587
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002588 /* obtain iterators */
2589 ittuple = PyTuple_New(tuplesize);
2590 if (ittuple == NULL)
2591 return NULL;
2592 for (i=0; i < tuplesize; ++i) {
2593 PyObject *item = PyTuple_GET_ITEM(args, i);
2594 PyObject *it = PyObject_GetIter(item);
2595 if (it == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002596 Py_DECREF(ittuple);
2597 return NULL;
2598 }
2599 PyTuple_SET_ITEM(ittuple, i, it);
2600 }
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002601
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002602 /* create a result holder */
2603 result = PyTuple_New(tuplesize);
2604 if (result == NULL) {
2605 Py_DECREF(ittuple);
2606 return NULL;
2607 }
2608 for (i=0 ; i < tuplesize ; i++) {
2609 Py_INCREF(Py_None);
2610 PyTuple_SET_ITEM(result, i, Py_None);
2611 }
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002612
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002613 /* create zipobject structure */
2614 lz = (zipobject *)type->tp_alloc(type, 0);
2615 if (lz == NULL) {
2616 Py_DECREF(ittuple);
2617 Py_DECREF(result);
2618 return NULL;
2619 }
2620 lz->ittuple = ittuple;
2621 lz->tuplesize = tuplesize;
2622 lz->result = result;
Guido van Rossum310f6aa2020-06-19 03:16:57 -07002623 lz->strict = strict;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002624
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002625 return (PyObject *)lz;
Barry Warsawbd599b52000-08-03 15:45:29 +00002626}
2627
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002628static void
2629zip_dealloc(zipobject *lz)
2630{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002631 PyObject_GC_UnTrack(lz);
2632 Py_XDECREF(lz->ittuple);
2633 Py_XDECREF(lz->result);
2634 Py_TYPE(lz)->tp_free(lz);
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002635}
2636
2637static int
2638zip_traverse(zipobject *lz, visitproc visit, void *arg)
2639{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002640 Py_VISIT(lz->ittuple);
2641 Py_VISIT(lz->result);
2642 return 0;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002643}
2644
2645static PyObject *
2646zip_next(zipobject *lz)
2647{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002648 Py_ssize_t i;
2649 Py_ssize_t tuplesize = lz->tuplesize;
2650 PyObject *result = lz->result;
2651 PyObject *it;
2652 PyObject *item;
2653 PyObject *olditem;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002654
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002655 if (tuplesize == 0)
2656 return NULL;
2657 if (Py_REFCNT(result) == 1) {
2658 Py_INCREF(result);
2659 for (i=0 ; i < tuplesize ; i++) {
2660 it = PyTuple_GET_ITEM(lz->ittuple, i);
2661 item = (*Py_TYPE(it)->tp_iternext)(it);
Serhiy Storchaka278d03b2013-04-06 22:52:34 +03002662 if (item == NULL) {
2663 Py_DECREF(result);
Guido van Rossum310f6aa2020-06-19 03:16:57 -07002664 if (lz->strict) {
2665 goto check;
2666 }
Serhiy Storchaka278d03b2013-04-06 22:52:34 +03002667 return NULL;
2668 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002669 olditem = PyTuple_GET_ITEM(result, i);
2670 PyTuple_SET_ITEM(result, i, item);
2671 Py_DECREF(olditem);
2672 }
Brandt Bucher226a0122020-12-04 19:45:57 -08002673 // bpo-42536: The GC may have untracked this result tuple. Since we're
2674 // recycling it, make sure it's tracked again:
2675 if (!_PyObject_GC_IS_TRACKED(result)) {
2676 _PyObject_GC_TRACK(result);
2677 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002678 } else {
2679 result = PyTuple_New(tuplesize);
2680 if (result == NULL)
Serhiy Storchaka278d03b2013-04-06 22:52:34 +03002681 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002682 for (i=0 ; i < tuplesize ; i++) {
2683 it = PyTuple_GET_ITEM(lz->ittuple, i);
2684 item = (*Py_TYPE(it)->tp_iternext)(it);
Serhiy Storchaka278d03b2013-04-06 22:52:34 +03002685 if (item == NULL) {
2686 Py_DECREF(result);
Guido van Rossum310f6aa2020-06-19 03:16:57 -07002687 if (lz->strict) {
2688 goto check;
2689 }
Serhiy Storchaka278d03b2013-04-06 22:52:34 +03002690 return NULL;
2691 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002692 PyTuple_SET_ITEM(result, i, item);
2693 }
2694 }
2695 return result;
Guido van Rossum310f6aa2020-06-19 03:16:57 -07002696check:
2697 if (PyErr_Occurred()) {
2698 if (!PyErr_ExceptionMatches(PyExc_StopIteration)) {
2699 // next() on argument i raised an exception (not StopIteration)
2700 return NULL;
2701 }
2702 PyErr_Clear();
2703 }
2704 if (i) {
2705 // ValueError: zip() argument 2 is shorter than argument 1
2706 // ValueError: zip() argument 3 is shorter than arguments 1-2
2707 const char* plural = i == 1 ? " " : "s 1-";
2708 return PyErr_Format(PyExc_ValueError,
2709 "zip() argument %d is shorter than argument%s%d",
2710 i + 1, plural, i);
2711 }
2712 for (i = 1; i < tuplesize; i++) {
2713 it = PyTuple_GET_ITEM(lz->ittuple, i);
2714 item = (*Py_TYPE(it)->tp_iternext)(it);
2715 if (item) {
2716 Py_DECREF(item);
2717 const char* plural = i == 1 ? " " : "s 1-";
2718 return PyErr_Format(PyExc_ValueError,
2719 "zip() argument %d is longer than argument%s%d",
2720 i + 1, plural, i);
2721 }
2722 if (PyErr_Occurred()) {
2723 if (!PyErr_ExceptionMatches(PyExc_StopIteration)) {
2724 // next() on argument i raised an exception (not StopIteration)
2725 return NULL;
2726 }
2727 PyErr_Clear();
2728 }
2729 // Argument i is exhausted. So far so good...
2730 }
2731 // All arguments are exhausted. Success!
2732 return NULL;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002733}
Barry Warsawbd599b52000-08-03 15:45:29 +00002734
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002735static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05302736zip_reduce(zipobject *lz, PyObject *Py_UNUSED(ignored))
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002737{
2738 /* Just recreate the zip with the internal iterator tuple */
Guido van Rossum310f6aa2020-06-19 03:16:57 -07002739 if (lz->strict) {
2740 return PyTuple_Pack(3, Py_TYPE(lz), lz->ittuple, Py_True);
2741 }
2742 return PyTuple_Pack(2, Py_TYPE(lz), lz->ittuple);
2743}
2744
2745PyDoc_STRVAR(setstate_doc, "Set state information for unpickling.");
2746
2747static PyObject *
2748zip_setstate(zipobject *lz, PyObject *state)
2749{
2750 int strict = PyObject_IsTrue(state);
2751 if (strict < 0) {
2752 return NULL;
2753 }
2754 lz->strict = strict;
2755 Py_RETURN_NONE;
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002756}
2757
2758static PyMethodDef zip_methods[] = {
2759 {"__reduce__", (PyCFunction)zip_reduce, METH_NOARGS, reduce_doc},
Guido van Rossum310f6aa2020-06-19 03:16:57 -07002760 {"__setstate__", (PyCFunction)zip_setstate, METH_O, setstate_doc},
2761 {NULL} /* sentinel */
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002762};
2763
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002764PyDoc_STRVAR(zip_doc,
Guido van Rossum310f6aa2020-06-19 03:16:57 -07002765"zip(*iterables, strict=False) --> Yield tuples until an input is exhausted.\n\
Barry Warsawbd599b52000-08-03 15:45:29 +00002766\n\
Gregory P. Smith6a5d3ff2020-05-15 14:26:00 -07002767 >>> list(zip('abcdefg', range(3), range(4)))\n\
2768 [('a', 0, 0), ('b', 1, 1), ('c', 2, 2)]\n\
2769\n\
2770The zip object yields n-length tuples, where n is the number of iterables\n\
2771passed as positional arguments to zip(). The i-th element in every tuple\n\
2772comes from the i-th iterable argument to zip(). This continues until the\n\
Guido van Rossum310f6aa2020-06-19 03:16:57 -07002773shortest argument is exhausted.\n\
2774\n\
2775If strict is true and one of the arguments is exhausted before the others,\n\
2776raise a ValueError.");
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002777
2778PyTypeObject PyZip_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002779 PyVarObject_HEAD_INIT(&PyType_Type, 0)
2780 "zip", /* tp_name */
2781 sizeof(zipobject), /* tp_basicsize */
2782 0, /* tp_itemsize */
2783 /* methods */
2784 (destructor)zip_dealloc, /* tp_dealloc */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02002785 0, /* tp_vectorcall_offset */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002786 0, /* tp_getattr */
2787 0, /* tp_setattr */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02002788 0, /* tp_as_async */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002789 0, /* tp_repr */
2790 0, /* tp_as_number */
2791 0, /* tp_as_sequence */
2792 0, /* tp_as_mapping */
2793 0, /* tp_hash */
2794 0, /* tp_call */
2795 0, /* tp_str */
2796 PyObject_GenericGetAttr, /* tp_getattro */
2797 0, /* tp_setattro */
2798 0, /* tp_as_buffer */
2799 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
2800 Py_TPFLAGS_BASETYPE, /* tp_flags */
2801 zip_doc, /* tp_doc */
2802 (traverseproc)zip_traverse, /* tp_traverse */
2803 0, /* tp_clear */
2804 0, /* tp_richcompare */
2805 0, /* tp_weaklistoffset */
2806 PyObject_SelfIter, /* tp_iter */
2807 (iternextfunc)zip_next, /* tp_iternext */
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002808 zip_methods, /* tp_methods */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002809 0, /* tp_members */
2810 0, /* tp_getset */
2811 0, /* tp_base */
2812 0, /* tp_dict */
2813 0, /* tp_descr_get */
2814 0, /* tp_descr_set */
2815 0, /* tp_dictoffset */
2816 0, /* tp_init */
2817 PyType_GenericAlloc, /* tp_alloc */
2818 zip_new, /* tp_new */
2819 PyObject_GC_Del, /* tp_free */
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002820};
Barry Warsawbd599b52000-08-03 15:45:29 +00002821
2822
Guido van Rossum79f25d91997-04-29 20:08:16 +00002823static PyMethodDef builtin_methods[] = {
Serhiy Storchaka62be7422018-11-27 13:27:31 +02002824 {"__build_class__", (PyCFunction)(void(*)(void))builtin___build_class__,
Serhiy Storchaka6969eaf2017-07-03 21:20:15 +03002825 METH_FASTCALL | METH_KEYWORDS, build_class_doc},
Serhiy Storchaka62be7422018-11-27 13:27:31 +02002826 {"__import__", (PyCFunction)(void(*)(void))builtin___import__, METH_VARARGS | METH_KEYWORDS, import_doc},
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002827 BUILTIN_ABS_METHODDEF
2828 BUILTIN_ALL_METHODDEF
2829 BUILTIN_ANY_METHODDEF
2830 BUILTIN_ASCII_METHODDEF
2831 BUILTIN_BIN_METHODDEF
Serhiy Storchaka62be7422018-11-27 13:27:31 +02002832 {"breakpoint", (PyCFunction)(void(*)(void))builtin_breakpoint, METH_FASTCALL | METH_KEYWORDS, breakpoint_doc},
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002833 BUILTIN_CALLABLE_METHODDEF
2834 BUILTIN_CHR_METHODDEF
2835 BUILTIN_COMPILE_METHODDEF
2836 BUILTIN_DELATTR_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002837 {"dir", builtin_dir, METH_VARARGS, dir_doc},
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002838 BUILTIN_DIVMOD_METHODDEF
2839 BUILTIN_EVAL_METHODDEF
2840 BUILTIN_EXEC_METHODDEF
2841 BUILTIN_FORMAT_METHODDEF
Serhiy Storchaka62be7422018-11-27 13:27:31 +02002842 {"getattr", (PyCFunction)(void(*)(void))builtin_getattr, METH_FASTCALL, getattr_doc},
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002843 BUILTIN_GLOBALS_METHODDEF
2844 BUILTIN_HASATTR_METHODDEF
2845 BUILTIN_HASH_METHODDEF
2846 BUILTIN_HEX_METHODDEF
2847 BUILTIN_ID_METHODDEF
2848 BUILTIN_INPUT_METHODDEF
2849 BUILTIN_ISINSTANCE_METHODDEF
2850 BUILTIN_ISSUBCLASS_METHODDEF
Serhiy Storchaka79342662019-01-12 08:25:41 +02002851 {"iter", (PyCFunction)(void(*)(void))builtin_iter, METH_FASTCALL, iter_doc},
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002852 BUILTIN_LEN_METHODDEF
2853 BUILTIN_LOCALS_METHODDEF
Serhiy Storchaka62be7422018-11-27 13:27:31 +02002854 {"max", (PyCFunction)(void(*)(void))builtin_max, METH_VARARGS | METH_KEYWORDS, max_doc},
2855 {"min", (PyCFunction)(void(*)(void))builtin_min, METH_VARARGS | METH_KEYWORDS, min_doc},
2856 {"next", (PyCFunction)(void(*)(void))builtin_next, METH_FASTCALL, next_doc},
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002857 BUILTIN_OCT_METHODDEF
2858 BUILTIN_ORD_METHODDEF
2859 BUILTIN_POW_METHODDEF
Serhiy Storchaka62be7422018-11-27 13:27:31 +02002860 {"print", (PyCFunction)(void(*)(void))builtin_print, METH_FASTCALL | METH_KEYWORDS, print_doc},
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002861 BUILTIN_REPR_METHODDEF
Serhiy Storchakaaca7f572017-11-15 17:51:14 +02002862 BUILTIN_ROUND_METHODDEF
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002863 BUILTIN_SETATTR_METHODDEF
2864 BUILTIN_SORTED_METHODDEF
2865 BUILTIN_SUM_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002866 {"vars", builtin_vars, METH_VARARGS, vars_doc},
2867 {NULL, NULL},
Guido van Rossum3f5da241990-12-20 15:06:42 +00002868};
2869
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002870PyDoc_STRVAR(builtin_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002871"Built-in functions, exceptions, and other objects.\n\
2872\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002873Noteworthy: None is the `nil' object; Ellipsis represents `...' in slices.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002874
Martin v. Löwis1a214512008-06-11 05:26:20 +00002875static struct PyModuleDef builtinsmodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002876 PyModuleDef_HEAD_INIT,
2877 "builtins",
2878 builtin_doc,
2879 -1, /* multiple "initialization" just copies the module dict. */
2880 builtin_methods,
2881 NULL,
2882 NULL,
2883 NULL,
2884 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00002885};
2886
2887
Guido van Rossum25ce5661997-08-02 03:10:38 +00002888PyObject *
Victor Stinnerbcb094b2021-02-19 15:10:45 +01002889_PyBuiltin_Init(PyInterpreterState *interp)
Guido van Rossum25ce5661997-08-02 03:10:38 +00002890{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002891 PyObject *mod, *dict, *debug;
Benjamin Peterson42124a72012-10-30 23:41:54 -04002892
Victor Stinnerbcb094b2021-02-19 15:10:45 +01002893 const PyConfig *config = _PyInterpreterState_GetConfig(interp);
Victor Stinnerfbca9082018-08-30 00:50:45 +02002894
Benjamin Peterson42124a72012-10-30 23:41:54 -04002895 if (PyType_Ready(&PyFilter_Type) < 0 ||
2896 PyType_Ready(&PyMap_Type) < 0 ||
2897 PyType_Ready(&PyZip_Type) < 0)
2898 return NULL;
2899
Eric Snowd393c1b2017-09-14 12:18:12 -06002900 mod = _PyModule_CreateInitialized(&builtinsmodule, PYTHON_API_VERSION);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002901 if (mod == NULL)
2902 return NULL;
2903 dict = PyModule_GetDict(mod);
Tim Peters4b7625e2001-09-13 21:37:17 +00002904
Tim Peters7571a0f2003-03-23 17:52:28 +00002905#ifdef Py_TRACE_REFS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002906 /* "builtins" exposes a number of statically allocated objects
2907 * that, before this code was added in 2.3, never showed up in
2908 * the list of "all objects" maintained by Py_TRACE_REFS. As a
2909 * result, programs leaking references to None and False (etc)
2910 * couldn't be diagnosed by examining sys.getobjects(0).
2911 */
Tim Peters7571a0f2003-03-23 17:52:28 +00002912#define ADD_TO_ALL(OBJECT) _Py_AddToAllObjects((PyObject *)(OBJECT), 0)
2913#else
2914#define ADD_TO_ALL(OBJECT) (void)0
2915#endif
2916
Tim Peters4b7625e2001-09-13 21:37:17 +00002917#define SETBUILTIN(NAME, OBJECT) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002918 if (PyDict_SetItemString(dict, NAME, (PyObject *)OBJECT) < 0) \
2919 return NULL; \
2920 ADD_TO_ALL(OBJECT)
Tim Peters4b7625e2001-09-13 21:37:17 +00002921
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002922 SETBUILTIN("None", Py_None);
2923 SETBUILTIN("Ellipsis", Py_Ellipsis);
2924 SETBUILTIN("NotImplemented", Py_NotImplemented);
2925 SETBUILTIN("False", Py_False);
2926 SETBUILTIN("True", Py_True);
2927 SETBUILTIN("bool", &PyBool_Type);
2928 SETBUILTIN("memoryview", &PyMemoryView_Type);
2929 SETBUILTIN("bytearray", &PyByteArray_Type);
2930 SETBUILTIN("bytes", &PyBytes_Type);
2931 SETBUILTIN("classmethod", &PyClassMethod_Type);
2932 SETBUILTIN("complex", &PyComplex_Type);
2933 SETBUILTIN("dict", &PyDict_Type);
2934 SETBUILTIN("enumerate", &PyEnum_Type);
2935 SETBUILTIN("filter", &PyFilter_Type);
2936 SETBUILTIN("float", &PyFloat_Type);
2937 SETBUILTIN("frozenset", &PyFrozenSet_Type);
2938 SETBUILTIN("property", &PyProperty_Type);
2939 SETBUILTIN("int", &PyLong_Type);
2940 SETBUILTIN("list", &PyList_Type);
2941 SETBUILTIN("map", &PyMap_Type);
2942 SETBUILTIN("object", &PyBaseObject_Type);
2943 SETBUILTIN("range", &PyRange_Type);
2944 SETBUILTIN("reversed", &PyReversed_Type);
2945 SETBUILTIN("set", &PySet_Type);
2946 SETBUILTIN("slice", &PySlice_Type);
2947 SETBUILTIN("staticmethod", &PyStaticMethod_Type);
2948 SETBUILTIN("str", &PyUnicode_Type);
2949 SETBUILTIN("super", &PySuper_Type);
2950 SETBUILTIN("tuple", &PyTuple_Type);
2951 SETBUILTIN("type", &PyType_Type);
2952 SETBUILTIN("zip", &PyZip_Type);
Victor Stinnerfbca9082018-08-30 00:50:45 +02002953 debug = PyBool_FromLong(config->optimization_level == 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002954 if (PyDict_SetItemString(dict, "__debug__", debug) < 0) {
Serhiy Storchakacfdfbb42016-06-18 09:44:03 +03002955 Py_DECREF(debug);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002956 return NULL;
2957 }
Serhiy Storchakacfdfbb42016-06-18 09:44:03 +03002958 Py_DECREF(debug);
Barry Warsaw757af0e1997-08-29 22:13:51 +00002959
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002960 return mod;
Tim Peters7571a0f2003-03-23 17:52:28 +00002961#undef ADD_TO_ALL
Tim Peters4b7625e2001-09-13 21:37:17 +00002962#undef SETBUILTIN
Guido van Rossum3f5da241990-12-20 15:06:42 +00002963}