blob: afe0f820cf347da98727e176aa1a5ffe97747f54 [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
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000831 arena = PyArena_New();
Stefan Krah07795df2012-08-20 17:19:50 +0200832 if (arena == NULL)
833 goto error;
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000834 mod = PyAST_obj2mod(source, arena, compile_mode);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000835 if (mod == NULL) {
836 PyArena_Free(arena);
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000837 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000838 }
Victor Stinnereec8e612021-03-18 14:57:49 +0100839 if (!_PyAST_Validate(mod)) {
Benjamin Peterson832bfe22011-08-09 16:15:04 -0500840 PyArena_Free(arena);
841 goto error;
842 }
Victor Stinnera81fca62021-03-24 00:51:50 +0100843 result = (PyObject*)_PyAST_Compile(mod, filename,
844 &cf, optimize, arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000845 PyArena_Free(arena);
846 }
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000847 goto finally;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000848 }
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000849
Dino Viehland41540692019-05-28 16:21:17 -0700850 str = _Py_SourceAsString(source, "compile", "string, bytes or AST", &cf, &source_copy);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000851 if (str == NULL)
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000852 goto error;
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000853
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000854 result = Py_CompileStringObject(str, filename, start[compile_mode], &cf, optimize);
Guido van Rossumc001c092020-04-30 12:12:19 -0700855
Martin Panter61d6e4a2015-11-07 02:56:11 +0000856 Py_XDECREF(source_copy);
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000857 goto finally;
858
859error:
860 result = NULL;
861finally:
Victor Stinner14e461d2013-08-26 22:28:21 +0200862 Py_DECREF(filename);
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000863 return result;
Guido van Rossum5b722181993-03-30 17:46:03 +0000864}
865
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000866/* AC: cannot convert yet, as needs PEP 457 group support in inspect */
Guido van Rossum79f25d91997-04-29 20:08:16 +0000867static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000868builtin_dir(PyObject *self, PyObject *args)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000869{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000870 PyObject *arg = NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000871
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000872 if (!PyArg_UnpackTuple(args, "dir", 0, 1, &arg))
873 return NULL;
874 return PyObject_Dir(arg);
Guido van Rossum3f5da241990-12-20 15:06:42 +0000875}
876
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000877PyDoc_STRVAR(dir_doc,
Tim Peters5d2b77c2001-09-03 05:47:38 +0000878"dir([object]) -> list of strings\n"
879"\n"
Georg Brandle32b4222007-03-10 22:13:27 +0000880"If called without an argument, return the names in the current scope.\n"
881"Else, return an alphabetized list of names comprising (some of) the attributes\n"
882"of the given object, and of attributes reachable from it.\n"
883"If the object supplies a method named __dir__, it will be used; otherwise\n"
884"the default dir() logic is used and returns:\n"
885" for a module object: the module's attributes.\n"
886" for a class object: its attributes, and recursively the attributes\n"
887" of its bases.\n"
Guido van Rossumd8faa362007-04-27 19:54:29 +0000888" for any other object: its attributes, its class's attributes, and\n"
Georg Brandle32b4222007-03-10 22:13:27 +0000889" recursively the attributes of its class's base classes.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000890
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000891/*[clinic input]
892divmod as builtin_divmod
Guido van Rossum6a00cd81995-01-07 12:39:01 +0000893
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300894 x: object
895 y: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000896 /
897
Zachary Ware7f227d92016-04-28 14:39:50 -0500898Return the tuple (x//y, x%y). Invariant: div*y + mod == x.
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000899[clinic start generated code]*/
900
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000901static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300902builtin_divmod_impl(PyObject *module, PyObject *x, PyObject *y)
903/*[clinic end generated code: output=b06d8a5f6e0c745e input=175ad9c84ff41a85]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000904{
905 return PyNumber_Divmod(x, y);
906}
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000907
908
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000909/*[clinic input]
910eval as builtin_eval
911
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300912 source: object
913 globals: object = None
914 locals: object = None
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000915 /
916
917Evaluate the given source in the context of globals and locals.
918
919The source may be a string representing a Python expression
920or a code object as returned by compile().
921The globals must be a dictionary and locals can be any mapping,
922defaulting to the current globals and locals.
923If only globals is given, locals defaults to it.
924[clinic start generated code]*/
925
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000926static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300927builtin_eval_impl(PyObject *module, PyObject *source, PyObject *globals,
Larry Hastings89964c42015-04-14 18:07:59 -0400928 PyObject *locals)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300929/*[clinic end generated code: output=0a0824aa70093116 input=11ee718a8640e527]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000930{
Martin Panter61d6e4a2015-11-07 02:56:11 +0000931 PyObject *result, *source_copy;
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +0200932 const char *str;
Guido van Rossum590baa41993-11-30 13:40:46 +0000933
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000934 if (locals != Py_None && !PyMapping_Check(locals)) {
935 PyErr_SetString(PyExc_TypeError, "locals must be a mapping");
936 return NULL;
937 }
938 if (globals != Py_None && !PyDict_Check(globals)) {
939 PyErr_SetString(PyExc_TypeError, PyMapping_Check(globals) ?
940 "globals must be a real dict; try eval(expr, {}, mapping)"
941 : "globals must be a dict");
942 return NULL;
943 }
944 if (globals == Py_None) {
945 globals = PyEval_GetGlobals();
Victor Stinner41bb43a2013-10-29 01:19:37 +0100946 if (locals == Py_None) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000947 locals = PyEval_GetLocals();
Victor Stinner41bb43a2013-10-29 01:19:37 +0100948 if (locals == NULL)
949 return NULL;
950 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000951 }
952 else if (locals == Py_None)
953 locals = globals;
Tim Peters9fa96be2001-08-17 23:04:59 +0000954
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000955 if (globals == NULL || locals == NULL) {
956 PyErr_SetString(PyExc_TypeError,
957 "eval must be given globals and locals "
958 "when called without a frame");
959 return NULL;
960 }
Georg Brandl77c85e62005-09-15 10:46:13 +0000961
Serhiy Storchakab510e102020-10-26 12:47:57 +0200962 int r = _PyDict_ContainsId(globals, &PyId___builtins__);
963 if (r == 0) {
964 r = _PyDict_SetItemId(globals, &PyId___builtins__,
965 PyEval_GetBuiltins());
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000966 }
Serhiy Storchakab510e102020-10-26 12:47:57 +0200967 if (r < 0) {
Serhiy Storchakaa24107b2019-02-25 17:59:46 +0200968 return NULL;
969 }
Tim Peters9fa96be2001-08-17 23:04:59 +0000970
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000971 if (PyCode_Check(source)) {
Steve Dowerb82e17e2019-05-23 08:45:22 -0700972 if (PySys_Audit("exec", "O", source) < 0) {
973 return NULL;
974 }
975
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000976 if (PyCode_GetNumFree((PyCodeObject *)source) > 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000977 PyErr_SetString(PyExc_TypeError,
Steve Dowerb82e17e2019-05-23 08:45:22 -0700978 "code object passed to eval() may not contain free variables");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000979 return NULL;
980 }
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000981 return PyEval_EvalCode(source, globals, locals);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000982 }
Tim Peters9fa96be2001-08-17 23:04:59 +0000983
Victor Stinner37d66d72019-06-13 02:16:41 +0200984 PyCompilerFlags cf = _PyCompilerFlags_INIT;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000985 cf.cf_flags = PyCF_SOURCE_IS_UTF8;
Dino Viehland41540692019-05-28 16:21:17 -0700986 str = _Py_SourceAsString(source, "eval", "string, bytes or code", &cf, &source_copy);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000987 if (str == NULL)
988 return NULL;
Just van Rossum3aaf42c2003-02-10 08:21:10 +0000989
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000990 while (*str == ' ' || *str == '\t')
991 str++;
Tim Peters9fa96be2001-08-17 23:04:59 +0000992
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000993 (void)PyEval_MergeCompilerFlags(&cf);
994 result = PyRun_StringFlags(str, Py_eval_input, globals, locals, &cf);
Martin Panter61d6e4a2015-11-07 02:56:11 +0000995 Py_XDECREF(source_copy);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000996 return result;
Guido van Rossum3f5da241990-12-20 15:06:42 +0000997}
998
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000999/*[clinic input]
1000exec as builtin_exec
1001
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001002 source: object
1003 globals: object = None
1004 locals: object = None
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001005 /
1006
1007Execute the given source in the context of globals and locals.
1008
1009The source may be a string representing one or more Python statements
1010or a code object as returned by compile().
1011The globals must be a dictionary and locals can be any mapping,
1012defaulting to the current globals and locals.
1013If only globals is given, locals defaults to it.
1014[clinic start generated code]*/
1015
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001016static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001017builtin_exec_impl(PyObject *module, PyObject *source, PyObject *globals,
Larry Hastings89964c42015-04-14 18:07:59 -04001018 PyObject *locals)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001019/*[clinic end generated code: output=3c90efc6ab68ef5d input=01ca3e1c01692829]*/
Georg Brandl7cae87c2006-09-06 06:51:57 +00001020{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001021 PyObject *v;
Georg Brandl2cabc562008-08-28 07:57:16 +00001022
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001023 if (globals == Py_None) {
1024 globals = PyEval_GetGlobals();
1025 if (locals == Py_None) {
1026 locals = PyEval_GetLocals();
Victor Stinner41bb43a2013-10-29 01:19:37 +01001027 if (locals == NULL)
1028 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001029 }
1030 if (!globals || !locals) {
1031 PyErr_SetString(PyExc_SystemError,
1032 "globals and locals cannot be NULL");
1033 return NULL;
1034 }
1035 }
1036 else if (locals == Py_None)
1037 locals = globals;
Georg Brandl7cae87c2006-09-06 06:51:57 +00001038
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001039 if (!PyDict_Check(globals)) {
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001040 PyErr_Format(PyExc_TypeError, "exec() globals must be a dict, not %.100s",
Victor Stinnera102ed72020-02-07 02:24:48 +01001041 Py_TYPE(globals)->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001042 return NULL;
1043 }
1044 if (!PyMapping_Check(locals)) {
1045 PyErr_Format(PyExc_TypeError,
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001046 "locals must be a mapping or None, not %.100s",
Victor Stinnera102ed72020-02-07 02:24:48 +01001047 Py_TYPE(locals)->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001048 return NULL;
1049 }
Serhiy Storchakab510e102020-10-26 12:47:57 +02001050 int r = _PyDict_ContainsId(globals, &PyId___builtins__);
1051 if (r == 0) {
1052 r = _PyDict_SetItemId(globals, &PyId___builtins__,
1053 PyEval_GetBuiltins());
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001054 }
Serhiy Storchakab510e102020-10-26 12:47:57 +02001055 if (r < 0) {
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02001056 return NULL;
1057 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001058
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001059 if (PyCode_Check(source)) {
Steve Dowerb82e17e2019-05-23 08:45:22 -07001060 if (PySys_Audit("exec", "O", source) < 0) {
1061 return NULL;
1062 }
1063
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001064 if (PyCode_GetNumFree((PyCodeObject *)source) > 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001065 PyErr_SetString(PyExc_TypeError,
1066 "code object passed to exec() may not "
1067 "contain free variables");
1068 return NULL;
1069 }
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001070 v = PyEval_EvalCode(source, globals, locals);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001071 }
1072 else {
Martin Panter61d6e4a2015-11-07 02:56:11 +00001073 PyObject *source_copy;
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +02001074 const char *str;
Victor Stinner37d66d72019-06-13 02:16:41 +02001075 PyCompilerFlags cf = _PyCompilerFlags_INIT;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001076 cf.cf_flags = PyCF_SOURCE_IS_UTF8;
Dino Viehland41540692019-05-28 16:21:17 -07001077 str = _Py_SourceAsString(source, "exec",
Martin Panter61d6e4a2015-11-07 02:56:11 +00001078 "string, bytes or code", &cf,
1079 &source_copy);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001080 if (str == NULL)
1081 return NULL;
1082 if (PyEval_MergeCompilerFlags(&cf))
1083 v = PyRun_StringFlags(str, Py_file_input, globals,
1084 locals, &cf);
1085 else
1086 v = PyRun_String(str, Py_file_input, globals, locals);
Martin Panter61d6e4a2015-11-07 02:56:11 +00001087 Py_XDECREF(source_copy);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001088 }
1089 if (v == NULL)
1090 return NULL;
1091 Py_DECREF(v);
1092 Py_RETURN_NONE;
Georg Brandl7cae87c2006-09-06 06:51:57 +00001093}
1094
Georg Brandl7cae87c2006-09-06 06:51:57 +00001095
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001096/* AC: cannot convert yet, as needs PEP 457 group support in inspect */
Guido van Rossum79f25d91997-04-29 20:08:16 +00001097static PyObject *
Serhiy Storchakaa5552f02017-12-15 13:11:11 +02001098builtin_getattr(PyObject *self, PyObject *const *args, Py_ssize_t nargs)
Guido van Rossum33894be1992-01-27 16:53:09 +00001099{
Serhiy Storchaka79342662019-01-12 08:25:41 +02001100 PyObject *v, *name, *result;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001101
Serhiy Storchaka79342662019-01-12 08:25:41 +02001102 if (!_PyArg_CheckPositional("getattr", nargs, 2, 3))
Sylvain96c7c062017-06-15 17:05:23 +02001103 return NULL;
1104
Serhiy Storchaka79342662019-01-12 08:25:41 +02001105 v = args[0];
1106 name = args[1];
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001107 if (!PyUnicode_Check(name)) {
1108 PyErr_SetString(PyExc_TypeError,
1109 "getattr(): attribute name must be string");
1110 return NULL;
1111 }
Serhiy Storchaka79342662019-01-12 08:25:41 +02001112 if (nargs > 2) {
Serhiy Storchakaf320be72018-01-25 10:49:40 +02001113 if (_PyObject_LookupAttr(v, name, &result) == 0) {
Serhiy Storchaka79342662019-01-12 08:25:41 +02001114 PyObject *dflt = args[2];
INADA Naoki378edee2018-01-16 20:52:41 +09001115 Py_INCREF(dflt);
1116 return dflt;
1117 }
1118 }
1119 else {
1120 result = PyObject_GetAttr(v, name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001121 }
1122 return result;
Guido van Rossum9bfef441993-03-29 10:43:31 +00001123}
1124
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001125PyDoc_STRVAR(getattr_doc,
Guido van Rossum950ff291998-06-29 13:38:57 +00001126"getattr(object, name[, default]) -> value\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001127\n\
Guido van Rossum950ff291998-06-29 13:38:57 +00001128Get a named attribute from an object; getattr(x, 'y') is equivalent to x.y.\n\
1129When a default argument is given, it is returned when the attribute doesn't\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001130exist; without it, an exception is raised in that case.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001131
1132
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001133/*[clinic input]
1134globals as builtin_globals
1135
1136Return the dictionary containing the current scope's global variables.
1137
1138NOTE: Updates to this dictionary *will* affect name lookups in the current
1139global scope and vice-versa.
1140[clinic start generated code]*/
1141
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001142static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001143builtin_globals_impl(PyObject *module)
1144/*[clinic end generated code: output=e5dd1527067b94d2 input=9327576f92bb48ba]*/
Guido van Rossum872537c1995-07-07 22:43:42 +00001145{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001146 PyObject *d;
Guido van Rossum872537c1995-07-07 22:43:42 +00001147
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001148 d = PyEval_GetGlobals();
1149 Py_XINCREF(d);
1150 return d;
Guido van Rossum872537c1995-07-07 22:43:42 +00001151}
1152
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001153
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001154/*[clinic input]
1155hasattr as builtin_hasattr
1156
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001157 obj: object
1158 name: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001159 /
1160
1161Return whether the object has an attribute with the given name.
1162
1163This is done by calling getattr(obj, name) and catching AttributeError.
1164[clinic start generated code]*/
1165
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001166static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001167builtin_hasattr_impl(PyObject *module, PyObject *obj, PyObject *name)
1168/*[clinic end generated code: output=a7aff2090a4151e5 input=0faec9787d979542]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001169{
1170 PyObject *v;
1171
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001172 if (!PyUnicode_Check(name)) {
1173 PyErr_SetString(PyExc_TypeError,
1174 "hasattr(): attribute name must be string");
1175 return NULL;
1176 }
Serhiy Storchakaf320be72018-01-25 10:49:40 +02001177 if (_PyObject_LookupAttr(obj, name, &v) < 0) {
Benjamin Peterson17689992010-08-24 03:26:23 +00001178 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001179 }
Serhiy Storchakaf320be72018-01-25 10:49:40 +02001180 if (v == NULL) {
1181 Py_RETURN_FALSE;
1182 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001183 Py_DECREF(v);
Benjamin Peterson17689992010-08-24 03:26:23 +00001184 Py_RETURN_TRUE;
Guido van Rossum33894be1992-01-27 16:53:09 +00001185}
1186
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001187
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001188/* AC: gdb's integration with CPython relies on builtin_id having
1189 * the *exact* parameter names of "self" and "v", so we ensure we
1190 * preserve those name rather than using the AC defaults.
1191 */
1192/*[clinic input]
1193id as builtin_id
1194
Serhiy Storchaka24182a32016-05-05 16:21:35 +03001195 self: self(type="PyModuleDef *")
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001196 obj as v: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001197 /
1198
1199Return the identity of an object.
1200
1201This is guaranteed to be unique among simultaneously existing objects.
1202(CPython uses the object's memory address.)
1203[clinic start generated code]*/
1204
Guido van Rossum79f25d91997-04-29 20:08:16 +00001205static PyObject *
Serhiy Storchaka24182a32016-05-05 16:21:35 +03001206builtin_id(PyModuleDef *self, PyObject *v)
1207/*[clinic end generated code: output=0aa640785f697f65 input=5a534136419631f4]*/
Guido van Rossum5b722181993-03-30 17:46:03 +00001208{
Steve Dowerb82e17e2019-05-23 08:45:22 -07001209 PyObject *id = PyLong_FromVoidPtr(v);
1210
1211 if (id && PySys_Audit("builtins.id", "O", id) < 0) {
1212 Py_DECREF(id);
1213 return NULL;
1214 }
1215
1216 return id;
Guido van Rossum5b722181993-03-30 17:46:03 +00001217}
1218
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001219
Raymond Hettingera6c60372008-03-13 01:26:19 +00001220/* map object ************************************************************/
1221
1222typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001223 PyObject_HEAD
1224 PyObject *iters;
1225 PyObject *func;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001226} mapobject;
1227
Guido van Rossum79f25d91997-04-29 20:08:16 +00001228static PyObject *
Raymond Hettingera6c60372008-03-13 01:26:19 +00001229map_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
Guido van Rossum12d12c51993-10-26 17:58:25 +00001230{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001231 PyObject *it, *iters, *func;
1232 mapobject *lz;
1233 Py_ssize_t numargs, i;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001234
Serhiy Storchaka6cca5c82017-06-08 14:41:19 +03001235 if (type == &PyMap_Type && !_PyArg_NoKeywords("map", kwds))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001236 return NULL;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001237
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001238 numargs = PyTuple_Size(args);
1239 if (numargs < 2) {
1240 PyErr_SetString(PyExc_TypeError,
1241 "map() must have at least two arguments.");
1242 return NULL;
1243 }
Raymond Hettingera6c60372008-03-13 01:26:19 +00001244
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001245 iters = PyTuple_New(numargs-1);
1246 if (iters == NULL)
1247 return NULL;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001248
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001249 for (i=1 ; i<numargs ; i++) {
1250 /* Get iterator. */
1251 it = PyObject_GetIter(PyTuple_GET_ITEM(args, i));
1252 if (it == NULL) {
1253 Py_DECREF(iters);
1254 return NULL;
1255 }
1256 PyTuple_SET_ITEM(iters, i-1, it);
1257 }
Raymond Hettingera6c60372008-03-13 01:26:19 +00001258
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001259 /* create mapobject structure */
1260 lz = (mapobject *)type->tp_alloc(type, 0);
1261 if (lz == NULL) {
1262 Py_DECREF(iters);
1263 return NULL;
1264 }
1265 lz->iters = iters;
1266 func = PyTuple_GET_ITEM(args, 0);
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
1663 return PyAnextAwaitable_New(awaitable, default_value);
1664}
1665
1666
1667/*[clinic input]
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001668len as builtin_len
1669
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001670 obj: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001671 /
1672
1673Return the number of items in a container.
1674[clinic start generated code]*/
1675
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001676static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001677builtin_len(PyObject *module, PyObject *obj)
1678/*[clinic end generated code: output=fa7a270d314dfb6c input=bc55598da9e9c9b5]*/
Guido van Rossum3f5da241990-12-20 15:06:42 +00001679{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001680 Py_ssize_t res;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001681
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001682 res = PyObject_Size(obj);
Serhiy Storchaka813f9432017-04-16 09:21:44 +03001683 if (res < 0) {
1684 assert(PyErr_Occurred());
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001685 return NULL;
Serhiy Storchaka813f9432017-04-16 09:21:44 +03001686 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001687 return PyLong_FromSsize_t(res);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001688}
1689
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001690
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001691/*[clinic input]
1692locals as builtin_locals
1693
1694Return a dictionary containing the current scope's local variables.
1695
1696NOTE: Whether or not updates to this dictionary will affect name lookups in
1697the local scope and vice-versa is *implementation dependent* and not
1698covered by any backwards compatibility guarantees.
1699[clinic start generated code]*/
1700
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001701static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001702builtin_locals_impl(PyObject *module)
1703/*[clinic end generated code: output=b46c94015ce11448 input=7874018d478d5c4b]*/
Guido van Rossum872537c1995-07-07 22:43:42 +00001704{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001705 PyObject *d;
Guido van Rossum872537c1995-07-07 22:43:42 +00001706
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001707 d = PyEval_GetLocals();
1708 Py_XINCREF(d);
1709 return d;
Guido van Rossum872537c1995-07-07 22:43:42 +00001710}
1711
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001712
Guido van Rossum79f25d91997-04-29 20:08:16 +00001713static PyObject *
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001714min_max(PyObject *args, PyObject *kwds, int op)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001715{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001716 PyObject *v, *it, *item, *val, *maxitem, *maxval, *keyfunc=NULL;
Raymond Hettinger4d6018f2013-06-24 22:43:02 -07001717 PyObject *emptytuple, *defaultval = NULL;
1718 static char *kwlist[] = {"key", "default", NULL};
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001719 const char *name = op == Py_LT ? "min" : "max";
Raymond Hettinger4d6018f2013-06-24 22:43:02 -07001720 const int positional = PyTuple_Size(args) > 1;
1721 int ret;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001722
Dong-hee Naabdc6342020-01-11 01:31:43 +09001723 if (positional) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001724 v = args;
Dong-hee Naabdc6342020-01-11 01:31:43 +09001725 }
1726 else if (!PyArg_UnpackTuple(args, name, 1, 1, &v)) {
1727 if (PyExceptionClass_Check(PyExc_TypeError)) {
1728 PyErr_Format(PyExc_TypeError, "%s expected at least 1 argument, got 0", name);
1729 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001730 return NULL;
Dong-hee Naabdc6342020-01-11 01:31:43 +09001731 }
Tim Peters67d687a2002-04-29 21:27:32 +00001732
Raymond Hettinger4d6018f2013-06-24 22:43:02 -07001733 emptytuple = PyTuple_New(0);
1734 if (emptytuple == NULL)
1735 return NULL;
Oren Milman58cf7482017-08-21 20:19:07 +03001736 ret = PyArg_ParseTupleAndKeywords(emptytuple, kwds,
1737 (op == Py_LT) ? "|$OO:min" : "|$OO:max",
1738 kwlist, &keyfunc, &defaultval);
Raymond Hettinger4d6018f2013-06-24 22:43:02 -07001739 Py_DECREF(emptytuple);
1740 if (!ret)
1741 return NULL;
1742
1743 if (positional && defaultval != NULL) {
1744 PyErr_Format(PyExc_TypeError,
1745 "Cannot specify a default for %s() with multiple "
1746 "positional arguments", name);
1747 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001748 }
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001749
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001750 it = PyObject_GetIter(v);
1751 if (it == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001752 return NULL;
1753 }
Tim Petersc3074532001-05-03 07:00:32 +00001754
Alexander Marshalove22072f2018-07-24 10:58:21 +07001755 if (keyfunc == Py_None) {
1756 keyfunc = NULL;
1757 }
1758
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001759 maxitem = NULL; /* the result */
1760 maxval = NULL; /* the value associated with the result */
1761 while (( item = PyIter_Next(it) )) {
1762 /* get the value from the key function */
1763 if (keyfunc != NULL) {
Petr Viktorinffd97532020-02-11 17:46:57 +01001764 val = PyObject_CallOneArg(keyfunc, item);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001765 if (val == NULL)
1766 goto Fail_it_item;
1767 }
1768 /* no key function; the value is the item */
1769 else {
1770 val = item;
1771 Py_INCREF(val);
1772 }
Tim Petersc3074532001-05-03 07:00:32 +00001773
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001774 /* maximum value and item are unset; set them */
1775 if (maxval == NULL) {
1776 maxitem = item;
1777 maxval = val;
1778 }
1779 /* maximum value and item are set; update them as necessary */
1780 else {
1781 int cmp = PyObject_RichCompareBool(val, maxval, op);
1782 if (cmp < 0)
1783 goto Fail_it_item_and_val;
1784 else if (cmp > 0) {
1785 Py_DECREF(maxval);
1786 Py_DECREF(maxitem);
1787 maxval = val;
1788 maxitem = item;
1789 }
1790 else {
1791 Py_DECREF(item);
1792 Py_DECREF(val);
1793 }
1794 }
1795 }
1796 if (PyErr_Occurred())
1797 goto Fail_it;
1798 if (maxval == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001799 assert(maxitem == NULL);
Raymond Hettinger4d6018f2013-06-24 22:43:02 -07001800 if (defaultval != NULL) {
1801 Py_INCREF(defaultval);
1802 maxitem = defaultval;
1803 } else {
1804 PyErr_Format(PyExc_ValueError,
1805 "%s() arg is an empty sequence", name);
1806 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001807 }
1808 else
1809 Py_DECREF(maxval);
1810 Py_DECREF(it);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001811 return maxitem;
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001812
1813Fail_it_item_and_val:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001814 Py_DECREF(val);
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001815Fail_it_item:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001816 Py_DECREF(item);
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001817Fail_it:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001818 Py_XDECREF(maxval);
1819 Py_XDECREF(maxitem);
1820 Py_DECREF(it);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001821 return NULL;
Guido van Rossum3f5da241990-12-20 15:06:42 +00001822}
1823
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001824/* AC: cannot convert yet, waiting for *args support */
Guido van Rossum79f25d91997-04-29 20:08:16 +00001825static PyObject *
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001826builtin_min(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001827{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001828 return min_max(args, kwds, Py_LT);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001829}
1830
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001831PyDoc_STRVAR(min_doc,
Raymond Hettinger2a545822014-05-19 22:20:52 +01001832"min(iterable, *[, default=obj, key=func]) -> value\n\
1833min(arg1, arg2, *args, *[, key=func]) -> value\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001834\n\
Raymond Hettinger2a545822014-05-19 22:20:52 +01001835With a single iterable argument, return its smallest item. The\n\
1836default keyword-only argument specifies an object to return if\n\
1837the provided iterable is empty.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001838With two or more arguments, return the smallest argument.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001839
1840
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001841/* AC: cannot convert yet, waiting for *args support */
Guido van Rossum79f25d91997-04-29 20:08:16 +00001842static PyObject *
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001843builtin_max(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001844{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001845 return min_max(args, kwds, Py_GT);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001846}
1847
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001848PyDoc_STRVAR(max_doc,
Raymond Hettinger2a545822014-05-19 22:20:52 +01001849"max(iterable, *[, default=obj, key=func]) -> value\n\
1850max(arg1, arg2, *args, *[, key=func]) -> value\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001851\n\
Raymond Hettinger2a545822014-05-19 22:20:52 +01001852With a single iterable argument, return its biggest item. The\n\
1853default keyword-only argument specifies an object to return if\n\
1854the provided iterable is empty.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001855With two or more arguments, return the largest argument.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001856
1857
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001858/*[clinic input]
1859oct as builtin_oct
1860
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001861 number: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001862 /
1863
1864Return the octal representation of an integer.
1865
1866 >>> oct(342391)
1867 '0o1234567'
1868[clinic start generated code]*/
1869
Guido van Rossum79f25d91997-04-29 20:08:16 +00001870static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001871builtin_oct(PyObject *module, PyObject *number)
1872/*[clinic end generated code: output=40a34656b6875352 input=ad6b274af4016c72]*/
Guido van Rossum006bcd41991-10-24 14:54:44 +00001873{
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001874 return PyNumber_ToBase(number, 8);
Guido van Rossum006bcd41991-10-24 14:54:44 +00001875}
1876
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001877
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001878/*[clinic input]
1879ord as builtin_ord
1880
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001881 c: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001882 /
1883
1884Return the Unicode code point for a one-character string.
1885[clinic start generated code]*/
1886
Guido van Rossum79f25d91997-04-29 20:08:16 +00001887static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001888builtin_ord(PyObject *module, PyObject *c)
1889/*[clinic end generated code: output=4fa5e87a323bae71 input=3064e5d6203ad012]*/
Guido van Rossum3f5da241990-12-20 15:06:42 +00001890{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001891 long ord;
1892 Py_ssize_t size;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001893
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001894 if (PyBytes_Check(c)) {
1895 size = PyBytes_GET_SIZE(c);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001896 if (size == 1) {
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001897 ord = (long)((unsigned char)*PyBytes_AS_STRING(c));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001898 return PyLong_FromLong(ord);
1899 }
1900 }
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001901 else if (PyUnicode_Check(c)) {
1902 if (PyUnicode_READY(c) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001903 return NULL;
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001904 size = PyUnicode_GET_LENGTH(c);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001905 if (size == 1) {
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001906 ord = (long)PyUnicode_READ_CHAR(c, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001907 return PyLong_FromLong(ord);
1908 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001909 }
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001910 else if (PyByteArray_Check(c)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001911 /* XXX Hopefully this is temporary */
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001912 size = PyByteArray_GET_SIZE(c);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001913 if (size == 1) {
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001914 ord = (long)((unsigned char)*PyByteArray_AS_STRING(c));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001915 return PyLong_FromLong(ord);
1916 }
1917 }
1918 else {
1919 PyErr_Format(PyExc_TypeError,
1920 "ord() expected string of length 1, but " \
Victor Stinnera102ed72020-02-07 02:24:48 +01001921 "%.200s found", Py_TYPE(c)->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001922 return NULL;
1923 }
Guido van Rossum09095f32000-03-10 23:00:52 +00001924
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001925 PyErr_Format(PyExc_TypeError,
1926 "ord() expected a character, "
1927 "but string of length %zd found",
1928 size);
1929 return NULL;
Guido van Rossum3f5da241990-12-20 15:06:42 +00001930}
1931
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001932
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001933/*[clinic input]
1934pow as builtin_pow
1935
Ammar Askar87d6cd32019-09-21 00:28:49 -04001936 base: object
1937 exp: object
1938 mod: object = None
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001939
Raymond Hettingerb104ecb2019-09-21 12:57:44 -07001940Equivalent to base**exp with 2 arguments or base**exp % mod with 3 arguments
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001941
1942Some types, such as ints, are able to use a more efficient algorithm when
1943invoked using the three argument form.
1944[clinic start generated code]*/
1945
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001946static PyObject *
Ammar Askar87d6cd32019-09-21 00:28:49 -04001947builtin_pow_impl(PyObject *module, PyObject *base, PyObject *exp,
1948 PyObject *mod)
Raymond Hettingerb104ecb2019-09-21 12:57:44 -07001949/*[clinic end generated code: output=3ca1538221bbf15f input=435dbd48a12efb23]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001950{
Ammar Askar87d6cd32019-09-21 00:28:49 -04001951 return PyNumber_Power(base, exp, mod);
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001952}
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001953
1954
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001955/* AC: cannot convert yet, waiting for *args support */
Guido van Rossum34343512006-11-30 22:13:52 +00001956static PyObject *
Serhiy Storchakaa5552f02017-12-15 13:11:11 +02001957builtin_print(PyObject *self, PyObject *const *args, Py_ssize_t nargs, PyObject *kwnames)
Guido van Rossum34343512006-11-30 22:13:52 +00001958{
INADA Naokibd584f12017-01-19 12:50:34 +01001959 static const char * const _keywords[] = {"sep", "end", "file", "flush", 0};
Serhiy Storchaka1f21eaa2019-09-01 12:16:51 +03001960 static struct _PyArg_Parser _parser = {"|OOOp:print", _keywords, 0};
1961 PyObject *sep = NULL, *end = NULL, *file = NULL;
1962 int flush = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001963 int i, err;
Guido van Rossum34343512006-11-30 22:13:52 +00001964
INADA Naokibd584f12017-01-19 12:50:34 +01001965 if (kwnames != NULL &&
1966 !_PyArg_ParseStackAndKeywords(args + nargs, 0, kwnames, &_parser,
1967 &sep, &end, &file, &flush)) {
Georg Brandlbc3b6822012-01-13 19:41:25 +01001968 return NULL;
INADA Naokibd584f12017-01-19 12:50:34 +01001969 }
1970
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001971 if (file == NULL || file == Py_None) {
Victor Stinnerbd303c12013-11-07 23:07:29 +01001972 file = _PySys_GetObjectId(&PyId_stdout);
Victor Stinner1e53bba2013-07-16 22:26:05 +02001973 if (file == NULL) {
1974 PyErr_SetString(PyExc_RuntimeError, "lost sys.stdout");
1975 return NULL;
1976 }
1977
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001978 /* sys.stdout may be None when FILE* stdout isn't connected */
1979 if (file == Py_None)
1980 Py_RETURN_NONE;
1981 }
Guido van Rossum34343512006-11-30 22:13:52 +00001982
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001983 if (sep == Py_None) {
1984 sep = NULL;
1985 }
1986 else if (sep && !PyUnicode_Check(sep)) {
1987 PyErr_Format(PyExc_TypeError,
1988 "sep must be None or a string, not %.200s",
Victor Stinnera102ed72020-02-07 02:24:48 +01001989 Py_TYPE(sep)->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001990 return NULL;
1991 }
1992 if (end == Py_None) {
1993 end = NULL;
1994 }
1995 else if (end && !PyUnicode_Check(end)) {
1996 PyErr_Format(PyExc_TypeError,
1997 "end must be None or a string, not %.200s",
Victor Stinnera102ed72020-02-07 02:24:48 +01001998 Py_TYPE(end)->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001999 return NULL;
2000 }
Guido van Rossum34343512006-11-30 22:13:52 +00002001
INADA Naokibd584f12017-01-19 12:50:34 +01002002 for (i = 0; i < nargs; i++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002003 if (i > 0) {
2004 if (sep == NULL)
2005 err = PyFile_WriteString(" ", file);
2006 else
2007 err = PyFile_WriteObject(sep, file,
2008 Py_PRINT_RAW);
2009 if (err)
2010 return NULL;
2011 }
INADA Naokibd584f12017-01-19 12:50:34 +01002012 err = PyFile_WriteObject(args[i], file, Py_PRINT_RAW);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002013 if (err)
2014 return NULL;
2015 }
Guido van Rossum34343512006-11-30 22:13:52 +00002016
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002017 if (end == NULL)
2018 err = PyFile_WriteString("\n", file);
2019 else
2020 err = PyFile_WriteObject(end, file, Py_PRINT_RAW);
2021 if (err)
2022 return NULL;
Guido van Rossum34343512006-11-30 22:13:52 +00002023
Serhiy Storchaka1f21eaa2019-09-01 12:16:51 +03002024 if (flush) {
2025 PyObject *tmp = _PyObject_CallMethodIdNoArgs(file, &PyId_flush);
2026 if (tmp == NULL)
Georg Brandlbc3b6822012-01-13 19:41:25 +01002027 return NULL;
Serhiy Storchaka1f21eaa2019-09-01 12:16:51 +03002028 Py_DECREF(tmp);
Georg Brandlbc3b6822012-01-13 19:41:25 +01002029 }
2030
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002031 Py_RETURN_NONE;
Guido van Rossum34343512006-11-30 22:13:52 +00002032}
2033
2034PyDoc_STRVAR(print_doc,
Senthil Kumarane9175bd2012-08-10 13:53:45 -07002035"print(value, ..., sep=' ', end='\\n', file=sys.stdout, flush=False)\n\
Guido van Rossum34343512006-11-30 22:13:52 +00002036\n\
2037Prints the values to a stream, or to sys.stdout by default.\n\
2038Optional keyword arguments:\n\
Senthil Kumarane9175bd2012-08-10 13:53:45 -07002039file: a file-like object (stream); defaults to the current sys.stdout.\n\
2040sep: string inserted between values, default a space.\n\
2041end: string appended after the last value, default a newline.\n\
2042flush: whether to forcibly flush the stream.");
Guido van Rossum34343512006-11-30 22:13:52 +00002043
2044
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002045/*[clinic input]
2046input as builtin_input
2047
2048 prompt: object(c_default="NULL") = None
2049 /
2050
2051Read a string from standard input. The trailing newline is stripped.
2052
2053The prompt string, if given, is printed to standard output without a
2054trailing newline before reading input.
2055
2056If the user hits EOF (*nix: Ctrl-D, Windows: Ctrl-Z+Return), raise EOFError.
2057On *nix systems, readline is used if available.
2058[clinic start generated code]*/
2059
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002060static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002061builtin_input_impl(PyObject *module, PyObject *prompt)
2062/*[clinic end generated code: output=83db5a191e7a0d60 input=5e8bb70c2908fe3c]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002063{
Victor Stinnerbd303c12013-11-07 23:07:29 +01002064 PyObject *fin = _PySys_GetObjectId(&PyId_stdin);
2065 PyObject *fout = _PySys_GetObjectId(&PyId_stdout);
2066 PyObject *ferr = _PySys_GetObjectId(&PyId_stderr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002067 PyObject *tmp;
2068 long fd;
2069 int tty;
Guido van Rossuma88a0332007-02-26 16:59:55 +00002070
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002071 /* Check that stdin/out/err are intact */
2072 if (fin == NULL || fin == Py_None) {
2073 PyErr_SetString(PyExc_RuntimeError,
2074 "input(): lost sys.stdin");
2075 return NULL;
2076 }
2077 if (fout == NULL || fout == Py_None) {
2078 PyErr_SetString(PyExc_RuntimeError,
2079 "input(): lost sys.stdout");
2080 return NULL;
2081 }
2082 if (ferr == NULL || ferr == Py_None) {
2083 PyErr_SetString(PyExc_RuntimeError,
2084 "input(): lost sys.stderr");
2085 return NULL;
2086 }
Guido van Rossumeba76962007-05-27 09:13:28 +00002087
Steve Dowerb82e17e2019-05-23 08:45:22 -07002088 if (PySys_Audit("builtins.input", "O", prompt ? prompt : Py_None) < 0) {
2089 return NULL;
2090 }
2091
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002092 /* First of all, flush stderr */
Jeroen Demeyer762f93f2019-07-08 10:19:25 +02002093 tmp = _PyObject_CallMethodIdNoArgs(ferr, &PyId_flush);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002094 if (tmp == NULL)
2095 PyErr_Clear();
2096 else
2097 Py_DECREF(tmp);
Guido van Rossumeba76962007-05-27 09:13:28 +00002098
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002099 /* We should only use (GNU) readline if Python's sys.stdin and
2100 sys.stdout are the same as C's stdin and stdout, because we
2101 need to pass it those. */
Jeroen Demeyer762f93f2019-07-08 10:19:25 +02002102 tmp = _PyObject_CallMethodIdNoArgs(fin, &PyId_fileno);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002103 if (tmp == NULL) {
2104 PyErr_Clear();
2105 tty = 0;
2106 }
2107 else {
2108 fd = PyLong_AsLong(tmp);
2109 Py_DECREF(tmp);
2110 if (fd < 0 && PyErr_Occurred())
2111 return NULL;
2112 tty = fd == fileno(stdin) && isatty(fd);
2113 }
2114 if (tty) {
Jeroen Demeyer762f93f2019-07-08 10:19:25 +02002115 tmp = _PyObject_CallMethodIdNoArgs(fout, &PyId_fileno);
Martin Panterc9a6ab52015-10-10 01:25:38 +00002116 if (tmp == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002117 PyErr_Clear();
Martin Panterc9a6ab52015-10-10 01:25:38 +00002118 tty = 0;
2119 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002120 else {
2121 fd = PyLong_AsLong(tmp);
2122 Py_DECREF(tmp);
2123 if (fd < 0 && PyErr_Occurred())
2124 return NULL;
2125 tty = fd == fileno(stdout) && isatty(fd);
2126 }
2127 }
Guido van Rossumeba76962007-05-27 09:13:28 +00002128
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002129 /* If we're interactive, use (GNU) readline */
2130 if (tty) {
Antoine Pitrou0d776b12011-11-06 00:34:26 +01002131 PyObject *po = NULL;
Serhiy Storchakae2f92de2017-11-11 13:06:26 +02002132 const char *promptstr;
Antoine Pitrou0d776b12011-11-06 00:34:26 +01002133 char *s = NULL;
2134 PyObject *stdin_encoding = NULL, *stdin_errors = NULL;
2135 PyObject *stdout_encoding = NULL, *stdout_errors = NULL;
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +02002136 const char *stdin_encoding_str, *stdin_errors_str;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002137 PyObject *result;
Victor Stinnerc0f1a1a2011-02-23 12:07:37 +00002138 size_t len;
Martin v. Löwis4a7b5d52007-09-04 05:24:49 +00002139
Serhiy Storchakac2cf1282017-03-12 13:50:36 +02002140 /* stdin is a text stream, so it must have an encoding. */
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02002141 stdin_encoding = _PyObject_GetAttrId(fin, &PyId_encoding);
Antoine Pitrou5ee9d8a2011-11-06 00:38:45 +01002142 stdin_errors = _PyObject_GetAttrId(fin, &PyId_errors);
Serhiy Storchakac2cf1282017-03-12 13:50:36 +02002143 if (!stdin_encoding || !stdin_errors ||
2144 !PyUnicode_Check(stdin_encoding) ||
2145 !PyUnicode_Check(stdin_errors)) {
2146 tty = 0;
Antoine Pitrou0d776b12011-11-06 00:34:26 +01002147 goto _readline_errors;
Serhiy Storchakac2cf1282017-03-12 13:50:36 +02002148 }
Serhiy Storchaka06515832016-11-20 09:13:07 +02002149 stdin_encoding_str = PyUnicode_AsUTF8(stdin_encoding);
2150 stdin_errors_str = PyUnicode_AsUTF8(stdin_errors);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01002151 if (!stdin_encoding_str || !stdin_errors_str)
2152 goto _readline_errors;
Jeroen Demeyer762f93f2019-07-08 10:19:25 +02002153 tmp = _PyObject_CallMethodIdNoArgs(fout, &PyId_flush);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002154 if (tmp == NULL)
2155 PyErr_Clear();
2156 else
2157 Py_DECREF(tmp);
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002158 if (prompt != NULL) {
Antoine Pitrou0d776b12011-11-06 00:34:26 +01002159 /* We have a prompt, encode it as stdout would */
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +02002160 const char *stdout_encoding_str, *stdout_errors_str;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002161 PyObject *stringpo;
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02002162 stdout_encoding = _PyObject_GetAttrId(fout, &PyId_encoding);
Antoine Pitrou5ee9d8a2011-11-06 00:38:45 +01002163 stdout_errors = _PyObject_GetAttrId(fout, &PyId_errors);
Serhiy Storchakac2cf1282017-03-12 13:50:36 +02002164 if (!stdout_encoding || !stdout_errors ||
2165 !PyUnicode_Check(stdout_encoding) ||
2166 !PyUnicode_Check(stdout_errors)) {
2167 tty = 0;
Antoine Pitrou0d776b12011-11-06 00:34:26 +01002168 goto _readline_errors;
Serhiy Storchakac2cf1282017-03-12 13:50:36 +02002169 }
Serhiy Storchaka06515832016-11-20 09:13:07 +02002170 stdout_encoding_str = PyUnicode_AsUTF8(stdout_encoding);
2171 stdout_errors_str = PyUnicode_AsUTF8(stdout_errors);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01002172 if (!stdout_encoding_str || !stdout_errors_str)
2173 goto _readline_errors;
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002174 stringpo = PyObject_Str(prompt);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01002175 if (stringpo == NULL)
2176 goto _readline_errors;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002177 po = PyUnicode_AsEncodedString(stringpo,
Antoine Pitrou0d776b12011-11-06 00:34:26 +01002178 stdout_encoding_str, stdout_errors_str);
2179 Py_CLEAR(stdout_encoding);
2180 Py_CLEAR(stdout_errors);
2181 Py_CLEAR(stringpo);
2182 if (po == NULL)
2183 goto _readline_errors;
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03002184 assert(PyBytes_Check(po));
2185 promptstr = PyBytes_AS_STRING(po);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002186 }
2187 else {
2188 po = NULL;
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002189 promptstr = "";
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002190 }
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002191 s = PyOS_Readline(stdin, stdout, promptstr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002192 if (s == NULL) {
Richard Oudkerk614c5782013-04-03 13:44:50 +01002193 PyErr_CheckSignals();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002194 if (!PyErr_Occurred())
2195 PyErr_SetNone(PyExc_KeyboardInterrupt);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01002196 goto _readline_errors;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002197 }
Victor Stinnerc0f1a1a2011-02-23 12:07:37 +00002198
2199 len = strlen(s);
2200 if (len == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002201 PyErr_SetNone(PyExc_EOFError);
2202 result = NULL;
2203 }
Victor Stinnerc0f1a1a2011-02-23 12:07:37 +00002204 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002205 if (len > PY_SSIZE_T_MAX) {
2206 PyErr_SetString(PyExc_OverflowError,
2207 "input: input too long");
2208 result = NULL;
2209 }
2210 else {
Victor Stinnerc0f1a1a2011-02-23 12:07:37 +00002211 len--; /* strip trailing '\n' */
2212 if (len != 0 && s[len-1] == '\r')
2213 len--; /* strip trailing '\r' */
Antoine Pitrou0d776b12011-11-06 00:34:26 +01002214 result = PyUnicode_Decode(s, len, stdin_encoding_str,
2215 stdin_errors_str);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002216 }
2217 }
2218 Py_DECREF(stdin_encoding);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01002219 Py_DECREF(stdin_errors);
2220 Py_XDECREF(po);
Victor Stinner00d7abd2020-12-01 09:56:42 +01002221 PyMem_Free(s);
Steve Dowerb82e17e2019-05-23 08:45:22 -07002222
2223 if (result != NULL) {
2224 if (PySys_Audit("builtins.input/result", "O", result) < 0) {
2225 return NULL;
2226 }
2227 }
2228
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002229 return result;
Serhiy Storchakac2cf1282017-03-12 13:50:36 +02002230
Antoine Pitrou0d776b12011-11-06 00:34:26 +01002231 _readline_errors:
2232 Py_XDECREF(stdin_encoding);
2233 Py_XDECREF(stdout_encoding);
2234 Py_XDECREF(stdin_errors);
2235 Py_XDECREF(stdout_errors);
2236 Py_XDECREF(po);
Serhiy Storchakac2cf1282017-03-12 13:50:36 +02002237 if (tty)
2238 return NULL;
2239
2240 PyErr_Clear();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002241 }
Guido van Rossumeba76962007-05-27 09:13:28 +00002242
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002243 /* Fallback if we're not interactive */
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002244 if (prompt != NULL) {
2245 if (PyFile_WriteObject(prompt, fout, Py_PRINT_RAW) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002246 return NULL;
2247 }
Jeroen Demeyer762f93f2019-07-08 10:19:25 +02002248 tmp = _PyObject_CallMethodIdNoArgs(fout, &PyId_flush);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002249 if (tmp == NULL)
2250 PyErr_Clear();
2251 else
2252 Py_DECREF(tmp);
2253 return PyFile_GetLine(fin, -1);
Guido van Rossuma88a0332007-02-26 16:59:55 +00002254}
2255
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002256
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002257/*[clinic input]
2258repr as builtin_repr
2259
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03002260 obj: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002261 /
2262
2263Return the canonical string representation of the object.
2264
2265For many object types, including most builtins, eval(repr(obj)) == obj.
2266[clinic start generated code]*/
2267
Guido van Rossum79f25d91997-04-29 20:08:16 +00002268static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002269builtin_repr(PyObject *module, PyObject *obj)
2270/*[clinic end generated code: output=7ed3778c44fd0194 input=1c9e6d66d3e3be04]*/
Guido van Rossumc89705d1992-11-26 08:54:07 +00002271{
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002272 return PyObject_Repr(obj);
Guido van Rossumc89705d1992-11-26 08:54:07 +00002273}
2274
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002275
Serhiy Storchakaaca7f572017-11-15 17:51:14 +02002276/*[clinic input]
2277round as builtin_round
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002278
Serhiy Storchakaaca7f572017-11-15 17:51:14 +02002279 number: object
Serhiy Storchaka279f4462019-09-14 12:24:05 +03002280 ndigits: object = None
Serhiy Storchakaaca7f572017-11-15 17:51:14 +02002281
2282Round a number to a given precision in decimal digits.
2283
2284The return value is an integer if ndigits is omitted or None. Otherwise
2285the return value has the same type as the number. ndigits may be negative.
2286[clinic start generated code]*/
2287
2288static PyObject *
2289builtin_round_impl(PyObject *module, PyObject *number, PyObject *ndigits)
Serhiy Storchaka279f4462019-09-14 12:24:05 +03002290/*[clinic end generated code: output=ff0d9dd176c02ede input=275678471d7aca15]*/
Serhiy Storchakaaca7f572017-11-15 17:51:14 +02002291{
2292 PyObject *round, *result;
Alex Martelliae211f92007-08-22 23:21:33 +00002293
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002294 if (Py_TYPE(number)->tp_dict == NULL) {
2295 if (PyType_Ready(Py_TYPE(number)) < 0)
2296 return NULL;
2297 }
Guido van Rossum15d3d042007-08-24 02:02:45 +00002298
Benjamin Peterson214a7d22013-04-13 17:19:01 -04002299 round = _PyObject_LookupSpecial(number, &PyId___round__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002300 if (round == NULL) {
Benjamin Peterson214a7d22013-04-13 17:19:01 -04002301 if (!PyErr_Occurred())
2302 PyErr_Format(PyExc_TypeError,
2303 "type %.100s doesn't define __round__ method",
2304 Py_TYPE(number)->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002305 return NULL;
2306 }
Alex Martelliae211f92007-08-22 23:21:33 +00002307
Serhiy Storchaka279f4462019-09-14 12:24:05 +03002308 if (ndigits == Py_None)
Victor Stinnerf17c3de2016-12-06 18:46:19 +01002309 result = _PyObject_CallNoArg(round);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002310 else
Petr Viktorinffd97532020-02-11 17:46:57 +01002311 result = PyObject_CallOneArg(round, ndigits);
Benjamin Peterson214a7d22013-04-13 17:19:01 -04002312 Py_DECREF(round);
2313 return result;
Guido van Rossum9e51f9b1993-02-12 16:29:05 +00002314}
2315
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002316
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002317/*AC: we need to keep the kwds dict intact to easily call into the
2318 * list.sort method, which isn't currently supported in AC. So we just use
2319 * the initially generated signature with a custom implementation.
2320 */
2321/* [disabled clinic input]
2322sorted as builtin_sorted
2323
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03002324 iterable as seq: object
2325 key as keyfunc: object = None
2326 reverse: object = False
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002327
2328Return a new list containing all items from the iterable in ascending order.
2329
Raymond Hettinger7ea386e2016-08-25 21:11:50 -07002330A custom key function can be supplied to customize the sort order, and the
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002331reverse flag can be set to request the result in descending order.
2332[end disabled clinic input]*/
2333
2334PyDoc_STRVAR(builtin_sorted__doc__,
Serhiy Storchaka3a104252017-01-23 12:29:47 +02002335"sorted($module, iterable, /, *, key=None, reverse=False)\n"
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002336"--\n"
2337"\n"
2338"Return a new list containing all items from the iterable in ascending order.\n"
2339"\n"
Raymond Hettinger7ea386e2016-08-25 21:11:50 -07002340"A custom key function can be supplied to customize the sort order, and the\n"
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002341"reverse flag can be set to request the result in descending order.");
2342
2343#define BUILTIN_SORTED_METHODDEF \
Serhiy Storchaka62be7422018-11-27 13:27:31 +02002344 {"sorted", (PyCFunction)(void(*)(void))builtin_sorted, METH_FASTCALL | METH_KEYWORDS, builtin_sorted__doc__},
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002345
Raymond Hettinger64958a12003-12-17 20:43:33 +00002346static PyObject *
Serhiy Storchakaa5552f02017-12-15 13:11:11 +02002347builtin_sorted(PyObject *self, PyObject *const *args, Py_ssize_t nargs, PyObject *kwnames)
Raymond Hettinger64958a12003-12-17 20:43:33 +00002348{
Serhiy Storchaka7cf8beb2017-01-21 23:05:00 +02002349 PyObject *newlist, *v, *seq, *callable;
Victor Stinner5a60eca2017-01-17 15:17:49 +01002350
Serhiy Storchaka7cf8beb2017-01-21 23:05:00 +02002351 /* Keyword arguments are passed through list.sort() which will check
2352 them. */
2353 if (!_PyArg_UnpackStack(args, nargs, "sorted", 1, 1, &seq))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002354 return NULL;
Raymond Hettinger64958a12003-12-17 20:43:33 +00002355
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002356 newlist = PySequence_List(seq);
2357 if (newlist == NULL)
2358 return NULL;
Raymond Hettinger64958a12003-12-17 20:43:33 +00002359
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02002360 callable = _PyObject_GetAttrId(newlist, &PyId_sort);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002361 if (callable == NULL) {
2362 Py_DECREF(newlist);
2363 return NULL;
2364 }
Georg Brandl99d7e4e2005-08-31 22:21:15 +00002365
Serhiy Storchaka299dc232017-01-20 08:35:18 +02002366 assert(nargs >= 1);
Petr Viktorinffd97532020-02-11 17:46:57 +01002367 v = PyObject_Vectorcall(callable, args + 1, nargs - 1, kwnames);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002368 Py_DECREF(callable);
2369 if (v == NULL) {
2370 Py_DECREF(newlist);
2371 return NULL;
2372 }
2373 Py_DECREF(v);
2374 return newlist;
Raymond Hettinger64958a12003-12-17 20:43:33 +00002375}
2376
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002377
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002378/* AC: cannot convert yet, as needs PEP 457 group support in inspect */
Guido van Rossum79f25d91997-04-29 20:08:16 +00002379static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002380builtin_vars(PyObject *self, PyObject *args)
Guido van Rossum2d951851994-08-29 12:52:16 +00002381{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002382 PyObject *v = NULL;
2383 PyObject *d;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002384
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002385 if (!PyArg_UnpackTuple(args, "vars", 0, 1, &v))
2386 return NULL;
2387 if (v == NULL) {
2388 d = PyEval_GetLocals();
Serhiy Storchaka41c57b32019-09-01 12:03:39 +03002389 Py_XINCREF(d);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002390 }
2391 else {
Serhiy Storchaka41c57b32019-09-01 12:03:39 +03002392 if (_PyObject_LookupAttrId(v, &PyId___dict__, &d) == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002393 PyErr_SetString(PyExc_TypeError,
2394 "vars() argument must have __dict__ attribute");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002395 }
2396 }
2397 return d;
Guido van Rossum2d951851994-08-29 12:52:16 +00002398}
2399
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002400PyDoc_STRVAR(vars_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002401"vars([object]) -> dictionary\n\
2402\n\
2403Without arguments, equivalent to locals().\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002404With an argument, equivalent to object.__dict__.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002405
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002406
2407/*[clinic input]
2408sum as builtin_sum
2409
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03002410 iterable: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002411 /
Raymond Hettinger9dfa0fe2018-09-12 10:54:06 -07002412 start: object(c_default="NULL") = 0
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002413
2414Return the sum of a 'start' value (default: 0) plus an iterable of numbers
2415
2416When the iterable is empty, return the start value.
2417This function is intended specifically for use with numeric values and may
2418reject non-numeric types.
2419[clinic start generated code]*/
2420
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002421static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002422builtin_sum_impl(PyObject *module, PyObject *iterable, PyObject *start)
Raymond Hettinger9dfa0fe2018-09-12 10:54:06 -07002423/*[clinic end generated code: output=df758cec7d1d302f input=162b50765250d222]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002424{
2425 PyObject *result = start;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002426 PyObject *temp, *item, *iter;
Alex Martellia70b1912003-04-22 08:12:33 +00002427
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002428 iter = PyObject_GetIter(iterable);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002429 if (iter == NULL)
2430 return NULL;
Alex Martellia70b1912003-04-22 08:12:33 +00002431
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002432 if (result == NULL) {
2433 result = PyLong_FromLong(0);
2434 if (result == NULL) {
2435 Py_DECREF(iter);
2436 return NULL;
2437 }
2438 } else {
2439 /* reject string values for 'start' parameter */
2440 if (PyUnicode_Check(result)) {
2441 PyErr_SetString(PyExc_TypeError,
2442 "sum() can't sum strings [use ''.join(seq) instead]");
2443 Py_DECREF(iter);
2444 return NULL;
2445 }
Benjamin Petersonce071ca2011-07-29 14:23:47 -05002446 if (PyBytes_Check(result)) {
2447 PyErr_SetString(PyExc_TypeError,
2448 "sum() can't sum bytes [use b''.join(seq) instead]");
Benjamin Peterson405f32c2011-07-29 22:43:45 -05002449 Py_DECREF(iter);
Benjamin Petersonce071ca2011-07-29 14:23:47 -05002450 return NULL;
2451 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002452 if (PyByteArray_Check(result)) {
2453 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson4f921c22011-07-29 14:24:29 -05002454 "sum() can't sum bytearray [use b''.join(seq) instead]");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002455 Py_DECREF(iter);
2456 return NULL;
2457 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002458 Py_INCREF(result);
2459 }
Alex Martellia70b1912003-04-22 08:12:33 +00002460
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002461#ifndef SLOW_SUM
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002462 /* Fast addition by keeping temporary sums in C instead of new Python objects.
2463 Assumes all inputs are the same type. If the assumption fails, default
2464 to the more general routine.
2465 */
2466 if (PyLong_CheckExact(result)) {
2467 int overflow;
2468 long i_result = PyLong_AsLongAndOverflow(result, &overflow);
2469 /* If this already overflowed, don't even enter the loop. */
2470 if (overflow == 0) {
2471 Py_DECREF(result);
2472 result = NULL;
2473 }
2474 while(result == NULL) {
2475 item = PyIter_Next(iter);
2476 if (item == NULL) {
2477 Py_DECREF(iter);
2478 if (PyErr_Occurred())
2479 return NULL;
2480 return PyLong_FromLong(i_result);
2481 }
Serhiy Storchaka88bdb922019-09-10 16:31:01 +03002482 if (PyLong_CheckExact(item) || PyBool_Check(item)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002483 long b = PyLong_AsLongAndOverflow(item, &overflow);
Serhiy Storchaka29500732019-05-05 14:26:23 +03002484 if (overflow == 0 &&
2485 (i_result >= 0 ? (b <= LONG_MAX - i_result)
2486 : (b >= LONG_MIN - i_result)))
2487 {
2488 i_result += b;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002489 Py_DECREF(item);
2490 continue;
2491 }
2492 }
2493 /* Either overflowed or is not an int. Restore real objects and process normally */
2494 result = PyLong_FromLong(i_result);
Christian Heimes704e2d32013-07-26 22:49:26 +02002495 if (result == NULL) {
2496 Py_DECREF(item);
2497 Py_DECREF(iter);
2498 return NULL;
2499 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002500 temp = PyNumber_Add(result, item);
2501 Py_DECREF(result);
2502 Py_DECREF(item);
2503 result = temp;
2504 if (result == NULL) {
2505 Py_DECREF(iter);
2506 return NULL;
2507 }
2508 }
2509 }
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002510
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002511 if (PyFloat_CheckExact(result)) {
2512 double f_result = PyFloat_AS_DOUBLE(result);
2513 Py_DECREF(result);
2514 result = NULL;
2515 while(result == NULL) {
2516 item = PyIter_Next(iter);
2517 if (item == NULL) {
2518 Py_DECREF(iter);
2519 if (PyErr_Occurred())
2520 return NULL;
2521 return PyFloat_FromDouble(f_result);
2522 }
2523 if (PyFloat_CheckExact(item)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002524 f_result += PyFloat_AS_DOUBLE(item);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002525 Py_DECREF(item);
2526 continue;
2527 }
Serhiy Storchaka88bdb922019-09-10 16:31:01 +03002528 if (PyLong_Check(item)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002529 long value;
2530 int overflow;
2531 value = PyLong_AsLongAndOverflow(item, &overflow);
2532 if (!overflow) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002533 f_result += (double)value;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002534 Py_DECREF(item);
2535 continue;
2536 }
2537 }
2538 result = PyFloat_FromDouble(f_result);
Alexey Izbyshev2b824b22018-08-24 07:27:52 +03002539 if (result == NULL) {
2540 Py_DECREF(item);
2541 Py_DECREF(iter);
2542 return NULL;
2543 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002544 temp = PyNumber_Add(result, item);
2545 Py_DECREF(result);
2546 Py_DECREF(item);
2547 result = temp;
2548 if (result == NULL) {
2549 Py_DECREF(iter);
2550 return NULL;
2551 }
2552 }
2553 }
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002554#endif
2555
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002556 for(;;) {
2557 item = PyIter_Next(iter);
2558 if (item == NULL) {
2559 /* error, or end-of-sequence */
2560 if (PyErr_Occurred()) {
2561 Py_DECREF(result);
2562 result = NULL;
2563 }
2564 break;
2565 }
2566 /* It's tempting to use PyNumber_InPlaceAdd instead of
2567 PyNumber_Add here, to avoid quadratic running time
2568 when doing 'sum(list_of_lists, [])'. However, this
2569 would produce a change in behaviour: a snippet like
Mark Dickinson9acadc52009-10-26 14:19:42 +00002570
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002571 empty = []
2572 sum([[x] for x in range(10)], empty)
Mark Dickinson9acadc52009-10-26 14:19:42 +00002573
Brandt Bucherabb9a442020-02-01 03:08:34 -08002574 would change the value of empty. In fact, using
2575 in-place addition rather that binary addition for
2576 any of the steps introduces subtle behavior changes:
Victor Stinner58f4e1a2020-02-05 18:24:33 +01002577
Brandt Bucherabb9a442020-02-01 03:08:34 -08002578 https://bugs.python.org/issue18305 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002579 temp = PyNumber_Add(result, item);
2580 Py_DECREF(result);
2581 Py_DECREF(item);
2582 result = temp;
2583 if (result == NULL)
2584 break;
2585 }
2586 Py_DECREF(iter);
2587 return result;
Alex Martellia70b1912003-04-22 08:12:33 +00002588}
2589
Alex Martellia70b1912003-04-22 08:12:33 +00002590
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002591/*[clinic input]
2592isinstance as builtin_isinstance
2593
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03002594 obj: object
2595 class_or_tuple: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002596 /
2597
2598Return whether an object is an instance of a class or of a subclass thereof.
2599
2600A tuple, as in ``isinstance(x, (A, B, ...))``, may be given as the target to
2601check against. This is equivalent to ``isinstance(x, A) or isinstance(x, B)
2602or ...`` etc.
2603[clinic start generated code]*/
2604
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002605static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002606builtin_isinstance_impl(PyObject *module, PyObject *obj,
Larry Hastings89964c42015-04-14 18:07:59 -04002607 PyObject *class_or_tuple)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002608/*[clinic end generated code: output=6faf01472c13b003 input=ffa743db1daf7549]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002609{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002610 int retval;
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002611
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002612 retval = PyObject_IsInstance(obj, class_or_tuple);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002613 if (retval < 0)
2614 return NULL;
2615 return PyBool_FromLong(retval);
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002616}
2617
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002618
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002619/*[clinic input]
2620issubclass as builtin_issubclass
2621
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03002622 cls: object
2623 class_or_tuple: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002624 /
2625
Alex Poveldf773f82020-06-03 15:19:45 +02002626Return whether 'cls' is derived from another class or is the same class.
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002627
2628A tuple, as in ``issubclass(x, (A, B, ...))``, may be given as the target to
2629check against. This is equivalent to ``issubclass(x, A) or issubclass(x, B)
Alex Poveldf773f82020-06-03 15:19:45 +02002630or ...``.
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002631[clinic start generated code]*/
2632
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002633static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002634builtin_issubclass_impl(PyObject *module, PyObject *cls,
Larry Hastings89964c42015-04-14 18:07:59 -04002635 PyObject *class_or_tuple)
Alex Poveldf773f82020-06-03 15:19:45 +02002636/*[clinic end generated code: output=358412410cd7a250 input=a24b9f3d58c370d6]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002637{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002638 int retval;
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002639
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002640 retval = PyObject_IsSubclass(cls, class_or_tuple);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002641 if (retval < 0)
2642 return NULL;
2643 return PyBool_FromLong(retval);
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002644}
2645
2646
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002647typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002648 PyObject_HEAD
Guido van Rossum310f6aa2020-06-19 03:16:57 -07002649 Py_ssize_t tuplesize;
2650 PyObject *ittuple; /* tuple of iterators */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002651 PyObject *result;
Guido van Rossum310f6aa2020-06-19 03:16:57 -07002652 int strict;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002653} zipobject;
2654
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002655static PyObject *
2656zip_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
Barry Warsawbd599b52000-08-03 15:45:29 +00002657{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002658 zipobject *lz;
2659 Py_ssize_t i;
2660 PyObject *ittuple; /* tuple of iterators */
2661 PyObject *result;
Serhiy Storchakabf623ae2017-04-19 20:03:52 +03002662 Py_ssize_t tuplesize;
Guido van Rossum310f6aa2020-06-19 03:16:57 -07002663 int strict = 0;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002664
Guido van Rossum310f6aa2020-06-19 03:16:57 -07002665 if (kwds) {
2666 PyObject *empty = PyTuple_New(0);
2667 if (empty == NULL) {
2668 return NULL;
2669 }
2670 static char *kwlist[] = {"strict", NULL};
2671 int parsed = PyArg_ParseTupleAndKeywords(
2672 empty, kwds, "|$p:zip", kwlist, &strict);
2673 Py_DECREF(empty);
2674 if (!parsed) {
2675 return NULL;
2676 }
2677 }
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002678
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002679 /* args must be a tuple */
2680 assert(PyTuple_Check(args));
Serhiy Storchakabf623ae2017-04-19 20:03:52 +03002681 tuplesize = PyTuple_GET_SIZE(args);
Barry Warsawbd599b52000-08-03 15:45:29 +00002682
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002683 /* obtain iterators */
2684 ittuple = PyTuple_New(tuplesize);
2685 if (ittuple == NULL)
2686 return NULL;
2687 for (i=0; i < tuplesize; ++i) {
2688 PyObject *item = PyTuple_GET_ITEM(args, i);
2689 PyObject *it = PyObject_GetIter(item);
2690 if (it == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002691 Py_DECREF(ittuple);
2692 return NULL;
2693 }
2694 PyTuple_SET_ITEM(ittuple, i, it);
2695 }
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002696
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002697 /* create a result holder */
2698 result = PyTuple_New(tuplesize);
2699 if (result == NULL) {
2700 Py_DECREF(ittuple);
2701 return NULL;
2702 }
2703 for (i=0 ; i < tuplesize ; i++) {
2704 Py_INCREF(Py_None);
2705 PyTuple_SET_ITEM(result, i, Py_None);
2706 }
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002707
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002708 /* create zipobject structure */
2709 lz = (zipobject *)type->tp_alloc(type, 0);
2710 if (lz == NULL) {
2711 Py_DECREF(ittuple);
2712 Py_DECREF(result);
2713 return NULL;
2714 }
2715 lz->ittuple = ittuple;
2716 lz->tuplesize = tuplesize;
2717 lz->result = result;
Guido van Rossum310f6aa2020-06-19 03:16:57 -07002718 lz->strict = strict;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002719
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002720 return (PyObject *)lz;
Barry Warsawbd599b52000-08-03 15:45:29 +00002721}
2722
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002723static void
2724zip_dealloc(zipobject *lz)
2725{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002726 PyObject_GC_UnTrack(lz);
2727 Py_XDECREF(lz->ittuple);
2728 Py_XDECREF(lz->result);
2729 Py_TYPE(lz)->tp_free(lz);
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002730}
2731
2732static int
2733zip_traverse(zipobject *lz, visitproc visit, void *arg)
2734{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002735 Py_VISIT(lz->ittuple);
2736 Py_VISIT(lz->result);
2737 return 0;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002738}
2739
2740static PyObject *
2741zip_next(zipobject *lz)
2742{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002743 Py_ssize_t i;
2744 Py_ssize_t tuplesize = lz->tuplesize;
2745 PyObject *result = lz->result;
2746 PyObject *it;
2747 PyObject *item;
2748 PyObject *olditem;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002749
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002750 if (tuplesize == 0)
2751 return NULL;
2752 if (Py_REFCNT(result) == 1) {
2753 Py_INCREF(result);
2754 for (i=0 ; i < tuplesize ; i++) {
2755 it = PyTuple_GET_ITEM(lz->ittuple, i);
2756 item = (*Py_TYPE(it)->tp_iternext)(it);
Serhiy Storchaka278d03b2013-04-06 22:52:34 +03002757 if (item == NULL) {
2758 Py_DECREF(result);
Guido van Rossum310f6aa2020-06-19 03:16:57 -07002759 if (lz->strict) {
2760 goto check;
2761 }
Serhiy Storchaka278d03b2013-04-06 22:52:34 +03002762 return NULL;
2763 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002764 olditem = PyTuple_GET_ITEM(result, i);
2765 PyTuple_SET_ITEM(result, i, item);
2766 Py_DECREF(olditem);
2767 }
Brandt Bucher226a0122020-12-04 19:45:57 -08002768 // bpo-42536: The GC may have untracked this result tuple. Since we're
2769 // recycling it, make sure it's tracked again:
2770 if (!_PyObject_GC_IS_TRACKED(result)) {
2771 _PyObject_GC_TRACK(result);
2772 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002773 } else {
2774 result = PyTuple_New(tuplesize);
2775 if (result == NULL)
Serhiy Storchaka278d03b2013-04-06 22:52:34 +03002776 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002777 for (i=0 ; i < tuplesize ; i++) {
2778 it = PyTuple_GET_ITEM(lz->ittuple, i);
2779 item = (*Py_TYPE(it)->tp_iternext)(it);
Serhiy Storchaka278d03b2013-04-06 22:52:34 +03002780 if (item == NULL) {
2781 Py_DECREF(result);
Guido van Rossum310f6aa2020-06-19 03:16:57 -07002782 if (lz->strict) {
2783 goto check;
2784 }
Serhiy Storchaka278d03b2013-04-06 22:52:34 +03002785 return NULL;
2786 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002787 PyTuple_SET_ITEM(result, i, item);
2788 }
2789 }
2790 return result;
Guido van Rossum310f6aa2020-06-19 03:16:57 -07002791check:
2792 if (PyErr_Occurred()) {
2793 if (!PyErr_ExceptionMatches(PyExc_StopIteration)) {
2794 // next() on argument i raised an exception (not StopIteration)
2795 return NULL;
2796 }
2797 PyErr_Clear();
2798 }
2799 if (i) {
2800 // ValueError: zip() argument 2 is shorter than argument 1
2801 // ValueError: zip() argument 3 is shorter than arguments 1-2
2802 const char* plural = i == 1 ? " " : "s 1-";
2803 return PyErr_Format(PyExc_ValueError,
2804 "zip() argument %d is shorter than argument%s%d",
2805 i + 1, plural, i);
2806 }
2807 for (i = 1; i < tuplesize; i++) {
2808 it = PyTuple_GET_ITEM(lz->ittuple, i);
2809 item = (*Py_TYPE(it)->tp_iternext)(it);
2810 if (item) {
2811 Py_DECREF(item);
2812 const char* plural = i == 1 ? " " : "s 1-";
2813 return PyErr_Format(PyExc_ValueError,
2814 "zip() argument %d is longer than argument%s%d",
2815 i + 1, plural, i);
2816 }
2817 if (PyErr_Occurred()) {
2818 if (!PyErr_ExceptionMatches(PyExc_StopIteration)) {
2819 // next() on argument i raised an exception (not StopIteration)
2820 return NULL;
2821 }
2822 PyErr_Clear();
2823 }
2824 // Argument i is exhausted. So far so good...
2825 }
2826 // All arguments are exhausted. Success!
2827 return NULL;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002828}
Barry Warsawbd599b52000-08-03 15:45:29 +00002829
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002830static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05302831zip_reduce(zipobject *lz, PyObject *Py_UNUSED(ignored))
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002832{
2833 /* Just recreate the zip with the internal iterator tuple */
Guido van Rossum310f6aa2020-06-19 03:16:57 -07002834 if (lz->strict) {
2835 return PyTuple_Pack(3, Py_TYPE(lz), lz->ittuple, Py_True);
2836 }
2837 return PyTuple_Pack(2, Py_TYPE(lz), lz->ittuple);
2838}
2839
2840PyDoc_STRVAR(setstate_doc, "Set state information for unpickling.");
2841
2842static PyObject *
2843zip_setstate(zipobject *lz, PyObject *state)
2844{
2845 int strict = PyObject_IsTrue(state);
2846 if (strict < 0) {
2847 return NULL;
2848 }
2849 lz->strict = strict;
2850 Py_RETURN_NONE;
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002851}
2852
2853static PyMethodDef zip_methods[] = {
2854 {"__reduce__", (PyCFunction)zip_reduce, METH_NOARGS, reduce_doc},
Guido van Rossum310f6aa2020-06-19 03:16:57 -07002855 {"__setstate__", (PyCFunction)zip_setstate, METH_O, setstate_doc},
2856 {NULL} /* sentinel */
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002857};
2858
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002859PyDoc_STRVAR(zip_doc,
Guido van Rossum310f6aa2020-06-19 03:16:57 -07002860"zip(*iterables, strict=False) --> Yield tuples until an input is exhausted.\n\
Barry Warsawbd599b52000-08-03 15:45:29 +00002861\n\
Gregory P. Smith6a5d3ff2020-05-15 14:26:00 -07002862 >>> list(zip('abcdefg', range(3), range(4)))\n\
2863 [('a', 0, 0), ('b', 1, 1), ('c', 2, 2)]\n\
2864\n\
2865The zip object yields n-length tuples, where n is the number of iterables\n\
2866passed as positional arguments to zip(). The i-th element in every tuple\n\
2867comes from the i-th iterable argument to zip(). This continues until the\n\
Guido van Rossum310f6aa2020-06-19 03:16:57 -07002868shortest argument is exhausted.\n\
2869\n\
2870If strict is true and one of the arguments is exhausted before the others,\n\
2871raise a ValueError.");
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002872
2873PyTypeObject PyZip_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002874 PyVarObject_HEAD_INIT(&PyType_Type, 0)
2875 "zip", /* tp_name */
2876 sizeof(zipobject), /* tp_basicsize */
2877 0, /* tp_itemsize */
2878 /* methods */
2879 (destructor)zip_dealloc, /* tp_dealloc */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02002880 0, /* tp_vectorcall_offset */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002881 0, /* tp_getattr */
2882 0, /* tp_setattr */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02002883 0, /* tp_as_async */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002884 0, /* tp_repr */
2885 0, /* tp_as_number */
2886 0, /* tp_as_sequence */
2887 0, /* tp_as_mapping */
2888 0, /* tp_hash */
2889 0, /* tp_call */
2890 0, /* tp_str */
2891 PyObject_GenericGetAttr, /* tp_getattro */
2892 0, /* tp_setattro */
2893 0, /* tp_as_buffer */
2894 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
2895 Py_TPFLAGS_BASETYPE, /* tp_flags */
2896 zip_doc, /* tp_doc */
2897 (traverseproc)zip_traverse, /* tp_traverse */
2898 0, /* tp_clear */
2899 0, /* tp_richcompare */
2900 0, /* tp_weaklistoffset */
2901 PyObject_SelfIter, /* tp_iter */
2902 (iternextfunc)zip_next, /* tp_iternext */
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002903 zip_methods, /* tp_methods */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002904 0, /* tp_members */
2905 0, /* tp_getset */
2906 0, /* tp_base */
2907 0, /* tp_dict */
2908 0, /* tp_descr_get */
2909 0, /* tp_descr_set */
2910 0, /* tp_dictoffset */
2911 0, /* tp_init */
2912 PyType_GenericAlloc, /* tp_alloc */
2913 zip_new, /* tp_new */
2914 PyObject_GC_Del, /* tp_free */
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002915};
Barry Warsawbd599b52000-08-03 15:45:29 +00002916
2917
Guido van Rossum79f25d91997-04-29 20:08:16 +00002918static PyMethodDef builtin_methods[] = {
Serhiy Storchaka62be7422018-11-27 13:27:31 +02002919 {"__build_class__", (PyCFunction)(void(*)(void))builtin___build_class__,
Serhiy Storchaka6969eaf2017-07-03 21:20:15 +03002920 METH_FASTCALL | METH_KEYWORDS, build_class_doc},
Serhiy Storchaka62be7422018-11-27 13:27:31 +02002921 {"__import__", (PyCFunction)(void(*)(void))builtin___import__, METH_VARARGS | METH_KEYWORDS, import_doc},
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002922 BUILTIN_ABS_METHODDEF
2923 BUILTIN_ALL_METHODDEF
2924 BUILTIN_ANY_METHODDEF
2925 BUILTIN_ASCII_METHODDEF
2926 BUILTIN_BIN_METHODDEF
Serhiy Storchaka62be7422018-11-27 13:27:31 +02002927 {"breakpoint", (PyCFunction)(void(*)(void))builtin_breakpoint, METH_FASTCALL | METH_KEYWORDS, breakpoint_doc},
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002928 BUILTIN_CALLABLE_METHODDEF
2929 BUILTIN_CHR_METHODDEF
2930 BUILTIN_COMPILE_METHODDEF
2931 BUILTIN_DELATTR_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002932 {"dir", builtin_dir, METH_VARARGS, dir_doc},
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002933 BUILTIN_DIVMOD_METHODDEF
2934 BUILTIN_EVAL_METHODDEF
2935 BUILTIN_EXEC_METHODDEF
2936 BUILTIN_FORMAT_METHODDEF
Serhiy Storchaka62be7422018-11-27 13:27:31 +02002937 {"getattr", (PyCFunction)(void(*)(void))builtin_getattr, METH_FASTCALL, getattr_doc},
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002938 BUILTIN_GLOBALS_METHODDEF
2939 BUILTIN_HASATTR_METHODDEF
2940 BUILTIN_HASH_METHODDEF
2941 BUILTIN_HEX_METHODDEF
2942 BUILTIN_ID_METHODDEF
2943 BUILTIN_INPUT_METHODDEF
2944 BUILTIN_ISINSTANCE_METHODDEF
2945 BUILTIN_ISSUBCLASS_METHODDEF
Serhiy Storchaka79342662019-01-12 08:25:41 +02002946 {"iter", (PyCFunction)(void(*)(void))builtin_iter, METH_FASTCALL, iter_doc},
Joshua Bronsonf0a6fde2021-03-23 18:47:21 -04002947 BUILTIN_AITER_METHODDEF
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002948 BUILTIN_LEN_METHODDEF
2949 BUILTIN_LOCALS_METHODDEF
Serhiy Storchaka62be7422018-11-27 13:27:31 +02002950 {"max", (PyCFunction)(void(*)(void))builtin_max, METH_VARARGS | METH_KEYWORDS, max_doc},
2951 {"min", (PyCFunction)(void(*)(void))builtin_min, METH_VARARGS | METH_KEYWORDS, min_doc},
2952 {"next", (PyCFunction)(void(*)(void))builtin_next, METH_FASTCALL, next_doc},
Joshua Bronsonf0a6fde2021-03-23 18:47:21 -04002953 BUILTIN_ANEXT_METHODDEF
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002954 BUILTIN_OCT_METHODDEF
2955 BUILTIN_ORD_METHODDEF
2956 BUILTIN_POW_METHODDEF
Serhiy Storchaka62be7422018-11-27 13:27:31 +02002957 {"print", (PyCFunction)(void(*)(void))builtin_print, METH_FASTCALL | METH_KEYWORDS, print_doc},
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002958 BUILTIN_REPR_METHODDEF
Serhiy Storchakaaca7f572017-11-15 17:51:14 +02002959 BUILTIN_ROUND_METHODDEF
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002960 BUILTIN_SETATTR_METHODDEF
2961 BUILTIN_SORTED_METHODDEF
2962 BUILTIN_SUM_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002963 {"vars", builtin_vars, METH_VARARGS, vars_doc},
2964 {NULL, NULL},
Guido van Rossum3f5da241990-12-20 15:06:42 +00002965};
2966
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002967PyDoc_STRVAR(builtin_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002968"Built-in functions, exceptions, and other objects.\n\
2969\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002970Noteworthy: None is the `nil' object; Ellipsis represents `...' in slices.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002971
Martin v. Löwis1a214512008-06-11 05:26:20 +00002972static struct PyModuleDef builtinsmodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002973 PyModuleDef_HEAD_INIT,
2974 "builtins",
2975 builtin_doc,
2976 -1, /* multiple "initialization" just copies the module dict. */
2977 builtin_methods,
2978 NULL,
2979 NULL,
2980 NULL,
2981 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00002982};
2983
2984
Guido van Rossum25ce5661997-08-02 03:10:38 +00002985PyObject *
Victor Stinnerbcb094b2021-02-19 15:10:45 +01002986_PyBuiltin_Init(PyInterpreterState *interp)
Guido van Rossum25ce5661997-08-02 03:10:38 +00002987{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002988 PyObject *mod, *dict, *debug;
Benjamin Peterson42124a72012-10-30 23:41:54 -04002989
Victor Stinnerbcb094b2021-02-19 15:10:45 +01002990 const PyConfig *config = _PyInterpreterState_GetConfig(interp);
Victor Stinnerfbca9082018-08-30 00:50:45 +02002991
Benjamin Peterson42124a72012-10-30 23:41:54 -04002992 if (PyType_Ready(&PyFilter_Type) < 0 ||
2993 PyType_Ready(&PyMap_Type) < 0 ||
2994 PyType_Ready(&PyZip_Type) < 0)
2995 return NULL;
2996
Eric Snowd393c1b2017-09-14 12:18:12 -06002997 mod = _PyModule_CreateInitialized(&builtinsmodule, PYTHON_API_VERSION);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002998 if (mod == NULL)
2999 return NULL;
3000 dict = PyModule_GetDict(mod);
Tim Peters4b7625e2001-09-13 21:37:17 +00003001
Tim Peters7571a0f2003-03-23 17:52:28 +00003002#ifdef Py_TRACE_REFS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003003 /* "builtins" exposes a number of statically allocated objects
3004 * that, before this code was added in 2.3, never showed up in
3005 * the list of "all objects" maintained by Py_TRACE_REFS. As a
3006 * result, programs leaking references to None and False (etc)
3007 * couldn't be diagnosed by examining sys.getobjects(0).
3008 */
Tim Peters7571a0f2003-03-23 17:52:28 +00003009#define ADD_TO_ALL(OBJECT) _Py_AddToAllObjects((PyObject *)(OBJECT), 0)
3010#else
3011#define ADD_TO_ALL(OBJECT) (void)0
3012#endif
3013
Tim Peters4b7625e2001-09-13 21:37:17 +00003014#define SETBUILTIN(NAME, OBJECT) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003015 if (PyDict_SetItemString(dict, NAME, (PyObject *)OBJECT) < 0) \
3016 return NULL; \
3017 ADD_TO_ALL(OBJECT)
Tim Peters4b7625e2001-09-13 21:37:17 +00003018
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003019 SETBUILTIN("None", Py_None);
3020 SETBUILTIN("Ellipsis", Py_Ellipsis);
3021 SETBUILTIN("NotImplemented", Py_NotImplemented);
3022 SETBUILTIN("False", Py_False);
3023 SETBUILTIN("True", Py_True);
3024 SETBUILTIN("bool", &PyBool_Type);
3025 SETBUILTIN("memoryview", &PyMemoryView_Type);
3026 SETBUILTIN("bytearray", &PyByteArray_Type);
3027 SETBUILTIN("bytes", &PyBytes_Type);
3028 SETBUILTIN("classmethod", &PyClassMethod_Type);
3029 SETBUILTIN("complex", &PyComplex_Type);
3030 SETBUILTIN("dict", &PyDict_Type);
3031 SETBUILTIN("enumerate", &PyEnum_Type);
3032 SETBUILTIN("filter", &PyFilter_Type);
3033 SETBUILTIN("float", &PyFloat_Type);
3034 SETBUILTIN("frozenset", &PyFrozenSet_Type);
3035 SETBUILTIN("property", &PyProperty_Type);
3036 SETBUILTIN("int", &PyLong_Type);
3037 SETBUILTIN("list", &PyList_Type);
3038 SETBUILTIN("map", &PyMap_Type);
3039 SETBUILTIN("object", &PyBaseObject_Type);
3040 SETBUILTIN("range", &PyRange_Type);
3041 SETBUILTIN("reversed", &PyReversed_Type);
3042 SETBUILTIN("set", &PySet_Type);
3043 SETBUILTIN("slice", &PySlice_Type);
3044 SETBUILTIN("staticmethod", &PyStaticMethod_Type);
3045 SETBUILTIN("str", &PyUnicode_Type);
3046 SETBUILTIN("super", &PySuper_Type);
3047 SETBUILTIN("tuple", &PyTuple_Type);
3048 SETBUILTIN("type", &PyType_Type);
3049 SETBUILTIN("zip", &PyZip_Type);
Victor Stinnerfbca9082018-08-30 00:50:45 +02003050 debug = PyBool_FromLong(config->optimization_level == 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003051 if (PyDict_SetItemString(dict, "__debug__", debug) < 0) {
Serhiy Storchakacfdfbb42016-06-18 09:44:03 +03003052 Py_DECREF(debug);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003053 return NULL;
3054 }
Serhiy Storchakacfdfbb42016-06-18 09:44:03 +03003055 Py_DECREF(debug);
Barry Warsaw757af0e1997-08-29 22:13:51 +00003056
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003057 return mod;
Tim Peters7571a0f2003-03-23 17:52:28 +00003058#undef ADD_TO_ALL
Tim Peters4b7625e2001-09-13 21:37:17 +00003059#undef SETBUILTIN
Guido van Rossum3f5da241990-12-20 15:06:42 +00003060}