blob: a076006d6523133288cb06db5fb9ac39f6e289d9 [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 Stinnereec8e612021-03-18 14:57:49 +01005#include "pycore_ast.h" // _PyAST_Validate()
Victor Stinner94faa072021-03-23 20:47:40 +01006#undef Yield /* undefine macro conflicting with <winbase.h> */
Victor Stinnera81fca62021-03-24 00:51:50 +01007#include "pycore_compile.h" // _PyAST_Compile()
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
Victor Stinner8370e072021-03-24 02:23:01 +0100831 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) {
Victor Stinner8370e072021-03-24 02:23:01 +0100836 _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)) {
Victor Stinner8370e072021-03-24 02:23:01 +0100840 _PyArena_Free(arena);
Benjamin Peterson832bfe22011-08-09 16:15:04 -0500841 goto error;
842 }
Victor Stinnera81fca62021-03-24 00:51:50 +0100843 result = (PyObject*)_PyAST_Compile(mod, filename,
844 &cf, optimize, arena);
Victor Stinner8370e072021-03-24 02:23:01 +0100845 _PyArena_Free(arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000846 }
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);
Dong-hee Na86883d42021-03-22 19:01:14 +09001267 lz->func = Py_NewRef(func);
1268
1269 return (PyObject *)lz;
1270}
1271
1272static PyObject *
1273map_vectorcall(PyObject *type, PyObject * const*args,
1274 size_t nargsf, PyObject *kwnames)
1275{
1276 PyTypeObject *tp = (PyTypeObject *)type;
1277 if (tp == &PyMap_Type && !_PyArg_NoKwnames("map", kwnames)) {
1278 return NULL;
1279 }
1280
1281 Py_ssize_t nargs = PyVectorcall_NARGS(nargsf);
1282 if (nargs < 2) {
1283 PyErr_SetString(PyExc_TypeError,
1284 "map() must have at least two arguments.");
1285 return NULL;
1286 }
1287
1288 PyObject *iters = PyTuple_New(nargs-1);
1289 if (iters == NULL) {
1290 return NULL;
1291 }
1292
1293 for (int i=1; i<nargs; i++) {
1294 PyObject *it = PyObject_GetIter(args[i]);
1295 if (it == NULL) {
1296 Py_DECREF(iters);
1297 return NULL;
1298 }
1299 PyTuple_SET_ITEM(iters, i-1, it);
1300 }
1301
1302 mapobject *lz = (mapobject *)tp->tp_alloc(tp, 0);
1303 if (lz == NULL) {
1304 Py_DECREF(iters);
1305 return NULL;
1306 }
1307 lz->iters = iters;
1308 lz->func = Py_NewRef(args[0]);
Raymond Hettingera6c60372008-03-13 01:26:19 +00001309
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001310 return (PyObject *)lz;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001311}
1312
1313static void
1314map_dealloc(mapobject *lz)
1315{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001316 PyObject_GC_UnTrack(lz);
1317 Py_XDECREF(lz->iters);
1318 Py_XDECREF(lz->func);
1319 Py_TYPE(lz)->tp_free(lz);
Raymond Hettingera6c60372008-03-13 01:26:19 +00001320}
1321
1322static int
1323map_traverse(mapobject *lz, visitproc visit, void *arg)
1324{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001325 Py_VISIT(lz->iters);
1326 Py_VISIT(lz->func);
1327 return 0;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001328}
1329
1330static PyObject *
1331map_next(mapobject *lz)
1332{
Victor Stinnerbc08ab42016-12-15 12:40:53 +01001333 PyObject *small_stack[_PY_FASTCALL_SMALL_STACK];
Victor Stinnercdb5cee2016-08-24 01:45:13 +02001334 PyObject **stack;
Victor Stinnercdb5cee2016-08-24 01:45:13 +02001335 PyObject *result = NULL;
Victor Stinner4d231bc2019-11-14 13:36:21 +01001336 PyThreadState *tstate = _PyThreadState_GET();
Raymond Hettingera6c60372008-03-13 01:26:19 +00001337
Victor Stinner4d231bc2019-11-14 13:36:21 +01001338 const Py_ssize_t niters = PyTuple_GET_SIZE(lz->iters);
Victor Stinnercdb5cee2016-08-24 01:45:13 +02001339 if (niters <= (Py_ssize_t)Py_ARRAY_LENGTH(small_stack)) {
1340 stack = small_stack;
1341 }
1342 else {
1343 stack = PyMem_Malloc(niters * sizeof(stack[0]));
1344 if (stack == NULL) {
Victor Stinner4d231bc2019-11-14 13:36:21 +01001345 _PyErr_NoMemory(tstate);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001346 return NULL;
1347 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001348 }
Victor Stinnercdb5cee2016-08-24 01:45:13 +02001349
Victor Stinner4d231bc2019-11-14 13:36:21 +01001350 Py_ssize_t nargs = 0;
1351 for (Py_ssize_t i=0; i < niters; i++) {
Victor Stinnercdb5cee2016-08-24 01:45:13 +02001352 PyObject *it = PyTuple_GET_ITEM(lz->iters, i);
1353 PyObject *val = Py_TYPE(it)->tp_iternext(it);
1354 if (val == NULL) {
1355 goto exit;
1356 }
1357 stack[i] = val;
1358 nargs++;
1359 }
1360
Victor Stinner4d231bc2019-11-14 13:36:21 +01001361 result = _PyObject_VectorcallTstate(tstate, lz->func, stack, nargs, NULL);
Victor Stinnercdb5cee2016-08-24 01:45:13 +02001362
1363exit:
Victor Stinner4d231bc2019-11-14 13:36:21 +01001364 for (Py_ssize_t i=0; i < nargs; i++) {
Victor Stinnercdb5cee2016-08-24 01:45:13 +02001365 Py_DECREF(stack[i]);
1366 }
1367 if (stack != small_stack) {
1368 PyMem_Free(stack);
1369 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001370 return result;
Guido van Rossum12d12c51993-10-26 17:58:25 +00001371}
1372
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001373static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05301374map_reduce(mapobject *lz, PyObject *Py_UNUSED(ignored))
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001375{
1376 Py_ssize_t numargs = PyTuple_GET_SIZE(lz->iters);
1377 PyObject *args = PyTuple_New(numargs+1);
1378 Py_ssize_t i;
1379 if (args == NULL)
1380 return NULL;
1381 Py_INCREF(lz->func);
1382 PyTuple_SET_ITEM(args, 0, lz->func);
1383 for (i = 0; i<numargs; i++){
1384 PyObject *it = PyTuple_GET_ITEM(lz->iters, i);
1385 Py_INCREF(it);
1386 PyTuple_SET_ITEM(args, i+1, it);
1387 }
1388
1389 return Py_BuildValue("ON", Py_TYPE(lz), args);
1390}
1391
1392static PyMethodDef map_methods[] = {
1393 {"__reduce__", (PyCFunction)map_reduce, METH_NOARGS, reduce_doc},
1394 {NULL, NULL} /* sentinel */
1395};
1396
1397
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001398PyDoc_STRVAR(map_doc,
Raymond Hettingera6c60372008-03-13 01:26:19 +00001399"map(func, *iterables) --> map object\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001400\n\
Raymond Hettingera6c60372008-03-13 01:26:19 +00001401Make an iterator that computes the function using arguments from\n\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001402each of the iterables. Stops when the shortest iterable is exhausted.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001403
Raymond Hettingera6c60372008-03-13 01:26:19 +00001404PyTypeObject PyMap_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001405 PyVarObject_HEAD_INIT(&PyType_Type, 0)
1406 "map", /* tp_name */
1407 sizeof(mapobject), /* tp_basicsize */
1408 0, /* tp_itemsize */
1409 /* methods */
1410 (destructor)map_dealloc, /* tp_dealloc */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02001411 0, /* tp_vectorcall_offset */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001412 0, /* tp_getattr */
1413 0, /* tp_setattr */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02001414 0, /* tp_as_async */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001415 0, /* tp_repr */
1416 0, /* tp_as_number */
1417 0, /* tp_as_sequence */
1418 0, /* tp_as_mapping */
1419 0, /* tp_hash */
1420 0, /* tp_call */
1421 0, /* tp_str */
1422 PyObject_GenericGetAttr, /* tp_getattro */
1423 0, /* tp_setattro */
1424 0, /* tp_as_buffer */
1425 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
1426 Py_TPFLAGS_BASETYPE, /* tp_flags */
1427 map_doc, /* tp_doc */
1428 (traverseproc)map_traverse, /* tp_traverse */
1429 0, /* tp_clear */
1430 0, /* tp_richcompare */
1431 0, /* tp_weaklistoffset */
1432 PyObject_SelfIter, /* tp_iter */
1433 (iternextfunc)map_next, /* tp_iternext */
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001434 map_methods, /* tp_methods */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001435 0, /* tp_members */
1436 0, /* tp_getset */
1437 0, /* tp_base */
1438 0, /* tp_dict */
1439 0, /* tp_descr_get */
1440 0, /* tp_descr_set */
1441 0, /* tp_dictoffset */
1442 0, /* tp_init */
1443 PyType_GenericAlloc, /* tp_alloc */
1444 map_new, /* tp_new */
1445 PyObject_GC_Del, /* tp_free */
Dong-hee Na86883d42021-03-22 19:01:14 +09001446 .tp_vectorcall = (vectorcallfunc)map_vectorcall
Raymond Hettingera6c60372008-03-13 01:26:19 +00001447};
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001448
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001449
1450/* AC: cannot convert yet, as needs PEP 457 group support in inspect */
Guido van Rossum79f25d91997-04-29 20:08:16 +00001451static PyObject *
Serhiy Storchakaa5552f02017-12-15 13:11:11 +02001452builtin_next(PyObject *self, PyObject *const *args, Py_ssize_t nargs)
Georg Brandla18af4e2007-04-21 15:47:16 +00001453{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001454 PyObject *it, *res;
Georg Brandla18af4e2007-04-21 15:47:16 +00001455
Serhiy Storchaka79342662019-01-12 08:25:41 +02001456 if (!_PyArg_CheckPositional("next", nargs, 1, 2))
Sylvain96c7c062017-06-15 17:05:23 +02001457 return NULL;
1458
Serhiy Storchaka79342662019-01-12 08:25:41 +02001459 it = args[0];
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001460 if (!PyIter_Check(it)) {
1461 PyErr_Format(PyExc_TypeError,
Philip Jenvey50add042011-11-06 16:37:52 -08001462 "'%.200s' object is not an iterator",
Victor Stinnera102ed72020-02-07 02:24:48 +01001463 Py_TYPE(it)->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001464 return NULL;
1465 }
1466
Victor Stinnera102ed72020-02-07 02:24:48 +01001467 res = (*Py_TYPE(it)->tp_iternext)(it);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001468 if (res != NULL) {
1469 return res;
Serhiy Storchaka79342662019-01-12 08:25:41 +02001470 } else if (nargs > 1) {
1471 PyObject *def = args[1];
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001472 if (PyErr_Occurred()) {
1473 if(!PyErr_ExceptionMatches(PyExc_StopIteration))
1474 return NULL;
1475 PyErr_Clear();
1476 }
1477 Py_INCREF(def);
1478 return def;
1479 } else if (PyErr_Occurred()) {
1480 return NULL;
1481 } else {
1482 PyErr_SetNone(PyExc_StopIteration);
1483 return NULL;
1484 }
Georg Brandla18af4e2007-04-21 15:47:16 +00001485}
1486
1487PyDoc_STRVAR(next_doc,
1488"next(iterator[, default])\n\
1489\n\
1490Return the next item from the iterator. If default is given and the iterator\n\
1491is exhausted, it is returned instead of raising StopIteration.");
1492
1493
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001494/*[clinic input]
1495setattr as builtin_setattr
1496
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001497 obj: object
1498 name: object
1499 value: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001500 /
1501
1502Sets the named attribute on the given object to the specified value.
1503
1504setattr(x, 'y', v) is equivalent to ``x.y = v''
1505[clinic start generated code]*/
1506
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001507static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001508builtin_setattr_impl(PyObject *module, PyObject *obj, PyObject *name,
Larry Hastings89964c42015-04-14 18:07:59 -04001509 PyObject *value)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001510/*[clinic end generated code: output=dc2ce1d1add9acb4 input=bd2b7ca6875a1899]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001511{
1512 if (PyObject_SetAttr(obj, name, value) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001513 return NULL;
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02001514 Py_RETURN_NONE;
Guido van Rossum33894be1992-01-27 16:53:09 +00001515}
1516
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001517
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001518/*[clinic input]
1519delattr as builtin_delattr
1520
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001521 obj: object
1522 name: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001523 /
1524
1525Deletes the named attribute from the given object.
1526
1527delattr(x, 'y') is equivalent to ``del x.y''
1528[clinic start generated code]*/
1529
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001530static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001531builtin_delattr_impl(PyObject *module, PyObject *obj, PyObject *name)
1532/*[clinic end generated code: output=85134bc58dff79fa input=db16685d6b4b9410]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001533{
1534 if (PyObject_SetAttr(obj, name, (PyObject *)NULL) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001535 return NULL;
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02001536 Py_RETURN_NONE;
Guido van Rossum14144fc1994-08-29 12:53:40 +00001537}
1538
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001539
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001540/*[clinic input]
1541hash as builtin_hash
1542
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001543 obj: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001544 /
1545
1546Return the hash value for the given object.
1547
1548Two objects that compare equal must also have the same hash value, but the
1549reverse is not necessarily true.
1550[clinic start generated code]*/
1551
Guido van Rossum79f25d91997-04-29 20:08:16 +00001552static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001553builtin_hash(PyObject *module, PyObject *obj)
1554/*[clinic end generated code: output=237668e9d7688db7 input=58c48be822bf9c54]*/
Guido van Rossum9bfef441993-03-29 10:43:31 +00001555{
Benjamin Peterson8f67d082010-10-17 20:54:53 +00001556 Py_hash_t x;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001557
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001558 x = PyObject_Hash(obj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001559 if (x == -1)
1560 return NULL;
Benjamin Peterson8f67d082010-10-17 20:54:53 +00001561 return PyLong_FromSsize_t(x);
Guido van Rossum9bfef441993-03-29 10:43:31 +00001562}
1563
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001564
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001565/*[clinic input]
1566hex as builtin_hex
1567
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001568 number: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001569 /
1570
1571Return the hexadecimal representation of an integer.
1572
1573 >>> hex(12648430)
1574 '0xc0ffee'
1575[clinic start generated code]*/
1576
Guido van Rossum79f25d91997-04-29 20:08:16 +00001577static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001578builtin_hex(PyObject *module, PyObject *number)
1579/*[clinic end generated code: output=e46b612169099408 input=e645aff5fc7d540e]*/
Guido van Rossum006bcd41991-10-24 14:54:44 +00001580{
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001581 return PyNumber_ToBase(number, 16);
Guido van Rossum006bcd41991-10-24 14:54:44 +00001582}
1583
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001584
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001585/* AC: cannot convert yet, as needs PEP 457 group support in inspect */
Guido van Rossum79f25d91997-04-29 20:08:16 +00001586static PyObject *
Serhiy Storchaka79342662019-01-12 08:25:41 +02001587builtin_iter(PyObject *self, PyObject *const *args, Py_ssize_t nargs)
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001588{
Serhiy Storchaka79342662019-01-12 08:25:41 +02001589 PyObject *v;
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001590
Serhiy Storchaka79342662019-01-12 08:25:41 +02001591 if (!_PyArg_CheckPositional("iter", nargs, 1, 2))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001592 return NULL;
Serhiy Storchaka79342662019-01-12 08:25:41 +02001593 v = args[0];
1594 if (nargs == 1)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001595 return PyObject_GetIter(v);
1596 if (!PyCallable_Check(v)) {
1597 PyErr_SetString(PyExc_TypeError,
1598 "iter(v, w): v must be callable");
1599 return NULL;
1600 }
Serhiy Storchaka79342662019-01-12 08:25:41 +02001601 PyObject *sentinel = args[1];
1602 return PyCallIter_New(v, sentinel);
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001603}
1604
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001605PyDoc_STRVAR(iter_doc,
Georg Brandld11ae5d2008-05-16 13:27:32 +00001606"iter(iterable) -> iterator\n\
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001607iter(callable, sentinel) -> iterator\n\
1608\n\
1609Get an iterator from an object. In the first form, the argument must\n\
1610supply its own iterator, or be a sequence.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001611In the second form, the callable is called until it returns the sentinel.");
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001612
1613
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001614/*[clinic input]
Joshua Bronsonf0a6fde2021-03-23 18:47:21 -04001615aiter as builtin_aiter
1616
1617 async_iterable: object
1618 /
1619
1620Return an AsyncIterator for an AsyncIterable object.
1621[clinic start generated code]*/
1622
1623static PyObject *
1624builtin_aiter(PyObject *module, PyObject *async_iterable)
1625/*[clinic end generated code: output=1bae108d86f7960e input=473993d0cacc7d23]*/
1626{
1627 return PyObject_GetAiter(async_iterable);
1628}
1629
1630PyObject *PyAnextAwaitable_New(PyObject *, PyObject *);
1631
1632/*[clinic input]
1633anext as builtin_anext
1634
1635 aiterator: object
1636 default: object = NULL
1637 /
1638
1639Return the next item from the async iterator.
1640[clinic start generated code]*/
1641
1642static PyObject *
1643builtin_anext_impl(PyObject *module, PyObject *aiterator,
1644 PyObject *default_value)
1645/*[clinic end generated code: output=f02c060c163a81fa input=699d11f4e38eca24]*/
1646{
1647 PyTypeObject *t;
1648 PyObject *awaitable;
1649
1650 t = Py_TYPE(aiterator);
1651 if (t->tp_as_async == NULL || t->tp_as_async->am_anext == NULL) {
1652 PyErr_Format(PyExc_TypeError,
1653 "'%.200s' object is not an async iterator",
1654 t->tp_name);
1655 return NULL;
1656 }
1657
1658 awaitable = (*t->tp_as_async->am_anext)(aiterator);
1659 if (default_value == NULL) {
1660 return awaitable;
1661 }
1662
Pablo Galindoa02683a2021-03-24 01:42:13 +00001663 PyObject* new_awaitable = PyAnextAwaitable_New(
1664 awaitable, default_value);
1665 Py_DECREF(awaitable);
1666 return new_awaitable;
Joshua Bronsonf0a6fde2021-03-23 18:47:21 -04001667}
1668
1669
1670/*[clinic input]
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001671len as builtin_len
1672
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001673 obj: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001674 /
1675
1676Return the number of items in a container.
1677[clinic start generated code]*/
1678
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001679static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001680builtin_len(PyObject *module, PyObject *obj)
1681/*[clinic end generated code: output=fa7a270d314dfb6c input=bc55598da9e9c9b5]*/
Guido van Rossum3f5da241990-12-20 15:06:42 +00001682{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001683 Py_ssize_t res;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001684
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001685 res = PyObject_Size(obj);
Serhiy Storchaka813f9432017-04-16 09:21:44 +03001686 if (res < 0) {
1687 assert(PyErr_Occurred());
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001688 return NULL;
Serhiy Storchaka813f9432017-04-16 09:21:44 +03001689 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001690 return PyLong_FromSsize_t(res);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001691}
1692
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001693
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001694/*[clinic input]
1695locals as builtin_locals
1696
1697Return a dictionary containing the current scope's local variables.
1698
1699NOTE: Whether or not updates to this dictionary will affect name lookups in
1700the local scope and vice-versa is *implementation dependent* and not
1701covered by any backwards compatibility guarantees.
1702[clinic start generated code]*/
1703
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001704static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001705builtin_locals_impl(PyObject *module)
1706/*[clinic end generated code: output=b46c94015ce11448 input=7874018d478d5c4b]*/
Guido van Rossum872537c1995-07-07 22:43:42 +00001707{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001708 PyObject *d;
Guido van Rossum872537c1995-07-07 22:43:42 +00001709
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001710 d = PyEval_GetLocals();
1711 Py_XINCREF(d);
1712 return d;
Guido van Rossum872537c1995-07-07 22:43:42 +00001713}
1714
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001715
Guido van Rossum79f25d91997-04-29 20:08:16 +00001716static PyObject *
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001717min_max(PyObject *args, PyObject *kwds, int op)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001718{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001719 PyObject *v, *it, *item, *val, *maxitem, *maxval, *keyfunc=NULL;
Raymond Hettinger4d6018f2013-06-24 22:43:02 -07001720 PyObject *emptytuple, *defaultval = NULL;
1721 static char *kwlist[] = {"key", "default", NULL};
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001722 const char *name = op == Py_LT ? "min" : "max";
Raymond Hettinger4d6018f2013-06-24 22:43:02 -07001723 const int positional = PyTuple_Size(args) > 1;
1724 int ret;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001725
Dong-hee Naabdc6342020-01-11 01:31:43 +09001726 if (positional) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001727 v = args;
Dong-hee Naabdc6342020-01-11 01:31:43 +09001728 }
1729 else if (!PyArg_UnpackTuple(args, name, 1, 1, &v)) {
1730 if (PyExceptionClass_Check(PyExc_TypeError)) {
1731 PyErr_Format(PyExc_TypeError, "%s expected at least 1 argument, got 0", name);
1732 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001733 return NULL;
Dong-hee Naabdc6342020-01-11 01:31:43 +09001734 }
Tim Peters67d687a2002-04-29 21:27:32 +00001735
Raymond Hettinger4d6018f2013-06-24 22:43:02 -07001736 emptytuple = PyTuple_New(0);
1737 if (emptytuple == NULL)
1738 return NULL;
Oren Milman58cf7482017-08-21 20:19:07 +03001739 ret = PyArg_ParseTupleAndKeywords(emptytuple, kwds,
1740 (op == Py_LT) ? "|$OO:min" : "|$OO:max",
1741 kwlist, &keyfunc, &defaultval);
Raymond Hettinger4d6018f2013-06-24 22:43:02 -07001742 Py_DECREF(emptytuple);
1743 if (!ret)
1744 return NULL;
1745
1746 if (positional && defaultval != NULL) {
1747 PyErr_Format(PyExc_TypeError,
1748 "Cannot specify a default for %s() with multiple "
1749 "positional arguments", name);
1750 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001751 }
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001752
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001753 it = PyObject_GetIter(v);
1754 if (it == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001755 return NULL;
1756 }
Tim Petersc3074532001-05-03 07:00:32 +00001757
Alexander Marshalove22072f2018-07-24 10:58:21 +07001758 if (keyfunc == Py_None) {
1759 keyfunc = NULL;
1760 }
1761
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001762 maxitem = NULL; /* the result */
1763 maxval = NULL; /* the value associated with the result */
1764 while (( item = PyIter_Next(it) )) {
1765 /* get the value from the key function */
1766 if (keyfunc != NULL) {
Petr Viktorinffd97532020-02-11 17:46:57 +01001767 val = PyObject_CallOneArg(keyfunc, item);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001768 if (val == NULL)
1769 goto Fail_it_item;
1770 }
1771 /* no key function; the value is the item */
1772 else {
1773 val = item;
1774 Py_INCREF(val);
1775 }
Tim Petersc3074532001-05-03 07:00:32 +00001776
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001777 /* maximum value and item are unset; set them */
1778 if (maxval == NULL) {
1779 maxitem = item;
1780 maxval = val;
1781 }
1782 /* maximum value and item are set; update them as necessary */
1783 else {
1784 int cmp = PyObject_RichCompareBool(val, maxval, op);
1785 if (cmp < 0)
1786 goto Fail_it_item_and_val;
1787 else if (cmp > 0) {
1788 Py_DECREF(maxval);
1789 Py_DECREF(maxitem);
1790 maxval = val;
1791 maxitem = item;
1792 }
1793 else {
1794 Py_DECREF(item);
1795 Py_DECREF(val);
1796 }
1797 }
1798 }
1799 if (PyErr_Occurred())
1800 goto Fail_it;
1801 if (maxval == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001802 assert(maxitem == NULL);
Raymond Hettinger4d6018f2013-06-24 22:43:02 -07001803 if (defaultval != NULL) {
1804 Py_INCREF(defaultval);
1805 maxitem = defaultval;
1806 } else {
1807 PyErr_Format(PyExc_ValueError,
1808 "%s() arg is an empty sequence", name);
1809 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001810 }
1811 else
1812 Py_DECREF(maxval);
1813 Py_DECREF(it);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001814 return maxitem;
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001815
1816Fail_it_item_and_val:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001817 Py_DECREF(val);
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001818Fail_it_item:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001819 Py_DECREF(item);
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001820Fail_it:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001821 Py_XDECREF(maxval);
1822 Py_XDECREF(maxitem);
1823 Py_DECREF(it);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001824 return NULL;
Guido van Rossum3f5da241990-12-20 15:06:42 +00001825}
1826
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001827/* AC: cannot convert yet, waiting for *args support */
Guido van Rossum79f25d91997-04-29 20:08:16 +00001828static PyObject *
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001829builtin_min(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001830{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001831 return min_max(args, kwds, Py_LT);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001832}
1833
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001834PyDoc_STRVAR(min_doc,
Raymond Hettinger2a545822014-05-19 22:20:52 +01001835"min(iterable, *[, default=obj, key=func]) -> value\n\
1836min(arg1, arg2, *args, *[, key=func]) -> value\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001837\n\
Raymond Hettinger2a545822014-05-19 22:20:52 +01001838With a single iterable argument, return its smallest item. The\n\
1839default keyword-only argument specifies an object to return if\n\
1840the provided iterable is empty.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001841With two or more arguments, return the smallest argument.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001842
1843
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001844/* AC: cannot convert yet, waiting for *args support */
Guido van Rossum79f25d91997-04-29 20:08:16 +00001845static PyObject *
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001846builtin_max(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001847{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001848 return min_max(args, kwds, Py_GT);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001849}
1850
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001851PyDoc_STRVAR(max_doc,
Raymond Hettinger2a545822014-05-19 22:20:52 +01001852"max(iterable, *[, default=obj, key=func]) -> value\n\
1853max(arg1, arg2, *args, *[, key=func]) -> value\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001854\n\
Raymond Hettinger2a545822014-05-19 22:20:52 +01001855With a single iterable argument, return its biggest item. The\n\
1856default keyword-only argument specifies an object to return if\n\
1857the provided iterable is empty.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001858With two or more arguments, return the largest argument.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001859
1860
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001861/*[clinic input]
1862oct as builtin_oct
1863
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001864 number: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001865 /
1866
1867Return the octal representation of an integer.
1868
1869 >>> oct(342391)
1870 '0o1234567'
1871[clinic start generated code]*/
1872
Guido van Rossum79f25d91997-04-29 20:08:16 +00001873static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001874builtin_oct(PyObject *module, PyObject *number)
1875/*[clinic end generated code: output=40a34656b6875352 input=ad6b274af4016c72]*/
Guido van Rossum006bcd41991-10-24 14:54:44 +00001876{
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001877 return PyNumber_ToBase(number, 8);
Guido van Rossum006bcd41991-10-24 14:54:44 +00001878}
1879
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001880
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001881/*[clinic input]
1882ord as builtin_ord
1883
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001884 c: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001885 /
1886
1887Return the Unicode code point for a one-character string.
1888[clinic start generated code]*/
1889
Guido van Rossum79f25d91997-04-29 20:08:16 +00001890static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001891builtin_ord(PyObject *module, PyObject *c)
1892/*[clinic end generated code: output=4fa5e87a323bae71 input=3064e5d6203ad012]*/
Guido van Rossum3f5da241990-12-20 15:06:42 +00001893{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001894 long ord;
1895 Py_ssize_t size;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001896
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001897 if (PyBytes_Check(c)) {
1898 size = PyBytes_GET_SIZE(c);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001899 if (size == 1) {
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001900 ord = (long)((unsigned char)*PyBytes_AS_STRING(c));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001901 return PyLong_FromLong(ord);
1902 }
1903 }
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001904 else if (PyUnicode_Check(c)) {
1905 if (PyUnicode_READY(c) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001906 return NULL;
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001907 size = PyUnicode_GET_LENGTH(c);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001908 if (size == 1) {
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001909 ord = (long)PyUnicode_READ_CHAR(c, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001910 return PyLong_FromLong(ord);
1911 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001912 }
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001913 else if (PyByteArray_Check(c)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001914 /* XXX Hopefully this is temporary */
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001915 size = PyByteArray_GET_SIZE(c);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001916 if (size == 1) {
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001917 ord = (long)((unsigned char)*PyByteArray_AS_STRING(c));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001918 return PyLong_FromLong(ord);
1919 }
1920 }
1921 else {
1922 PyErr_Format(PyExc_TypeError,
1923 "ord() expected string of length 1, but " \
Victor Stinnera102ed72020-02-07 02:24:48 +01001924 "%.200s found", Py_TYPE(c)->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001925 return NULL;
1926 }
Guido van Rossum09095f32000-03-10 23:00:52 +00001927
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001928 PyErr_Format(PyExc_TypeError,
1929 "ord() expected a character, "
1930 "but string of length %zd found",
1931 size);
1932 return NULL;
Guido van Rossum3f5da241990-12-20 15:06:42 +00001933}
1934
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001935
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001936/*[clinic input]
1937pow as builtin_pow
1938
Ammar Askar87d6cd32019-09-21 00:28:49 -04001939 base: object
1940 exp: object
1941 mod: object = None
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001942
Raymond Hettingerb104ecb2019-09-21 12:57:44 -07001943Equivalent to base**exp with 2 arguments or base**exp % mod with 3 arguments
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001944
1945Some types, such as ints, are able to use a more efficient algorithm when
1946invoked using the three argument form.
1947[clinic start generated code]*/
1948
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001949static PyObject *
Ammar Askar87d6cd32019-09-21 00:28:49 -04001950builtin_pow_impl(PyObject *module, PyObject *base, PyObject *exp,
1951 PyObject *mod)
Raymond Hettingerb104ecb2019-09-21 12:57:44 -07001952/*[clinic end generated code: output=3ca1538221bbf15f input=435dbd48a12efb23]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001953{
Ammar Askar87d6cd32019-09-21 00:28:49 -04001954 return PyNumber_Power(base, exp, mod);
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001955}
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001956
1957
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001958/* AC: cannot convert yet, waiting for *args support */
Guido van Rossum34343512006-11-30 22:13:52 +00001959static PyObject *
Serhiy Storchakaa5552f02017-12-15 13:11:11 +02001960builtin_print(PyObject *self, PyObject *const *args, Py_ssize_t nargs, PyObject *kwnames)
Guido van Rossum34343512006-11-30 22:13:52 +00001961{
INADA Naokibd584f12017-01-19 12:50:34 +01001962 static const char * const _keywords[] = {"sep", "end", "file", "flush", 0};
Serhiy Storchaka1f21eaa2019-09-01 12:16:51 +03001963 static struct _PyArg_Parser _parser = {"|OOOp:print", _keywords, 0};
1964 PyObject *sep = NULL, *end = NULL, *file = NULL;
1965 int flush = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001966 int i, err;
Guido van Rossum34343512006-11-30 22:13:52 +00001967
INADA Naokibd584f12017-01-19 12:50:34 +01001968 if (kwnames != NULL &&
1969 !_PyArg_ParseStackAndKeywords(args + nargs, 0, kwnames, &_parser,
1970 &sep, &end, &file, &flush)) {
Georg Brandlbc3b6822012-01-13 19:41:25 +01001971 return NULL;
INADA Naokibd584f12017-01-19 12:50:34 +01001972 }
1973
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001974 if (file == NULL || file == Py_None) {
Victor Stinnerbd303c12013-11-07 23:07:29 +01001975 file = _PySys_GetObjectId(&PyId_stdout);
Victor Stinner1e53bba2013-07-16 22:26:05 +02001976 if (file == NULL) {
1977 PyErr_SetString(PyExc_RuntimeError, "lost sys.stdout");
1978 return NULL;
1979 }
1980
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001981 /* sys.stdout may be None when FILE* stdout isn't connected */
1982 if (file == Py_None)
1983 Py_RETURN_NONE;
1984 }
Guido van Rossum34343512006-11-30 22:13:52 +00001985
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001986 if (sep == Py_None) {
1987 sep = NULL;
1988 }
1989 else if (sep && !PyUnicode_Check(sep)) {
1990 PyErr_Format(PyExc_TypeError,
1991 "sep must be None or a string, not %.200s",
Victor Stinnera102ed72020-02-07 02:24:48 +01001992 Py_TYPE(sep)->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001993 return NULL;
1994 }
1995 if (end == Py_None) {
1996 end = NULL;
1997 }
1998 else if (end && !PyUnicode_Check(end)) {
1999 PyErr_Format(PyExc_TypeError,
2000 "end must be None or a string, not %.200s",
Victor Stinnera102ed72020-02-07 02:24:48 +01002001 Py_TYPE(end)->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002002 return NULL;
2003 }
Guido van Rossum34343512006-11-30 22:13:52 +00002004
INADA Naokibd584f12017-01-19 12:50:34 +01002005 for (i = 0; i < nargs; i++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002006 if (i > 0) {
2007 if (sep == NULL)
2008 err = PyFile_WriteString(" ", file);
2009 else
2010 err = PyFile_WriteObject(sep, file,
2011 Py_PRINT_RAW);
2012 if (err)
2013 return NULL;
2014 }
INADA Naokibd584f12017-01-19 12:50:34 +01002015 err = PyFile_WriteObject(args[i], file, Py_PRINT_RAW);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002016 if (err)
2017 return NULL;
2018 }
Guido van Rossum34343512006-11-30 22:13:52 +00002019
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002020 if (end == NULL)
2021 err = PyFile_WriteString("\n", file);
2022 else
2023 err = PyFile_WriteObject(end, file, Py_PRINT_RAW);
2024 if (err)
2025 return NULL;
Guido van Rossum34343512006-11-30 22:13:52 +00002026
Serhiy Storchaka1f21eaa2019-09-01 12:16:51 +03002027 if (flush) {
2028 PyObject *tmp = _PyObject_CallMethodIdNoArgs(file, &PyId_flush);
2029 if (tmp == NULL)
Georg Brandlbc3b6822012-01-13 19:41:25 +01002030 return NULL;
Serhiy Storchaka1f21eaa2019-09-01 12:16:51 +03002031 Py_DECREF(tmp);
Georg Brandlbc3b6822012-01-13 19:41:25 +01002032 }
2033
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002034 Py_RETURN_NONE;
Guido van Rossum34343512006-11-30 22:13:52 +00002035}
2036
2037PyDoc_STRVAR(print_doc,
Senthil Kumarane9175bd2012-08-10 13:53:45 -07002038"print(value, ..., sep=' ', end='\\n', file=sys.stdout, flush=False)\n\
Guido van Rossum34343512006-11-30 22:13:52 +00002039\n\
2040Prints the values to a stream, or to sys.stdout by default.\n\
2041Optional keyword arguments:\n\
Senthil Kumarane9175bd2012-08-10 13:53:45 -07002042file: a file-like object (stream); defaults to the current sys.stdout.\n\
2043sep: string inserted between values, default a space.\n\
2044end: string appended after the last value, default a newline.\n\
2045flush: whether to forcibly flush the stream.");
Guido van Rossum34343512006-11-30 22:13:52 +00002046
2047
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002048/*[clinic input]
2049input as builtin_input
2050
2051 prompt: object(c_default="NULL") = None
2052 /
2053
2054Read a string from standard input. The trailing newline is stripped.
2055
2056The prompt string, if given, is printed to standard output without a
2057trailing newline before reading input.
2058
2059If the user hits EOF (*nix: Ctrl-D, Windows: Ctrl-Z+Return), raise EOFError.
2060On *nix systems, readline is used if available.
2061[clinic start generated code]*/
2062
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002063static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002064builtin_input_impl(PyObject *module, PyObject *prompt)
2065/*[clinic end generated code: output=83db5a191e7a0d60 input=5e8bb70c2908fe3c]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002066{
Victor Stinnerbd303c12013-11-07 23:07:29 +01002067 PyObject *fin = _PySys_GetObjectId(&PyId_stdin);
2068 PyObject *fout = _PySys_GetObjectId(&PyId_stdout);
2069 PyObject *ferr = _PySys_GetObjectId(&PyId_stderr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002070 PyObject *tmp;
2071 long fd;
2072 int tty;
Guido van Rossuma88a0332007-02-26 16:59:55 +00002073
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002074 /* Check that stdin/out/err are intact */
2075 if (fin == NULL || fin == Py_None) {
2076 PyErr_SetString(PyExc_RuntimeError,
2077 "input(): lost sys.stdin");
2078 return NULL;
2079 }
2080 if (fout == NULL || fout == Py_None) {
2081 PyErr_SetString(PyExc_RuntimeError,
2082 "input(): lost sys.stdout");
2083 return NULL;
2084 }
2085 if (ferr == NULL || ferr == Py_None) {
2086 PyErr_SetString(PyExc_RuntimeError,
2087 "input(): lost sys.stderr");
2088 return NULL;
2089 }
Guido van Rossumeba76962007-05-27 09:13:28 +00002090
Steve Dowerb82e17e2019-05-23 08:45:22 -07002091 if (PySys_Audit("builtins.input", "O", prompt ? prompt : Py_None) < 0) {
2092 return NULL;
2093 }
2094
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002095 /* First of all, flush stderr */
Jeroen Demeyer762f93f2019-07-08 10:19:25 +02002096 tmp = _PyObject_CallMethodIdNoArgs(ferr, &PyId_flush);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002097 if (tmp == NULL)
2098 PyErr_Clear();
2099 else
2100 Py_DECREF(tmp);
Guido van Rossumeba76962007-05-27 09:13:28 +00002101
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002102 /* We should only use (GNU) readline if Python's sys.stdin and
2103 sys.stdout are the same as C's stdin and stdout, because we
2104 need to pass it those. */
Jeroen Demeyer762f93f2019-07-08 10:19:25 +02002105 tmp = _PyObject_CallMethodIdNoArgs(fin, &PyId_fileno);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002106 if (tmp == NULL) {
2107 PyErr_Clear();
2108 tty = 0;
2109 }
2110 else {
2111 fd = PyLong_AsLong(tmp);
2112 Py_DECREF(tmp);
2113 if (fd < 0 && PyErr_Occurred())
2114 return NULL;
2115 tty = fd == fileno(stdin) && isatty(fd);
2116 }
2117 if (tty) {
Jeroen Demeyer762f93f2019-07-08 10:19:25 +02002118 tmp = _PyObject_CallMethodIdNoArgs(fout, &PyId_fileno);
Martin Panterc9a6ab52015-10-10 01:25:38 +00002119 if (tmp == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002120 PyErr_Clear();
Martin Panterc9a6ab52015-10-10 01:25:38 +00002121 tty = 0;
2122 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002123 else {
2124 fd = PyLong_AsLong(tmp);
2125 Py_DECREF(tmp);
2126 if (fd < 0 && PyErr_Occurred())
2127 return NULL;
2128 tty = fd == fileno(stdout) && isatty(fd);
2129 }
2130 }
Guido van Rossumeba76962007-05-27 09:13:28 +00002131
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002132 /* If we're interactive, use (GNU) readline */
2133 if (tty) {
Antoine Pitrou0d776b12011-11-06 00:34:26 +01002134 PyObject *po = NULL;
Serhiy Storchakae2f92de2017-11-11 13:06:26 +02002135 const char *promptstr;
Antoine Pitrou0d776b12011-11-06 00:34:26 +01002136 char *s = NULL;
2137 PyObject *stdin_encoding = NULL, *stdin_errors = NULL;
2138 PyObject *stdout_encoding = NULL, *stdout_errors = NULL;
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +02002139 const char *stdin_encoding_str, *stdin_errors_str;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002140 PyObject *result;
Victor Stinnerc0f1a1a2011-02-23 12:07:37 +00002141 size_t len;
Martin v. Löwis4a7b5d52007-09-04 05:24:49 +00002142
Serhiy Storchakac2cf1282017-03-12 13:50:36 +02002143 /* stdin is a text stream, so it must have an encoding. */
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02002144 stdin_encoding = _PyObject_GetAttrId(fin, &PyId_encoding);
Antoine Pitrou5ee9d8a2011-11-06 00:38:45 +01002145 stdin_errors = _PyObject_GetAttrId(fin, &PyId_errors);
Serhiy Storchakac2cf1282017-03-12 13:50:36 +02002146 if (!stdin_encoding || !stdin_errors ||
2147 !PyUnicode_Check(stdin_encoding) ||
2148 !PyUnicode_Check(stdin_errors)) {
2149 tty = 0;
Antoine Pitrou0d776b12011-11-06 00:34:26 +01002150 goto _readline_errors;
Serhiy Storchakac2cf1282017-03-12 13:50:36 +02002151 }
Serhiy Storchaka06515832016-11-20 09:13:07 +02002152 stdin_encoding_str = PyUnicode_AsUTF8(stdin_encoding);
2153 stdin_errors_str = PyUnicode_AsUTF8(stdin_errors);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01002154 if (!stdin_encoding_str || !stdin_errors_str)
2155 goto _readline_errors;
Jeroen Demeyer762f93f2019-07-08 10:19:25 +02002156 tmp = _PyObject_CallMethodIdNoArgs(fout, &PyId_flush);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002157 if (tmp == NULL)
2158 PyErr_Clear();
2159 else
2160 Py_DECREF(tmp);
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002161 if (prompt != NULL) {
Antoine Pitrou0d776b12011-11-06 00:34:26 +01002162 /* We have a prompt, encode it as stdout would */
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +02002163 const char *stdout_encoding_str, *stdout_errors_str;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002164 PyObject *stringpo;
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02002165 stdout_encoding = _PyObject_GetAttrId(fout, &PyId_encoding);
Antoine Pitrou5ee9d8a2011-11-06 00:38:45 +01002166 stdout_errors = _PyObject_GetAttrId(fout, &PyId_errors);
Serhiy Storchakac2cf1282017-03-12 13:50:36 +02002167 if (!stdout_encoding || !stdout_errors ||
2168 !PyUnicode_Check(stdout_encoding) ||
2169 !PyUnicode_Check(stdout_errors)) {
2170 tty = 0;
Antoine Pitrou0d776b12011-11-06 00:34:26 +01002171 goto _readline_errors;
Serhiy Storchakac2cf1282017-03-12 13:50:36 +02002172 }
Serhiy Storchaka06515832016-11-20 09:13:07 +02002173 stdout_encoding_str = PyUnicode_AsUTF8(stdout_encoding);
2174 stdout_errors_str = PyUnicode_AsUTF8(stdout_errors);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01002175 if (!stdout_encoding_str || !stdout_errors_str)
2176 goto _readline_errors;
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002177 stringpo = PyObject_Str(prompt);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01002178 if (stringpo == NULL)
2179 goto _readline_errors;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002180 po = PyUnicode_AsEncodedString(stringpo,
Antoine Pitrou0d776b12011-11-06 00:34:26 +01002181 stdout_encoding_str, stdout_errors_str);
2182 Py_CLEAR(stdout_encoding);
2183 Py_CLEAR(stdout_errors);
2184 Py_CLEAR(stringpo);
2185 if (po == NULL)
2186 goto _readline_errors;
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03002187 assert(PyBytes_Check(po));
2188 promptstr = PyBytes_AS_STRING(po);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002189 }
2190 else {
2191 po = NULL;
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002192 promptstr = "";
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002193 }
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002194 s = PyOS_Readline(stdin, stdout, promptstr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002195 if (s == NULL) {
Richard Oudkerk614c5782013-04-03 13:44:50 +01002196 PyErr_CheckSignals();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002197 if (!PyErr_Occurred())
2198 PyErr_SetNone(PyExc_KeyboardInterrupt);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01002199 goto _readline_errors;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002200 }
Victor Stinnerc0f1a1a2011-02-23 12:07:37 +00002201
2202 len = strlen(s);
2203 if (len == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002204 PyErr_SetNone(PyExc_EOFError);
2205 result = NULL;
2206 }
Victor Stinnerc0f1a1a2011-02-23 12:07:37 +00002207 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002208 if (len > PY_SSIZE_T_MAX) {
2209 PyErr_SetString(PyExc_OverflowError,
2210 "input: input too long");
2211 result = NULL;
2212 }
2213 else {
Victor Stinnerc0f1a1a2011-02-23 12:07:37 +00002214 len--; /* strip trailing '\n' */
2215 if (len != 0 && s[len-1] == '\r')
2216 len--; /* strip trailing '\r' */
Antoine Pitrou0d776b12011-11-06 00:34:26 +01002217 result = PyUnicode_Decode(s, len, stdin_encoding_str,
2218 stdin_errors_str);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002219 }
2220 }
2221 Py_DECREF(stdin_encoding);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01002222 Py_DECREF(stdin_errors);
2223 Py_XDECREF(po);
Victor Stinner00d7abd2020-12-01 09:56:42 +01002224 PyMem_Free(s);
Steve Dowerb82e17e2019-05-23 08:45:22 -07002225
2226 if (result != NULL) {
2227 if (PySys_Audit("builtins.input/result", "O", result) < 0) {
2228 return NULL;
2229 }
2230 }
2231
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002232 return result;
Serhiy Storchakac2cf1282017-03-12 13:50:36 +02002233
Antoine Pitrou0d776b12011-11-06 00:34:26 +01002234 _readline_errors:
2235 Py_XDECREF(stdin_encoding);
2236 Py_XDECREF(stdout_encoding);
2237 Py_XDECREF(stdin_errors);
2238 Py_XDECREF(stdout_errors);
2239 Py_XDECREF(po);
Serhiy Storchakac2cf1282017-03-12 13:50:36 +02002240 if (tty)
2241 return NULL;
2242
2243 PyErr_Clear();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002244 }
Guido van Rossumeba76962007-05-27 09:13:28 +00002245
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002246 /* Fallback if we're not interactive */
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002247 if (prompt != NULL) {
2248 if (PyFile_WriteObject(prompt, fout, Py_PRINT_RAW) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002249 return NULL;
2250 }
Jeroen Demeyer762f93f2019-07-08 10:19:25 +02002251 tmp = _PyObject_CallMethodIdNoArgs(fout, &PyId_flush);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002252 if (tmp == NULL)
2253 PyErr_Clear();
2254 else
2255 Py_DECREF(tmp);
2256 return PyFile_GetLine(fin, -1);
Guido van Rossuma88a0332007-02-26 16:59:55 +00002257}
2258
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002259
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002260/*[clinic input]
2261repr as builtin_repr
2262
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03002263 obj: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002264 /
2265
2266Return the canonical string representation of the object.
2267
2268For many object types, including most builtins, eval(repr(obj)) == obj.
2269[clinic start generated code]*/
2270
Guido van Rossum79f25d91997-04-29 20:08:16 +00002271static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002272builtin_repr(PyObject *module, PyObject *obj)
2273/*[clinic end generated code: output=7ed3778c44fd0194 input=1c9e6d66d3e3be04]*/
Guido van Rossumc89705d1992-11-26 08:54:07 +00002274{
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002275 return PyObject_Repr(obj);
Guido van Rossumc89705d1992-11-26 08:54:07 +00002276}
2277
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002278
Serhiy Storchakaaca7f572017-11-15 17:51:14 +02002279/*[clinic input]
2280round as builtin_round
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002281
Serhiy Storchakaaca7f572017-11-15 17:51:14 +02002282 number: object
Serhiy Storchaka279f4462019-09-14 12:24:05 +03002283 ndigits: object = None
Serhiy Storchakaaca7f572017-11-15 17:51:14 +02002284
2285Round a number to a given precision in decimal digits.
2286
2287The return value is an integer if ndigits is omitted or None. Otherwise
2288the return value has the same type as the number. ndigits may be negative.
2289[clinic start generated code]*/
2290
2291static PyObject *
2292builtin_round_impl(PyObject *module, PyObject *number, PyObject *ndigits)
Serhiy Storchaka279f4462019-09-14 12:24:05 +03002293/*[clinic end generated code: output=ff0d9dd176c02ede input=275678471d7aca15]*/
Serhiy Storchakaaca7f572017-11-15 17:51:14 +02002294{
2295 PyObject *round, *result;
Alex Martelliae211f92007-08-22 23:21:33 +00002296
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002297 if (Py_TYPE(number)->tp_dict == NULL) {
2298 if (PyType_Ready(Py_TYPE(number)) < 0)
2299 return NULL;
2300 }
Guido van Rossum15d3d042007-08-24 02:02:45 +00002301
Benjamin Peterson214a7d22013-04-13 17:19:01 -04002302 round = _PyObject_LookupSpecial(number, &PyId___round__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002303 if (round == NULL) {
Benjamin Peterson214a7d22013-04-13 17:19:01 -04002304 if (!PyErr_Occurred())
2305 PyErr_Format(PyExc_TypeError,
2306 "type %.100s doesn't define __round__ method",
2307 Py_TYPE(number)->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002308 return NULL;
2309 }
Alex Martelliae211f92007-08-22 23:21:33 +00002310
Serhiy Storchaka279f4462019-09-14 12:24:05 +03002311 if (ndigits == Py_None)
Victor Stinnerf17c3de2016-12-06 18:46:19 +01002312 result = _PyObject_CallNoArg(round);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002313 else
Petr Viktorinffd97532020-02-11 17:46:57 +01002314 result = PyObject_CallOneArg(round, ndigits);
Benjamin Peterson214a7d22013-04-13 17:19:01 -04002315 Py_DECREF(round);
2316 return result;
Guido van Rossum9e51f9b1993-02-12 16:29:05 +00002317}
2318
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002319
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002320/*AC: we need to keep the kwds dict intact to easily call into the
2321 * list.sort method, which isn't currently supported in AC. So we just use
2322 * the initially generated signature with a custom implementation.
2323 */
2324/* [disabled clinic input]
2325sorted as builtin_sorted
2326
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03002327 iterable as seq: object
2328 key as keyfunc: object = None
2329 reverse: object = False
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002330
2331Return a new list containing all items from the iterable in ascending order.
2332
Raymond Hettinger7ea386e2016-08-25 21:11:50 -07002333A custom key function can be supplied to customize the sort order, and the
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002334reverse flag can be set to request the result in descending order.
2335[end disabled clinic input]*/
2336
2337PyDoc_STRVAR(builtin_sorted__doc__,
Serhiy Storchaka3a104252017-01-23 12:29:47 +02002338"sorted($module, iterable, /, *, key=None, reverse=False)\n"
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002339"--\n"
2340"\n"
2341"Return a new list containing all items from the iterable in ascending order.\n"
2342"\n"
Raymond Hettinger7ea386e2016-08-25 21:11:50 -07002343"A custom key function can be supplied to customize the sort order, and the\n"
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002344"reverse flag can be set to request the result in descending order.");
2345
2346#define BUILTIN_SORTED_METHODDEF \
Serhiy Storchaka62be7422018-11-27 13:27:31 +02002347 {"sorted", (PyCFunction)(void(*)(void))builtin_sorted, METH_FASTCALL | METH_KEYWORDS, builtin_sorted__doc__},
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002348
Raymond Hettinger64958a12003-12-17 20:43:33 +00002349static PyObject *
Serhiy Storchakaa5552f02017-12-15 13:11:11 +02002350builtin_sorted(PyObject *self, PyObject *const *args, Py_ssize_t nargs, PyObject *kwnames)
Raymond Hettinger64958a12003-12-17 20:43:33 +00002351{
Serhiy Storchaka7cf8beb2017-01-21 23:05:00 +02002352 PyObject *newlist, *v, *seq, *callable;
Victor Stinner5a60eca2017-01-17 15:17:49 +01002353
Serhiy Storchaka7cf8beb2017-01-21 23:05:00 +02002354 /* Keyword arguments are passed through list.sort() which will check
2355 them. */
2356 if (!_PyArg_UnpackStack(args, nargs, "sorted", 1, 1, &seq))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002357 return NULL;
Raymond Hettinger64958a12003-12-17 20:43:33 +00002358
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002359 newlist = PySequence_List(seq);
2360 if (newlist == NULL)
2361 return NULL;
Raymond Hettinger64958a12003-12-17 20:43:33 +00002362
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02002363 callable = _PyObject_GetAttrId(newlist, &PyId_sort);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002364 if (callable == NULL) {
2365 Py_DECREF(newlist);
2366 return NULL;
2367 }
Georg Brandl99d7e4e2005-08-31 22:21:15 +00002368
Serhiy Storchaka299dc232017-01-20 08:35:18 +02002369 assert(nargs >= 1);
Petr Viktorinffd97532020-02-11 17:46:57 +01002370 v = PyObject_Vectorcall(callable, args + 1, nargs - 1, kwnames);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002371 Py_DECREF(callable);
2372 if (v == NULL) {
2373 Py_DECREF(newlist);
2374 return NULL;
2375 }
2376 Py_DECREF(v);
2377 return newlist;
Raymond Hettinger64958a12003-12-17 20:43:33 +00002378}
2379
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002380
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002381/* AC: cannot convert yet, as needs PEP 457 group support in inspect */
Guido van Rossum79f25d91997-04-29 20:08:16 +00002382static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002383builtin_vars(PyObject *self, PyObject *args)
Guido van Rossum2d951851994-08-29 12:52:16 +00002384{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002385 PyObject *v = NULL;
2386 PyObject *d;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002387
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002388 if (!PyArg_UnpackTuple(args, "vars", 0, 1, &v))
2389 return NULL;
2390 if (v == NULL) {
2391 d = PyEval_GetLocals();
Serhiy Storchaka41c57b32019-09-01 12:03:39 +03002392 Py_XINCREF(d);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002393 }
2394 else {
Serhiy Storchaka41c57b32019-09-01 12:03:39 +03002395 if (_PyObject_LookupAttrId(v, &PyId___dict__, &d) == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002396 PyErr_SetString(PyExc_TypeError,
2397 "vars() argument must have __dict__ attribute");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002398 }
2399 }
2400 return d;
Guido van Rossum2d951851994-08-29 12:52:16 +00002401}
2402
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002403PyDoc_STRVAR(vars_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002404"vars([object]) -> dictionary\n\
2405\n\
2406Without arguments, equivalent to locals().\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002407With an argument, equivalent to object.__dict__.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002408
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002409
2410/*[clinic input]
2411sum as builtin_sum
2412
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03002413 iterable: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002414 /
Raymond Hettinger9dfa0fe2018-09-12 10:54:06 -07002415 start: object(c_default="NULL") = 0
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002416
2417Return the sum of a 'start' value (default: 0) plus an iterable of numbers
2418
2419When the iterable is empty, return the start value.
2420This function is intended specifically for use with numeric values and may
2421reject non-numeric types.
2422[clinic start generated code]*/
2423
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002424static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002425builtin_sum_impl(PyObject *module, PyObject *iterable, PyObject *start)
Raymond Hettinger9dfa0fe2018-09-12 10:54:06 -07002426/*[clinic end generated code: output=df758cec7d1d302f input=162b50765250d222]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002427{
2428 PyObject *result = start;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002429 PyObject *temp, *item, *iter;
Alex Martellia70b1912003-04-22 08:12:33 +00002430
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002431 iter = PyObject_GetIter(iterable);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002432 if (iter == NULL)
2433 return NULL;
Alex Martellia70b1912003-04-22 08:12:33 +00002434
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002435 if (result == NULL) {
2436 result = PyLong_FromLong(0);
2437 if (result == NULL) {
2438 Py_DECREF(iter);
2439 return NULL;
2440 }
2441 } else {
2442 /* reject string values for 'start' parameter */
2443 if (PyUnicode_Check(result)) {
2444 PyErr_SetString(PyExc_TypeError,
2445 "sum() can't sum strings [use ''.join(seq) instead]");
2446 Py_DECREF(iter);
2447 return NULL;
2448 }
Benjamin Petersonce071ca2011-07-29 14:23:47 -05002449 if (PyBytes_Check(result)) {
2450 PyErr_SetString(PyExc_TypeError,
2451 "sum() can't sum bytes [use b''.join(seq) instead]");
Benjamin Peterson405f32c2011-07-29 22:43:45 -05002452 Py_DECREF(iter);
Benjamin Petersonce071ca2011-07-29 14:23:47 -05002453 return NULL;
2454 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002455 if (PyByteArray_Check(result)) {
2456 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson4f921c22011-07-29 14:24:29 -05002457 "sum() can't sum bytearray [use b''.join(seq) instead]");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002458 Py_DECREF(iter);
2459 return NULL;
2460 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002461 Py_INCREF(result);
2462 }
Alex Martellia70b1912003-04-22 08:12:33 +00002463
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002464#ifndef SLOW_SUM
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002465 /* Fast addition by keeping temporary sums in C instead of new Python objects.
2466 Assumes all inputs are the same type. If the assumption fails, default
2467 to the more general routine.
2468 */
2469 if (PyLong_CheckExact(result)) {
2470 int overflow;
2471 long i_result = PyLong_AsLongAndOverflow(result, &overflow);
2472 /* If this already overflowed, don't even enter the loop. */
2473 if (overflow == 0) {
2474 Py_DECREF(result);
2475 result = NULL;
2476 }
2477 while(result == NULL) {
2478 item = PyIter_Next(iter);
2479 if (item == NULL) {
2480 Py_DECREF(iter);
2481 if (PyErr_Occurred())
2482 return NULL;
2483 return PyLong_FromLong(i_result);
2484 }
Serhiy Storchaka88bdb922019-09-10 16:31:01 +03002485 if (PyLong_CheckExact(item) || PyBool_Check(item)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002486 long b = PyLong_AsLongAndOverflow(item, &overflow);
Serhiy Storchaka29500732019-05-05 14:26:23 +03002487 if (overflow == 0 &&
2488 (i_result >= 0 ? (b <= LONG_MAX - i_result)
2489 : (b >= LONG_MIN - i_result)))
2490 {
2491 i_result += b;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002492 Py_DECREF(item);
2493 continue;
2494 }
2495 }
2496 /* Either overflowed or is not an int. Restore real objects and process normally */
2497 result = PyLong_FromLong(i_result);
Christian Heimes704e2d32013-07-26 22:49:26 +02002498 if (result == NULL) {
2499 Py_DECREF(item);
2500 Py_DECREF(iter);
2501 return NULL;
2502 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002503 temp = PyNumber_Add(result, item);
2504 Py_DECREF(result);
2505 Py_DECREF(item);
2506 result = temp;
2507 if (result == NULL) {
2508 Py_DECREF(iter);
2509 return NULL;
2510 }
2511 }
2512 }
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002513
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002514 if (PyFloat_CheckExact(result)) {
2515 double f_result = PyFloat_AS_DOUBLE(result);
2516 Py_DECREF(result);
2517 result = NULL;
2518 while(result == NULL) {
2519 item = PyIter_Next(iter);
2520 if (item == NULL) {
2521 Py_DECREF(iter);
2522 if (PyErr_Occurred())
2523 return NULL;
2524 return PyFloat_FromDouble(f_result);
2525 }
2526 if (PyFloat_CheckExact(item)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002527 f_result += PyFloat_AS_DOUBLE(item);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002528 Py_DECREF(item);
2529 continue;
2530 }
Serhiy Storchaka88bdb922019-09-10 16:31:01 +03002531 if (PyLong_Check(item)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002532 long value;
2533 int overflow;
2534 value = PyLong_AsLongAndOverflow(item, &overflow);
2535 if (!overflow) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002536 f_result += (double)value;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002537 Py_DECREF(item);
2538 continue;
2539 }
2540 }
2541 result = PyFloat_FromDouble(f_result);
Alexey Izbyshev2b824b22018-08-24 07:27:52 +03002542 if (result == NULL) {
2543 Py_DECREF(item);
2544 Py_DECREF(iter);
2545 return NULL;
2546 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002547 temp = PyNumber_Add(result, item);
2548 Py_DECREF(result);
2549 Py_DECREF(item);
2550 result = temp;
2551 if (result == NULL) {
2552 Py_DECREF(iter);
2553 return NULL;
2554 }
2555 }
2556 }
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002557#endif
2558
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002559 for(;;) {
2560 item = PyIter_Next(iter);
2561 if (item == NULL) {
2562 /* error, or end-of-sequence */
2563 if (PyErr_Occurred()) {
2564 Py_DECREF(result);
2565 result = NULL;
2566 }
2567 break;
2568 }
2569 /* It's tempting to use PyNumber_InPlaceAdd instead of
2570 PyNumber_Add here, to avoid quadratic running time
2571 when doing 'sum(list_of_lists, [])'. However, this
2572 would produce a change in behaviour: a snippet like
Mark Dickinson9acadc52009-10-26 14:19:42 +00002573
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002574 empty = []
2575 sum([[x] for x in range(10)], empty)
Mark Dickinson9acadc52009-10-26 14:19:42 +00002576
Brandt Bucherabb9a442020-02-01 03:08:34 -08002577 would change the value of empty. In fact, using
2578 in-place addition rather that binary addition for
2579 any of the steps introduces subtle behavior changes:
Victor Stinner58f4e1a2020-02-05 18:24:33 +01002580
Brandt Bucherabb9a442020-02-01 03:08:34 -08002581 https://bugs.python.org/issue18305 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002582 temp = PyNumber_Add(result, item);
2583 Py_DECREF(result);
2584 Py_DECREF(item);
2585 result = temp;
2586 if (result == NULL)
2587 break;
2588 }
2589 Py_DECREF(iter);
2590 return result;
Alex Martellia70b1912003-04-22 08:12:33 +00002591}
2592
Alex Martellia70b1912003-04-22 08:12:33 +00002593
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002594/*[clinic input]
2595isinstance as builtin_isinstance
2596
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03002597 obj: object
2598 class_or_tuple: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002599 /
2600
2601Return whether an object is an instance of a class or of a subclass thereof.
2602
2603A tuple, as in ``isinstance(x, (A, B, ...))``, may be given as the target to
2604check against. This is equivalent to ``isinstance(x, A) or isinstance(x, B)
2605or ...`` etc.
2606[clinic start generated code]*/
2607
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002608static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002609builtin_isinstance_impl(PyObject *module, PyObject *obj,
Larry Hastings89964c42015-04-14 18:07:59 -04002610 PyObject *class_or_tuple)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002611/*[clinic end generated code: output=6faf01472c13b003 input=ffa743db1daf7549]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002612{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002613 int retval;
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002614
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002615 retval = PyObject_IsInstance(obj, class_or_tuple);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002616 if (retval < 0)
2617 return NULL;
2618 return PyBool_FromLong(retval);
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002619}
2620
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002621
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002622/*[clinic input]
2623issubclass as builtin_issubclass
2624
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03002625 cls: object
2626 class_or_tuple: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002627 /
2628
Alex Poveldf773f82020-06-03 15:19:45 +02002629Return whether 'cls' is derived from another class or is the same class.
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002630
2631A tuple, as in ``issubclass(x, (A, B, ...))``, may be given as the target to
2632check against. This is equivalent to ``issubclass(x, A) or issubclass(x, B)
Alex Poveldf773f82020-06-03 15:19:45 +02002633or ...``.
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002634[clinic start generated code]*/
2635
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002636static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002637builtin_issubclass_impl(PyObject *module, PyObject *cls,
Larry Hastings89964c42015-04-14 18:07:59 -04002638 PyObject *class_or_tuple)
Alex Poveldf773f82020-06-03 15:19:45 +02002639/*[clinic end generated code: output=358412410cd7a250 input=a24b9f3d58c370d6]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002640{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002641 int retval;
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002642
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002643 retval = PyObject_IsSubclass(cls, class_or_tuple);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002644 if (retval < 0)
2645 return NULL;
2646 return PyBool_FromLong(retval);
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002647}
2648
2649
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002650typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002651 PyObject_HEAD
Guido van Rossum310f6aa2020-06-19 03:16:57 -07002652 Py_ssize_t tuplesize;
2653 PyObject *ittuple; /* tuple of iterators */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002654 PyObject *result;
Guido van Rossum310f6aa2020-06-19 03:16:57 -07002655 int strict;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002656} zipobject;
2657
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002658static PyObject *
2659zip_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
Barry Warsawbd599b52000-08-03 15:45:29 +00002660{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002661 zipobject *lz;
2662 Py_ssize_t i;
2663 PyObject *ittuple; /* tuple of iterators */
2664 PyObject *result;
Serhiy Storchakabf623ae2017-04-19 20:03:52 +03002665 Py_ssize_t tuplesize;
Guido van Rossum310f6aa2020-06-19 03:16:57 -07002666 int strict = 0;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002667
Guido van Rossum310f6aa2020-06-19 03:16:57 -07002668 if (kwds) {
2669 PyObject *empty = PyTuple_New(0);
2670 if (empty == NULL) {
2671 return NULL;
2672 }
2673 static char *kwlist[] = {"strict", NULL};
2674 int parsed = PyArg_ParseTupleAndKeywords(
2675 empty, kwds, "|$p:zip", kwlist, &strict);
2676 Py_DECREF(empty);
2677 if (!parsed) {
2678 return NULL;
2679 }
2680 }
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002681
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002682 /* args must be a tuple */
2683 assert(PyTuple_Check(args));
Serhiy Storchakabf623ae2017-04-19 20:03:52 +03002684 tuplesize = PyTuple_GET_SIZE(args);
Barry Warsawbd599b52000-08-03 15:45:29 +00002685
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002686 /* obtain iterators */
2687 ittuple = PyTuple_New(tuplesize);
2688 if (ittuple == NULL)
2689 return NULL;
2690 for (i=0; i < tuplesize; ++i) {
2691 PyObject *item = PyTuple_GET_ITEM(args, i);
2692 PyObject *it = PyObject_GetIter(item);
2693 if (it == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002694 Py_DECREF(ittuple);
2695 return NULL;
2696 }
2697 PyTuple_SET_ITEM(ittuple, i, it);
2698 }
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002699
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002700 /* create a result holder */
2701 result = PyTuple_New(tuplesize);
2702 if (result == NULL) {
2703 Py_DECREF(ittuple);
2704 return NULL;
2705 }
2706 for (i=0 ; i < tuplesize ; i++) {
2707 Py_INCREF(Py_None);
2708 PyTuple_SET_ITEM(result, i, Py_None);
2709 }
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002710
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002711 /* create zipobject structure */
2712 lz = (zipobject *)type->tp_alloc(type, 0);
2713 if (lz == NULL) {
2714 Py_DECREF(ittuple);
2715 Py_DECREF(result);
2716 return NULL;
2717 }
2718 lz->ittuple = ittuple;
2719 lz->tuplesize = tuplesize;
2720 lz->result = result;
Guido van Rossum310f6aa2020-06-19 03:16:57 -07002721 lz->strict = strict;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002722
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002723 return (PyObject *)lz;
Barry Warsawbd599b52000-08-03 15:45:29 +00002724}
2725
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002726static void
2727zip_dealloc(zipobject *lz)
2728{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002729 PyObject_GC_UnTrack(lz);
2730 Py_XDECREF(lz->ittuple);
2731 Py_XDECREF(lz->result);
2732 Py_TYPE(lz)->tp_free(lz);
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002733}
2734
2735static int
2736zip_traverse(zipobject *lz, visitproc visit, void *arg)
2737{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002738 Py_VISIT(lz->ittuple);
2739 Py_VISIT(lz->result);
2740 return 0;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002741}
2742
2743static PyObject *
2744zip_next(zipobject *lz)
2745{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002746 Py_ssize_t i;
2747 Py_ssize_t tuplesize = lz->tuplesize;
2748 PyObject *result = lz->result;
2749 PyObject *it;
2750 PyObject *item;
2751 PyObject *olditem;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002752
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002753 if (tuplesize == 0)
2754 return NULL;
2755 if (Py_REFCNT(result) == 1) {
2756 Py_INCREF(result);
2757 for (i=0 ; i < tuplesize ; i++) {
2758 it = PyTuple_GET_ITEM(lz->ittuple, i);
2759 item = (*Py_TYPE(it)->tp_iternext)(it);
Serhiy Storchaka278d03b2013-04-06 22:52:34 +03002760 if (item == NULL) {
2761 Py_DECREF(result);
Guido van Rossum310f6aa2020-06-19 03:16:57 -07002762 if (lz->strict) {
2763 goto check;
2764 }
Serhiy Storchaka278d03b2013-04-06 22:52:34 +03002765 return NULL;
2766 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002767 olditem = PyTuple_GET_ITEM(result, i);
2768 PyTuple_SET_ITEM(result, i, item);
2769 Py_DECREF(olditem);
2770 }
Brandt Bucher226a0122020-12-04 19:45:57 -08002771 // bpo-42536: The GC may have untracked this result tuple. Since we're
2772 // recycling it, make sure it's tracked again:
2773 if (!_PyObject_GC_IS_TRACKED(result)) {
2774 _PyObject_GC_TRACK(result);
2775 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002776 } else {
2777 result = PyTuple_New(tuplesize);
2778 if (result == NULL)
Serhiy Storchaka278d03b2013-04-06 22:52:34 +03002779 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002780 for (i=0 ; i < tuplesize ; i++) {
2781 it = PyTuple_GET_ITEM(lz->ittuple, i);
2782 item = (*Py_TYPE(it)->tp_iternext)(it);
Serhiy Storchaka278d03b2013-04-06 22:52:34 +03002783 if (item == NULL) {
2784 Py_DECREF(result);
Guido van Rossum310f6aa2020-06-19 03:16:57 -07002785 if (lz->strict) {
2786 goto check;
2787 }
Serhiy Storchaka278d03b2013-04-06 22:52:34 +03002788 return NULL;
2789 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002790 PyTuple_SET_ITEM(result, i, item);
2791 }
2792 }
2793 return result;
Guido van Rossum310f6aa2020-06-19 03:16:57 -07002794check:
2795 if (PyErr_Occurred()) {
2796 if (!PyErr_ExceptionMatches(PyExc_StopIteration)) {
2797 // next() on argument i raised an exception (not StopIteration)
2798 return NULL;
2799 }
2800 PyErr_Clear();
2801 }
2802 if (i) {
2803 // ValueError: zip() argument 2 is shorter than argument 1
2804 // ValueError: zip() argument 3 is shorter than arguments 1-2
2805 const char* plural = i == 1 ? " " : "s 1-";
2806 return PyErr_Format(PyExc_ValueError,
2807 "zip() argument %d is shorter than argument%s%d",
2808 i + 1, plural, i);
2809 }
2810 for (i = 1; i < tuplesize; i++) {
2811 it = PyTuple_GET_ITEM(lz->ittuple, i);
2812 item = (*Py_TYPE(it)->tp_iternext)(it);
2813 if (item) {
2814 Py_DECREF(item);
2815 const char* plural = i == 1 ? " " : "s 1-";
2816 return PyErr_Format(PyExc_ValueError,
2817 "zip() argument %d is longer than argument%s%d",
2818 i + 1, plural, i);
2819 }
2820 if (PyErr_Occurred()) {
2821 if (!PyErr_ExceptionMatches(PyExc_StopIteration)) {
2822 // next() on argument i raised an exception (not StopIteration)
2823 return NULL;
2824 }
2825 PyErr_Clear();
2826 }
2827 // Argument i is exhausted. So far so good...
2828 }
2829 // All arguments are exhausted. Success!
2830 return NULL;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002831}
Barry Warsawbd599b52000-08-03 15:45:29 +00002832
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002833static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05302834zip_reduce(zipobject *lz, PyObject *Py_UNUSED(ignored))
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002835{
2836 /* Just recreate the zip with the internal iterator tuple */
Guido van Rossum310f6aa2020-06-19 03:16:57 -07002837 if (lz->strict) {
2838 return PyTuple_Pack(3, Py_TYPE(lz), lz->ittuple, Py_True);
2839 }
2840 return PyTuple_Pack(2, Py_TYPE(lz), lz->ittuple);
2841}
2842
2843PyDoc_STRVAR(setstate_doc, "Set state information for unpickling.");
2844
2845static PyObject *
2846zip_setstate(zipobject *lz, PyObject *state)
2847{
2848 int strict = PyObject_IsTrue(state);
2849 if (strict < 0) {
2850 return NULL;
2851 }
2852 lz->strict = strict;
2853 Py_RETURN_NONE;
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002854}
2855
2856static PyMethodDef zip_methods[] = {
2857 {"__reduce__", (PyCFunction)zip_reduce, METH_NOARGS, reduce_doc},
Guido van Rossum310f6aa2020-06-19 03:16:57 -07002858 {"__setstate__", (PyCFunction)zip_setstate, METH_O, setstate_doc},
2859 {NULL} /* sentinel */
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002860};
2861
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002862PyDoc_STRVAR(zip_doc,
Guido van Rossum310f6aa2020-06-19 03:16:57 -07002863"zip(*iterables, strict=False) --> Yield tuples until an input is exhausted.\n\
Barry Warsawbd599b52000-08-03 15:45:29 +00002864\n\
Gregory P. Smith6a5d3ff2020-05-15 14:26:00 -07002865 >>> list(zip('abcdefg', range(3), range(4)))\n\
2866 [('a', 0, 0), ('b', 1, 1), ('c', 2, 2)]\n\
2867\n\
2868The zip object yields n-length tuples, where n is the number of iterables\n\
2869passed as positional arguments to zip(). The i-th element in every tuple\n\
2870comes from the i-th iterable argument to zip(). This continues until the\n\
Guido van Rossum310f6aa2020-06-19 03:16:57 -07002871shortest argument is exhausted.\n\
2872\n\
2873If strict is true and one of the arguments is exhausted before the others,\n\
2874raise a ValueError.");
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002875
2876PyTypeObject PyZip_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002877 PyVarObject_HEAD_INIT(&PyType_Type, 0)
2878 "zip", /* tp_name */
2879 sizeof(zipobject), /* tp_basicsize */
2880 0, /* tp_itemsize */
2881 /* methods */
2882 (destructor)zip_dealloc, /* tp_dealloc */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02002883 0, /* tp_vectorcall_offset */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002884 0, /* tp_getattr */
2885 0, /* tp_setattr */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02002886 0, /* tp_as_async */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002887 0, /* tp_repr */
2888 0, /* tp_as_number */
2889 0, /* tp_as_sequence */
2890 0, /* tp_as_mapping */
2891 0, /* tp_hash */
2892 0, /* tp_call */
2893 0, /* tp_str */
2894 PyObject_GenericGetAttr, /* tp_getattro */
2895 0, /* tp_setattro */
2896 0, /* tp_as_buffer */
2897 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
2898 Py_TPFLAGS_BASETYPE, /* tp_flags */
2899 zip_doc, /* tp_doc */
2900 (traverseproc)zip_traverse, /* tp_traverse */
2901 0, /* tp_clear */
2902 0, /* tp_richcompare */
2903 0, /* tp_weaklistoffset */
2904 PyObject_SelfIter, /* tp_iter */
2905 (iternextfunc)zip_next, /* tp_iternext */
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002906 zip_methods, /* tp_methods */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002907 0, /* tp_members */
2908 0, /* tp_getset */
2909 0, /* tp_base */
2910 0, /* tp_dict */
2911 0, /* tp_descr_get */
2912 0, /* tp_descr_set */
2913 0, /* tp_dictoffset */
2914 0, /* tp_init */
2915 PyType_GenericAlloc, /* tp_alloc */
2916 zip_new, /* tp_new */
2917 PyObject_GC_Del, /* tp_free */
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002918};
Barry Warsawbd599b52000-08-03 15:45:29 +00002919
2920
Guido van Rossum79f25d91997-04-29 20:08:16 +00002921static PyMethodDef builtin_methods[] = {
Serhiy Storchaka62be7422018-11-27 13:27:31 +02002922 {"__build_class__", (PyCFunction)(void(*)(void))builtin___build_class__,
Serhiy Storchaka6969eaf2017-07-03 21:20:15 +03002923 METH_FASTCALL | METH_KEYWORDS, build_class_doc},
Serhiy Storchaka62be7422018-11-27 13:27:31 +02002924 {"__import__", (PyCFunction)(void(*)(void))builtin___import__, METH_VARARGS | METH_KEYWORDS, import_doc},
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002925 BUILTIN_ABS_METHODDEF
2926 BUILTIN_ALL_METHODDEF
2927 BUILTIN_ANY_METHODDEF
2928 BUILTIN_ASCII_METHODDEF
2929 BUILTIN_BIN_METHODDEF
Serhiy Storchaka62be7422018-11-27 13:27:31 +02002930 {"breakpoint", (PyCFunction)(void(*)(void))builtin_breakpoint, METH_FASTCALL | METH_KEYWORDS, breakpoint_doc},
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002931 BUILTIN_CALLABLE_METHODDEF
2932 BUILTIN_CHR_METHODDEF
2933 BUILTIN_COMPILE_METHODDEF
2934 BUILTIN_DELATTR_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002935 {"dir", builtin_dir, METH_VARARGS, dir_doc},
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002936 BUILTIN_DIVMOD_METHODDEF
2937 BUILTIN_EVAL_METHODDEF
2938 BUILTIN_EXEC_METHODDEF
2939 BUILTIN_FORMAT_METHODDEF
Serhiy Storchaka62be7422018-11-27 13:27:31 +02002940 {"getattr", (PyCFunction)(void(*)(void))builtin_getattr, METH_FASTCALL, getattr_doc},
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002941 BUILTIN_GLOBALS_METHODDEF
2942 BUILTIN_HASATTR_METHODDEF
2943 BUILTIN_HASH_METHODDEF
2944 BUILTIN_HEX_METHODDEF
2945 BUILTIN_ID_METHODDEF
2946 BUILTIN_INPUT_METHODDEF
2947 BUILTIN_ISINSTANCE_METHODDEF
2948 BUILTIN_ISSUBCLASS_METHODDEF
Serhiy Storchaka79342662019-01-12 08:25:41 +02002949 {"iter", (PyCFunction)(void(*)(void))builtin_iter, METH_FASTCALL, iter_doc},
Joshua Bronsonf0a6fde2021-03-23 18:47:21 -04002950 BUILTIN_AITER_METHODDEF
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002951 BUILTIN_LEN_METHODDEF
2952 BUILTIN_LOCALS_METHODDEF
Serhiy Storchaka62be7422018-11-27 13:27:31 +02002953 {"max", (PyCFunction)(void(*)(void))builtin_max, METH_VARARGS | METH_KEYWORDS, max_doc},
2954 {"min", (PyCFunction)(void(*)(void))builtin_min, METH_VARARGS | METH_KEYWORDS, min_doc},
2955 {"next", (PyCFunction)(void(*)(void))builtin_next, METH_FASTCALL, next_doc},
Joshua Bronsonf0a6fde2021-03-23 18:47:21 -04002956 BUILTIN_ANEXT_METHODDEF
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002957 BUILTIN_OCT_METHODDEF
2958 BUILTIN_ORD_METHODDEF
2959 BUILTIN_POW_METHODDEF
Serhiy Storchaka62be7422018-11-27 13:27:31 +02002960 {"print", (PyCFunction)(void(*)(void))builtin_print, METH_FASTCALL | METH_KEYWORDS, print_doc},
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002961 BUILTIN_REPR_METHODDEF
Serhiy Storchakaaca7f572017-11-15 17:51:14 +02002962 BUILTIN_ROUND_METHODDEF
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002963 BUILTIN_SETATTR_METHODDEF
2964 BUILTIN_SORTED_METHODDEF
2965 BUILTIN_SUM_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002966 {"vars", builtin_vars, METH_VARARGS, vars_doc},
2967 {NULL, NULL},
Guido van Rossum3f5da241990-12-20 15:06:42 +00002968};
2969
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002970PyDoc_STRVAR(builtin_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002971"Built-in functions, exceptions, and other objects.\n\
2972\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002973Noteworthy: None is the `nil' object; Ellipsis represents `...' in slices.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002974
Martin v. Löwis1a214512008-06-11 05:26:20 +00002975static struct PyModuleDef builtinsmodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002976 PyModuleDef_HEAD_INIT,
2977 "builtins",
2978 builtin_doc,
2979 -1, /* multiple "initialization" just copies the module dict. */
2980 builtin_methods,
2981 NULL,
2982 NULL,
2983 NULL,
2984 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00002985};
2986
2987
Guido van Rossum25ce5661997-08-02 03:10:38 +00002988PyObject *
Victor Stinnerbcb094b2021-02-19 15:10:45 +01002989_PyBuiltin_Init(PyInterpreterState *interp)
Guido van Rossum25ce5661997-08-02 03:10:38 +00002990{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002991 PyObject *mod, *dict, *debug;
Benjamin Peterson42124a72012-10-30 23:41:54 -04002992
Victor Stinnerbcb094b2021-02-19 15:10:45 +01002993 const PyConfig *config = _PyInterpreterState_GetConfig(interp);
Victor Stinnerfbca9082018-08-30 00:50:45 +02002994
Benjamin Peterson42124a72012-10-30 23:41:54 -04002995 if (PyType_Ready(&PyFilter_Type) < 0 ||
2996 PyType_Ready(&PyMap_Type) < 0 ||
2997 PyType_Ready(&PyZip_Type) < 0)
2998 return NULL;
2999
Eric Snowd393c1b2017-09-14 12:18:12 -06003000 mod = _PyModule_CreateInitialized(&builtinsmodule, PYTHON_API_VERSION);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003001 if (mod == NULL)
3002 return NULL;
3003 dict = PyModule_GetDict(mod);
Tim Peters4b7625e2001-09-13 21:37:17 +00003004
Tim Peters7571a0f2003-03-23 17:52:28 +00003005#ifdef Py_TRACE_REFS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003006 /* "builtins" exposes a number of statically allocated objects
3007 * that, before this code was added in 2.3, never showed up in
3008 * the list of "all objects" maintained by Py_TRACE_REFS. As a
3009 * result, programs leaking references to None and False (etc)
3010 * couldn't be diagnosed by examining sys.getobjects(0).
3011 */
Tim Peters7571a0f2003-03-23 17:52:28 +00003012#define ADD_TO_ALL(OBJECT) _Py_AddToAllObjects((PyObject *)(OBJECT), 0)
3013#else
3014#define ADD_TO_ALL(OBJECT) (void)0
3015#endif
3016
Tim Peters4b7625e2001-09-13 21:37:17 +00003017#define SETBUILTIN(NAME, OBJECT) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003018 if (PyDict_SetItemString(dict, NAME, (PyObject *)OBJECT) < 0) \
3019 return NULL; \
3020 ADD_TO_ALL(OBJECT)
Tim Peters4b7625e2001-09-13 21:37:17 +00003021
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003022 SETBUILTIN("None", Py_None);
3023 SETBUILTIN("Ellipsis", Py_Ellipsis);
3024 SETBUILTIN("NotImplemented", Py_NotImplemented);
3025 SETBUILTIN("False", Py_False);
3026 SETBUILTIN("True", Py_True);
3027 SETBUILTIN("bool", &PyBool_Type);
3028 SETBUILTIN("memoryview", &PyMemoryView_Type);
3029 SETBUILTIN("bytearray", &PyByteArray_Type);
3030 SETBUILTIN("bytes", &PyBytes_Type);
3031 SETBUILTIN("classmethod", &PyClassMethod_Type);
3032 SETBUILTIN("complex", &PyComplex_Type);
3033 SETBUILTIN("dict", &PyDict_Type);
3034 SETBUILTIN("enumerate", &PyEnum_Type);
3035 SETBUILTIN("filter", &PyFilter_Type);
3036 SETBUILTIN("float", &PyFloat_Type);
3037 SETBUILTIN("frozenset", &PyFrozenSet_Type);
3038 SETBUILTIN("property", &PyProperty_Type);
3039 SETBUILTIN("int", &PyLong_Type);
3040 SETBUILTIN("list", &PyList_Type);
3041 SETBUILTIN("map", &PyMap_Type);
3042 SETBUILTIN("object", &PyBaseObject_Type);
3043 SETBUILTIN("range", &PyRange_Type);
3044 SETBUILTIN("reversed", &PyReversed_Type);
3045 SETBUILTIN("set", &PySet_Type);
3046 SETBUILTIN("slice", &PySlice_Type);
3047 SETBUILTIN("staticmethod", &PyStaticMethod_Type);
3048 SETBUILTIN("str", &PyUnicode_Type);
3049 SETBUILTIN("super", &PySuper_Type);
3050 SETBUILTIN("tuple", &PyTuple_Type);
3051 SETBUILTIN("type", &PyType_Type);
3052 SETBUILTIN("zip", &PyZip_Type);
Victor Stinnerfbca9082018-08-30 00:50:45 +02003053 debug = PyBool_FromLong(config->optimization_level == 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003054 if (PyDict_SetItemString(dict, "__debug__", debug) < 0) {
Serhiy Storchakacfdfbb42016-06-18 09:44:03 +03003055 Py_DECREF(debug);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003056 return NULL;
3057 }
Serhiy Storchakacfdfbb42016-06-18 09:44:03 +03003058 Py_DECREF(debug);
Barry Warsaw757af0e1997-08-29 22:13:51 +00003059
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003060 return mod;
Tim Peters7571a0f2003-03-23 17:52:28 +00003061#undef ADD_TO_ALL
Tim Peters4b7625e2001-09-13 21:37:17 +00003062#undef SETBUILTIN
Guido van Rossum3f5da241990-12-20 15:06:42 +00003063}