blob: 4683103e09437ea7b030e41cecb81094d740ee51 [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 Stinnereec8e612021-03-18 14:57:49 +01007#include "pycore_ast.h" // _PyAST_Validate()
Victor Stinnerc96d00e2020-06-22 18:02:49 +02008#include "pycore_object.h" // _Py_AddToAllObjects()
Victor Stinner384621c2020-06-22 17:27:35 +02009#include "pycore_pyerrors.h" // _PyErr_NoMemory()
10#include "pycore_pystate.h" // _PyThreadState_GET()
11#include "pycore_tuple.h" // _PyTuple_FromArray()
Mark Shannon0332e562021-02-01 10:42:03 +000012#include "pycore_ceval.h" // _PyEval_Vector()
Guido van Rossum6bf62da1997-04-11 20:37:35 +000013
Victor Stinnerbd303c12013-11-07 23:07:29 +010014_Py_IDENTIFIER(__builtins__);
15_Py_IDENTIFIER(__dict__);
16_Py_IDENTIFIER(__prepare__);
17_Py_IDENTIFIER(__round__);
Ivan Levkivskyi2b5fd1e2017-12-14 23:32:56 +010018_Py_IDENTIFIER(__mro_entries__);
Victor Stinnerbd303c12013-11-07 23:07:29 +010019_Py_IDENTIFIER(encoding);
20_Py_IDENTIFIER(errors);
Martin v. Löwisbd928fe2011-10-14 10:20:37 +020021_Py_IDENTIFIER(fileno);
22_Py_IDENTIFIER(flush);
Victor Stinnerbd303c12013-11-07 23:07:29 +010023_Py_IDENTIFIER(metaclass);
24_Py_IDENTIFIER(sort);
25_Py_IDENTIFIER(stdin);
26_Py_IDENTIFIER(stdout);
27_Py_IDENTIFIER(stderr);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +020028
Serhiy Storchaka1009bf12015-04-03 23:53:51 +030029#include "clinic/bltinmodule.c.h"
30
Ivan Levkivskyi2b5fd1e2017-12-14 23:32:56 +010031static PyObject*
Victor Stinner05d68a82018-01-18 11:15:25 +010032update_bases(PyObject *bases, PyObject *const *args, Py_ssize_t nargs)
Ivan Levkivskyi2b5fd1e2017-12-14 23:32:56 +010033{
Victor Stinner05d68a82018-01-18 11:15:25 +010034 Py_ssize_t i, j;
Ivan Levkivskyi2b5fd1e2017-12-14 23:32:56 +010035 PyObject *base, *meth, *new_base, *result, *new_bases = NULL;
Ivan Levkivskyi2b5fd1e2017-12-14 23:32:56 +010036 assert(PyTuple_Check(bases));
37
38 for (i = 0; i < nargs; i++) {
39 base = args[i];
40 if (PyType_Check(base)) {
41 if (new_bases) {
42 /* If we already have made a replacement, then we append every normal base,
43 otherwise just skip it. */
44 if (PyList_Append(new_bases, base) < 0) {
45 goto error;
46 }
47 }
48 continue;
49 }
Serhiy Storchakaf320be72018-01-25 10:49:40 +020050 if (_PyObject_LookupAttrId(base, &PyId___mro_entries__, &meth) < 0) {
51 goto error;
52 }
Ivan Levkivskyi2b5fd1e2017-12-14 23:32:56 +010053 if (!meth) {
Ivan Levkivskyi2b5fd1e2017-12-14 23:32:56 +010054 if (new_bases) {
55 if (PyList_Append(new_bases, base) < 0) {
56 goto error;
57 }
58 }
59 continue;
60 }
Petr Viktorinffd97532020-02-11 17:46:57 +010061 new_base = PyObject_CallOneArg(meth, bases);
Ivan Levkivskyi2b5fd1e2017-12-14 23:32:56 +010062 Py_DECREF(meth);
63 if (!new_base) {
64 goto error;
65 }
66 if (!PyTuple_Check(new_base)) {
67 PyErr_SetString(PyExc_TypeError,
68 "__mro_entries__ must return a tuple");
69 Py_DECREF(new_base);
70 goto error;
71 }
72 if (!new_bases) {
73 /* If this is a first successful replacement, create new_bases list and
74 copy previously encountered bases. */
75 if (!(new_bases = PyList_New(i))) {
76 goto error;
77 }
78 for (j = 0; j < i; j++) {
79 base = args[j];
80 PyList_SET_ITEM(new_bases, j, base);
81 Py_INCREF(base);
82 }
83 }
84 j = PyList_GET_SIZE(new_bases);
85 if (PyList_SetSlice(new_bases, j, j, new_base) < 0) {
86 goto error;
87 }
88 Py_DECREF(new_base);
89 }
90 if (!new_bases) {
91 return bases;
92 }
93 result = PyList_AsTuple(new_bases);
94 Py_DECREF(new_bases);
95 return result;
96
97error:
98 Py_XDECREF(new_bases);
99 return NULL;
100}
101
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000102/* AC: cannot convert yet, waiting for *args support */
Guido van Rossum79f25d91997-04-29 20:08:16 +0000103static PyObject *
Serhiy Storchakaa5552f02017-12-15 13:11:11 +0200104builtin___build_class__(PyObject *self, PyObject *const *args, Py_ssize_t nargs,
Victor Stinner773dc6d2017-01-16 23:46:26 +0100105 PyObject *kwnames)
Guido van Rossum52cc1d82007-03-18 15:41:51 +0000106{
Ivan Levkivskyi2b5fd1e2017-12-14 23:32:56 +0100107 PyObject *func, *name, *bases, *mkw, *meta, *winner, *prep, *ns, *orig_bases;
Nick Coghlan19d24672016-12-05 16:47:55 +1000108 PyObject *cls = NULL, *cell = NULL;
Victor Stinner0c39b1b2015-03-18 15:02:06 +0100109 int isclass = 0; /* initialize to prevent gcc warning */
Guido van Rossum52cc1d82007-03-18 15:41:51 +0000110
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000111 if (nargs < 2) {
112 PyErr_SetString(PyExc_TypeError,
113 "__build_class__: not enough arguments");
114 return NULL;
115 }
Victor Stinner773dc6d2017-01-16 23:46:26 +0100116 func = args[0]; /* Better be callable */
Benjamin Petersone8e14592013-05-16 14:37:25 -0500117 if (!PyFunction_Check(func)) {
118 PyErr_SetString(PyExc_TypeError,
Zachary Ware9b338722014-08-05 14:01:10 -0500119 "__build_class__: func must be a function");
Benjamin Petersone8e14592013-05-16 14:37:25 -0500120 return NULL;
121 }
Victor Stinner773dc6d2017-01-16 23:46:26 +0100122 name = args[1];
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000123 if (!PyUnicode_Check(name)) {
124 PyErr_SetString(PyExc_TypeError,
125 "__build_class__: name is not a string");
126 return NULL;
127 }
Sergey Fedoseevf1b9abe2019-02-26 02:37:26 +0500128 orig_bases = _PyTuple_FromArray(args + 2, nargs - 2);
Ivan Levkivskyi2b5fd1e2017-12-14 23:32:56 +0100129 if (orig_bases == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000130 return NULL;
Guido van Rossum52cc1d82007-03-18 15:41:51 +0000131
Ivan Levkivskyi2b5fd1e2017-12-14 23:32:56 +0100132 bases = update_bases(orig_bases, args + 2, nargs - 2);
133 if (bases == NULL) {
134 Py_DECREF(orig_bases);
135 return NULL;
136 }
137
Victor Stinner773dc6d2017-01-16 23:46:26 +0100138 if (kwnames == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000139 meta = NULL;
140 mkw = NULL;
141 }
142 else {
Victor Stinner773dc6d2017-01-16 23:46:26 +0100143 mkw = _PyStack_AsDict(args + nargs, kwnames);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000144 if (mkw == NULL) {
145 Py_DECREF(bases);
146 return NULL;
Guido van Rossum52cc1d82007-03-18 15:41:51 +0000147 }
Victor Stinner773dc6d2017-01-16 23:46:26 +0100148
Serhiy Storchakaa24107b2019-02-25 17:59:46 +0200149 meta = _PyDict_GetItemIdWithError(mkw, &PyId_metaclass);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000150 if (meta != NULL) {
151 Py_INCREF(meta);
Victor Stinnerae9f1612013-11-06 22:46:51 +0100152 if (_PyDict_DelItemId(mkw, &PyId_metaclass) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000153 Py_DECREF(meta);
154 Py_DECREF(mkw);
155 Py_DECREF(bases);
156 return NULL;
157 }
Nick Coghlande31b192011-10-23 22:04:16 +1000158 /* metaclass is explicitly given, check if it's indeed a class */
159 isclass = PyType_Check(meta);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000160 }
Serhiy Storchakaa24107b2019-02-25 17:59:46 +0200161 else if (PyErr_Occurred()) {
162 Py_DECREF(mkw);
163 Py_DECREF(bases);
164 return NULL;
165 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000166 }
167 if (meta == NULL) {
Nick Coghlande31b192011-10-23 22:04:16 +1000168 /* if there are no bases, use type: */
169 if (PyTuple_GET_SIZE(bases) == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000170 meta = (PyObject *) (&PyType_Type);
Nick Coghlande31b192011-10-23 22:04:16 +1000171 }
172 /* else get the type of the first base */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000173 else {
174 PyObject *base0 = PyTuple_GET_ITEM(bases, 0);
Victor Stinnera102ed72020-02-07 02:24:48 +0100175 meta = (PyObject *)Py_TYPE(base0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000176 }
177 Py_INCREF(meta);
Nick Coghlande31b192011-10-23 22:04:16 +1000178 isclass = 1; /* meta is really a class */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000179 }
Nick Coghlan9715d262011-10-23 22:36:42 +1000180
Nick Coghlande31b192011-10-23 22:04:16 +1000181 if (isclass) {
182 /* meta is really a class, so check for a more derived
183 metaclass, or possible metaclass conflicts: */
184 winner = (PyObject *)_PyType_CalculateMetaclass((PyTypeObject *)meta,
185 bases);
186 if (winner == NULL) {
187 Py_DECREF(meta);
188 Py_XDECREF(mkw);
189 Py_DECREF(bases);
190 return NULL;
191 }
192 if (winner != meta) {
193 Py_DECREF(meta);
194 meta = winner;
195 Py_INCREF(meta);
196 }
197 }
198 /* else: meta is not a class, so we cannot do the metaclass
199 calculation, so we will use the explicitly given object as it is */
Serhiy Storchakaf320be72018-01-25 10:49:40 +0200200 if (_PyObject_LookupAttrId(meta, &PyId___prepare__, &prep) < 0) {
201 ns = NULL;
202 }
203 else if (prep == NULL) {
204 ns = PyDict_New();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000205 }
206 else {
Victor Stinner463b86a2016-08-22 23:33:13 +0200207 PyObject *pargs[2] = {name, bases};
Petr Viktorinffd97532020-02-11 17:46:57 +0100208 ns = PyObject_VectorcallDict(prep, pargs, 2, mkw);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000209 Py_DECREF(prep);
210 }
211 if (ns == NULL) {
212 Py_DECREF(meta);
213 Py_XDECREF(mkw);
214 Py_DECREF(bases);
215 return NULL;
216 }
Oren Milman5837d042017-09-27 17:04:37 +0300217 if (!PyMapping_Check(ns)) {
218 PyErr_Format(PyExc_TypeError,
219 "%.200s.__prepare__() must return a mapping, not %.200s",
220 isclass ? ((PyTypeObject *)meta)->tp_name : "<metaclass>",
221 Py_TYPE(ns)->tp_name);
222 goto error;
223 }
Mark Shannon0332e562021-02-01 10:42:03 +0000224 PyFrameConstructor *f = PyFunction_AS_FRAME_CONSTRUCTOR(func);
225 PyThreadState *tstate = PyThreadState_GET();
226 cell = _PyEval_Vector(tstate, f, ns, NULL, 0, NULL);
Nick Coghlan19d24672016-12-05 16:47:55 +1000227 if (cell != NULL) {
Ivan Levkivskyi2b5fd1e2017-12-14 23:32:56 +0100228 if (bases != orig_bases) {
229 if (PyMapping_SetItemString(ns, "__orig_bases__", orig_bases) < 0) {
230 goto error;
231 }
232 }
Victor Stinnerd1c2a8e2016-08-23 01:34:35 +0200233 PyObject *margs[3] = {name, bases, ns};
Petr Viktorinffd97532020-02-11 17:46:57 +0100234 cls = PyObject_VectorcallDict(meta, margs, 3, mkw);
Nick Coghlan19d24672016-12-05 16:47:55 +1000235 if (cls != NULL && PyType_Check(cls) && PyCell_Check(cell)) {
236 PyObject *cell_cls = PyCell_GET(cell);
237 if (cell_cls != cls) {
Nick Coghlan19d24672016-12-05 16:47:55 +1000238 if (cell_cls == NULL) {
239 const char *msg =
240 "__class__ not set defining %.200R as %.200R. "
241 "Was __classcell__ propagated to type.__new__?";
Serhiy Storchakaf5e7b192018-05-20 08:48:12 +0300242 PyErr_Format(PyExc_RuntimeError, msg, name, cls);
Nick Coghlan19d24672016-12-05 16:47:55 +1000243 } else {
244 const char *msg =
245 "__class__ set to %.200R defining %.200R as %.200R";
246 PyErr_Format(PyExc_TypeError, msg, cell_cls, name, cls);
Nick Coghlan19d24672016-12-05 16:47:55 +1000247 }
Serhiy Storchakaf5e7b192018-05-20 08:48:12 +0300248 Py_DECREF(cls);
249 cls = NULL;
250 goto error;
Nick Coghlan19d24672016-12-05 16:47:55 +1000251 }
252 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000253 }
Nick Coghlan19d24672016-12-05 16:47:55 +1000254error:
255 Py_XDECREF(cell);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000256 Py_DECREF(ns);
257 Py_DECREF(meta);
258 Py_XDECREF(mkw);
259 Py_DECREF(bases);
Ivan Levkivskyi2b5fd1e2017-12-14 23:32:56 +0100260 if (bases != orig_bases) {
261 Py_DECREF(orig_bases);
262 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000263 return cls;
Guido van Rossum52cc1d82007-03-18 15:41:51 +0000264}
265
266PyDoc_STRVAR(build_class_doc,
Pablo Galindoe3babbd2019-10-13 16:35:41 +0100267"__build_class__(func, name, /, *bases, [metaclass], **kwds) -> class\n\
Guido van Rossum52cc1d82007-03-18 15:41:51 +0000268\n\
269Internal helper function used by the class statement.");
270
271static PyObject *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000272builtin___import__(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000273{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000274 static char *kwlist[] = {"name", "globals", "locals", "fromlist",
275 "level", 0};
Victor Stinnerfe93faf2011-03-14 15:54:52 -0400276 PyObject *name, *globals = NULL, *locals = NULL, *fromlist = NULL;
Brett Cannonfd074152012-04-14 14:10:13 -0400277 int level = 0;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000278
Victor Stinnerfe93faf2011-03-14 15:54:52 -0400279 if (!PyArg_ParseTupleAndKeywords(args, kwds, "U|OOOi:__import__",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000280 kwlist, &name, &globals, &locals, &fromlist, &level))
281 return NULL;
Victor Stinnerfe93faf2011-03-14 15:54:52 -0400282 return PyImport_ImportModuleLevelObject(name, globals, locals,
283 fromlist, level);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000284}
285
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000286PyDoc_STRVAR(import_doc,
Brett Cannoncb4996a2012-08-06 16:34:44 -0400287"__import__(name, globals=None, locals=None, fromlist=(), level=0) -> module\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000288\n\
Brett Cannon5305a992010-09-27 21:08:38 +0000289Import a module. Because this function is meant for use by the Python\n\
oldk461d2252018-02-02 12:20:00 +0800290interpreter and not for general use, it is better to use\n\
Brett Cannon5305a992010-09-27 21:08:38 +0000291importlib.import_module() to programmatically import a module.\n\
292\n\
293The globals argument is only used to determine the context;\n\
294they are not modified. The locals argument is unused. The fromlist\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000295should be a list of names to emulate ``from name import ...'', or an\n\
296empty list to emulate ``import name''.\n\
297When importing a module from a package, note that __import__('A.B', ...)\n\
298returns package A when fromlist is empty, but its submodule B when\n\
oldk461d2252018-02-02 12:20:00 +0800299fromlist is not empty. The level argument is used to determine whether to\n\
300perform absolute or relative imports: 0 is absolute, while a positive number\n\
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000301is the number of parent directories to search relative to the current module.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000302
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000303
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000304/*[clinic input]
305abs as builtin_abs
306
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300307 x: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000308 /
309
310Return the absolute value of the argument.
311[clinic start generated code]*/
312
Guido van Rossum79f25d91997-04-29 20:08:16 +0000313static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300314builtin_abs(PyObject *module, PyObject *x)
315/*[clinic end generated code: output=b1b433b9e51356f5 input=bed4ca14e29c20d1]*/
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000316{
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000317 return PyNumber_Absolute(x);
Guido van Rossum3f5da241990-12-20 15:06:42 +0000318}
319
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000320/*[clinic input]
321all as builtin_all
322
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300323 iterable: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000324 /
325
326Return True if bool(x) is True for all values x in the iterable.
327
328If the iterable is empty, return True.
329[clinic start generated code]*/
330
Raymond Hettinger96229b12005-03-11 06:49:40 +0000331static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300332builtin_all(PyObject *module, PyObject *iterable)
333/*[clinic end generated code: output=ca2a7127276f79b3 input=1a7c5d1bc3438a21]*/
Raymond Hettinger96229b12005-03-11 06:49:40 +0000334{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000335 PyObject *it, *item;
336 PyObject *(*iternext)(PyObject *);
337 int cmp;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000338
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000339 it = PyObject_GetIter(iterable);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000340 if (it == NULL)
341 return NULL;
342 iternext = *Py_TYPE(it)->tp_iternext;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000343
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000344 for (;;) {
345 item = iternext(it);
346 if (item == NULL)
347 break;
348 cmp = PyObject_IsTrue(item);
349 Py_DECREF(item);
350 if (cmp < 0) {
351 Py_DECREF(it);
352 return NULL;
353 }
354 if (cmp == 0) {
355 Py_DECREF(it);
356 Py_RETURN_FALSE;
357 }
358 }
359 Py_DECREF(it);
360 if (PyErr_Occurred()) {
361 if (PyErr_ExceptionMatches(PyExc_StopIteration))
362 PyErr_Clear();
363 else
364 return NULL;
365 }
366 Py_RETURN_TRUE;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000367}
368
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000369/*[clinic input]
370any as builtin_any
371
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300372 iterable: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000373 /
374
375Return True if bool(x) is True for any x in the iterable.
376
377If the iterable is empty, return False.
378[clinic start generated code]*/
379
Raymond Hettinger96229b12005-03-11 06:49:40 +0000380static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300381builtin_any(PyObject *module, PyObject *iterable)
382/*[clinic end generated code: output=fa65684748caa60e input=41d7451c23384f24]*/
Raymond Hettinger96229b12005-03-11 06:49:40 +0000383{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000384 PyObject *it, *item;
385 PyObject *(*iternext)(PyObject *);
386 int cmp;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000387
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000388 it = PyObject_GetIter(iterable);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000389 if (it == NULL)
390 return NULL;
391 iternext = *Py_TYPE(it)->tp_iternext;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000392
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000393 for (;;) {
394 item = iternext(it);
395 if (item == NULL)
396 break;
397 cmp = PyObject_IsTrue(item);
398 Py_DECREF(item);
399 if (cmp < 0) {
400 Py_DECREF(it);
401 return NULL;
402 }
Raymond Hettinger5098b582015-10-09 00:42:47 -0400403 if (cmp > 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000404 Py_DECREF(it);
405 Py_RETURN_TRUE;
406 }
407 }
408 Py_DECREF(it);
409 if (PyErr_Occurred()) {
410 if (PyErr_ExceptionMatches(PyExc_StopIteration))
411 PyErr_Clear();
412 else
413 return NULL;
414 }
415 Py_RETURN_FALSE;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000416}
417
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000418/*[clinic input]
419ascii as builtin_ascii
420
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300421 obj: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000422 /
423
424Return an ASCII-only representation of an object.
425
426As repr(), return a string containing a printable representation of an
427object, but escape the non-ASCII characters in the string returned by
428repr() using \\x, \\u or \\U escapes. This generates a string similar
429to that returned by repr() in Python 2.
430[clinic start generated code]*/
431
Georg Brandl559e5d72008-06-11 18:37:52 +0000432static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300433builtin_ascii(PyObject *module, PyObject *obj)
434/*[clinic end generated code: output=6d37b3f0984c7eb9 input=4c62732e1b3a3cc9]*/
Georg Brandl559e5d72008-06-11 18:37:52 +0000435{
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000436 return PyObject_ASCII(obj);
Georg Brandl559e5d72008-06-11 18:37:52 +0000437}
438
Georg Brandl559e5d72008-06-11 18:37:52 +0000439
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000440/*[clinic input]
441bin as builtin_bin
442
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300443 number: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000444 /
445
446Return the binary representation of an integer.
447
448 >>> bin(2796202)
449 '0b1010101010101010101010'
450[clinic start generated code]*/
451
Guido van Rossum79f25d91997-04-29 20:08:16 +0000452static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300453builtin_bin(PyObject *module, PyObject *number)
454/*[clinic end generated code: output=b6fc4ad5e649f4f7 input=53f8a0264bacaf90]*/
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000455{
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000456 return PyNumber_ToBase(number, 2);
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000457}
458
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000459
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000460/*[clinic input]
461callable as builtin_callable
462
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300463 obj: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000464 /
465
466Return whether the object is callable (i.e., some kind of function).
467
468Note that classes are callable, as are instances of classes with a
469__call__() method.
470[clinic start generated code]*/
471
Antoine Pitroue71362d2010-11-27 22:00:11 +0000472static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300473builtin_callable(PyObject *module, PyObject *obj)
474/*[clinic end generated code: output=2b095d59d934cb7e input=1423bab99cc41f58]*/
Antoine Pitroue71362d2010-11-27 22:00:11 +0000475{
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000476 return PyBool_FromLong((long)PyCallable_Check(obj));
Antoine Pitroue71362d2010-11-27 22:00:11 +0000477}
478
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400479static PyObject *
Serhiy Storchakaa5552f02017-12-15 13:11:11 +0200480builtin_breakpoint(PyObject *self, PyObject *const *args, Py_ssize_t nargs, PyObject *keywords)
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400481{
482 PyObject *hook = PySys_GetObject("breakpointhook");
483
484 if (hook == NULL) {
485 PyErr_SetString(PyExc_RuntimeError, "lost sys.breakpointhook");
486 return NULL;
487 }
Steve Dower60419a72019-06-24 08:42:54 -0700488
489 if (PySys_Audit("builtins.breakpoint", "O", hook) < 0) {
490 return NULL;
491 }
492
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400493 Py_INCREF(hook);
Petr Viktorinffd97532020-02-11 17:46:57 +0100494 PyObject *retval = PyObject_Vectorcall(hook, args, nargs, keywords);
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400495 Py_DECREF(hook);
496 return retval;
497}
498
499PyDoc_STRVAR(breakpoint_doc,
500"breakpoint(*args, **kws)\n\
501\n\
502Call sys.breakpointhook(*args, **kws). sys.breakpointhook() must accept\n\
503whatever arguments are passed.\n\
504\n\
505By default, this drops you into the pdb debugger.");
Antoine Pitroue71362d2010-11-27 22:00:11 +0000506
Raymond Hettinger17301e92008-03-13 00:19:26 +0000507typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000508 PyObject_HEAD
509 PyObject *func;
510 PyObject *it;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000511} filterobject;
512
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000513static PyObject *
Raymond Hettinger17301e92008-03-13 00:19:26 +0000514filter_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
Guido van Rossum12d12c51993-10-26 17:58:25 +0000515{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000516 PyObject *func, *seq;
517 PyObject *it;
518 filterobject *lz;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000519
Serhiy Storchaka6cca5c82017-06-08 14:41:19 +0300520 if (type == &PyFilter_Type && !_PyArg_NoKeywords("filter", kwds))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000521 return NULL;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000522
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000523 if (!PyArg_UnpackTuple(args, "filter", 2, 2, &func, &seq))
524 return NULL;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000525
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000526 /* Get iterator. */
527 it = PyObject_GetIter(seq);
528 if (it == NULL)
529 return NULL;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000530
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000531 /* create filterobject structure */
532 lz = (filterobject *)type->tp_alloc(type, 0);
533 if (lz == NULL) {
534 Py_DECREF(it);
535 return NULL;
536 }
Dong-hee Na9a9c11a2021-03-11 01:39:52 +0900537
538 lz->func = Py_NewRef(func);
539 lz->it = it;
540
541 return (PyObject *)lz;
542}
543
544static PyObject *
545filter_vectorcall(PyObject *type, PyObject * const*args,
546 size_t nargsf, PyObject *kwnames)
547{
548 PyTypeObject *tp = (PyTypeObject *)type;
549 if (tp == &PyFilter_Type && !_PyArg_NoKwnames("filter", kwnames)) {
550 return NULL;
551 }
552
553 Py_ssize_t nargs = PyVectorcall_NARGS(nargsf);
554 if (!_PyArg_CheckPositional("filter", nargs, 2, 2)) {
555 return NULL;
556 }
557
558 PyObject *it = PyObject_GetIter(args[1]);
559 if (it == NULL) {
560 return NULL;
561 }
562
563 filterobject *lz = (filterobject *)tp->tp_alloc(tp, 0);
564
565 if (lz == NULL) {
566 Py_DECREF(it);
567 return NULL;
568 }
569
570 lz->func = Py_NewRef(args[0]);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000571 lz->it = it;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000572
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000573 return (PyObject *)lz;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000574}
575
576static void
577filter_dealloc(filterobject *lz)
578{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000579 PyObject_GC_UnTrack(lz);
580 Py_XDECREF(lz->func);
581 Py_XDECREF(lz->it);
582 Py_TYPE(lz)->tp_free(lz);
Raymond Hettinger17301e92008-03-13 00:19:26 +0000583}
584
585static int
586filter_traverse(filterobject *lz, visitproc visit, void *arg)
587{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000588 Py_VISIT(lz->it);
589 Py_VISIT(lz->func);
590 return 0;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000591}
592
593static PyObject *
594filter_next(filterobject *lz)
595{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000596 PyObject *item;
597 PyObject *it = lz->it;
598 long ok;
599 PyObject *(*iternext)(PyObject *);
Raymond Hettingerbd5f0e82015-10-09 01:34:08 -0400600 int checktrue = lz->func == Py_None || lz->func == (PyObject *)&PyBool_Type;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000601
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000602 iternext = *Py_TYPE(it)->tp_iternext;
603 for (;;) {
604 item = iternext(it);
605 if (item == NULL)
606 return NULL;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000607
Raymond Hettingerbd5f0e82015-10-09 01:34:08 -0400608 if (checktrue) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000609 ok = PyObject_IsTrue(item);
610 } else {
611 PyObject *good;
Petr Viktorinffd97532020-02-11 17:46:57 +0100612 good = PyObject_CallOneArg(lz->func, item);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000613 if (good == NULL) {
614 Py_DECREF(item);
615 return NULL;
616 }
617 ok = PyObject_IsTrue(good);
618 Py_DECREF(good);
619 }
Antoine Pitrou6f430e42012-08-15 23:18:25 +0200620 if (ok > 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000621 return item;
622 Py_DECREF(item);
Antoine Pitrou6f430e42012-08-15 23:18:25 +0200623 if (ok < 0)
624 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000625 }
Guido van Rossum12d12c51993-10-26 17:58:25 +0000626}
627
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +0000628static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +0530629filter_reduce(filterobject *lz, PyObject *Py_UNUSED(ignored))
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +0000630{
631 return Py_BuildValue("O(OO)", Py_TYPE(lz), lz->func, lz->it);
632}
633
634PyDoc_STRVAR(reduce_doc, "Return state information for pickling.");
635
636static PyMethodDef filter_methods[] = {
637 {"__reduce__", (PyCFunction)filter_reduce, METH_NOARGS, reduce_doc},
638 {NULL, NULL} /* sentinel */
639};
640
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000641PyDoc_STRVAR(filter_doc,
Georg Brandld11ae5d2008-05-16 13:27:32 +0000642"filter(function or None, iterable) --> filter object\n\
Guido van Rossumc1f779c2007-07-03 08:25:58 +0000643\n\
Georg Brandld11ae5d2008-05-16 13:27:32 +0000644Return an iterator yielding those items of iterable for which function(item)\n\
Raymond Hettinger17301e92008-03-13 00:19:26 +0000645is true. If function is None, return the items that are true.");
646
647PyTypeObject PyFilter_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000648 PyVarObject_HEAD_INIT(&PyType_Type, 0)
649 "filter", /* tp_name */
650 sizeof(filterobject), /* tp_basicsize */
651 0, /* tp_itemsize */
652 /* methods */
653 (destructor)filter_dealloc, /* tp_dealloc */
Jeroen Demeyer530f5062019-05-31 04:13:39 +0200654 0, /* tp_vectorcall_offset */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000655 0, /* tp_getattr */
656 0, /* tp_setattr */
Jeroen Demeyer530f5062019-05-31 04:13:39 +0200657 0, /* tp_as_async */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000658 0, /* tp_repr */
659 0, /* tp_as_number */
660 0, /* tp_as_sequence */
661 0, /* tp_as_mapping */
662 0, /* tp_hash */
663 0, /* tp_call */
664 0, /* tp_str */
665 PyObject_GenericGetAttr, /* tp_getattro */
666 0, /* tp_setattro */
667 0, /* tp_as_buffer */
668 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
669 Py_TPFLAGS_BASETYPE, /* tp_flags */
670 filter_doc, /* tp_doc */
671 (traverseproc)filter_traverse, /* tp_traverse */
672 0, /* tp_clear */
673 0, /* tp_richcompare */
674 0, /* tp_weaklistoffset */
675 PyObject_SelfIter, /* tp_iter */
676 (iternextfunc)filter_next, /* tp_iternext */
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +0000677 filter_methods, /* tp_methods */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000678 0, /* tp_members */
679 0, /* tp_getset */
680 0, /* tp_base */
681 0, /* tp_dict */
682 0, /* tp_descr_get */
683 0, /* tp_descr_set */
684 0, /* tp_dictoffset */
685 0, /* tp_init */
686 PyType_GenericAlloc, /* tp_alloc */
687 filter_new, /* tp_new */
688 PyObject_GC_Del, /* tp_free */
Dong-hee Na9a9c11a2021-03-11 01:39:52 +0900689 .tp_vectorcall = (vectorcallfunc)filter_vectorcall
Raymond Hettinger17301e92008-03-13 00:19:26 +0000690};
691
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000692
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000693/*[clinic input]
694format as builtin_format
695
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300696 value: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000697 format_spec: unicode(c_default="NULL") = ''
698 /
699
700Return value.__format__(format_spec)
701
Amit Kumar2e6bb442017-05-29 06:32:26 +0530702format_spec defaults to the empty string.
703See the Format Specification Mini-Language section of help('FORMATTING') for
704details.
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000705[clinic start generated code]*/
706
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000707static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300708builtin_format_impl(PyObject *module, PyObject *value, PyObject *format_spec)
Amit Kumar2e6bb442017-05-29 06:32:26 +0530709/*[clinic end generated code: output=2f40bdfa4954b077 input=88339c93ea522b33]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000710{
Eric Smith8fd3eba2008-02-17 19:48:00 +0000711 return PyObject_Format(value, format_spec);
Eric Smith8c663262007-08-25 02:26:07 +0000712}
713
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000714/*[clinic input]
715chr as builtin_chr
716
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300717 i: int
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000718 /
719
720Return a Unicode string of one character with ordinal i; 0 <= i <= 0x10ffff.
721[clinic start generated code]*/
722
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000723static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300724builtin_chr_impl(PyObject *module, int i)
725/*[clinic end generated code: output=c733afcd200afcb7 input=3f604ef45a70750d]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000726{
727 return PyUnicode_FromOrdinal(i);
728}
Guido van Rossum09095f32000-03-10 23:00:52 +0000729
730
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000731/*[clinic input]
732compile as builtin_compile
733
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300734 source: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000735 filename: object(converter="PyUnicode_FSDecoder")
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300736 mode: str
737 flags: int = 0
Serhiy Storchaka202fda52017-03-12 10:10:47 +0200738 dont_inherit: bool(accept={int}) = False
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300739 optimize: int = -1
Victor Stinnerefdf6ca2019-06-12 02:52:16 +0200740 *
741 _feature_version as feature_version: int = -1
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000742
743Compile source into a code object that can be executed by exec() or eval().
744
745The source code may represent a Python module, statement or expression.
746The filename will be used for run-time error messages.
747The mode must be 'exec' to compile a module, 'single' to compile a
748single (interactive) statement, or 'eval' to compile an expression.
749The flags argument, if present, controls which future statements influence
750the compilation of the code.
Serhiy Storchaka8b2e8b62015-05-30 11:30:39 +0300751The dont_inherit argument, if true, stops the compilation inheriting
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000752the effects of any future statements in effect in the code calling
Serhiy Storchaka8b2e8b62015-05-30 11:30:39 +0300753compile; if absent or false these statements do influence the compilation,
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000754in addition to any features explicitly specified.
755[clinic start generated code]*/
756
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000757static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300758builtin_compile_impl(PyObject *module, PyObject *source, PyObject *filename,
759 const char *mode, int flags, int dont_inherit,
Guido van Rossum495da292019-03-07 12:38:08 -0800760 int optimize, int feature_version)
Victor Stinnerefdf6ca2019-06-12 02:52:16 +0200761/*[clinic end generated code: output=b0c09c84f116d3d7 input=40171fb92c1d580d]*/
Guido van Rossum5b722181993-03-30 17:46:03 +0000762{
Martin Panter61d6e4a2015-11-07 02:56:11 +0000763 PyObject *source_copy;
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +0200764 const char *str;
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000765 int compile_mode = -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000766 int is_ast;
Guido van Rossumdcfcd142019-01-31 03:40:27 -0800767 int start[] = {Py_file_input, Py_eval_input, Py_single_input, Py_func_type_input};
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000768 PyObject *result;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000769
Victor Stinner37d66d72019-06-13 02:16:41 +0200770 PyCompilerFlags cf = _PyCompilerFlags_INIT;
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000771 cf.cf_flags = flags | PyCF_SOURCE_IS_UTF8;
Guido van Rossum495da292019-03-07 12:38:08 -0800772 if (feature_version >= 0 && (flags & PyCF_ONLY_AST)) {
773 cf.cf_feature_version = feature_version;
774 }
Tim Peters6cd6a822001-08-17 22:11:27 +0000775
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000776 if (flags &
Batuhan Taşkaya44540572020-04-22 19:09:03 +0300777 ~(PyCF_MASK | PyCF_MASK_OBSOLETE | PyCF_COMPILE_MASK))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000778 {
779 PyErr_SetString(PyExc_ValueError,
780 "compile(): unrecognised flags");
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000781 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000782 }
783 /* XXX Warn if (supplied_flags & PyCF_MASK_OBSOLETE) != 0? */
Tim Peters6cd6a822001-08-17 22:11:27 +0000784
Georg Brandl8334fd92010-12-04 10:26:46 +0000785 if (optimize < -1 || optimize > 2) {
786 PyErr_SetString(PyExc_ValueError,
787 "compile(): invalid optimize value");
788 goto error;
789 }
790
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000791 if (!dont_inherit) {
792 PyEval_MergeCompilerFlags(&cf);
793 }
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000794
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000795 if (strcmp(mode, "exec") == 0)
796 compile_mode = 0;
797 else if (strcmp(mode, "eval") == 0)
798 compile_mode = 1;
799 else if (strcmp(mode, "single") == 0)
800 compile_mode = 2;
Guido van Rossumdcfcd142019-01-31 03:40:27 -0800801 else if (strcmp(mode, "func_type") == 0) {
802 if (!(flags & PyCF_ONLY_AST)) {
803 PyErr_SetString(PyExc_ValueError,
804 "compile() mode 'func_type' requires flag PyCF_ONLY_AST");
805 goto error;
806 }
807 compile_mode = 3;
808 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000809 else {
Guido van Rossumdcfcd142019-01-31 03:40:27 -0800810 const char *msg;
811 if (flags & PyCF_ONLY_AST)
812 msg = "compile() mode must be 'exec', 'eval', 'single' or 'func_type'";
813 else
814 msg = "compile() mode must be 'exec', 'eval' or 'single'";
815 PyErr_SetString(PyExc_ValueError, msg);
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000816 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000817 }
Neal Norwitzdb4115f2008-03-31 04:20:05 +0000818
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000819 is_ast = PyAST_Check(source);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000820 if (is_ast == -1)
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000821 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000822 if (is_ast) {
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000823 if (flags & PyCF_ONLY_AST) {
824 Py_INCREF(source);
825 result = source;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000826 }
827 else {
828 PyArena *arena;
829 mod_ty mod;
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000830
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000831 arena = PyArena_New();
Stefan Krah07795df2012-08-20 17:19:50 +0200832 if (arena == NULL)
833 goto error;
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000834 mod = PyAST_obj2mod(source, arena, compile_mode);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000835 if (mod == NULL) {
836 PyArena_Free(arena);
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000837 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000838 }
Victor Stinnereec8e612021-03-18 14:57:49 +0100839 if (!_PyAST_Validate(mod)) {
Benjamin Peterson832bfe22011-08-09 16:15:04 -0500840 PyArena_Free(arena);
841 goto error;
842 }
Victor Stinner14e461d2013-08-26 22:28:21 +0200843 result = (PyObject*)PyAST_CompileObject(mod, filename,
844 &cf, optimize, arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000845 PyArena_Free(arena);
846 }
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000847 goto finally;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000848 }
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000849
Dino Viehland41540692019-05-28 16:21:17 -0700850 str = _Py_SourceAsString(source, "compile", "string, bytes or AST", &cf, &source_copy);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000851 if (str == NULL)
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000852 goto error;
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000853
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000854 result = Py_CompileStringObject(str, filename, start[compile_mode], &cf, optimize);
Guido van Rossumc001c092020-04-30 12:12:19 -0700855
Martin Panter61d6e4a2015-11-07 02:56:11 +0000856 Py_XDECREF(source_copy);
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000857 goto finally;
858
859error:
860 result = NULL;
861finally:
Victor Stinner14e461d2013-08-26 22:28:21 +0200862 Py_DECREF(filename);
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000863 return result;
Guido van Rossum5b722181993-03-30 17:46:03 +0000864}
865
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000866/* AC: cannot convert yet, as needs PEP 457 group support in inspect */
Guido van Rossum79f25d91997-04-29 20:08:16 +0000867static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000868builtin_dir(PyObject *self, PyObject *args)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000869{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000870 PyObject *arg = NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000871
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000872 if (!PyArg_UnpackTuple(args, "dir", 0, 1, &arg))
873 return NULL;
874 return PyObject_Dir(arg);
Guido van Rossum3f5da241990-12-20 15:06:42 +0000875}
876
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000877PyDoc_STRVAR(dir_doc,
Tim Peters5d2b77c2001-09-03 05:47:38 +0000878"dir([object]) -> list of strings\n"
879"\n"
Georg Brandle32b4222007-03-10 22:13:27 +0000880"If called without an argument, return the names in the current scope.\n"
881"Else, return an alphabetized list of names comprising (some of) the attributes\n"
882"of the given object, and of attributes reachable from it.\n"
883"If the object supplies a method named __dir__, it will be used; otherwise\n"
884"the default dir() logic is used and returns:\n"
885" for a module object: the module's attributes.\n"
886" for a class object: its attributes, and recursively the attributes\n"
887" of its bases.\n"
Guido van Rossumd8faa362007-04-27 19:54:29 +0000888" for any other object: its attributes, its class's attributes, and\n"
Georg Brandle32b4222007-03-10 22:13:27 +0000889" recursively the attributes of its class's base classes.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000890
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000891/*[clinic input]
892divmod as builtin_divmod
Guido van Rossum6a00cd81995-01-07 12:39:01 +0000893
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300894 x: object
895 y: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000896 /
897
Zachary Ware7f227d92016-04-28 14:39:50 -0500898Return the tuple (x//y, x%y). Invariant: div*y + mod == x.
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000899[clinic start generated code]*/
900
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000901static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300902builtin_divmod_impl(PyObject *module, PyObject *x, PyObject *y)
903/*[clinic end generated code: output=b06d8a5f6e0c745e input=175ad9c84ff41a85]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000904{
905 return PyNumber_Divmod(x, y);
906}
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000907
908
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000909/*[clinic input]
910eval as builtin_eval
911
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300912 source: object
913 globals: object = None
914 locals: object = None
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000915 /
916
917Evaluate the given source in the context of globals and locals.
918
919The source may be a string representing a Python expression
920or a code object as returned by compile().
921The globals must be a dictionary and locals can be any mapping,
922defaulting to the current globals and locals.
923If only globals is given, locals defaults to it.
924[clinic start generated code]*/
925
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000926static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300927builtin_eval_impl(PyObject *module, PyObject *source, PyObject *globals,
Larry Hastings89964c42015-04-14 18:07:59 -0400928 PyObject *locals)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300929/*[clinic end generated code: output=0a0824aa70093116 input=11ee718a8640e527]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000930{
Martin Panter61d6e4a2015-11-07 02:56:11 +0000931 PyObject *result, *source_copy;
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +0200932 const char *str;
Guido van Rossum590baa41993-11-30 13:40:46 +0000933
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000934 if (locals != Py_None && !PyMapping_Check(locals)) {
935 PyErr_SetString(PyExc_TypeError, "locals must be a mapping");
936 return NULL;
937 }
938 if (globals != Py_None && !PyDict_Check(globals)) {
939 PyErr_SetString(PyExc_TypeError, PyMapping_Check(globals) ?
940 "globals must be a real dict; try eval(expr, {}, mapping)"
941 : "globals must be a dict");
942 return NULL;
943 }
944 if (globals == Py_None) {
945 globals = PyEval_GetGlobals();
Victor Stinner41bb43a2013-10-29 01:19:37 +0100946 if (locals == Py_None) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000947 locals = PyEval_GetLocals();
Victor Stinner41bb43a2013-10-29 01:19:37 +0100948 if (locals == NULL)
949 return NULL;
950 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000951 }
952 else if (locals == Py_None)
953 locals = globals;
Tim Peters9fa96be2001-08-17 23:04:59 +0000954
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000955 if (globals == NULL || locals == NULL) {
956 PyErr_SetString(PyExc_TypeError,
957 "eval must be given globals and locals "
958 "when called without a frame");
959 return NULL;
960 }
Georg Brandl77c85e62005-09-15 10:46:13 +0000961
Serhiy Storchakab510e102020-10-26 12:47:57 +0200962 int r = _PyDict_ContainsId(globals, &PyId___builtins__);
963 if (r == 0) {
964 r = _PyDict_SetItemId(globals, &PyId___builtins__,
965 PyEval_GetBuiltins());
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000966 }
Serhiy Storchakab510e102020-10-26 12:47:57 +0200967 if (r < 0) {
Serhiy Storchakaa24107b2019-02-25 17:59:46 +0200968 return NULL;
969 }
Tim Peters9fa96be2001-08-17 23:04:59 +0000970
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000971 if (PyCode_Check(source)) {
Steve Dowerb82e17e2019-05-23 08:45:22 -0700972 if (PySys_Audit("exec", "O", source) < 0) {
973 return NULL;
974 }
975
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000976 if (PyCode_GetNumFree((PyCodeObject *)source) > 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000977 PyErr_SetString(PyExc_TypeError,
Steve Dowerb82e17e2019-05-23 08:45:22 -0700978 "code object passed to eval() may not contain free variables");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000979 return NULL;
980 }
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000981 return PyEval_EvalCode(source, globals, locals);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000982 }
Tim Peters9fa96be2001-08-17 23:04:59 +0000983
Victor Stinner37d66d72019-06-13 02:16:41 +0200984 PyCompilerFlags cf = _PyCompilerFlags_INIT;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000985 cf.cf_flags = PyCF_SOURCE_IS_UTF8;
Dino Viehland41540692019-05-28 16:21:17 -0700986 str = _Py_SourceAsString(source, "eval", "string, bytes or code", &cf, &source_copy);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000987 if (str == NULL)
988 return NULL;
Just van Rossum3aaf42c2003-02-10 08:21:10 +0000989
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000990 while (*str == ' ' || *str == '\t')
991 str++;
Tim Peters9fa96be2001-08-17 23:04:59 +0000992
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000993 (void)PyEval_MergeCompilerFlags(&cf);
994 result = PyRun_StringFlags(str, Py_eval_input, globals, locals, &cf);
Martin Panter61d6e4a2015-11-07 02:56:11 +0000995 Py_XDECREF(source_copy);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000996 return result;
Guido van Rossum3f5da241990-12-20 15:06:42 +0000997}
998
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000999/*[clinic input]
1000exec as builtin_exec
1001
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001002 source: object
1003 globals: object = None
1004 locals: object = None
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001005 /
1006
1007Execute the given source in the context of globals and locals.
1008
1009The source may be a string representing one or more Python statements
1010or a code object as returned by compile().
1011The globals must be a dictionary and locals can be any mapping,
1012defaulting to the current globals and locals.
1013If only globals is given, locals defaults to it.
1014[clinic start generated code]*/
1015
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001016static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001017builtin_exec_impl(PyObject *module, PyObject *source, PyObject *globals,
Larry Hastings89964c42015-04-14 18:07:59 -04001018 PyObject *locals)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001019/*[clinic end generated code: output=3c90efc6ab68ef5d input=01ca3e1c01692829]*/
Georg Brandl7cae87c2006-09-06 06:51:57 +00001020{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001021 PyObject *v;
Georg Brandl2cabc562008-08-28 07:57:16 +00001022
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001023 if (globals == Py_None) {
1024 globals = PyEval_GetGlobals();
1025 if (locals == Py_None) {
1026 locals = PyEval_GetLocals();
Victor Stinner41bb43a2013-10-29 01:19:37 +01001027 if (locals == NULL)
1028 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001029 }
1030 if (!globals || !locals) {
1031 PyErr_SetString(PyExc_SystemError,
1032 "globals and locals cannot be NULL");
1033 return NULL;
1034 }
1035 }
1036 else if (locals == Py_None)
1037 locals = globals;
Georg Brandl7cae87c2006-09-06 06:51:57 +00001038
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001039 if (!PyDict_Check(globals)) {
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001040 PyErr_Format(PyExc_TypeError, "exec() globals must be a dict, not %.100s",
Victor Stinnera102ed72020-02-07 02:24:48 +01001041 Py_TYPE(globals)->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001042 return NULL;
1043 }
1044 if (!PyMapping_Check(locals)) {
1045 PyErr_Format(PyExc_TypeError,
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001046 "locals must be a mapping or None, not %.100s",
Victor Stinnera102ed72020-02-07 02:24:48 +01001047 Py_TYPE(locals)->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001048 return NULL;
1049 }
Serhiy Storchakab510e102020-10-26 12:47:57 +02001050 int r = _PyDict_ContainsId(globals, &PyId___builtins__);
1051 if (r == 0) {
1052 r = _PyDict_SetItemId(globals, &PyId___builtins__,
1053 PyEval_GetBuiltins());
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001054 }
Serhiy Storchakab510e102020-10-26 12:47:57 +02001055 if (r < 0) {
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02001056 return NULL;
1057 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001058
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001059 if (PyCode_Check(source)) {
Steve Dowerb82e17e2019-05-23 08:45:22 -07001060 if (PySys_Audit("exec", "O", source) < 0) {
1061 return NULL;
1062 }
1063
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001064 if (PyCode_GetNumFree((PyCodeObject *)source) > 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001065 PyErr_SetString(PyExc_TypeError,
1066 "code object passed to exec() may not "
1067 "contain free variables");
1068 return NULL;
1069 }
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001070 v = PyEval_EvalCode(source, globals, locals);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001071 }
1072 else {
Martin Panter61d6e4a2015-11-07 02:56:11 +00001073 PyObject *source_copy;
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +02001074 const char *str;
Victor Stinner37d66d72019-06-13 02:16:41 +02001075 PyCompilerFlags cf = _PyCompilerFlags_INIT;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001076 cf.cf_flags = PyCF_SOURCE_IS_UTF8;
Dino Viehland41540692019-05-28 16:21:17 -07001077 str = _Py_SourceAsString(source, "exec",
Martin Panter61d6e4a2015-11-07 02:56:11 +00001078 "string, bytes or code", &cf,
1079 &source_copy);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001080 if (str == NULL)
1081 return NULL;
1082 if (PyEval_MergeCompilerFlags(&cf))
1083 v = PyRun_StringFlags(str, Py_file_input, globals,
1084 locals, &cf);
1085 else
1086 v = PyRun_String(str, Py_file_input, globals, locals);
Martin Panter61d6e4a2015-11-07 02:56:11 +00001087 Py_XDECREF(source_copy);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001088 }
1089 if (v == NULL)
1090 return NULL;
1091 Py_DECREF(v);
1092 Py_RETURN_NONE;
Georg Brandl7cae87c2006-09-06 06:51:57 +00001093}
1094
Georg Brandl7cae87c2006-09-06 06:51:57 +00001095
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001096/* AC: cannot convert yet, as needs PEP 457 group support in inspect */
Guido van Rossum79f25d91997-04-29 20:08:16 +00001097static PyObject *
Serhiy Storchakaa5552f02017-12-15 13:11:11 +02001098builtin_getattr(PyObject *self, PyObject *const *args, Py_ssize_t nargs)
Guido van Rossum33894be1992-01-27 16:53:09 +00001099{
Serhiy Storchaka79342662019-01-12 08:25:41 +02001100 PyObject *v, *name, *result;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001101
Serhiy Storchaka79342662019-01-12 08:25:41 +02001102 if (!_PyArg_CheckPositional("getattr", nargs, 2, 3))
Sylvain96c7c062017-06-15 17:05:23 +02001103 return NULL;
1104
Serhiy Storchaka79342662019-01-12 08:25:41 +02001105 v = args[0];
1106 name = args[1];
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001107 if (!PyUnicode_Check(name)) {
1108 PyErr_SetString(PyExc_TypeError,
1109 "getattr(): attribute name must be string");
1110 return NULL;
1111 }
Serhiy Storchaka79342662019-01-12 08:25:41 +02001112 if (nargs > 2) {
Serhiy Storchakaf320be72018-01-25 10:49:40 +02001113 if (_PyObject_LookupAttr(v, name, &result) == 0) {
Serhiy Storchaka79342662019-01-12 08:25:41 +02001114 PyObject *dflt = args[2];
INADA Naoki378edee2018-01-16 20:52:41 +09001115 Py_INCREF(dflt);
1116 return dflt;
1117 }
1118 }
1119 else {
1120 result = PyObject_GetAttr(v, name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001121 }
1122 return result;
Guido van Rossum9bfef441993-03-29 10:43:31 +00001123}
1124
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001125PyDoc_STRVAR(getattr_doc,
Guido van Rossum950ff291998-06-29 13:38:57 +00001126"getattr(object, name[, default]) -> value\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001127\n\
Guido van Rossum950ff291998-06-29 13:38:57 +00001128Get a named attribute from an object; getattr(x, 'y') is equivalent to x.y.\n\
1129When a default argument is given, it is returned when the attribute doesn't\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001130exist; without it, an exception is raised in that case.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001131
1132
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001133/*[clinic input]
1134globals as builtin_globals
1135
1136Return the dictionary containing the current scope's global variables.
1137
1138NOTE: Updates to this dictionary *will* affect name lookups in the current
1139global scope and vice-versa.
1140[clinic start generated code]*/
1141
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001142static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001143builtin_globals_impl(PyObject *module)
1144/*[clinic end generated code: output=e5dd1527067b94d2 input=9327576f92bb48ba]*/
Guido van Rossum872537c1995-07-07 22:43:42 +00001145{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001146 PyObject *d;
Guido van Rossum872537c1995-07-07 22:43:42 +00001147
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001148 d = PyEval_GetGlobals();
1149 Py_XINCREF(d);
1150 return d;
Guido van Rossum872537c1995-07-07 22:43:42 +00001151}
1152
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001153
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001154/*[clinic input]
1155hasattr as builtin_hasattr
1156
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001157 obj: object
1158 name: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001159 /
1160
1161Return whether the object has an attribute with the given name.
1162
1163This is done by calling getattr(obj, name) and catching AttributeError.
1164[clinic start generated code]*/
1165
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001166static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001167builtin_hasattr_impl(PyObject *module, PyObject *obj, PyObject *name)
1168/*[clinic end generated code: output=a7aff2090a4151e5 input=0faec9787d979542]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001169{
1170 PyObject *v;
1171
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001172 if (!PyUnicode_Check(name)) {
1173 PyErr_SetString(PyExc_TypeError,
1174 "hasattr(): attribute name must be string");
1175 return NULL;
1176 }
Serhiy Storchakaf320be72018-01-25 10:49:40 +02001177 if (_PyObject_LookupAttr(obj, name, &v) < 0) {
Benjamin Peterson17689992010-08-24 03:26:23 +00001178 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001179 }
Serhiy Storchakaf320be72018-01-25 10:49:40 +02001180 if (v == NULL) {
1181 Py_RETURN_FALSE;
1182 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001183 Py_DECREF(v);
Benjamin Peterson17689992010-08-24 03:26:23 +00001184 Py_RETURN_TRUE;
Guido van Rossum33894be1992-01-27 16:53:09 +00001185}
1186
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001187
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001188/* AC: gdb's integration with CPython relies on builtin_id having
1189 * the *exact* parameter names of "self" and "v", so we ensure we
1190 * preserve those name rather than using the AC defaults.
1191 */
1192/*[clinic input]
1193id as builtin_id
1194
Serhiy Storchaka24182a32016-05-05 16:21:35 +03001195 self: self(type="PyModuleDef *")
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001196 obj as v: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001197 /
1198
1199Return the identity of an object.
1200
1201This is guaranteed to be unique among simultaneously existing objects.
1202(CPython uses the object's memory address.)
1203[clinic start generated code]*/
1204
Guido van Rossum79f25d91997-04-29 20:08:16 +00001205static PyObject *
Serhiy Storchaka24182a32016-05-05 16:21:35 +03001206builtin_id(PyModuleDef *self, PyObject *v)
1207/*[clinic end generated code: output=0aa640785f697f65 input=5a534136419631f4]*/
Guido van Rossum5b722181993-03-30 17:46:03 +00001208{
Steve Dowerb82e17e2019-05-23 08:45:22 -07001209 PyObject *id = PyLong_FromVoidPtr(v);
1210
1211 if (id && PySys_Audit("builtins.id", "O", id) < 0) {
1212 Py_DECREF(id);
1213 return NULL;
1214 }
1215
1216 return id;
Guido van Rossum5b722181993-03-30 17:46:03 +00001217}
1218
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001219
Raymond Hettingera6c60372008-03-13 01:26:19 +00001220/* map object ************************************************************/
1221
1222typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001223 PyObject_HEAD
1224 PyObject *iters;
1225 PyObject *func;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001226} mapobject;
1227
Guido van Rossum79f25d91997-04-29 20:08:16 +00001228static PyObject *
Raymond Hettingera6c60372008-03-13 01:26:19 +00001229map_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
Guido van Rossum12d12c51993-10-26 17:58:25 +00001230{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001231 PyObject *it, *iters, *func;
1232 mapobject *lz;
1233 Py_ssize_t numargs, i;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001234
Serhiy Storchaka6cca5c82017-06-08 14:41:19 +03001235 if (type == &PyMap_Type && !_PyArg_NoKeywords("map", kwds))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001236 return NULL;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001237
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001238 numargs = PyTuple_Size(args);
1239 if (numargs < 2) {
1240 PyErr_SetString(PyExc_TypeError,
1241 "map() must have at least two arguments.");
1242 return NULL;
1243 }
Raymond Hettingera6c60372008-03-13 01:26:19 +00001244
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001245 iters = PyTuple_New(numargs-1);
1246 if (iters == NULL)
1247 return NULL;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001248
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001249 for (i=1 ; i<numargs ; i++) {
1250 /* Get iterator. */
1251 it = PyObject_GetIter(PyTuple_GET_ITEM(args, i));
1252 if (it == NULL) {
1253 Py_DECREF(iters);
1254 return NULL;
1255 }
1256 PyTuple_SET_ITEM(iters, i-1, it);
1257 }
Raymond Hettingera6c60372008-03-13 01:26:19 +00001258
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001259 /* create mapobject structure */
1260 lz = (mapobject *)type->tp_alloc(type, 0);
1261 if (lz == NULL) {
1262 Py_DECREF(iters);
1263 return NULL;
1264 }
1265 lz->iters = iters;
1266 func = PyTuple_GET_ITEM(args, 0);
1267 Py_INCREF(func);
1268 lz->func = func;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001269
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001270 return (PyObject *)lz;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001271}
1272
1273static void
1274map_dealloc(mapobject *lz)
1275{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001276 PyObject_GC_UnTrack(lz);
1277 Py_XDECREF(lz->iters);
1278 Py_XDECREF(lz->func);
1279 Py_TYPE(lz)->tp_free(lz);
Raymond Hettingera6c60372008-03-13 01:26:19 +00001280}
1281
1282static int
1283map_traverse(mapobject *lz, visitproc visit, void *arg)
1284{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001285 Py_VISIT(lz->iters);
1286 Py_VISIT(lz->func);
1287 return 0;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001288}
1289
1290static PyObject *
1291map_next(mapobject *lz)
1292{
Victor Stinnerbc08ab42016-12-15 12:40:53 +01001293 PyObject *small_stack[_PY_FASTCALL_SMALL_STACK];
Victor Stinnercdb5cee2016-08-24 01:45:13 +02001294 PyObject **stack;
Victor Stinnercdb5cee2016-08-24 01:45:13 +02001295 PyObject *result = NULL;
Victor Stinner4d231bc2019-11-14 13:36:21 +01001296 PyThreadState *tstate = _PyThreadState_GET();
Raymond Hettingera6c60372008-03-13 01:26:19 +00001297
Victor Stinner4d231bc2019-11-14 13:36:21 +01001298 const Py_ssize_t niters = PyTuple_GET_SIZE(lz->iters);
Victor Stinnercdb5cee2016-08-24 01:45:13 +02001299 if (niters <= (Py_ssize_t)Py_ARRAY_LENGTH(small_stack)) {
1300 stack = small_stack;
1301 }
1302 else {
1303 stack = PyMem_Malloc(niters * sizeof(stack[0]));
1304 if (stack == NULL) {
Victor Stinner4d231bc2019-11-14 13:36:21 +01001305 _PyErr_NoMemory(tstate);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001306 return NULL;
1307 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001308 }
Victor Stinnercdb5cee2016-08-24 01:45:13 +02001309
Victor Stinner4d231bc2019-11-14 13:36:21 +01001310 Py_ssize_t nargs = 0;
1311 for (Py_ssize_t i=0; i < niters; i++) {
Victor Stinnercdb5cee2016-08-24 01:45:13 +02001312 PyObject *it = PyTuple_GET_ITEM(lz->iters, i);
1313 PyObject *val = Py_TYPE(it)->tp_iternext(it);
1314 if (val == NULL) {
1315 goto exit;
1316 }
1317 stack[i] = val;
1318 nargs++;
1319 }
1320
Victor Stinner4d231bc2019-11-14 13:36:21 +01001321 result = _PyObject_VectorcallTstate(tstate, lz->func, stack, nargs, NULL);
Victor Stinnercdb5cee2016-08-24 01:45:13 +02001322
1323exit:
Victor Stinner4d231bc2019-11-14 13:36:21 +01001324 for (Py_ssize_t i=0; i < nargs; i++) {
Victor Stinnercdb5cee2016-08-24 01:45:13 +02001325 Py_DECREF(stack[i]);
1326 }
1327 if (stack != small_stack) {
1328 PyMem_Free(stack);
1329 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001330 return result;
Guido van Rossum12d12c51993-10-26 17:58:25 +00001331}
1332
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001333static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05301334map_reduce(mapobject *lz, PyObject *Py_UNUSED(ignored))
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001335{
1336 Py_ssize_t numargs = PyTuple_GET_SIZE(lz->iters);
1337 PyObject *args = PyTuple_New(numargs+1);
1338 Py_ssize_t i;
1339 if (args == NULL)
1340 return NULL;
1341 Py_INCREF(lz->func);
1342 PyTuple_SET_ITEM(args, 0, lz->func);
1343 for (i = 0; i<numargs; i++){
1344 PyObject *it = PyTuple_GET_ITEM(lz->iters, i);
1345 Py_INCREF(it);
1346 PyTuple_SET_ITEM(args, i+1, it);
1347 }
1348
1349 return Py_BuildValue("ON", Py_TYPE(lz), args);
1350}
1351
1352static PyMethodDef map_methods[] = {
1353 {"__reduce__", (PyCFunction)map_reduce, METH_NOARGS, reduce_doc},
1354 {NULL, NULL} /* sentinel */
1355};
1356
1357
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001358PyDoc_STRVAR(map_doc,
Raymond Hettingera6c60372008-03-13 01:26:19 +00001359"map(func, *iterables) --> map object\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001360\n\
Raymond Hettingera6c60372008-03-13 01:26:19 +00001361Make an iterator that computes the function using arguments from\n\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001362each of the iterables. Stops when the shortest iterable is exhausted.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001363
Raymond Hettingera6c60372008-03-13 01:26:19 +00001364PyTypeObject PyMap_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001365 PyVarObject_HEAD_INIT(&PyType_Type, 0)
1366 "map", /* tp_name */
1367 sizeof(mapobject), /* tp_basicsize */
1368 0, /* tp_itemsize */
1369 /* methods */
1370 (destructor)map_dealloc, /* tp_dealloc */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02001371 0, /* tp_vectorcall_offset */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001372 0, /* tp_getattr */
1373 0, /* tp_setattr */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02001374 0, /* tp_as_async */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001375 0, /* tp_repr */
1376 0, /* tp_as_number */
1377 0, /* tp_as_sequence */
1378 0, /* tp_as_mapping */
1379 0, /* tp_hash */
1380 0, /* tp_call */
1381 0, /* tp_str */
1382 PyObject_GenericGetAttr, /* tp_getattro */
1383 0, /* tp_setattro */
1384 0, /* tp_as_buffer */
1385 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
1386 Py_TPFLAGS_BASETYPE, /* tp_flags */
1387 map_doc, /* tp_doc */
1388 (traverseproc)map_traverse, /* tp_traverse */
1389 0, /* tp_clear */
1390 0, /* tp_richcompare */
1391 0, /* tp_weaklistoffset */
1392 PyObject_SelfIter, /* tp_iter */
1393 (iternextfunc)map_next, /* tp_iternext */
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001394 map_methods, /* tp_methods */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001395 0, /* tp_members */
1396 0, /* tp_getset */
1397 0, /* tp_base */
1398 0, /* tp_dict */
1399 0, /* tp_descr_get */
1400 0, /* tp_descr_set */
1401 0, /* tp_dictoffset */
1402 0, /* tp_init */
1403 PyType_GenericAlloc, /* tp_alloc */
1404 map_new, /* tp_new */
1405 PyObject_GC_Del, /* tp_free */
Raymond Hettingera6c60372008-03-13 01:26:19 +00001406};
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001407
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001408
1409/* AC: cannot convert yet, as needs PEP 457 group support in inspect */
Guido van Rossum79f25d91997-04-29 20:08:16 +00001410static PyObject *
Serhiy Storchakaa5552f02017-12-15 13:11:11 +02001411builtin_next(PyObject *self, PyObject *const *args, Py_ssize_t nargs)
Georg Brandla18af4e2007-04-21 15:47:16 +00001412{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001413 PyObject *it, *res;
Georg Brandla18af4e2007-04-21 15:47:16 +00001414
Serhiy Storchaka79342662019-01-12 08:25:41 +02001415 if (!_PyArg_CheckPositional("next", nargs, 1, 2))
Sylvain96c7c062017-06-15 17:05:23 +02001416 return NULL;
1417
Serhiy Storchaka79342662019-01-12 08:25:41 +02001418 it = args[0];
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001419 if (!PyIter_Check(it)) {
1420 PyErr_Format(PyExc_TypeError,
Philip Jenvey50add042011-11-06 16:37:52 -08001421 "'%.200s' object is not an iterator",
Victor Stinnera102ed72020-02-07 02:24:48 +01001422 Py_TYPE(it)->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001423 return NULL;
1424 }
1425
Victor Stinnera102ed72020-02-07 02:24:48 +01001426 res = (*Py_TYPE(it)->tp_iternext)(it);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001427 if (res != NULL) {
1428 return res;
Serhiy Storchaka79342662019-01-12 08:25:41 +02001429 } else if (nargs > 1) {
1430 PyObject *def = args[1];
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001431 if (PyErr_Occurred()) {
1432 if(!PyErr_ExceptionMatches(PyExc_StopIteration))
1433 return NULL;
1434 PyErr_Clear();
1435 }
1436 Py_INCREF(def);
1437 return def;
1438 } else if (PyErr_Occurred()) {
1439 return NULL;
1440 } else {
1441 PyErr_SetNone(PyExc_StopIteration);
1442 return NULL;
1443 }
Georg Brandla18af4e2007-04-21 15:47:16 +00001444}
1445
1446PyDoc_STRVAR(next_doc,
1447"next(iterator[, default])\n\
1448\n\
1449Return the next item from the iterator. If default is given and the iterator\n\
1450is exhausted, it is returned instead of raising StopIteration.");
1451
1452
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001453/*[clinic input]
1454setattr as builtin_setattr
1455
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001456 obj: object
1457 name: object
1458 value: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001459 /
1460
1461Sets the named attribute on the given object to the specified value.
1462
1463setattr(x, 'y', v) is equivalent to ``x.y = v''
1464[clinic start generated code]*/
1465
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001466static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001467builtin_setattr_impl(PyObject *module, PyObject *obj, PyObject *name,
Larry Hastings89964c42015-04-14 18:07:59 -04001468 PyObject *value)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001469/*[clinic end generated code: output=dc2ce1d1add9acb4 input=bd2b7ca6875a1899]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001470{
1471 if (PyObject_SetAttr(obj, name, value) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001472 return NULL;
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02001473 Py_RETURN_NONE;
Guido van Rossum33894be1992-01-27 16:53:09 +00001474}
1475
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001476
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001477/*[clinic input]
1478delattr as builtin_delattr
1479
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001480 obj: object
1481 name: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001482 /
1483
1484Deletes the named attribute from the given object.
1485
1486delattr(x, 'y') is equivalent to ``del x.y''
1487[clinic start generated code]*/
1488
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001489static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001490builtin_delattr_impl(PyObject *module, PyObject *obj, PyObject *name)
1491/*[clinic end generated code: output=85134bc58dff79fa input=db16685d6b4b9410]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001492{
1493 if (PyObject_SetAttr(obj, name, (PyObject *)NULL) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001494 return NULL;
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02001495 Py_RETURN_NONE;
Guido van Rossum14144fc1994-08-29 12:53:40 +00001496}
1497
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001498
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001499/*[clinic input]
1500hash as builtin_hash
1501
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001502 obj: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001503 /
1504
1505Return the hash value for the given object.
1506
1507Two objects that compare equal must also have the same hash value, but the
1508reverse is not necessarily true.
1509[clinic start generated code]*/
1510
Guido van Rossum79f25d91997-04-29 20:08:16 +00001511static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001512builtin_hash(PyObject *module, PyObject *obj)
1513/*[clinic end generated code: output=237668e9d7688db7 input=58c48be822bf9c54]*/
Guido van Rossum9bfef441993-03-29 10:43:31 +00001514{
Benjamin Peterson8f67d082010-10-17 20:54:53 +00001515 Py_hash_t x;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001516
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001517 x = PyObject_Hash(obj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001518 if (x == -1)
1519 return NULL;
Benjamin Peterson8f67d082010-10-17 20:54:53 +00001520 return PyLong_FromSsize_t(x);
Guido van Rossum9bfef441993-03-29 10:43:31 +00001521}
1522
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001523
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001524/*[clinic input]
1525hex as builtin_hex
1526
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001527 number: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001528 /
1529
1530Return the hexadecimal representation of an integer.
1531
1532 >>> hex(12648430)
1533 '0xc0ffee'
1534[clinic start generated code]*/
1535
Guido van Rossum79f25d91997-04-29 20:08:16 +00001536static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001537builtin_hex(PyObject *module, PyObject *number)
1538/*[clinic end generated code: output=e46b612169099408 input=e645aff5fc7d540e]*/
Guido van Rossum006bcd41991-10-24 14:54:44 +00001539{
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001540 return PyNumber_ToBase(number, 16);
Guido van Rossum006bcd41991-10-24 14:54:44 +00001541}
1542
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001543
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001544/* AC: cannot convert yet, as needs PEP 457 group support in inspect */
Guido van Rossum79f25d91997-04-29 20:08:16 +00001545static PyObject *
Serhiy Storchaka79342662019-01-12 08:25:41 +02001546builtin_iter(PyObject *self, PyObject *const *args, Py_ssize_t nargs)
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001547{
Serhiy Storchaka79342662019-01-12 08:25:41 +02001548 PyObject *v;
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001549
Serhiy Storchaka79342662019-01-12 08:25:41 +02001550 if (!_PyArg_CheckPositional("iter", nargs, 1, 2))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001551 return NULL;
Serhiy Storchaka79342662019-01-12 08:25:41 +02001552 v = args[0];
1553 if (nargs == 1)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001554 return PyObject_GetIter(v);
1555 if (!PyCallable_Check(v)) {
1556 PyErr_SetString(PyExc_TypeError,
1557 "iter(v, w): v must be callable");
1558 return NULL;
1559 }
Serhiy Storchaka79342662019-01-12 08:25:41 +02001560 PyObject *sentinel = args[1];
1561 return PyCallIter_New(v, sentinel);
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001562}
1563
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001564PyDoc_STRVAR(iter_doc,
Georg Brandld11ae5d2008-05-16 13:27:32 +00001565"iter(iterable) -> iterator\n\
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001566iter(callable, sentinel) -> iterator\n\
1567\n\
1568Get an iterator from an object. In the first form, the argument must\n\
1569supply its own iterator, or be a sequence.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001570In the second form, the callable is called until it returns the sentinel.");
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001571
1572
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001573/*[clinic input]
1574len as builtin_len
1575
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001576 obj: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001577 /
1578
1579Return the number of items in a container.
1580[clinic start generated code]*/
1581
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001582static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001583builtin_len(PyObject *module, PyObject *obj)
1584/*[clinic end generated code: output=fa7a270d314dfb6c input=bc55598da9e9c9b5]*/
Guido van Rossum3f5da241990-12-20 15:06:42 +00001585{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001586 Py_ssize_t res;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001587
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001588 res = PyObject_Size(obj);
Serhiy Storchaka813f9432017-04-16 09:21:44 +03001589 if (res < 0) {
1590 assert(PyErr_Occurred());
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001591 return NULL;
Serhiy Storchaka813f9432017-04-16 09:21:44 +03001592 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001593 return PyLong_FromSsize_t(res);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001594}
1595
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001596
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001597/*[clinic input]
1598locals as builtin_locals
1599
1600Return a dictionary containing the current scope's local variables.
1601
1602NOTE: Whether or not updates to this dictionary will affect name lookups in
1603the local scope and vice-versa is *implementation dependent* and not
1604covered by any backwards compatibility guarantees.
1605[clinic start generated code]*/
1606
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001607static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001608builtin_locals_impl(PyObject *module)
1609/*[clinic end generated code: output=b46c94015ce11448 input=7874018d478d5c4b]*/
Guido van Rossum872537c1995-07-07 22:43:42 +00001610{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001611 PyObject *d;
Guido van Rossum872537c1995-07-07 22:43:42 +00001612
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001613 d = PyEval_GetLocals();
1614 Py_XINCREF(d);
1615 return d;
Guido van Rossum872537c1995-07-07 22:43:42 +00001616}
1617
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001618
Guido van Rossum79f25d91997-04-29 20:08:16 +00001619static PyObject *
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001620min_max(PyObject *args, PyObject *kwds, int op)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001621{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001622 PyObject *v, *it, *item, *val, *maxitem, *maxval, *keyfunc=NULL;
Raymond Hettinger4d6018f2013-06-24 22:43:02 -07001623 PyObject *emptytuple, *defaultval = NULL;
1624 static char *kwlist[] = {"key", "default", NULL};
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001625 const char *name = op == Py_LT ? "min" : "max";
Raymond Hettinger4d6018f2013-06-24 22:43:02 -07001626 const int positional = PyTuple_Size(args) > 1;
1627 int ret;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001628
Dong-hee Naabdc6342020-01-11 01:31:43 +09001629 if (positional) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001630 v = args;
Dong-hee Naabdc6342020-01-11 01:31:43 +09001631 }
1632 else if (!PyArg_UnpackTuple(args, name, 1, 1, &v)) {
1633 if (PyExceptionClass_Check(PyExc_TypeError)) {
1634 PyErr_Format(PyExc_TypeError, "%s expected at least 1 argument, got 0", name);
1635 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001636 return NULL;
Dong-hee Naabdc6342020-01-11 01:31:43 +09001637 }
Tim Peters67d687a2002-04-29 21:27:32 +00001638
Raymond Hettinger4d6018f2013-06-24 22:43:02 -07001639 emptytuple = PyTuple_New(0);
1640 if (emptytuple == NULL)
1641 return NULL;
Oren Milman58cf7482017-08-21 20:19:07 +03001642 ret = PyArg_ParseTupleAndKeywords(emptytuple, kwds,
1643 (op == Py_LT) ? "|$OO:min" : "|$OO:max",
1644 kwlist, &keyfunc, &defaultval);
Raymond Hettinger4d6018f2013-06-24 22:43:02 -07001645 Py_DECREF(emptytuple);
1646 if (!ret)
1647 return NULL;
1648
1649 if (positional && defaultval != NULL) {
1650 PyErr_Format(PyExc_TypeError,
1651 "Cannot specify a default for %s() with multiple "
1652 "positional arguments", name);
1653 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001654 }
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001655
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001656 it = PyObject_GetIter(v);
1657 if (it == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001658 return NULL;
1659 }
Tim Petersc3074532001-05-03 07:00:32 +00001660
Alexander Marshalove22072f2018-07-24 10:58:21 +07001661 if (keyfunc == Py_None) {
1662 keyfunc = NULL;
1663 }
1664
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001665 maxitem = NULL; /* the result */
1666 maxval = NULL; /* the value associated with the result */
1667 while (( item = PyIter_Next(it) )) {
1668 /* get the value from the key function */
1669 if (keyfunc != NULL) {
Petr Viktorinffd97532020-02-11 17:46:57 +01001670 val = PyObject_CallOneArg(keyfunc, item);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001671 if (val == NULL)
1672 goto Fail_it_item;
1673 }
1674 /* no key function; the value is the item */
1675 else {
1676 val = item;
1677 Py_INCREF(val);
1678 }
Tim Petersc3074532001-05-03 07:00:32 +00001679
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001680 /* maximum value and item are unset; set them */
1681 if (maxval == NULL) {
1682 maxitem = item;
1683 maxval = val;
1684 }
1685 /* maximum value and item are set; update them as necessary */
1686 else {
1687 int cmp = PyObject_RichCompareBool(val, maxval, op);
1688 if (cmp < 0)
1689 goto Fail_it_item_and_val;
1690 else if (cmp > 0) {
1691 Py_DECREF(maxval);
1692 Py_DECREF(maxitem);
1693 maxval = val;
1694 maxitem = item;
1695 }
1696 else {
1697 Py_DECREF(item);
1698 Py_DECREF(val);
1699 }
1700 }
1701 }
1702 if (PyErr_Occurred())
1703 goto Fail_it;
1704 if (maxval == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001705 assert(maxitem == NULL);
Raymond Hettinger4d6018f2013-06-24 22:43:02 -07001706 if (defaultval != NULL) {
1707 Py_INCREF(defaultval);
1708 maxitem = defaultval;
1709 } else {
1710 PyErr_Format(PyExc_ValueError,
1711 "%s() arg is an empty sequence", name);
1712 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001713 }
1714 else
1715 Py_DECREF(maxval);
1716 Py_DECREF(it);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001717 return maxitem;
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001718
1719Fail_it_item_and_val:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001720 Py_DECREF(val);
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001721Fail_it_item:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001722 Py_DECREF(item);
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001723Fail_it:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001724 Py_XDECREF(maxval);
1725 Py_XDECREF(maxitem);
1726 Py_DECREF(it);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001727 return NULL;
Guido van Rossum3f5da241990-12-20 15:06:42 +00001728}
1729
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001730/* AC: cannot convert yet, waiting for *args support */
Guido van Rossum79f25d91997-04-29 20:08:16 +00001731static PyObject *
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001732builtin_min(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001733{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001734 return min_max(args, kwds, Py_LT);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001735}
1736
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001737PyDoc_STRVAR(min_doc,
Raymond Hettinger2a545822014-05-19 22:20:52 +01001738"min(iterable, *[, default=obj, key=func]) -> value\n\
1739min(arg1, arg2, *args, *[, key=func]) -> value\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001740\n\
Raymond Hettinger2a545822014-05-19 22:20:52 +01001741With a single iterable argument, return its smallest item. The\n\
1742default keyword-only argument specifies an object to return if\n\
1743the provided iterable is empty.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001744With two or more arguments, return the smallest argument.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001745
1746
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001747/* AC: cannot convert yet, waiting for *args support */
Guido van Rossum79f25d91997-04-29 20:08:16 +00001748static PyObject *
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001749builtin_max(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001750{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001751 return min_max(args, kwds, Py_GT);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001752}
1753
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001754PyDoc_STRVAR(max_doc,
Raymond Hettinger2a545822014-05-19 22:20:52 +01001755"max(iterable, *[, default=obj, key=func]) -> value\n\
1756max(arg1, arg2, *args, *[, key=func]) -> value\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001757\n\
Raymond Hettinger2a545822014-05-19 22:20:52 +01001758With a single iterable argument, return its biggest item. The\n\
1759default keyword-only argument specifies an object to return if\n\
1760the provided iterable is empty.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001761With two or more arguments, return the largest argument.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001762
1763
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001764/*[clinic input]
1765oct as builtin_oct
1766
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001767 number: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001768 /
1769
1770Return the octal representation of an integer.
1771
1772 >>> oct(342391)
1773 '0o1234567'
1774[clinic start generated code]*/
1775
Guido van Rossum79f25d91997-04-29 20:08:16 +00001776static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001777builtin_oct(PyObject *module, PyObject *number)
1778/*[clinic end generated code: output=40a34656b6875352 input=ad6b274af4016c72]*/
Guido van Rossum006bcd41991-10-24 14:54:44 +00001779{
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001780 return PyNumber_ToBase(number, 8);
Guido van Rossum006bcd41991-10-24 14:54:44 +00001781}
1782
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001783
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001784/*[clinic input]
1785ord as builtin_ord
1786
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001787 c: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001788 /
1789
1790Return the Unicode code point for a one-character string.
1791[clinic start generated code]*/
1792
Guido van Rossum79f25d91997-04-29 20:08:16 +00001793static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001794builtin_ord(PyObject *module, PyObject *c)
1795/*[clinic end generated code: output=4fa5e87a323bae71 input=3064e5d6203ad012]*/
Guido van Rossum3f5da241990-12-20 15:06:42 +00001796{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001797 long ord;
1798 Py_ssize_t size;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001799
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001800 if (PyBytes_Check(c)) {
1801 size = PyBytes_GET_SIZE(c);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001802 if (size == 1) {
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001803 ord = (long)((unsigned char)*PyBytes_AS_STRING(c));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001804 return PyLong_FromLong(ord);
1805 }
1806 }
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001807 else if (PyUnicode_Check(c)) {
1808 if (PyUnicode_READY(c) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001809 return NULL;
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001810 size = PyUnicode_GET_LENGTH(c);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001811 if (size == 1) {
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001812 ord = (long)PyUnicode_READ_CHAR(c, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001813 return PyLong_FromLong(ord);
1814 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001815 }
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001816 else if (PyByteArray_Check(c)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001817 /* XXX Hopefully this is temporary */
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001818 size = PyByteArray_GET_SIZE(c);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001819 if (size == 1) {
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001820 ord = (long)((unsigned char)*PyByteArray_AS_STRING(c));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001821 return PyLong_FromLong(ord);
1822 }
1823 }
1824 else {
1825 PyErr_Format(PyExc_TypeError,
1826 "ord() expected string of length 1, but " \
Victor Stinnera102ed72020-02-07 02:24:48 +01001827 "%.200s found", Py_TYPE(c)->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001828 return NULL;
1829 }
Guido van Rossum09095f32000-03-10 23:00:52 +00001830
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001831 PyErr_Format(PyExc_TypeError,
1832 "ord() expected a character, "
1833 "but string of length %zd found",
1834 size);
1835 return NULL;
Guido van Rossum3f5da241990-12-20 15:06:42 +00001836}
1837
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001838
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001839/*[clinic input]
1840pow as builtin_pow
1841
Ammar Askar87d6cd32019-09-21 00:28:49 -04001842 base: object
1843 exp: object
1844 mod: object = None
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001845
Raymond Hettingerb104ecb2019-09-21 12:57:44 -07001846Equivalent to base**exp with 2 arguments or base**exp % mod with 3 arguments
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001847
1848Some types, such as ints, are able to use a more efficient algorithm when
1849invoked using the three argument form.
1850[clinic start generated code]*/
1851
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001852static PyObject *
Ammar Askar87d6cd32019-09-21 00:28:49 -04001853builtin_pow_impl(PyObject *module, PyObject *base, PyObject *exp,
1854 PyObject *mod)
Raymond Hettingerb104ecb2019-09-21 12:57:44 -07001855/*[clinic end generated code: output=3ca1538221bbf15f input=435dbd48a12efb23]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001856{
Ammar Askar87d6cd32019-09-21 00:28:49 -04001857 return PyNumber_Power(base, exp, mod);
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001858}
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001859
1860
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001861/* AC: cannot convert yet, waiting for *args support */
Guido van Rossum34343512006-11-30 22:13:52 +00001862static PyObject *
Serhiy Storchakaa5552f02017-12-15 13:11:11 +02001863builtin_print(PyObject *self, PyObject *const *args, Py_ssize_t nargs, PyObject *kwnames)
Guido van Rossum34343512006-11-30 22:13:52 +00001864{
INADA Naokibd584f12017-01-19 12:50:34 +01001865 static const char * const _keywords[] = {"sep", "end", "file", "flush", 0};
Serhiy Storchaka1f21eaa2019-09-01 12:16:51 +03001866 static struct _PyArg_Parser _parser = {"|OOOp:print", _keywords, 0};
1867 PyObject *sep = NULL, *end = NULL, *file = NULL;
1868 int flush = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001869 int i, err;
Guido van Rossum34343512006-11-30 22:13:52 +00001870
INADA Naokibd584f12017-01-19 12:50:34 +01001871 if (kwnames != NULL &&
1872 !_PyArg_ParseStackAndKeywords(args + nargs, 0, kwnames, &_parser,
1873 &sep, &end, &file, &flush)) {
Georg Brandlbc3b6822012-01-13 19:41:25 +01001874 return NULL;
INADA Naokibd584f12017-01-19 12:50:34 +01001875 }
1876
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001877 if (file == NULL || file == Py_None) {
Victor Stinnerbd303c12013-11-07 23:07:29 +01001878 file = _PySys_GetObjectId(&PyId_stdout);
Victor Stinner1e53bba2013-07-16 22:26:05 +02001879 if (file == NULL) {
1880 PyErr_SetString(PyExc_RuntimeError, "lost sys.stdout");
1881 return NULL;
1882 }
1883
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001884 /* sys.stdout may be None when FILE* stdout isn't connected */
1885 if (file == Py_None)
1886 Py_RETURN_NONE;
1887 }
Guido van Rossum34343512006-11-30 22:13:52 +00001888
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001889 if (sep == Py_None) {
1890 sep = NULL;
1891 }
1892 else if (sep && !PyUnicode_Check(sep)) {
1893 PyErr_Format(PyExc_TypeError,
1894 "sep must be None or a string, not %.200s",
Victor Stinnera102ed72020-02-07 02:24:48 +01001895 Py_TYPE(sep)->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001896 return NULL;
1897 }
1898 if (end == Py_None) {
1899 end = NULL;
1900 }
1901 else if (end && !PyUnicode_Check(end)) {
1902 PyErr_Format(PyExc_TypeError,
1903 "end must be None or a string, not %.200s",
Victor Stinnera102ed72020-02-07 02:24:48 +01001904 Py_TYPE(end)->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001905 return NULL;
1906 }
Guido van Rossum34343512006-11-30 22:13:52 +00001907
INADA Naokibd584f12017-01-19 12:50:34 +01001908 for (i = 0; i < nargs; i++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001909 if (i > 0) {
1910 if (sep == NULL)
1911 err = PyFile_WriteString(" ", file);
1912 else
1913 err = PyFile_WriteObject(sep, file,
1914 Py_PRINT_RAW);
1915 if (err)
1916 return NULL;
1917 }
INADA Naokibd584f12017-01-19 12:50:34 +01001918 err = PyFile_WriteObject(args[i], file, Py_PRINT_RAW);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001919 if (err)
1920 return NULL;
1921 }
Guido van Rossum34343512006-11-30 22:13:52 +00001922
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001923 if (end == NULL)
1924 err = PyFile_WriteString("\n", file);
1925 else
1926 err = PyFile_WriteObject(end, file, Py_PRINT_RAW);
1927 if (err)
1928 return NULL;
Guido van Rossum34343512006-11-30 22:13:52 +00001929
Serhiy Storchaka1f21eaa2019-09-01 12:16:51 +03001930 if (flush) {
1931 PyObject *tmp = _PyObject_CallMethodIdNoArgs(file, &PyId_flush);
1932 if (tmp == NULL)
Georg Brandlbc3b6822012-01-13 19:41:25 +01001933 return NULL;
Serhiy Storchaka1f21eaa2019-09-01 12:16:51 +03001934 Py_DECREF(tmp);
Georg Brandlbc3b6822012-01-13 19:41:25 +01001935 }
1936
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001937 Py_RETURN_NONE;
Guido van Rossum34343512006-11-30 22:13:52 +00001938}
1939
1940PyDoc_STRVAR(print_doc,
Senthil Kumarane9175bd2012-08-10 13:53:45 -07001941"print(value, ..., sep=' ', end='\\n', file=sys.stdout, flush=False)\n\
Guido van Rossum34343512006-11-30 22:13:52 +00001942\n\
1943Prints the values to a stream, or to sys.stdout by default.\n\
1944Optional keyword arguments:\n\
Senthil Kumarane9175bd2012-08-10 13:53:45 -07001945file: a file-like object (stream); defaults to the current sys.stdout.\n\
1946sep: string inserted between values, default a space.\n\
1947end: string appended after the last value, default a newline.\n\
1948flush: whether to forcibly flush the stream.");
Guido van Rossum34343512006-11-30 22:13:52 +00001949
1950
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001951/*[clinic input]
1952input as builtin_input
1953
1954 prompt: object(c_default="NULL") = None
1955 /
1956
1957Read a string from standard input. The trailing newline is stripped.
1958
1959The prompt string, if given, is printed to standard output without a
1960trailing newline before reading input.
1961
1962If the user hits EOF (*nix: Ctrl-D, Windows: Ctrl-Z+Return), raise EOFError.
1963On *nix systems, readline is used if available.
1964[clinic start generated code]*/
1965
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001966static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001967builtin_input_impl(PyObject *module, PyObject *prompt)
1968/*[clinic end generated code: output=83db5a191e7a0d60 input=5e8bb70c2908fe3c]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001969{
Victor Stinnerbd303c12013-11-07 23:07:29 +01001970 PyObject *fin = _PySys_GetObjectId(&PyId_stdin);
1971 PyObject *fout = _PySys_GetObjectId(&PyId_stdout);
1972 PyObject *ferr = _PySys_GetObjectId(&PyId_stderr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001973 PyObject *tmp;
1974 long fd;
1975 int tty;
Guido van Rossuma88a0332007-02-26 16:59:55 +00001976
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001977 /* Check that stdin/out/err are intact */
1978 if (fin == NULL || fin == Py_None) {
1979 PyErr_SetString(PyExc_RuntimeError,
1980 "input(): lost sys.stdin");
1981 return NULL;
1982 }
1983 if (fout == NULL || fout == Py_None) {
1984 PyErr_SetString(PyExc_RuntimeError,
1985 "input(): lost sys.stdout");
1986 return NULL;
1987 }
1988 if (ferr == NULL || ferr == Py_None) {
1989 PyErr_SetString(PyExc_RuntimeError,
1990 "input(): lost sys.stderr");
1991 return NULL;
1992 }
Guido van Rossumeba76962007-05-27 09:13:28 +00001993
Steve Dowerb82e17e2019-05-23 08:45:22 -07001994 if (PySys_Audit("builtins.input", "O", prompt ? prompt : Py_None) < 0) {
1995 return NULL;
1996 }
1997
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001998 /* First of all, flush stderr */
Jeroen Demeyer762f93f2019-07-08 10:19:25 +02001999 tmp = _PyObject_CallMethodIdNoArgs(ferr, &PyId_flush);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002000 if (tmp == NULL)
2001 PyErr_Clear();
2002 else
2003 Py_DECREF(tmp);
Guido van Rossumeba76962007-05-27 09:13:28 +00002004
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002005 /* We should only use (GNU) readline if Python's sys.stdin and
2006 sys.stdout are the same as C's stdin and stdout, because we
2007 need to pass it those. */
Jeroen Demeyer762f93f2019-07-08 10:19:25 +02002008 tmp = _PyObject_CallMethodIdNoArgs(fin, &PyId_fileno);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002009 if (tmp == NULL) {
2010 PyErr_Clear();
2011 tty = 0;
2012 }
2013 else {
2014 fd = PyLong_AsLong(tmp);
2015 Py_DECREF(tmp);
2016 if (fd < 0 && PyErr_Occurred())
2017 return NULL;
2018 tty = fd == fileno(stdin) && isatty(fd);
2019 }
2020 if (tty) {
Jeroen Demeyer762f93f2019-07-08 10:19:25 +02002021 tmp = _PyObject_CallMethodIdNoArgs(fout, &PyId_fileno);
Martin Panterc9a6ab52015-10-10 01:25:38 +00002022 if (tmp == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002023 PyErr_Clear();
Martin Panterc9a6ab52015-10-10 01:25:38 +00002024 tty = 0;
2025 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002026 else {
2027 fd = PyLong_AsLong(tmp);
2028 Py_DECREF(tmp);
2029 if (fd < 0 && PyErr_Occurred())
2030 return NULL;
2031 tty = fd == fileno(stdout) && isatty(fd);
2032 }
2033 }
Guido van Rossumeba76962007-05-27 09:13:28 +00002034
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002035 /* If we're interactive, use (GNU) readline */
2036 if (tty) {
Antoine Pitrou0d776b12011-11-06 00:34:26 +01002037 PyObject *po = NULL;
Serhiy Storchakae2f92de2017-11-11 13:06:26 +02002038 const char *promptstr;
Antoine Pitrou0d776b12011-11-06 00:34:26 +01002039 char *s = NULL;
2040 PyObject *stdin_encoding = NULL, *stdin_errors = NULL;
2041 PyObject *stdout_encoding = NULL, *stdout_errors = NULL;
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +02002042 const char *stdin_encoding_str, *stdin_errors_str;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002043 PyObject *result;
Victor Stinnerc0f1a1a2011-02-23 12:07:37 +00002044 size_t len;
Martin v. Löwis4a7b5d52007-09-04 05:24:49 +00002045
Serhiy Storchakac2cf1282017-03-12 13:50:36 +02002046 /* stdin is a text stream, so it must have an encoding. */
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02002047 stdin_encoding = _PyObject_GetAttrId(fin, &PyId_encoding);
Antoine Pitrou5ee9d8a2011-11-06 00:38:45 +01002048 stdin_errors = _PyObject_GetAttrId(fin, &PyId_errors);
Serhiy Storchakac2cf1282017-03-12 13:50:36 +02002049 if (!stdin_encoding || !stdin_errors ||
2050 !PyUnicode_Check(stdin_encoding) ||
2051 !PyUnicode_Check(stdin_errors)) {
2052 tty = 0;
Antoine Pitrou0d776b12011-11-06 00:34:26 +01002053 goto _readline_errors;
Serhiy Storchakac2cf1282017-03-12 13:50:36 +02002054 }
Serhiy Storchaka06515832016-11-20 09:13:07 +02002055 stdin_encoding_str = PyUnicode_AsUTF8(stdin_encoding);
2056 stdin_errors_str = PyUnicode_AsUTF8(stdin_errors);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01002057 if (!stdin_encoding_str || !stdin_errors_str)
2058 goto _readline_errors;
Jeroen Demeyer762f93f2019-07-08 10:19:25 +02002059 tmp = _PyObject_CallMethodIdNoArgs(fout, &PyId_flush);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002060 if (tmp == NULL)
2061 PyErr_Clear();
2062 else
2063 Py_DECREF(tmp);
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002064 if (prompt != NULL) {
Antoine Pitrou0d776b12011-11-06 00:34:26 +01002065 /* We have a prompt, encode it as stdout would */
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +02002066 const char *stdout_encoding_str, *stdout_errors_str;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002067 PyObject *stringpo;
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02002068 stdout_encoding = _PyObject_GetAttrId(fout, &PyId_encoding);
Antoine Pitrou5ee9d8a2011-11-06 00:38:45 +01002069 stdout_errors = _PyObject_GetAttrId(fout, &PyId_errors);
Serhiy Storchakac2cf1282017-03-12 13:50:36 +02002070 if (!stdout_encoding || !stdout_errors ||
2071 !PyUnicode_Check(stdout_encoding) ||
2072 !PyUnicode_Check(stdout_errors)) {
2073 tty = 0;
Antoine Pitrou0d776b12011-11-06 00:34:26 +01002074 goto _readline_errors;
Serhiy Storchakac2cf1282017-03-12 13:50:36 +02002075 }
Serhiy Storchaka06515832016-11-20 09:13:07 +02002076 stdout_encoding_str = PyUnicode_AsUTF8(stdout_encoding);
2077 stdout_errors_str = PyUnicode_AsUTF8(stdout_errors);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01002078 if (!stdout_encoding_str || !stdout_errors_str)
2079 goto _readline_errors;
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002080 stringpo = PyObject_Str(prompt);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01002081 if (stringpo == NULL)
2082 goto _readline_errors;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002083 po = PyUnicode_AsEncodedString(stringpo,
Antoine Pitrou0d776b12011-11-06 00:34:26 +01002084 stdout_encoding_str, stdout_errors_str);
2085 Py_CLEAR(stdout_encoding);
2086 Py_CLEAR(stdout_errors);
2087 Py_CLEAR(stringpo);
2088 if (po == NULL)
2089 goto _readline_errors;
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03002090 assert(PyBytes_Check(po));
2091 promptstr = PyBytes_AS_STRING(po);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002092 }
2093 else {
2094 po = NULL;
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002095 promptstr = "";
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002096 }
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002097 s = PyOS_Readline(stdin, stdout, promptstr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002098 if (s == NULL) {
Richard Oudkerk614c5782013-04-03 13:44:50 +01002099 PyErr_CheckSignals();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002100 if (!PyErr_Occurred())
2101 PyErr_SetNone(PyExc_KeyboardInterrupt);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01002102 goto _readline_errors;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002103 }
Victor Stinnerc0f1a1a2011-02-23 12:07:37 +00002104
2105 len = strlen(s);
2106 if (len == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002107 PyErr_SetNone(PyExc_EOFError);
2108 result = NULL;
2109 }
Victor Stinnerc0f1a1a2011-02-23 12:07:37 +00002110 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002111 if (len > PY_SSIZE_T_MAX) {
2112 PyErr_SetString(PyExc_OverflowError,
2113 "input: input too long");
2114 result = NULL;
2115 }
2116 else {
Victor Stinnerc0f1a1a2011-02-23 12:07:37 +00002117 len--; /* strip trailing '\n' */
2118 if (len != 0 && s[len-1] == '\r')
2119 len--; /* strip trailing '\r' */
Antoine Pitrou0d776b12011-11-06 00:34:26 +01002120 result = PyUnicode_Decode(s, len, stdin_encoding_str,
2121 stdin_errors_str);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002122 }
2123 }
2124 Py_DECREF(stdin_encoding);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01002125 Py_DECREF(stdin_errors);
2126 Py_XDECREF(po);
Victor Stinner00d7abd2020-12-01 09:56:42 +01002127 PyMem_Free(s);
Steve Dowerb82e17e2019-05-23 08:45:22 -07002128
2129 if (result != NULL) {
2130 if (PySys_Audit("builtins.input/result", "O", result) < 0) {
2131 return NULL;
2132 }
2133 }
2134
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002135 return result;
Serhiy Storchakac2cf1282017-03-12 13:50:36 +02002136
Antoine Pitrou0d776b12011-11-06 00:34:26 +01002137 _readline_errors:
2138 Py_XDECREF(stdin_encoding);
2139 Py_XDECREF(stdout_encoding);
2140 Py_XDECREF(stdin_errors);
2141 Py_XDECREF(stdout_errors);
2142 Py_XDECREF(po);
Serhiy Storchakac2cf1282017-03-12 13:50:36 +02002143 if (tty)
2144 return NULL;
2145
2146 PyErr_Clear();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002147 }
Guido van Rossumeba76962007-05-27 09:13:28 +00002148
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002149 /* Fallback if we're not interactive */
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002150 if (prompt != NULL) {
2151 if (PyFile_WriteObject(prompt, fout, Py_PRINT_RAW) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002152 return NULL;
2153 }
Jeroen Demeyer762f93f2019-07-08 10:19:25 +02002154 tmp = _PyObject_CallMethodIdNoArgs(fout, &PyId_flush);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002155 if (tmp == NULL)
2156 PyErr_Clear();
2157 else
2158 Py_DECREF(tmp);
2159 return PyFile_GetLine(fin, -1);
Guido van Rossuma88a0332007-02-26 16:59:55 +00002160}
2161
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002162
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002163/*[clinic input]
2164repr as builtin_repr
2165
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03002166 obj: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002167 /
2168
2169Return the canonical string representation of the object.
2170
2171For many object types, including most builtins, eval(repr(obj)) == obj.
2172[clinic start generated code]*/
2173
Guido van Rossum79f25d91997-04-29 20:08:16 +00002174static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002175builtin_repr(PyObject *module, PyObject *obj)
2176/*[clinic end generated code: output=7ed3778c44fd0194 input=1c9e6d66d3e3be04]*/
Guido van Rossumc89705d1992-11-26 08:54:07 +00002177{
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002178 return PyObject_Repr(obj);
Guido van Rossumc89705d1992-11-26 08:54:07 +00002179}
2180
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002181
Serhiy Storchakaaca7f572017-11-15 17:51:14 +02002182/*[clinic input]
2183round as builtin_round
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002184
Serhiy Storchakaaca7f572017-11-15 17:51:14 +02002185 number: object
Serhiy Storchaka279f4462019-09-14 12:24:05 +03002186 ndigits: object = None
Serhiy Storchakaaca7f572017-11-15 17:51:14 +02002187
2188Round a number to a given precision in decimal digits.
2189
2190The return value is an integer if ndigits is omitted or None. Otherwise
2191the return value has the same type as the number. ndigits may be negative.
2192[clinic start generated code]*/
2193
2194static PyObject *
2195builtin_round_impl(PyObject *module, PyObject *number, PyObject *ndigits)
Serhiy Storchaka279f4462019-09-14 12:24:05 +03002196/*[clinic end generated code: output=ff0d9dd176c02ede input=275678471d7aca15]*/
Serhiy Storchakaaca7f572017-11-15 17:51:14 +02002197{
2198 PyObject *round, *result;
Alex Martelliae211f92007-08-22 23:21:33 +00002199
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002200 if (Py_TYPE(number)->tp_dict == NULL) {
2201 if (PyType_Ready(Py_TYPE(number)) < 0)
2202 return NULL;
2203 }
Guido van Rossum15d3d042007-08-24 02:02:45 +00002204
Benjamin Peterson214a7d22013-04-13 17:19:01 -04002205 round = _PyObject_LookupSpecial(number, &PyId___round__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002206 if (round == NULL) {
Benjamin Peterson214a7d22013-04-13 17:19:01 -04002207 if (!PyErr_Occurred())
2208 PyErr_Format(PyExc_TypeError,
2209 "type %.100s doesn't define __round__ method",
2210 Py_TYPE(number)->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002211 return NULL;
2212 }
Alex Martelliae211f92007-08-22 23:21:33 +00002213
Serhiy Storchaka279f4462019-09-14 12:24:05 +03002214 if (ndigits == Py_None)
Victor Stinnerf17c3de2016-12-06 18:46:19 +01002215 result = _PyObject_CallNoArg(round);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002216 else
Petr Viktorinffd97532020-02-11 17:46:57 +01002217 result = PyObject_CallOneArg(round, ndigits);
Benjamin Peterson214a7d22013-04-13 17:19:01 -04002218 Py_DECREF(round);
2219 return result;
Guido van Rossum9e51f9b1993-02-12 16:29:05 +00002220}
2221
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002222
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002223/*AC: we need to keep the kwds dict intact to easily call into the
2224 * list.sort method, which isn't currently supported in AC. So we just use
2225 * the initially generated signature with a custom implementation.
2226 */
2227/* [disabled clinic input]
2228sorted as builtin_sorted
2229
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03002230 iterable as seq: object
2231 key as keyfunc: object = None
2232 reverse: object = False
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002233
2234Return a new list containing all items from the iterable in ascending order.
2235
Raymond Hettinger7ea386e2016-08-25 21:11:50 -07002236A custom key function can be supplied to customize the sort order, and the
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002237reverse flag can be set to request the result in descending order.
2238[end disabled clinic input]*/
2239
2240PyDoc_STRVAR(builtin_sorted__doc__,
Serhiy Storchaka3a104252017-01-23 12:29:47 +02002241"sorted($module, iterable, /, *, key=None, reverse=False)\n"
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002242"--\n"
2243"\n"
2244"Return a new list containing all items from the iterable in ascending order.\n"
2245"\n"
Raymond Hettinger7ea386e2016-08-25 21:11:50 -07002246"A custom key function can be supplied to customize the sort order, and the\n"
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002247"reverse flag can be set to request the result in descending order.");
2248
2249#define BUILTIN_SORTED_METHODDEF \
Serhiy Storchaka62be7422018-11-27 13:27:31 +02002250 {"sorted", (PyCFunction)(void(*)(void))builtin_sorted, METH_FASTCALL | METH_KEYWORDS, builtin_sorted__doc__},
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002251
Raymond Hettinger64958a12003-12-17 20:43:33 +00002252static PyObject *
Serhiy Storchakaa5552f02017-12-15 13:11:11 +02002253builtin_sorted(PyObject *self, PyObject *const *args, Py_ssize_t nargs, PyObject *kwnames)
Raymond Hettinger64958a12003-12-17 20:43:33 +00002254{
Serhiy Storchaka7cf8beb2017-01-21 23:05:00 +02002255 PyObject *newlist, *v, *seq, *callable;
Victor Stinner5a60eca2017-01-17 15:17:49 +01002256
Serhiy Storchaka7cf8beb2017-01-21 23:05:00 +02002257 /* Keyword arguments are passed through list.sort() which will check
2258 them. */
2259 if (!_PyArg_UnpackStack(args, nargs, "sorted", 1, 1, &seq))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002260 return NULL;
Raymond Hettinger64958a12003-12-17 20:43:33 +00002261
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002262 newlist = PySequence_List(seq);
2263 if (newlist == NULL)
2264 return NULL;
Raymond Hettinger64958a12003-12-17 20:43:33 +00002265
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02002266 callable = _PyObject_GetAttrId(newlist, &PyId_sort);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002267 if (callable == NULL) {
2268 Py_DECREF(newlist);
2269 return NULL;
2270 }
Georg Brandl99d7e4e2005-08-31 22:21:15 +00002271
Serhiy Storchaka299dc232017-01-20 08:35:18 +02002272 assert(nargs >= 1);
Petr Viktorinffd97532020-02-11 17:46:57 +01002273 v = PyObject_Vectorcall(callable, args + 1, nargs - 1, kwnames);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002274 Py_DECREF(callable);
2275 if (v == NULL) {
2276 Py_DECREF(newlist);
2277 return NULL;
2278 }
2279 Py_DECREF(v);
2280 return newlist;
Raymond Hettinger64958a12003-12-17 20:43:33 +00002281}
2282
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002283
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002284/* AC: cannot convert yet, as needs PEP 457 group support in inspect */
Guido van Rossum79f25d91997-04-29 20:08:16 +00002285static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002286builtin_vars(PyObject *self, PyObject *args)
Guido van Rossum2d951851994-08-29 12:52:16 +00002287{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002288 PyObject *v = NULL;
2289 PyObject *d;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002290
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002291 if (!PyArg_UnpackTuple(args, "vars", 0, 1, &v))
2292 return NULL;
2293 if (v == NULL) {
2294 d = PyEval_GetLocals();
Serhiy Storchaka41c57b32019-09-01 12:03:39 +03002295 Py_XINCREF(d);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002296 }
2297 else {
Serhiy Storchaka41c57b32019-09-01 12:03:39 +03002298 if (_PyObject_LookupAttrId(v, &PyId___dict__, &d) == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002299 PyErr_SetString(PyExc_TypeError,
2300 "vars() argument must have __dict__ attribute");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002301 }
2302 }
2303 return d;
Guido van Rossum2d951851994-08-29 12:52:16 +00002304}
2305
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002306PyDoc_STRVAR(vars_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002307"vars([object]) -> dictionary\n\
2308\n\
2309Without arguments, equivalent to locals().\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002310With an argument, equivalent to object.__dict__.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002311
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002312
2313/*[clinic input]
2314sum as builtin_sum
2315
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03002316 iterable: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002317 /
Raymond Hettinger9dfa0fe2018-09-12 10:54:06 -07002318 start: object(c_default="NULL") = 0
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002319
2320Return the sum of a 'start' value (default: 0) plus an iterable of numbers
2321
2322When the iterable is empty, return the start value.
2323This function is intended specifically for use with numeric values and may
2324reject non-numeric types.
2325[clinic start generated code]*/
2326
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002327static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002328builtin_sum_impl(PyObject *module, PyObject *iterable, PyObject *start)
Raymond Hettinger9dfa0fe2018-09-12 10:54:06 -07002329/*[clinic end generated code: output=df758cec7d1d302f input=162b50765250d222]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002330{
2331 PyObject *result = start;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002332 PyObject *temp, *item, *iter;
Alex Martellia70b1912003-04-22 08:12:33 +00002333
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002334 iter = PyObject_GetIter(iterable);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002335 if (iter == NULL)
2336 return NULL;
Alex Martellia70b1912003-04-22 08:12:33 +00002337
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002338 if (result == NULL) {
2339 result = PyLong_FromLong(0);
2340 if (result == NULL) {
2341 Py_DECREF(iter);
2342 return NULL;
2343 }
2344 } else {
2345 /* reject string values for 'start' parameter */
2346 if (PyUnicode_Check(result)) {
2347 PyErr_SetString(PyExc_TypeError,
2348 "sum() can't sum strings [use ''.join(seq) instead]");
2349 Py_DECREF(iter);
2350 return NULL;
2351 }
Benjamin Petersonce071ca2011-07-29 14:23:47 -05002352 if (PyBytes_Check(result)) {
2353 PyErr_SetString(PyExc_TypeError,
2354 "sum() can't sum bytes [use b''.join(seq) instead]");
Benjamin Peterson405f32c2011-07-29 22:43:45 -05002355 Py_DECREF(iter);
Benjamin Petersonce071ca2011-07-29 14:23:47 -05002356 return NULL;
2357 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002358 if (PyByteArray_Check(result)) {
2359 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson4f921c22011-07-29 14:24:29 -05002360 "sum() can't sum bytearray [use b''.join(seq) instead]");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002361 Py_DECREF(iter);
2362 return NULL;
2363 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002364 Py_INCREF(result);
2365 }
Alex Martellia70b1912003-04-22 08:12:33 +00002366
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002367#ifndef SLOW_SUM
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002368 /* Fast addition by keeping temporary sums in C instead of new Python objects.
2369 Assumes all inputs are the same type. If the assumption fails, default
2370 to the more general routine.
2371 */
2372 if (PyLong_CheckExact(result)) {
2373 int overflow;
2374 long i_result = PyLong_AsLongAndOverflow(result, &overflow);
2375 /* If this already overflowed, don't even enter the loop. */
2376 if (overflow == 0) {
2377 Py_DECREF(result);
2378 result = NULL;
2379 }
2380 while(result == NULL) {
2381 item = PyIter_Next(iter);
2382 if (item == NULL) {
2383 Py_DECREF(iter);
2384 if (PyErr_Occurred())
2385 return NULL;
2386 return PyLong_FromLong(i_result);
2387 }
Serhiy Storchaka88bdb922019-09-10 16:31:01 +03002388 if (PyLong_CheckExact(item) || PyBool_Check(item)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002389 long b = PyLong_AsLongAndOverflow(item, &overflow);
Serhiy Storchaka29500732019-05-05 14:26:23 +03002390 if (overflow == 0 &&
2391 (i_result >= 0 ? (b <= LONG_MAX - i_result)
2392 : (b >= LONG_MIN - i_result)))
2393 {
2394 i_result += b;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002395 Py_DECREF(item);
2396 continue;
2397 }
2398 }
2399 /* Either overflowed or is not an int. Restore real objects and process normally */
2400 result = PyLong_FromLong(i_result);
Christian Heimes704e2d32013-07-26 22:49:26 +02002401 if (result == NULL) {
2402 Py_DECREF(item);
2403 Py_DECREF(iter);
2404 return NULL;
2405 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002406 temp = PyNumber_Add(result, item);
2407 Py_DECREF(result);
2408 Py_DECREF(item);
2409 result = temp;
2410 if (result == NULL) {
2411 Py_DECREF(iter);
2412 return NULL;
2413 }
2414 }
2415 }
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002416
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002417 if (PyFloat_CheckExact(result)) {
2418 double f_result = PyFloat_AS_DOUBLE(result);
2419 Py_DECREF(result);
2420 result = NULL;
2421 while(result == NULL) {
2422 item = PyIter_Next(iter);
2423 if (item == NULL) {
2424 Py_DECREF(iter);
2425 if (PyErr_Occurred())
2426 return NULL;
2427 return PyFloat_FromDouble(f_result);
2428 }
2429 if (PyFloat_CheckExact(item)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002430 f_result += PyFloat_AS_DOUBLE(item);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002431 Py_DECREF(item);
2432 continue;
2433 }
Serhiy Storchaka88bdb922019-09-10 16:31:01 +03002434 if (PyLong_Check(item)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002435 long value;
2436 int overflow;
2437 value = PyLong_AsLongAndOverflow(item, &overflow);
2438 if (!overflow) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002439 f_result += (double)value;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002440 Py_DECREF(item);
2441 continue;
2442 }
2443 }
2444 result = PyFloat_FromDouble(f_result);
Alexey Izbyshev2b824b22018-08-24 07:27:52 +03002445 if (result == NULL) {
2446 Py_DECREF(item);
2447 Py_DECREF(iter);
2448 return NULL;
2449 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002450 temp = PyNumber_Add(result, item);
2451 Py_DECREF(result);
2452 Py_DECREF(item);
2453 result = temp;
2454 if (result == NULL) {
2455 Py_DECREF(iter);
2456 return NULL;
2457 }
2458 }
2459 }
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002460#endif
2461
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002462 for(;;) {
2463 item = PyIter_Next(iter);
2464 if (item == NULL) {
2465 /* error, or end-of-sequence */
2466 if (PyErr_Occurred()) {
2467 Py_DECREF(result);
2468 result = NULL;
2469 }
2470 break;
2471 }
2472 /* It's tempting to use PyNumber_InPlaceAdd instead of
2473 PyNumber_Add here, to avoid quadratic running time
2474 when doing 'sum(list_of_lists, [])'. However, this
2475 would produce a change in behaviour: a snippet like
Mark Dickinson9acadc52009-10-26 14:19:42 +00002476
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002477 empty = []
2478 sum([[x] for x in range(10)], empty)
Mark Dickinson9acadc52009-10-26 14:19:42 +00002479
Brandt Bucherabb9a442020-02-01 03:08:34 -08002480 would change the value of empty. In fact, using
2481 in-place addition rather that binary addition for
2482 any of the steps introduces subtle behavior changes:
Victor Stinner58f4e1a2020-02-05 18:24:33 +01002483
Brandt Bucherabb9a442020-02-01 03:08:34 -08002484 https://bugs.python.org/issue18305 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002485 temp = PyNumber_Add(result, item);
2486 Py_DECREF(result);
2487 Py_DECREF(item);
2488 result = temp;
2489 if (result == NULL)
2490 break;
2491 }
2492 Py_DECREF(iter);
2493 return result;
Alex Martellia70b1912003-04-22 08:12:33 +00002494}
2495
Alex Martellia70b1912003-04-22 08:12:33 +00002496
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002497/*[clinic input]
2498isinstance as builtin_isinstance
2499
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03002500 obj: object
2501 class_or_tuple: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002502 /
2503
2504Return whether an object is an instance of a class or of a subclass thereof.
2505
2506A tuple, as in ``isinstance(x, (A, B, ...))``, may be given as the target to
2507check against. This is equivalent to ``isinstance(x, A) or isinstance(x, B)
2508or ...`` etc.
2509[clinic start generated code]*/
2510
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002511static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002512builtin_isinstance_impl(PyObject *module, PyObject *obj,
Larry Hastings89964c42015-04-14 18:07:59 -04002513 PyObject *class_or_tuple)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002514/*[clinic end generated code: output=6faf01472c13b003 input=ffa743db1daf7549]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002515{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002516 int retval;
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002517
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002518 retval = PyObject_IsInstance(obj, class_or_tuple);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002519 if (retval < 0)
2520 return NULL;
2521 return PyBool_FromLong(retval);
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002522}
2523
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002524
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002525/*[clinic input]
2526issubclass as builtin_issubclass
2527
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03002528 cls: object
2529 class_or_tuple: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002530 /
2531
Alex Poveldf773f82020-06-03 15:19:45 +02002532Return whether 'cls' is derived from another class or is the same class.
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002533
2534A tuple, as in ``issubclass(x, (A, B, ...))``, may be given as the target to
2535check against. This is equivalent to ``issubclass(x, A) or issubclass(x, B)
Alex Poveldf773f82020-06-03 15:19:45 +02002536or ...``.
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002537[clinic start generated code]*/
2538
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002539static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002540builtin_issubclass_impl(PyObject *module, PyObject *cls,
Larry Hastings89964c42015-04-14 18:07:59 -04002541 PyObject *class_or_tuple)
Alex Poveldf773f82020-06-03 15:19:45 +02002542/*[clinic end generated code: output=358412410cd7a250 input=a24b9f3d58c370d6]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002543{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002544 int retval;
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002545
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002546 retval = PyObject_IsSubclass(cls, class_or_tuple);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002547 if (retval < 0)
2548 return NULL;
2549 return PyBool_FromLong(retval);
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002550}
2551
2552
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002553typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002554 PyObject_HEAD
Guido van Rossum310f6aa2020-06-19 03:16:57 -07002555 Py_ssize_t tuplesize;
2556 PyObject *ittuple; /* tuple of iterators */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002557 PyObject *result;
Guido van Rossum310f6aa2020-06-19 03:16:57 -07002558 int strict;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002559} zipobject;
2560
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002561static PyObject *
2562zip_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
Barry Warsawbd599b52000-08-03 15:45:29 +00002563{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002564 zipobject *lz;
2565 Py_ssize_t i;
2566 PyObject *ittuple; /* tuple of iterators */
2567 PyObject *result;
Serhiy Storchakabf623ae2017-04-19 20:03:52 +03002568 Py_ssize_t tuplesize;
Guido van Rossum310f6aa2020-06-19 03:16:57 -07002569 int strict = 0;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002570
Guido van Rossum310f6aa2020-06-19 03:16:57 -07002571 if (kwds) {
2572 PyObject *empty = PyTuple_New(0);
2573 if (empty == NULL) {
2574 return NULL;
2575 }
2576 static char *kwlist[] = {"strict", NULL};
2577 int parsed = PyArg_ParseTupleAndKeywords(
2578 empty, kwds, "|$p:zip", kwlist, &strict);
2579 Py_DECREF(empty);
2580 if (!parsed) {
2581 return NULL;
2582 }
2583 }
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002584
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002585 /* args must be a tuple */
2586 assert(PyTuple_Check(args));
Serhiy Storchakabf623ae2017-04-19 20:03:52 +03002587 tuplesize = PyTuple_GET_SIZE(args);
Barry Warsawbd599b52000-08-03 15:45:29 +00002588
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002589 /* obtain iterators */
2590 ittuple = PyTuple_New(tuplesize);
2591 if (ittuple == NULL)
2592 return NULL;
2593 for (i=0; i < tuplesize; ++i) {
2594 PyObject *item = PyTuple_GET_ITEM(args, i);
2595 PyObject *it = PyObject_GetIter(item);
2596 if (it == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002597 Py_DECREF(ittuple);
2598 return NULL;
2599 }
2600 PyTuple_SET_ITEM(ittuple, i, it);
2601 }
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002602
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002603 /* create a result holder */
2604 result = PyTuple_New(tuplesize);
2605 if (result == NULL) {
2606 Py_DECREF(ittuple);
2607 return NULL;
2608 }
2609 for (i=0 ; i < tuplesize ; i++) {
2610 Py_INCREF(Py_None);
2611 PyTuple_SET_ITEM(result, i, Py_None);
2612 }
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002613
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002614 /* create zipobject structure */
2615 lz = (zipobject *)type->tp_alloc(type, 0);
2616 if (lz == NULL) {
2617 Py_DECREF(ittuple);
2618 Py_DECREF(result);
2619 return NULL;
2620 }
2621 lz->ittuple = ittuple;
2622 lz->tuplesize = tuplesize;
2623 lz->result = result;
Guido van Rossum310f6aa2020-06-19 03:16:57 -07002624 lz->strict = strict;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002625
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002626 return (PyObject *)lz;
Barry Warsawbd599b52000-08-03 15:45:29 +00002627}
2628
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002629static void
2630zip_dealloc(zipobject *lz)
2631{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002632 PyObject_GC_UnTrack(lz);
2633 Py_XDECREF(lz->ittuple);
2634 Py_XDECREF(lz->result);
2635 Py_TYPE(lz)->tp_free(lz);
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002636}
2637
2638static int
2639zip_traverse(zipobject *lz, visitproc visit, void *arg)
2640{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002641 Py_VISIT(lz->ittuple);
2642 Py_VISIT(lz->result);
2643 return 0;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002644}
2645
2646static PyObject *
2647zip_next(zipobject *lz)
2648{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002649 Py_ssize_t i;
2650 Py_ssize_t tuplesize = lz->tuplesize;
2651 PyObject *result = lz->result;
2652 PyObject *it;
2653 PyObject *item;
2654 PyObject *olditem;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002655
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002656 if (tuplesize == 0)
2657 return NULL;
2658 if (Py_REFCNT(result) == 1) {
2659 Py_INCREF(result);
2660 for (i=0 ; i < tuplesize ; i++) {
2661 it = PyTuple_GET_ITEM(lz->ittuple, i);
2662 item = (*Py_TYPE(it)->tp_iternext)(it);
Serhiy Storchaka278d03b2013-04-06 22:52:34 +03002663 if (item == NULL) {
2664 Py_DECREF(result);
Guido van Rossum310f6aa2020-06-19 03:16:57 -07002665 if (lz->strict) {
2666 goto check;
2667 }
Serhiy Storchaka278d03b2013-04-06 22:52:34 +03002668 return NULL;
2669 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002670 olditem = PyTuple_GET_ITEM(result, i);
2671 PyTuple_SET_ITEM(result, i, item);
2672 Py_DECREF(olditem);
2673 }
Brandt Bucher226a0122020-12-04 19:45:57 -08002674 // bpo-42536: The GC may have untracked this result tuple. Since we're
2675 // recycling it, make sure it's tracked again:
2676 if (!_PyObject_GC_IS_TRACKED(result)) {
2677 _PyObject_GC_TRACK(result);
2678 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002679 } else {
2680 result = PyTuple_New(tuplesize);
2681 if (result == NULL)
Serhiy Storchaka278d03b2013-04-06 22:52:34 +03002682 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002683 for (i=0 ; i < tuplesize ; i++) {
2684 it = PyTuple_GET_ITEM(lz->ittuple, i);
2685 item = (*Py_TYPE(it)->tp_iternext)(it);
Serhiy Storchaka278d03b2013-04-06 22:52:34 +03002686 if (item == NULL) {
2687 Py_DECREF(result);
Guido van Rossum310f6aa2020-06-19 03:16:57 -07002688 if (lz->strict) {
2689 goto check;
2690 }
Serhiy Storchaka278d03b2013-04-06 22:52:34 +03002691 return NULL;
2692 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002693 PyTuple_SET_ITEM(result, i, item);
2694 }
2695 }
2696 return result;
Guido van Rossum310f6aa2020-06-19 03:16:57 -07002697check:
2698 if (PyErr_Occurred()) {
2699 if (!PyErr_ExceptionMatches(PyExc_StopIteration)) {
2700 // next() on argument i raised an exception (not StopIteration)
2701 return NULL;
2702 }
2703 PyErr_Clear();
2704 }
2705 if (i) {
2706 // ValueError: zip() argument 2 is shorter than argument 1
2707 // ValueError: zip() argument 3 is shorter than arguments 1-2
2708 const char* plural = i == 1 ? " " : "s 1-";
2709 return PyErr_Format(PyExc_ValueError,
2710 "zip() argument %d is shorter than argument%s%d",
2711 i + 1, plural, i);
2712 }
2713 for (i = 1; i < tuplesize; i++) {
2714 it = PyTuple_GET_ITEM(lz->ittuple, i);
2715 item = (*Py_TYPE(it)->tp_iternext)(it);
2716 if (item) {
2717 Py_DECREF(item);
2718 const char* plural = i == 1 ? " " : "s 1-";
2719 return PyErr_Format(PyExc_ValueError,
2720 "zip() argument %d is longer than argument%s%d",
2721 i + 1, plural, i);
2722 }
2723 if (PyErr_Occurred()) {
2724 if (!PyErr_ExceptionMatches(PyExc_StopIteration)) {
2725 // next() on argument i raised an exception (not StopIteration)
2726 return NULL;
2727 }
2728 PyErr_Clear();
2729 }
2730 // Argument i is exhausted. So far so good...
2731 }
2732 // All arguments are exhausted. Success!
2733 return NULL;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002734}
Barry Warsawbd599b52000-08-03 15:45:29 +00002735
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002736static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05302737zip_reduce(zipobject *lz, PyObject *Py_UNUSED(ignored))
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002738{
2739 /* Just recreate the zip with the internal iterator tuple */
Guido van Rossum310f6aa2020-06-19 03:16:57 -07002740 if (lz->strict) {
2741 return PyTuple_Pack(3, Py_TYPE(lz), lz->ittuple, Py_True);
2742 }
2743 return PyTuple_Pack(2, Py_TYPE(lz), lz->ittuple);
2744}
2745
2746PyDoc_STRVAR(setstate_doc, "Set state information for unpickling.");
2747
2748static PyObject *
2749zip_setstate(zipobject *lz, PyObject *state)
2750{
2751 int strict = PyObject_IsTrue(state);
2752 if (strict < 0) {
2753 return NULL;
2754 }
2755 lz->strict = strict;
2756 Py_RETURN_NONE;
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002757}
2758
2759static PyMethodDef zip_methods[] = {
2760 {"__reduce__", (PyCFunction)zip_reduce, METH_NOARGS, reduce_doc},
Guido van Rossum310f6aa2020-06-19 03:16:57 -07002761 {"__setstate__", (PyCFunction)zip_setstate, METH_O, setstate_doc},
2762 {NULL} /* sentinel */
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002763};
2764
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002765PyDoc_STRVAR(zip_doc,
Guido van Rossum310f6aa2020-06-19 03:16:57 -07002766"zip(*iterables, strict=False) --> Yield tuples until an input is exhausted.\n\
Barry Warsawbd599b52000-08-03 15:45:29 +00002767\n\
Gregory P. Smith6a5d3ff2020-05-15 14:26:00 -07002768 >>> list(zip('abcdefg', range(3), range(4)))\n\
2769 [('a', 0, 0), ('b', 1, 1), ('c', 2, 2)]\n\
2770\n\
2771The zip object yields n-length tuples, where n is the number of iterables\n\
2772passed as positional arguments to zip(). The i-th element in every tuple\n\
2773comes from the i-th iterable argument to zip(). This continues until the\n\
Guido van Rossum310f6aa2020-06-19 03:16:57 -07002774shortest argument is exhausted.\n\
2775\n\
2776If strict is true and one of the arguments is exhausted before the others,\n\
2777raise a ValueError.");
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002778
2779PyTypeObject PyZip_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002780 PyVarObject_HEAD_INIT(&PyType_Type, 0)
2781 "zip", /* tp_name */
2782 sizeof(zipobject), /* tp_basicsize */
2783 0, /* tp_itemsize */
2784 /* methods */
2785 (destructor)zip_dealloc, /* tp_dealloc */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02002786 0, /* tp_vectorcall_offset */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002787 0, /* tp_getattr */
2788 0, /* tp_setattr */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02002789 0, /* tp_as_async */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002790 0, /* tp_repr */
2791 0, /* tp_as_number */
2792 0, /* tp_as_sequence */
2793 0, /* tp_as_mapping */
2794 0, /* tp_hash */
2795 0, /* tp_call */
2796 0, /* tp_str */
2797 PyObject_GenericGetAttr, /* tp_getattro */
2798 0, /* tp_setattro */
2799 0, /* tp_as_buffer */
2800 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
2801 Py_TPFLAGS_BASETYPE, /* tp_flags */
2802 zip_doc, /* tp_doc */
2803 (traverseproc)zip_traverse, /* tp_traverse */
2804 0, /* tp_clear */
2805 0, /* tp_richcompare */
2806 0, /* tp_weaklistoffset */
2807 PyObject_SelfIter, /* tp_iter */
2808 (iternextfunc)zip_next, /* tp_iternext */
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002809 zip_methods, /* tp_methods */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002810 0, /* tp_members */
2811 0, /* tp_getset */
2812 0, /* tp_base */
2813 0, /* tp_dict */
2814 0, /* tp_descr_get */
2815 0, /* tp_descr_set */
2816 0, /* tp_dictoffset */
2817 0, /* tp_init */
2818 PyType_GenericAlloc, /* tp_alloc */
2819 zip_new, /* tp_new */
2820 PyObject_GC_Del, /* tp_free */
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002821};
Barry Warsawbd599b52000-08-03 15:45:29 +00002822
2823
Guido van Rossum79f25d91997-04-29 20:08:16 +00002824static PyMethodDef builtin_methods[] = {
Serhiy Storchaka62be7422018-11-27 13:27:31 +02002825 {"__build_class__", (PyCFunction)(void(*)(void))builtin___build_class__,
Serhiy Storchaka6969eaf2017-07-03 21:20:15 +03002826 METH_FASTCALL | METH_KEYWORDS, build_class_doc},
Serhiy Storchaka62be7422018-11-27 13:27:31 +02002827 {"__import__", (PyCFunction)(void(*)(void))builtin___import__, METH_VARARGS | METH_KEYWORDS, import_doc},
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002828 BUILTIN_ABS_METHODDEF
2829 BUILTIN_ALL_METHODDEF
2830 BUILTIN_ANY_METHODDEF
2831 BUILTIN_ASCII_METHODDEF
2832 BUILTIN_BIN_METHODDEF
Serhiy Storchaka62be7422018-11-27 13:27:31 +02002833 {"breakpoint", (PyCFunction)(void(*)(void))builtin_breakpoint, METH_FASTCALL | METH_KEYWORDS, breakpoint_doc},
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002834 BUILTIN_CALLABLE_METHODDEF
2835 BUILTIN_CHR_METHODDEF
2836 BUILTIN_COMPILE_METHODDEF
2837 BUILTIN_DELATTR_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002838 {"dir", builtin_dir, METH_VARARGS, dir_doc},
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002839 BUILTIN_DIVMOD_METHODDEF
2840 BUILTIN_EVAL_METHODDEF
2841 BUILTIN_EXEC_METHODDEF
2842 BUILTIN_FORMAT_METHODDEF
Serhiy Storchaka62be7422018-11-27 13:27:31 +02002843 {"getattr", (PyCFunction)(void(*)(void))builtin_getattr, METH_FASTCALL, getattr_doc},
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002844 BUILTIN_GLOBALS_METHODDEF
2845 BUILTIN_HASATTR_METHODDEF
2846 BUILTIN_HASH_METHODDEF
2847 BUILTIN_HEX_METHODDEF
2848 BUILTIN_ID_METHODDEF
2849 BUILTIN_INPUT_METHODDEF
2850 BUILTIN_ISINSTANCE_METHODDEF
2851 BUILTIN_ISSUBCLASS_METHODDEF
Serhiy Storchaka79342662019-01-12 08:25:41 +02002852 {"iter", (PyCFunction)(void(*)(void))builtin_iter, METH_FASTCALL, iter_doc},
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002853 BUILTIN_LEN_METHODDEF
2854 BUILTIN_LOCALS_METHODDEF
Serhiy Storchaka62be7422018-11-27 13:27:31 +02002855 {"max", (PyCFunction)(void(*)(void))builtin_max, METH_VARARGS | METH_KEYWORDS, max_doc},
2856 {"min", (PyCFunction)(void(*)(void))builtin_min, METH_VARARGS | METH_KEYWORDS, min_doc},
2857 {"next", (PyCFunction)(void(*)(void))builtin_next, METH_FASTCALL, next_doc},
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002858 BUILTIN_OCT_METHODDEF
2859 BUILTIN_ORD_METHODDEF
2860 BUILTIN_POW_METHODDEF
Serhiy Storchaka62be7422018-11-27 13:27:31 +02002861 {"print", (PyCFunction)(void(*)(void))builtin_print, METH_FASTCALL | METH_KEYWORDS, print_doc},
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002862 BUILTIN_REPR_METHODDEF
Serhiy Storchakaaca7f572017-11-15 17:51:14 +02002863 BUILTIN_ROUND_METHODDEF
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002864 BUILTIN_SETATTR_METHODDEF
2865 BUILTIN_SORTED_METHODDEF
2866 BUILTIN_SUM_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002867 {"vars", builtin_vars, METH_VARARGS, vars_doc},
2868 {NULL, NULL},
Guido van Rossum3f5da241990-12-20 15:06:42 +00002869};
2870
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002871PyDoc_STRVAR(builtin_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002872"Built-in functions, exceptions, and other objects.\n\
2873\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002874Noteworthy: None is the `nil' object; Ellipsis represents `...' in slices.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002875
Martin v. Löwis1a214512008-06-11 05:26:20 +00002876static struct PyModuleDef builtinsmodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002877 PyModuleDef_HEAD_INIT,
2878 "builtins",
2879 builtin_doc,
2880 -1, /* multiple "initialization" just copies the module dict. */
2881 builtin_methods,
2882 NULL,
2883 NULL,
2884 NULL,
2885 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00002886};
2887
2888
Guido van Rossum25ce5661997-08-02 03:10:38 +00002889PyObject *
Victor Stinnerbcb094b2021-02-19 15:10:45 +01002890_PyBuiltin_Init(PyInterpreterState *interp)
Guido van Rossum25ce5661997-08-02 03:10:38 +00002891{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002892 PyObject *mod, *dict, *debug;
Benjamin Peterson42124a72012-10-30 23:41:54 -04002893
Victor Stinnerbcb094b2021-02-19 15:10:45 +01002894 const PyConfig *config = _PyInterpreterState_GetConfig(interp);
Victor Stinnerfbca9082018-08-30 00:50:45 +02002895
Benjamin Peterson42124a72012-10-30 23:41:54 -04002896 if (PyType_Ready(&PyFilter_Type) < 0 ||
2897 PyType_Ready(&PyMap_Type) < 0 ||
2898 PyType_Ready(&PyZip_Type) < 0)
2899 return NULL;
2900
Eric Snowd393c1b2017-09-14 12:18:12 -06002901 mod = _PyModule_CreateInitialized(&builtinsmodule, PYTHON_API_VERSION);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002902 if (mod == NULL)
2903 return NULL;
2904 dict = PyModule_GetDict(mod);
Tim Peters4b7625e2001-09-13 21:37:17 +00002905
Tim Peters7571a0f2003-03-23 17:52:28 +00002906#ifdef Py_TRACE_REFS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002907 /* "builtins" exposes a number of statically allocated objects
2908 * that, before this code was added in 2.3, never showed up in
2909 * the list of "all objects" maintained by Py_TRACE_REFS. As a
2910 * result, programs leaking references to None and False (etc)
2911 * couldn't be diagnosed by examining sys.getobjects(0).
2912 */
Tim Peters7571a0f2003-03-23 17:52:28 +00002913#define ADD_TO_ALL(OBJECT) _Py_AddToAllObjects((PyObject *)(OBJECT), 0)
2914#else
2915#define ADD_TO_ALL(OBJECT) (void)0
2916#endif
2917
Tim Peters4b7625e2001-09-13 21:37:17 +00002918#define SETBUILTIN(NAME, OBJECT) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002919 if (PyDict_SetItemString(dict, NAME, (PyObject *)OBJECT) < 0) \
2920 return NULL; \
2921 ADD_TO_ALL(OBJECT)
Tim Peters4b7625e2001-09-13 21:37:17 +00002922
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002923 SETBUILTIN("None", Py_None);
2924 SETBUILTIN("Ellipsis", Py_Ellipsis);
2925 SETBUILTIN("NotImplemented", Py_NotImplemented);
2926 SETBUILTIN("False", Py_False);
2927 SETBUILTIN("True", Py_True);
2928 SETBUILTIN("bool", &PyBool_Type);
2929 SETBUILTIN("memoryview", &PyMemoryView_Type);
2930 SETBUILTIN("bytearray", &PyByteArray_Type);
2931 SETBUILTIN("bytes", &PyBytes_Type);
2932 SETBUILTIN("classmethod", &PyClassMethod_Type);
2933 SETBUILTIN("complex", &PyComplex_Type);
2934 SETBUILTIN("dict", &PyDict_Type);
2935 SETBUILTIN("enumerate", &PyEnum_Type);
2936 SETBUILTIN("filter", &PyFilter_Type);
2937 SETBUILTIN("float", &PyFloat_Type);
2938 SETBUILTIN("frozenset", &PyFrozenSet_Type);
2939 SETBUILTIN("property", &PyProperty_Type);
2940 SETBUILTIN("int", &PyLong_Type);
2941 SETBUILTIN("list", &PyList_Type);
2942 SETBUILTIN("map", &PyMap_Type);
2943 SETBUILTIN("object", &PyBaseObject_Type);
2944 SETBUILTIN("range", &PyRange_Type);
2945 SETBUILTIN("reversed", &PyReversed_Type);
2946 SETBUILTIN("set", &PySet_Type);
2947 SETBUILTIN("slice", &PySlice_Type);
2948 SETBUILTIN("staticmethod", &PyStaticMethod_Type);
2949 SETBUILTIN("str", &PyUnicode_Type);
2950 SETBUILTIN("super", &PySuper_Type);
2951 SETBUILTIN("tuple", &PyTuple_Type);
2952 SETBUILTIN("type", &PyType_Type);
2953 SETBUILTIN("zip", &PyZip_Type);
Victor Stinnerfbca9082018-08-30 00:50:45 +02002954 debug = PyBool_FromLong(config->optimization_level == 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002955 if (PyDict_SetItemString(dict, "__debug__", debug) < 0) {
Serhiy Storchakacfdfbb42016-06-18 09:44:03 +03002956 Py_DECREF(debug);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002957 return NULL;
2958 }
Serhiy Storchakacfdfbb42016-06-18 09:44:03 +03002959 Py_DECREF(debug);
Barry Warsaw757af0e1997-08-29 22:13:51 +00002960
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002961 return mod;
Tim Peters7571a0f2003-03-23 17:52:28 +00002962#undef ADD_TO_ALL
Tim Peters4b7625e2001-09-13 21:37:17 +00002963#undef SETBUILTIN
Guido van Rossum3f5da241990-12-20 15:06:42 +00002964}