blob: d069f2fd2610c4bf9cd80b9935b3ecf415b66b3a [file] [log] [blame]
Guido van Rossum3f5da241990-12-20 15:06:42 +00001/* Built-in functions */
2
Guido van Rossum79f25d91997-04-29 20:08:16 +00003#include "Python.h"
Guido van Rossum6bf62da1997-04-11 20:37:35 +00004#include <ctype.h>
Victor Stinner5f2df882018-11-12 00:56:19 +01005#include "ast.h"
Victor Stinner3bb183d2018-11-22 18:38:38 +01006#undef Yield /* undefine macro conflicting with <winbase.h> */
Victor Stinner621cebe2018-11-12 16:53:38 +01007#include "pycore_pystate.h"
Sergey Fedoseevf1b9abe2019-02-26 02:37:26 +05008#include "pycore_tupleobject.h"
Guido van Rossum6bf62da1997-04-11 20:37:35 +00009
Victor Stinnerbd303c12013-11-07 23:07:29 +010010_Py_IDENTIFIER(__builtins__);
11_Py_IDENTIFIER(__dict__);
12_Py_IDENTIFIER(__prepare__);
13_Py_IDENTIFIER(__round__);
Ivan Levkivskyi2b5fd1e2017-12-14 23:32:56 +010014_Py_IDENTIFIER(__mro_entries__);
Victor Stinnerbd303c12013-11-07 23:07:29 +010015_Py_IDENTIFIER(encoding);
16_Py_IDENTIFIER(errors);
Martin v. Löwisbd928fe2011-10-14 10:20:37 +020017_Py_IDENTIFIER(fileno);
18_Py_IDENTIFIER(flush);
Victor Stinnerbd303c12013-11-07 23:07:29 +010019_Py_IDENTIFIER(metaclass);
20_Py_IDENTIFIER(sort);
21_Py_IDENTIFIER(stdin);
22_Py_IDENTIFIER(stdout);
23_Py_IDENTIFIER(stderr);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +020024
Serhiy Storchaka1009bf12015-04-03 23:53:51 +030025#include "clinic/bltinmodule.c.h"
26
Ivan Levkivskyi2b5fd1e2017-12-14 23:32:56 +010027static PyObject*
Victor Stinner05d68a82018-01-18 11:15:25 +010028update_bases(PyObject *bases, PyObject *const *args, Py_ssize_t nargs)
Ivan Levkivskyi2b5fd1e2017-12-14 23:32:56 +010029{
Victor Stinner05d68a82018-01-18 11:15:25 +010030 Py_ssize_t i, j;
Ivan Levkivskyi2b5fd1e2017-12-14 23:32:56 +010031 PyObject *base, *meth, *new_base, *result, *new_bases = NULL;
Ivan Levkivskyi2b5fd1e2017-12-14 23:32:56 +010032 assert(PyTuple_Check(bases));
33
34 for (i = 0; i < nargs; i++) {
35 base = args[i];
36 if (PyType_Check(base)) {
37 if (new_bases) {
38 /* If we already have made a replacement, then we append every normal base,
39 otherwise just skip it. */
40 if (PyList_Append(new_bases, base) < 0) {
41 goto error;
42 }
43 }
44 continue;
45 }
Serhiy Storchakaf320be72018-01-25 10:49:40 +020046 if (_PyObject_LookupAttrId(base, &PyId___mro_entries__, &meth) < 0) {
47 goto error;
48 }
Ivan Levkivskyi2b5fd1e2017-12-14 23:32:56 +010049 if (!meth) {
Ivan Levkivskyi2b5fd1e2017-12-14 23:32:56 +010050 if (new_bases) {
51 if (PyList_Append(new_bases, base) < 0) {
52 goto error;
53 }
54 }
55 continue;
56 }
Jeroen Demeyer196a5302019-07-04 12:31:34 +020057 new_base = _PyObject_CallOneArg(meth, bases);
Ivan Levkivskyi2b5fd1e2017-12-14 23:32:56 +010058 Py_DECREF(meth);
59 if (!new_base) {
60 goto error;
61 }
62 if (!PyTuple_Check(new_base)) {
63 PyErr_SetString(PyExc_TypeError,
64 "__mro_entries__ must return a tuple");
65 Py_DECREF(new_base);
66 goto error;
67 }
68 if (!new_bases) {
69 /* If this is a first successful replacement, create new_bases list and
70 copy previously encountered bases. */
71 if (!(new_bases = PyList_New(i))) {
72 goto error;
73 }
74 for (j = 0; j < i; j++) {
75 base = args[j];
76 PyList_SET_ITEM(new_bases, j, base);
77 Py_INCREF(base);
78 }
79 }
80 j = PyList_GET_SIZE(new_bases);
81 if (PyList_SetSlice(new_bases, j, j, new_base) < 0) {
82 goto error;
83 }
84 Py_DECREF(new_base);
85 }
86 if (!new_bases) {
87 return bases;
88 }
89 result = PyList_AsTuple(new_bases);
90 Py_DECREF(new_bases);
91 return result;
92
93error:
94 Py_XDECREF(new_bases);
95 return NULL;
96}
97
Nick Coghlanf9e227e2014-08-17 14:01:19 +100098/* AC: cannot convert yet, waiting for *args support */
Guido van Rossum79f25d91997-04-29 20:08:16 +000099static PyObject *
Serhiy Storchakaa5552f02017-12-15 13:11:11 +0200100builtin___build_class__(PyObject *self, PyObject *const *args, Py_ssize_t nargs,
Victor Stinner773dc6d2017-01-16 23:46:26 +0100101 PyObject *kwnames)
Guido van Rossum52cc1d82007-03-18 15:41:51 +0000102{
Ivan Levkivskyi2b5fd1e2017-12-14 23:32:56 +0100103 PyObject *func, *name, *bases, *mkw, *meta, *winner, *prep, *ns, *orig_bases;
Nick Coghlan19d24672016-12-05 16:47:55 +1000104 PyObject *cls = NULL, *cell = NULL;
Victor Stinner0c39b1b2015-03-18 15:02:06 +0100105 int isclass = 0; /* initialize to prevent gcc warning */
Guido van Rossum52cc1d82007-03-18 15:41:51 +0000106
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000107 if (nargs < 2) {
108 PyErr_SetString(PyExc_TypeError,
109 "__build_class__: not enough arguments");
110 return NULL;
111 }
Victor Stinner773dc6d2017-01-16 23:46:26 +0100112 func = args[0]; /* Better be callable */
Benjamin Petersone8e14592013-05-16 14:37:25 -0500113 if (!PyFunction_Check(func)) {
114 PyErr_SetString(PyExc_TypeError,
Zachary Ware9b338722014-08-05 14:01:10 -0500115 "__build_class__: func must be a function");
Benjamin Petersone8e14592013-05-16 14:37:25 -0500116 return NULL;
117 }
Victor Stinner773dc6d2017-01-16 23:46:26 +0100118 name = args[1];
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000119 if (!PyUnicode_Check(name)) {
120 PyErr_SetString(PyExc_TypeError,
121 "__build_class__: name is not a string");
122 return NULL;
123 }
Sergey Fedoseevf1b9abe2019-02-26 02:37:26 +0500124 orig_bases = _PyTuple_FromArray(args + 2, nargs - 2);
Ivan Levkivskyi2b5fd1e2017-12-14 23:32:56 +0100125 if (orig_bases == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000126 return NULL;
Guido van Rossum52cc1d82007-03-18 15:41:51 +0000127
Ivan Levkivskyi2b5fd1e2017-12-14 23:32:56 +0100128 bases = update_bases(orig_bases, args + 2, nargs - 2);
129 if (bases == NULL) {
130 Py_DECREF(orig_bases);
131 return NULL;
132 }
133
Victor Stinner773dc6d2017-01-16 23:46:26 +0100134 if (kwnames == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000135 meta = NULL;
136 mkw = NULL;
137 }
138 else {
Victor Stinner773dc6d2017-01-16 23:46:26 +0100139 mkw = _PyStack_AsDict(args + nargs, kwnames);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000140 if (mkw == NULL) {
141 Py_DECREF(bases);
142 return NULL;
Guido van Rossum52cc1d82007-03-18 15:41:51 +0000143 }
Victor Stinner773dc6d2017-01-16 23:46:26 +0100144
Serhiy Storchakaa24107b2019-02-25 17:59:46 +0200145 meta = _PyDict_GetItemIdWithError(mkw, &PyId_metaclass);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000146 if (meta != NULL) {
147 Py_INCREF(meta);
Victor Stinnerae9f1612013-11-06 22:46:51 +0100148 if (_PyDict_DelItemId(mkw, &PyId_metaclass) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000149 Py_DECREF(meta);
150 Py_DECREF(mkw);
151 Py_DECREF(bases);
152 return NULL;
153 }
Nick Coghlande31b192011-10-23 22:04:16 +1000154 /* metaclass is explicitly given, check if it's indeed a class */
155 isclass = PyType_Check(meta);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000156 }
Serhiy Storchakaa24107b2019-02-25 17:59:46 +0200157 else if (PyErr_Occurred()) {
158 Py_DECREF(mkw);
159 Py_DECREF(bases);
160 return NULL;
161 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000162 }
163 if (meta == NULL) {
Nick Coghlande31b192011-10-23 22:04:16 +1000164 /* if there are no bases, use type: */
165 if (PyTuple_GET_SIZE(bases) == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000166 meta = (PyObject *) (&PyType_Type);
Nick Coghlande31b192011-10-23 22:04:16 +1000167 }
168 /* else get the type of the first base */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000169 else {
170 PyObject *base0 = PyTuple_GET_ITEM(bases, 0);
171 meta = (PyObject *) (base0->ob_type);
172 }
173 Py_INCREF(meta);
Nick Coghlande31b192011-10-23 22:04:16 +1000174 isclass = 1; /* meta is really a class */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000175 }
Nick Coghlan9715d262011-10-23 22:36:42 +1000176
Nick Coghlande31b192011-10-23 22:04:16 +1000177 if (isclass) {
178 /* meta is really a class, so check for a more derived
179 metaclass, or possible metaclass conflicts: */
180 winner = (PyObject *)_PyType_CalculateMetaclass((PyTypeObject *)meta,
181 bases);
182 if (winner == NULL) {
183 Py_DECREF(meta);
184 Py_XDECREF(mkw);
185 Py_DECREF(bases);
186 return NULL;
187 }
188 if (winner != meta) {
189 Py_DECREF(meta);
190 meta = winner;
191 Py_INCREF(meta);
192 }
193 }
194 /* else: meta is not a class, so we cannot do the metaclass
195 calculation, so we will use the explicitly given object as it is */
Serhiy Storchakaf320be72018-01-25 10:49:40 +0200196 if (_PyObject_LookupAttrId(meta, &PyId___prepare__, &prep) < 0) {
197 ns = NULL;
198 }
199 else if (prep == NULL) {
200 ns = PyDict_New();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000201 }
202 else {
Victor Stinner463b86a2016-08-22 23:33:13 +0200203 PyObject *pargs[2] = {name, bases};
204 ns = _PyObject_FastCallDict(prep, pargs, 2, mkw);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000205 Py_DECREF(prep);
206 }
207 if (ns == NULL) {
208 Py_DECREF(meta);
209 Py_XDECREF(mkw);
210 Py_DECREF(bases);
211 return NULL;
212 }
Oren Milman5837d042017-09-27 17:04:37 +0300213 if (!PyMapping_Check(ns)) {
214 PyErr_Format(PyExc_TypeError,
215 "%.200s.__prepare__() must return a mapping, not %.200s",
216 isclass ? ((PyTypeObject *)meta)->tp_name : "<metaclass>",
217 Py_TYPE(ns)->tp_name);
218 goto error;
219 }
Nick Coghlan19d24672016-12-05 16:47:55 +1000220 cell = PyEval_EvalCodeEx(PyFunction_GET_CODE(func), PyFunction_GET_GLOBALS(func), ns,
Benjamin Petersone8e14592013-05-16 14:37:25 -0500221 NULL, 0, NULL, 0, NULL, 0, NULL,
222 PyFunction_GET_CLOSURE(func));
Nick Coghlan19d24672016-12-05 16:47:55 +1000223 if (cell != NULL) {
Ivan Levkivskyi2b5fd1e2017-12-14 23:32:56 +0100224 if (bases != orig_bases) {
225 if (PyMapping_SetItemString(ns, "__orig_bases__", orig_bases) < 0) {
226 goto error;
227 }
228 }
Victor Stinnerd1c2a8e2016-08-23 01:34:35 +0200229 PyObject *margs[3] = {name, bases, ns};
230 cls = _PyObject_FastCallDict(meta, margs, 3, mkw);
Nick Coghlan19d24672016-12-05 16:47:55 +1000231 if (cls != NULL && PyType_Check(cls) && PyCell_Check(cell)) {
232 PyObject *cell_cls = PyCell_GET(cell);
233 if (cell_cls != cls) {
Nick Coghlan19d24672016-12-05 16:47:55 +1000234 if (cell_cls == NULL) {
235 const char *msg =
236 "__class__ not set defining %.200R as %.200R. "
237 "Was __classcell__ propagated to type.__new__?";
Serhiy Storchakaf5e7b192018-05-20 08:48:12 +0300238 PyErr_Format(PyExc_RuntimeError, msg, name, cls);
Nick Coghlan19d24672016-12-05 16:47:55 +1000239 } else {
240 const char *msg =
241 "__class__ set to %.200R defining %.200R as %.200R";
242 PyErr_Format(PyExc_TypeError, msg, cell_cls, name, cls);
Nick Coghlan19d24672016-12-05 16:47:55 +1000243 }
Serhiy Storchakaf5e7b192018-05-20 08:48:12 +0300244 Py_DECREF(cls);
245 cls = NULL;
246 goto error;
Nick Coghlan19d24672016-12-05 16:47:55 +1000247 }
248 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000249 }
Nick Coghlan19d24672016-12-05 16:47:55 +1000250error:
251 Py_XDECREF(cell);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000252 Py_DECREF(ns);
253 Py_DECREF(meta);
254 Py_XDECREF(mkw);
255 Py_DECREF(bases);
Ivan Levkivskyi2b5fd1e2017-12-14 23:32:56 +0100256 if (bases != orig_bases) {
257 Py_DECREF(orig_bases);
258 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000259 return cls;
Guido van Rossum52cc1d82007-03-18 15:41:51 +0000260}
261
262PyDoc_STRVAR(build_class_doc,
263"__build_class__(func, name, *bases, metaclass=None, **kwds) -> class\n\
264\n\
265Internal helper function used by the class statement.");
266
267static PyObject *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000268builtin___import__(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000269{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000270 static char *kwlist[] = {"name", "globals", "locals", "fromlist",
271 "level", 0};
Victor Stinnerfe93faf2011-03-14 15:54:52 -0400272 PyObject *name, *globals = NULL, *locals = NULL, *fromlist = NULL;
Brett Cannonfd074152012-04-14 14:10:13 -0400273 int level = 0;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000274
Victor Stinnerfe93faf2011-03-14 15:54:52 -0400275 if (!PyArg_ParseTupleAndKeywords(args, kwds, "U|OOOi:__import__",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000276 kwlist, &name, &globals, &locals, &fromlist, &level))
277 return NULL;
Victor Stinnerfe93faf2011-03-14 15:54:52 -0400278 return PyImport_ImportModuleLevelObject(name, globals, locals,
279 fromlist, level);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000280}
281
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000282PyDoc_STRVAR(import_doc,
Brett Cannoncb4996a2012-08-06 16:34:44 -0400283"__import__(name, globals=None, locals=None, fromlist=(), level=0) -> module\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000284\n\
Brett Cannon5305a992010-09-27 21:08:38 +0000285Import a module. Because this function is meant for use by the Python\n\
oldk461d2252018-02-02 12:20:00 +0800286interpreter and not for general use, it is better to use\n\
Brett Cannon5305a992010-09-27 21:08:38 +0000287importlib.import_module() to programmatically import a module.\n\
288\n\
289The globals argument is only used to determine the context;\n\
290they are not modified. The locals argument is unused. The fromlist\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000291should be a list of names to emulate ``from name import ...'', or an\n\
292empty list to emulate ``import name''.\n\
293When importing a module from a package, note that __import__('A.B', ...)\n\
294returns package A when fromlist is empty, but its submodule B when\n\
oldk461d2252018-02-02 12:20:00 +0800295fromlist is not empty. The level argument is used to determine whether to\n\
296perform absolute or relative imports: 0 is absolute, while a positive number\n\
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000297is the number of parent directories to search relative to the current module.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000298
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000299
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000300/*[clinic input]
301abs as builtin_abs
302
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300303 x: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000304 /
305
306Return the absolute value of the argument.
307[clinic start generated code]*/
308
Guido van Rossum79f25d91997-04-29 20:08:16 +0000309static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300310builtin_abs(PyObject *module, PyObject *x)
311/*[clinic end generated code: output=b1b433b9e51356f5 input=bed4ca14e29c20d1]*/
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000312{
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000313 return PyNumber_Absolute(x);
Guido van Rossum3f5da241990-12-20 15:06:42 +0000314}
315
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000316/*[clinic input]
317all as builtin_all
318
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300319 iterable: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000320 /
321
322Return True if bool(x) is True for all values x in the iterable.
323
324If the iterable is empty, return True.
325[clinic start generated code]*/
326
Raymond Hettinger96229b12005-03-11 06:49:40 +0000327static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300328builtin_all(PyObject *module, PyObject *iterable)
329/*[clinic end generated code: output=ca2a7127276f79b3 input=1a7c5d1bc3438a21]*/
Raymond Hettinger96229b12005-03-11 06:49:40 +0000330{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000331 PyObject *it, *item;
332 PyObject *(*iternext)(PyObject *);
333 int cmp;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000334
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000335 it = PyObject_GetIter(iterable);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000336 if (it == NULL)
337 return NULL;
338 iternext = *Py_TYPE(it)->tp_iternext;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000339
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000340 for (;;) {
341 item = iternext(it);
342 if (item == NULL)
343 break;
344 cmp = PyObject_IsTrue(item);
345 Py_DECREF(item);
346 if (cmp < 0) {
347 Py_DECREF(it);
348 return NULL;
349 }
350 if (cmp == 0) {
351 Py_DECREF(it);
352 Py_RETURN_FALSE;
353 }
354 }
355 Py_DECREF(it);
356 if (PyErr_Occurred()) {
357 if (PyErr_ExceptionMatches(PyExc_StopIteration))
358 PyErr_Clear();
359 else
360 return NULL;
361 }
362 Py_RETURN_TRUE;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000363}
364
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000365/*[clinic input]
366any as builtin_any
367
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300368 iterable: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000369 /
370
371Return True if bool(x) is True for any x in the iterable.
372
373If the iterable is empty, return False.
374[clinic start generated code]*/
375
Raymond Hettinger96229b12005-03-11 06:49:40 +0000376static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300377builtin_any(PyObject *module, PyObject *iterable)
378/*[clinic end generated code: output=fa65684748caa60e input=41d7451c23384f24]*/
Raymond Hettinger96229b12005-03-11 06:49:40 +0000379{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000380 PyObject *it, *item;
381 PyObject *(*iternext)(PyObject *);
382 int cmp;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000383
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000384 it = PyObject_GetIter(iterable);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000385 if (it == NULL)
386 return NULL;
387 iternext = *Py_TYPE(it)->tp_iternext;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000388
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000389 for (;;) {
390 item = iternext(it);
391 if (item == NULL)
392 break;
393 cmp = PyObject_IsTrue(item);
394 Py_DECREF(item);
395 if (cmp < 0) {
396 Py_DECREF(it);
397 return NULL;
398 }
Raymond Hettinger5098b582015-10-09 00:42:47 -0400399 if (cmp > 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000400 Py_DECREF(it);
401 Py_RETURN_TRUE;
402 }
403 }
404 Py_DECREF(it);
405 if (PyErr_Occurred()) {
406 if (PyErr_ExceptionMatches(PyExc_StopIteration))
407 PyErr_Clear();
408 else
409 return NULL;
410 }
411 Py_RETURN_FALSE;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000412}
413
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000414/*[clinic input]
415ascii as builtin_ascii
416
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300417 obj: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000418 /
419
420Return an ASCII-only representation of an object.
421
422As repr(), return a string containing a printable representation of an
423object, but escape the non-ASCII characters in the string returned by
424repr() using \\x, \\u or \\U escapes. This generates a string similar
425to that returned by repr() in Python 2.
426[clinic start generated code]*/
427
Georg Brandl559e5d72008-06-11 18:37:52 +0000428static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300429builtin_ascii(PyObject *module, PyObject *obj)
430/*[clinic end generated code: output=6d37b3f0984c7eb9 input=4c62732e1b3a3cc9]*/
Georg Brandl559e5d72008-06-11 18:37:52 +0000431{
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000432 return PyObject_ASCII(obj);
Georg Brandl559e5d72008-06-11 18:37:52 +0000433}
434
Georg Brandl559e5d72008-06-11 18:37:52 +0000435
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000436/*[clinic input]
437bin as builtin_bin
438
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300439 number: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000440 /
441
442Return the binary representation of an integer.
443
444 >>> bin(2796202)
445 '0b1010101010101010101010'
446[clinic start generated code]*/
447
Guido van Rossum79f25d91997-04-29 20:08:16 +0000448static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300449builtin_bin(PyObject *module, PyObject *number)
450/*[clinic end generated code: output=b6fc4ad5e649f4f7 input=53f8a0264bacaf90]*/
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000451{
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000452 return PyNumber_ToBase(number, 2);
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000453}
454
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000455
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000456/*[clinic input]
457callable as builtin_callable
458
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300459 obj: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000460 /
461
462Return whether the object is callable (i.e., some kind of function).
463
464Note that classes are callable, as are instances of classes with a
465__call__() method.
466[clinic start generated code]*/
467
Antoine Pitroue71362d2010-11-27 22:00:11 +0000468static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300469builtin_callable(PyObject *module, PyObject *obj)
470/*[clinic end generated code: output=2b095d59d934cb7e input=1423bab99cc41f58]*/
Antoine Pitroue71362d2010-11-27 22:00:11 +0000471{
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000472 return PyBool_FromLong((long)PyCallable_Check(obj));
Antoine Pitroue71362d2010-11-27 22:00:11 +0000473}
474
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400475static PyObject *
Serhiy Storchakaa5552f02017-12-15 13:11:11 +0200476builtin_breakpoint(PyObject *self, PyObject *const *args, Py_ssize_t nargs, PyObject *keywords)
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400477{
478 PyObject *hook = PySys_GetObject("breakpointhook");
479
480 if (hook == NULL) {
481 PyErr_SetString(PyExc_RuntimeError, "lost sys.breakpointhook");
482 return NULL;
483 }
Steve Dower60419a72019-06-24 08:42:54 -0700484
485 if (PySys_Audit("builtins.breakpoint", "O", hook) < 0) {
486 return NULL;
487 }
488
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400489 Py_INCREF(hook);
Jeroen Demeyeraacc77f2019-05-29 20:31:52 +0200490 PyObject *retval = _PyObject_Vectorcall(hook, args, nargs, keywords);
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400491 Py_DECREF(hook);
492 return retval;
493}
494
495PyDoc_STRVAR(breakpoint_doc,
496"breakpoint(*args, **kws)\n\
497\n\
498Call sys.breakpointhook(*args, **kws). sys.breakpointhook() must accept\n\
499whatever arguments are passed.\n\
500\n\
501By default, this drops you into the pdb debugger.");
Antoine Pitroue71362d2010-11-27 22:00:11 +0000502
Raymond Hettinger17301e92008-03-13 00:19:26 +0000503typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000504 PyObject_HEAD
505 PyObject *func;
506 PyObject *it;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000507} filterobject;
508
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000509static PyObject *
Raymond Hettinger17301e92008-03-13 00:19:26 +0000510filter_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
Guido van Rossum12d12c51993-10-26 17:58:25 +0000511{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000512 PyObject *func, *seq;
513 PyObject *it;
514 filterobject *lz;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000515
Serhiy Storchaka6cca5c82017-06-08 14:41:19 +0300516 if (type == &PyFilter_Type && !_PyArg_NoKeywords("filter", kwds))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000517 return NULL;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000518
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000519 if (!PyArg_UnpackTuple(args, "filter", 2, 2, &func, &seq))
520 return NULL;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000521
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000522 /* Get iterator. */
523 it = PyObject_GetIter(seq);
524 if (it == NULL)
525 return NULL;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000526
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000527 /* create filterobject structure */
528 lz = (filterobject *)type->tp_alloc(type, 0);
529 if (lz == NULL) {
530 Py_DECREF(it);
531 return NULL;
532 }
533 Py_INCREF(func);
534 lz->func = func;
535 lz->it = it;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000536
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000537 return (PyObject *)lz;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000538}
539
540static void
541filter_dealloc(filterobject *lz)
542{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000543 PyObject_GC_UnTrack(lz);
544 Py_XDECREF(lz->func);
545 Py_XDECREF(lz->it);
546 Py_TYPE(lz)->tp_free(lz);
Raymond Hettinger17301e92008-03-13 00:19:26 +0000547}
548
549static int
550filter_traverse(filterobject *lz, visitproc visit, void *arg)
551{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000552 Py_VISIT(lz->it);
553 Py_VISIT(lz->func);
554 return 0;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000555}
556
557static PyObject *
558filter_next(filterobject *lz)
559{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000560 PyObject *item;
561 PyObject *it = lz->it;
562 long ok;
563 PyObject *(*iternext)(PyObject *);
Raymond Hettingerbd5f0e82015-10-09 01:34:08 -0400564 int checktrue = lz->func == Py_None || lz->func == (PyObject *)&PyBool_Type;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000565
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000566 iternext = *Py_TYPE(it)->tp_iternext;
567 for (;;) {
568 item = iternext(it);
569 if (item == NULL)
570 return NULL;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000571
Raymond Hettingerbd5f0e82015-10-09 01:34:08 -0400572 if (checktrue) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000573 ok = PyObject_IsTrue(item);
574 } else {
575 PyObject *good;
Jeroen Demeyer196a5302019-07-04 12:31:34 +0200576 good = _PyObject_CallOneArg(lz->func, item);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000577 if (good == NULL) {
578 Py_DECREF(item);
579 return NULL;
580 }
581 ok = PyObject_IsTrue(good);
582 Py_DECREF(good);
583 }
Antoine Pitrou6f430e42012-08-15 23:18:25 +0200584 if (ok > 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000585 return item;
586 Py_DECREF(item);
Antoine Pitrou6f430e42012-08-15 23:18:25 +0200587 if (ok < 0)
588 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000589 }
Guido van Rossum12d12c51993-10-26 17:58:25 +0000590}
591
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +0000592static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +0530593filter_reduce(filterobject *lz, PyObject *Py_UNUSED(ignored))
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +0000594{
595 return Py_BuildValue("O(OO)", Py_TYPE(lz), lz->func, lz->it);
596}
597
598PyDoc_STRVAR(reduce_doc, "Return state information for pickling.");
599
600static PyMethodDef filter_methods[] = {
601 {"__reduce__", (PyCFunction)filter_reduce, METH_NOARGS, reduce_doc},
602 {NULL, NULL} /* sentinel */
603};
604
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000605PyDoc_STRVAR(filter_doc,
Georg Brandld11ae5d2008-05-16 13:27:32 +0000606"filter(function or None, iterable) --> filter object\n\
Guido van Rossumc1f779c2007-07-03 08:25:58 +0000607\n\
Georg Brandld11ae5d2008-05-16 13:27:32 +0000608Return an iterator yielding those items of iterable for which function(item)\n\
Raymond Hettinger17301e92008-03-13 00:19:26 +0000609is true. If function is None, return the items that are true.");
610
611PyTypeObject PyFilter_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000612 PyVarObject_HEAD_INIT(&PyType_Type, 0)
613 "filter", /* tp_name */
614 sizeof(filterobject), /* tp_basicsize */
615 0, /* tp_itemsize */
616 /* methods */
617 (destructor)filter_dealloc, /* tp_dealloc */
Jeroen Demeyer530f5062019-05-31 04:13:39 +0200618 0, /* tp_vectorcall_offset */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000619 0, /* tp_getattr */
620 0, /* tp_setattr */
Jeroen Demeyer530f5062019-05-31 04:13:39 +0200621 0, /* tp_as_async */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000622 0, /* tp_repr */
623 0, /* tp_as_number */
624 0, /* tp_as_sequence */
625 0, /* tp_as_mapping */
626 0, /* tp_hash */
627 0, /* tp_call */
628 0, /* tp_str */
629 PyObject_GenericGetAttr, /* tp_getattro */
630 0, /* tp_setattro */
631 0, /* tp_as_buffer */
632 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
633 Py_TPFLAGS_BASETYPE, /* tp_flags */
634 filter_doc, /* tp_doc */
635 (traverseproc)filter_traverse, /* tp_traverse */
636 0, /* tp_clear */
637 0, /* tp_richcompare */
638 0, /* tp_weaklistoffset */
639 PyObject_SelfIter, /* tp_iter */
640 (iternextfunc)filter_next, /* tp_iternext */
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +0000641 filter_methods, /* tp_methods */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000642 0, /* tp_members */
643 0, /* tp_getset */
644 0, /* tp_base */
645 0, /* tp_dict */
646 0, /* tp_descr_get */
647 0, /* tp_descr_set */
648 0, /* tp_dictoffset */
649 0, /* tp_init */
650 PyType_GenericAlloc, /* tp_alloc */
651 filter_new, /* tp_new */
652 PyObject_GC_Del, /* tp_free */
Raymond Hettinger17301e92008-03-13 00:19:26 +0000653};
654
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000655
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000656/*[clinic input]
657format as builtin_format
658
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300659 value: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000660 format_spec: unicode(c_default="NULL") = ''
661 /
662
663Return value.__format__(format_spec)
664
Amit Kumar2e6bb442017-05-29 06:32:26 +0530665format_spec defaults to the empty string.
666See the Format Specification Mini-Language section of help('FORMATTING') for
667details.
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000668[clinic start generated code]*/
669
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000670static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300671builtin_format_impl(PyObject *module, PyObject *value, PyObject *format_spec)
Amit Kumar2e6bb442017-05-29 06:32:26 +0530672/*[clinic end generated code: output=2f40bdfa4954b077 input=88339c93ea522b33]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000673{
Eric Smith8fd3eba2008-02-17 19:48:00 +0000674 return PyObject_Format(value, format_spec);
Eric Smith8c663262007-08-25 02:26:07 +0000675}
676
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000677/*[clinic input]
678chr as builtin_chr
679
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300680 i: int
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000681 /
682
683Return a Unicode string of one character with ordinal i; 0 <= i <= 0x10ffff.
684[clinic start generated code]*/
685
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000686static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300687builtin_chr_impl(PyObject *module, int i)
688/*[clinic end generated code: output=c733afcd200afcb7 input=3f604ef45a70750d]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000689{
690 return PyUnicode_FromOrdinal(i);
691}
Guido van Rossum09095f32000-03-10 23:00:52 +0000692
693
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000694/*[clinic input]
695compile as builtin_compile
696
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300697 source: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000698 filename: object(converter="PyUnicode_FSDecoder")
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300699 mode: str
700 flags: int = 0
Serhiy Storchaka202fda52017-03-12 10:10:47 +0200701 dont_inherit: bool(accept={int}) = False
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300702 optimize: int = -1
Victor Stinnerefdf6ca2019-06-12 02:52:16 +0200703 *
704 _feature_version as feature_version: int = -1
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000705
706Compile source into a code object that can be executed by exec() or eval().
707
708The source code may represent a Python module, statement or expression.
709The filename will be used for run-time error messages.
710The mode must be 'exec' to compile a module, 'single' to compile a
711single (interactive) statement, or 'eval' to compile an expression.
712The flags argument, if present, controls which future statements influence
713the compilation of the code.
Serhiy Storchaka8b2e8b62015-05-30 11:30:39 +0300714The dont_inherit argument, if true, stops the compilation inheriting
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000715the effects of any future statements in effect in the code calling
Serhiy Storchaka8b2e8b62015-05-30 11:30:39 +0300716compile; if absent or false these statements do influence the compilation,
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000717in addition to any features explicitly specified.
718[clinic start generated code]*/
719
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000720static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300721builtin_compile_impl(PyObject *module, PyObject *source, PyObject *filename,
722 const char *mode, int flags, int dont_inherit,
Guido van Rossum495da292019-03-07 12:38:08 -0800723 int optimize, int feature_version)
Victor Stinnerefdf6ca2019-06-12 02:52:16 +0200724/*[clinic end generated code: output=b0c09c84f116d3d7 input=40171fb92c1d580d]*/
Guido van Rossum5b722181993-03-30 17:46:03 +0000725{
Martin Panter61d6e4a2015-11-07 02:56:11 +0000726 PyObject *source_copy;
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +0200727 const char *str;
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000728 int compile_mode = -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000729 int is_ast;
Guido van Rossumdcfcd142019-01-31 03:40:27 -0800730 int start[] = {Py_file_input, Py_eval_input, Py_single_input, Py_func_type_input};
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000731 PyObject *result;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000732
Victor Stinner37d66d72019-06-13 02:16:41 +0200733 PyCompilerFlags cf = _PyCompilerFlags_INIT;
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000734 cf.cf_flags = flags | PyCF_SOURCE_IS_UTF8;
Guido van Rossum495da292019-03-07 12:38:08 -0800735 if (feature_version >= 0 && (flags & PyCF_ONLY_AST)) {
736 cf.cf_feature_version = feature_version;
737 }
Tim Peters6cd6a822001-08-17 22:11:27 +0000738
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000739 if (flags &
Guido van Rossumdcfcd142019-01-31 03:40:27 -0800740 ~(PyCF_MASK | PyCF_MASK_OBSOLETE | PyCF_DONT_IMPLY_DEDENT | PyCF_ONLY_AST | PyCF_TYPE_COMMENTS))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000741 {
742 PyErr_SetString(PyExc_ValueError,
743 "compile(): unrecognised flags");
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000744 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000745 }
746 /* XXX Warn if (supplied_flags & PyCF_MASK_OBSOLETE) != 0? */
Tim Peters6cd6a822001-08-17 22:11:27 +0000747
Georg Brandl8334fd92010-12-04 10:26:46 +0000748 if (optimize < -1 || optimize > 2) {
749 PyErr_SetString(PyExc_ValueError,
750 "compile(): invalid optimize value");
751 goto error;
752 }
753
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000754 if (!dont_inherit) {
755 PyEval_MergeCompilerFlags(&cf);
756 }
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000757
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000758 if (strcmp(mode, "exec") == 0)
759 compile_mode = 0;
760 else if (strcmp(mode, "eval") == 0)
761 compile_mode = 1;
762 else if (strcmp(mode, "single") == 0)
763 compile_mode = 2;
Guido van Rossumdcfcd142019-01-31 03:40:27 -0800764 else if (strcmp(mode, "func_type") == 0) {
765 if (!(flags & PyCF_ONLY_AST)) {
766 PyErr_SetString(PyExc_ValueError,
767 "compile() mode 'func_type' requires flag PyCF_ONLY_AST");
768 goto error;
769 }
770 compile_mode = 3;
771 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000772 else {
Guido van Rossumdcfcd142019-01-31 03:40:27 -0800773 const char *msg;
774 if (flags & PyCF_ONLY_AST)
775 msg = "compile() mode must be 'exec', 'eval', 'single' or 'func_type'";
776 else
777 msg = "compile() mode must be 'exec', 'eval' or 'single'";
778 PyErr_SetString(PyExc_ValueError, msg);
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000779 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000780 }
Neal Norwitzdb4115f2008-03-31 04:20:05 +0000781
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000782 is_ast = PyAST_Check(source);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000783 if (is_ast == -1)
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000784 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000785 if (is_ast) {
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000786 if (flags & PyCF_ONLY_AST) {
787 Py_INCREF(source);
788 result = source;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000789 }
790 else {
791 PyArena *arena;
792 mod_ty mod;
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000793
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000794 arena = PyArena_New();
Stefan Krah07795df2012-08-20 17:19:50 +0200795 if (arena == NULL)
796 goto error;
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000797 mod = PyAST_obj2mod(source, arena, compile_mode);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000798 if (mod == NULL) {
799 PyArena_Free(arena);
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000800 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000801 }
Benjamin Peterson832bfe22011-08-09 16:15:04 -0500802 if (!PyAST_Validate(mod)) {
803 PyArena_Free(arena);
804 goto error;
805 }
Victor Stinner14e461d2013-08-26 22:28:21 +0200806 result = (PyObject*)PyAST_CompileObject(mod, filename,
807 &cf, optimize, arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000808 PyArena_Free(arena);
809 }
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000810 goto finally;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000811 }
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000812
Dino Viehland41540692019-05-28 16:21:17 -0700813 str = _Py_SourceAsString(source, "compile", "string, bytes or AST", &cf, &source_copy);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000814 if (str == NULL)
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000815 goto error;
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000816
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000817 result = Py_CompileStringObject(str, filename, start[compile_mode], &cf, optimize);
Martin Panter61d6e4a2015-11-07 02:56:11 +0000818 Py_XDECREF(source_copy);
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000819 goto finally;
820
821error:
822 result = NULL;
823finally:
Victor Stinner14e461d2013-08-26 22:28:21 +0200824 Py_DECREF(filename);
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000825 return result;
Guido van Rossum5b722181993-03-30 17:46:03 +0000826}
827
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000828/* AC: cannot convert yet, as needs PEP 457 group support in inspect */
Guido van Rossum79f25d91997-04-29 20:08:16 +0000829static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000830builtin_dir(PyObject *self, PyObject *args)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000831{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000832 PyObject *arg = NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000833
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000834 if (!PyArg_UnpackTuple(args, "dir", 0, 1, &arg))
835 return NULL;
836 return PyObject_Dir(arg);
Guido van Rossum3f5da241990-12-20 15:06:42 +0000837}
838
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000839PyDoc_STRVAR(dir_doc,
Tim Peters5d2b77c2001-09-03 05:47:38 +0000840"dir([object]) -> list of strings\n"
841"\n"
Georg Brandle32b4222007-03-10 22:13:27 +0000842"If called without an argument, return the names in the current scope.\n"
843"Else, return an alphabetized list of names comprising (some of) the attributes\n"
844"of the given object, and of attributes reachable from it.\n"
845"If the object supplies a method named __dir__, it will be used; otherwise\n"
846"the default dir() logic is used and returns:\n"
847" for a module object: the module's attributes.\n"
848" for a class object: its attributes, and recursively the attributes\n"
849" of its bases.\n"
Guido van Rossumd8faa362007-04-27 19:54:29 +0000850" for any other object: its attributes, its class's attributes, and\n"
Georg Brandle32b4222007-03-10 22:13:27 +0000851" recursively the attributes of its class's base classes.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000852
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000853/*[clinic input]
854divmod as builtin_divmod
Guido van Rossum6a00cd81995-01-07 12:39:01 +0000855
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300856 x: object
857 y: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000858 /
859
Zachary Ware7f227d92016-04-28 14:39:50 -0500860Return the tuple (x//y, x%y). Invariant: div*y + mod == x.
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000861[clinic start generated code]*/
862
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000863static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300864builtin_divmod_impl(PyObject *module, PyObject *x, PyObject *y)
865/*[clinic end generated code: output=b06d8a5f6e0c745e input=175ad9c84ff41a85]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000866{
867 return PyNumber_Divmod(x, y);
868}
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000869
870
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000871/*[clinic input]
872eval as builtin_eval
873
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300874 source: object
875 globals: object = None
876 locals: object = None
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000877 /
878
879Evaluate the given source in the context of globals and locals.
880
881The source may be a string representing a Python expression
882or a code object as returned by compile().
883The globals must be a dictionary and locals can be any mapping,
884defaulting to the current globals and locals.
885If only globals is given, locals defaults to it.
886[clinic start generated code]*/
887
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000888static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300889builtin_eval_impl(PyObject *module, PyObject *source, PyObject *globals,
Larry Hastings89964c42015-04-14 18:07:59 -0400890 PyObject *locals)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300891/*[clinic end generated code: output=0a0824aa70093116 input=11ee718a8640e527]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000892{
Martin Panter61d6e4a2015-11-07 02:56:11 +0000893 PyObject *result, *source_copy;
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +0200894 const char *str;
Guido van Rossum590baa41993-11-30 13:40:46 +0000895
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000896 if (locals != Py_None && !PyMapping_Check(locals)) {
897 PyErr_SetString(PyExc_TypeError, "locals must be a mapping");
898 return NULL;
899 }
900 if (globals != Py_None && !PyDict_Check(globals)) {
901 PyErr_SetString(PyExc_TypeError, PyMapping_Check(globals) ?
902 "globals must be a real dict; try eval(expr, {}, mapping)"
903 : "globals must be a dict");
904 return NULL;
905 }
906 if (globals == Py_None) {
907 globals = PyEval_GetGlobals();
Victor Stinner41bb43a2013-10-29 01:19:37 +0100908 if (locals == Py_None) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000909 locals = PyEval_GetLocals();
Victor Stinner41bb43a2013-10-29 01:19:37 +0100910 if (locals == NULL)
911 return NULL;
912 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000913 }
914 else if (locals == Py_None)
915 locals = globals;
Tim Peters9fa96be2001-08-17 23:04:59 +0000916
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000917 if (globals == NULL || locals == NULL) {
918 PyErr_SetString(PyExc_TypeError,
919 "eval must be given globals and locals "
920 "when called without a frame");
921 return NULL;
922 }
Georg Brandl77c85e62005-09-15 10:46:13 +0000923
Serhiy Storchakaa24107b2019-02-25 17:59:46 +0200924 if (_PyDict_GetItemIdWithError(globals, &PyId___builtins__) == NULL) {
Victor Stinnerb44562b2013-11-06 19:03:11 +0100925 if (_PyDict_SetItemId(globals, &PyId___builtins__,
926 PyEval_GetBuiltins()) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000927 return NULL;
928 }
Serhiy Storchakaa24107b2019-02-25 17:59:46 +0200929 else if (PyErr_Occurred()) {
930 return NULL;
931 }
Tim Peters9fa96be2001-08-17 23:04:59 +0000932
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000933 if (PyCode_Check(source)) {
Steve Dowerb82e17e2019-05-23 08:45:22 -0700934 if (PySys_Audit("exec", "O", source) < 0) {
935 return NULL;
936 }
937
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000938 if (PyCode_GetNumFree((PyCodeObject *)source) > 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000939 PyErr_SetString(PyExc_TypeError,
Steve Dowerb82e17e2019-05-23 08:45:22 -0700940 "code object passed to eval() may not contain free variables");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000941 return NULL;
942 }
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000943 return PyEval_EvalCode(source, globals, locals);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000944 }
Tim Peters9fa96be2001-08-17 23:04:59 +0000945
Victor Stinner37d66d72019-06-13 02:16:41 +0200946 PyCompilerFlags cf = _PyCompilerFlags_INIT;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000947 cf.cf_flags = PyCF_SOURCE_IS_UTF8;
Dino Viehland41540692019-05-28 16:21:17 -0700948 str = _Py_SourceAsString(source, "eval", "string, bytes or code", &cf, &source_copy);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000949 if (str == NULL)
950 return NULL;
Just van Rossum3aaf42c2003-02-10 08:21:10 +0000951
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000952 while (*str == ' ' || *str == '\t')
953 str++;
Tim Peters9fa96be2001-08-17 23:04:59 +0000954
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000955 (void)PyEval_MergeCompilerFlags(&cf);
956 result = PyRun_StringFlags(str, Py_eval_input, globals, locals, &cf);
Martin Panter61d6e4a2015-11-07 02:56:11 +0000957 Py_XDECREF(source_copy);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000958 return result;
Guido van Rossum3f5da241990-12-20 15:06:42 +0000959}
960
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000961/*[clinic input]
962exec as builtin_exec
963
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300964 source: object
965 globals: object = None
966 locals: object = None
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000967 /
968
969Execute the given source in the context of globals and locals.
970
971The source may be a string representing one or more Python statements
972or a code object as returned by compile().
973The globals must be a dictionary and locals can be any mapping,
974defaulting to the current globals and locals.
975If only globals is given, locals defaults to it.
976[clinic start generated code]*/
977
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000978static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300979builtin_exec_impl(PyObject *module, PyObject *source, PyObject *globals,
Larry Hastings89964c42015-04-14 18:07:59 -0400980 PyObject *locals)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300981/*[clinic end generated code: output=3c90efc6ab68ef5d input=01ca3e1c01692829]*/
Georg Brandl7cae87c2006-09-06 06:51:57 +0000982{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000983 PyObject *v;
Georg Brandl2cabc562008-08-28 07:57:16 +0000984
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000985 if (globals == Py_None) {
986 globals = PyEval_GetGlobals();
987 if (locals == Py_None) {
988 locals = PyEval_GetLocals();
Victor Stinner41bb43a2013-10-29 01:19:37 +0100989 if (locals == NULL)
990 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000991 }
992 if (!globals || !locals) {
993 PyErr_SetString(PyExc_SystemError,
994 "globals and locals cannot be NULL");
995 return NULL;
996 }
997 }
998 else if (locals == Py_None)
999 locals = globals;
Georg Brandl7cae87c2006-09-06 06:51:57 +00001000
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001001 if (!PyDict_Check(globals)) {
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001002 PyErr_Format(PyExc_TypeError, "exec() globals must be a dict, not %.100s",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001003 globals->ob_type->tp_name);
1004 return NULL;
1005 }
1006 if (!PyMapping_Check(locals)) {
1007 PyErr_Format(PyExc_TypeError,
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001008 "locals must be a mapping or None, not %.100s",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001009 locals->ob_type->tp_name);
1010 return NULL;
1011 }
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02001012 if (_PyDict_GetItemIdWithError(globals, &PyId___builtins__) == NULL) {
Victor Stinnerb44562b2013-11-06 19:03:11 +01001013 if (_PyDict_SetItemId(globals, &PyId___builtins__,
1014 PyEval_GetBuiltins()) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001015 return NULL;
1016 }
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02001017 else if (PyErr_Occurred()) {
1018 return NULL;
1019 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001020
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001021 if (PyCode_Check(source)) {
Steve Dowerb82e17e2019-05-23 08:45:22 -07001022 if (PySys_Audit("exec", "O", source) < 0) {
1023 return NULL;
1024 }
1025
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001026 if (PyCode_GetNumFree((PyCodeObject *)source) > 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001027 PyErr_SetString(PyExc_TypeError,
1028 "code object passed to exec() may not "
1029 "contain free variables");
1030 return NULL;
1031 }
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001032 v = PyEval_EvalCode(source, globals, locals);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001033 }
1034 else {
Martin Panter61d6e4a2015-11-07 02:56:11 +00001035 PyObject *source_copy;
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +02001036 const char *str;
Victor Stinner37d66d72019-06-13 02:16:41 +02001037 PyCompilerFlags cf = _PyCompilerFlags_INIT;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001038 cf.cf_flags = PyCF_SOURCE_IS_UTF8;
Dino Viehland41540692019-05-28 16:21:17 -07001039 str = _Py_SourceAsString(source, "exec",
Martin Panter61d6e4a2015-11-07 02:56:11 +00001040 "string, bytes or code", &cf,
1041 &source_copy);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001042 if (str == NULL)
1043 return NULL;
1044 if (PyEval_MergeCompilerFlags(&cf))
1045 v = PyRun_StringFlags(str, Py_file_input, globals,
1046 locals, &cf);
1047 else
1048 v = PyRun_String(str, Py_file_input, globals, locals);
Martin Panter61d6e4a2015-11-07 02:56:11 +00001049 Py_XDECREF(source_copy);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001050 }
1051 if (v == NULL)
1052 return NULL;
1053 Py_DECREF(v);
1054 Py_RETURN_NONE;
Georg Brandl7cae87c2006-09-06 06:51:57 +00001055}
1056
Georg Brandl7cae87c2006-09-06 06:51:57 +00001057
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001058/* AC: cannot convert yet, as needs PEP 457 group support in inspect */
Guido van Rossum79f25d91997-04-29 20:08:16 +00001059static PyObject *
Serhiy Storchakaa5552f02017-12-15 13:11:11 +02001060builtin_getattr(PyObject *self, PyObject *const *args, Py_ssize_t nargs)
Guido van Rossum33894be1992-01-27 16:53:09 +00001061{
Serhiy Storchaka79342662019-01-12 08:25:41 +02001062 PyObject *v, *name, *result;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001063
Serhiy Storchaka79342662019-01-12 08:25:41 +02001064 if (!_PyArg_CheckPositional("getattr", nargs, 2, 3))
Sylvain96c7c062017-06-15 17:05:23 +02001065 return NULL;
1066
Serhiy Storchaka79342662019-01-12 08:25:41 +02001067 v = args[0];
1068 name = args[1];
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001069 if (!PyUnicode_Check(name)) {
1070 PyErr_SetString(PyExc_TypeError,
1071 "getattr(): attribute name must be string");
1072 return NULL;
1073 }
Serhiy Storchaka79342662019-01-12 08:25:41 +02001074 if (nargs > 2) {
Serhiy Storchakaf320be72018-01-25 10:49:40 +02001075 if (_PyObject_LookupAttr(v, name, &result) == 0) {
Serhiy Storchaka79342662019-01-12 08:25:41 +02001076 PyObject *dflt = args[2];
INADA Naoki378edee2018-01-16 20:52:41 +09001077 Py_INCREF(dflt);
1078 return dflt;
1079 }
1080 }
1081 else {
1082 result = PyObject_GetAttr(v, name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001083 }
1084 return result;
Guido van Rossum9bfef441993-03-29 10:43:31 +00001085}
1086
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001087PyDoc_STRVAR(getattr_doc,
Guido van Rossum950ff291998-06-29 13:38:57 +00001088"getattr(object, name[, default]) -> value\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001089\n\
Guido van Rossum950ff291998-06-29 13:38:57 +00001090Get a named attribute from an object; getattr(x, 'y') is equivalent to x.y.\n\
1091When a default argument is given, it is returned when the attribute doesn't\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001092exist; without it, an exception is raised in that case.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001093
1094
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001095/*[clinic input]
1096globals as builtin_globals
1097
1098Return the dictionary containing the current scope's global variables.
1099
1100NOTE: Updates to this dictionary *will* affect name lookups in the current
1101global scope and vice-versa.
1102[clinic start generated code]*/
1103
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001104static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001105builtin_globals_impl(PyObject *module)
1106/*[clinic end generated code: output=e5dd1527067b94d2 input=9327576f92bb48ba]*/
Guido van Rossum872537c1995-07-07 22:43:42 +00001107{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001108 PyObject *d;
Guido van Rossum872537c1995-07-07 22:43:42 +00001109
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001110 d = PyEval_GetGlobals();
1111 Py_XINCREF(d);
1112 return d;
Guido van Rossum872537c1995-07-07 22:43:42 +00001113}
1114
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001115
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001116/*[clinic input]
1117hasattr as builtin_hasattr
1118
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001119 obj: object
1120 name: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001121 /
1122
1123Return whether the object has an attribute with the given name.
1124
1125This is done by calling getattr(obj, name) and catching AttributeError.
1126[clinic start generated code]*/
1127
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001128static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001129builtin_hasattr_impl(PyObject *module, PyObject *obj, PyObject *name)
1130/*[clinic end generated code: output=a7aff2090a4151e5 input=0faec9787d979542]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001131{
1132 PyObject *v;
1133
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001134 if (!PyUnicode_Check(name)) {
1135 PyErr_SetString(PyExc_TypeError,
1136 "hasattr(): attribute name must be string");
1137 return NULL;
1138 }
Serhiy Storchakaf320be72018-01-25 10:49:40 +02001139 if (_PyObject_LookupAttr(obj, name, &v) < 0) {
Benjamin Peterson17689992010-08-24 03:26:23 +00001140 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001141 }
Serhiy Storchakaf320be72018-01-25 10:49:40 +02001142 if (v == NULL) {
1143 Py_RETURN_FALSE;
1144 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001145 Py_DECREF(v);
Benjamin Peterson17689992010-08-24 03:26:23 +00001146 Py_RETURN_TRUE;
Guido van Rossum33894be1992-01-27 16:53:09 +00001147}
1148
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001149
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001150/* AC: gdb's integration with CPython relies on builtin_id having
1151 * the *exact* parameter names of "self" and "v", so we ensure we
1152 * preserve those name rather than using the AC defaults.
1153 */
1154/*[clinic input]
1155id as builtin_id
1156
Serhiy Storchaka24182a32016-05-05 16:21:35 +03001157 self: self(type="PyModuleDef *")
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001158 obj as v: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001159 /
1160
1161Return the identity of an object.
1162
1163This is guaranteed to be unique among simultaneously existing objects.
1164(CPython uses the object's memory address.)
1165[clinic start generated code]*/
1166
Guido van Rossum79f25d91997-04-29 20:08:16 +00001167static PyObject *
Serhiy Storchaka24182a32016-05-05 16:21:35 +03001168builtin_id(PyModuleDef *self, PyObject *v)
1169/*[clinic end generated code: output=0aa640785f697f65 input=5a534136419631f4]*/
Guido van Rossum5b722181993-03-30 17:46:03 +00001170{
Steve Dowerb82e17e2019-05-23 08:45:22 -07001171 PyObject *id = PyLong_FromVoidPtr(v);
1172
1173 if (id && PySys_Audit("builtins.id", "O", id) < 0) {
1174 Py_DECREF(id);
1175 return NULL;
1176 }
1177
1178 return id;
Guido van Rossum5b722181993-03-30 17:46:03 +00001179}
1180
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001181
Raymond Hettingera6c60372008-03-13 01:26:19 +00001182/* map object ************************************************************/
1183
1184typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001185 PyObject_HEAD
1186 PyObject *iters;
1187 PyObject *func;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001188} mapobject;
1189
Guido van Rossum79f25d91997-04-29 20:08:16 +00001190static PyObject *
Raymond Hettingera6c60372008-03-13 01:26:19 +00001191map_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
Guido van Rossum12d12c51993-10-26 17:58:25 +00001192{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001193 PyObject *it, *iters, *func;
1194 mapobject *lz;
1195 Py_ssize_t numargs, i;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001196
Serhiy Storchaka6cca5c82017-06-08 14:41:19 +03001197 if (type == &PyMap_Type && !_PyArg_NoKeywords("map", kwds))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001198 return NULL;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001199
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001200 numargs = PyTuple_Size(args);
1201 if (numargs < 2) {
1202 PyErr_SetString(PyExc_TypeError,
1203 "map() must have at least two arguments.");
1204 return NULL;
1205 }
Raymond Hettingera6c60372008-03-13 01:26:19 +00001206
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001207 iters = PyTuple_New(numargs-1);
1208 if (iters == NULL)
1209 return NULL;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001210
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001211 for (i=1 ; i<numargs ; i++) {
1212 /* Get iterator. */
1213 it = PyObject_GetIter(PyTuple_GET_ITEM(args, i));
1214 if (it == NULL) {
1215 Py_DECREF(iters);
1216 return NULL;
1217 }
1218 PyTuple_SET_ITEM(iters, i-1, it);
1219 }
Raymond Hettingera6c60372008-03-13 01:26:19 +00001220
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001221 /* create mapobject structure */
1222 lz = (mapobject *)type->tp_alloc(type, 0);
1223 if (lz == NULL) {
1224 Py_DECREF(iters);
1225 return NULL;
1226 }
1227 lz->iters = iters;
1228 func = PyTuple_GET_ITEM(args, 0);
1229 Py_INCREF(func);
1230 lz->func = func;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001231
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001232 return (PyObject *)lz;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001233}
1234
1235static void
1236map_dealloc(mapobject *lz)
1237{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001238 PyObject_GC_UnTrack(lz);
1239 Py_XDECREF(lz->iters);
1240 Py_XDECREF(lz->func);
1241 Py_TYPE(lz)->tp_free(lz);
Raymond Hettingera6c60372008-03-13 01:26:19 +00001242}
1243
1244static int
1245map_traverse(mapobject *lz, visitproc visit, void *arg)
1246{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001247 Py_VISIT(lz->iters);
1248 Py_VISIT(lz->func);
1249 return 0;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001250}
1251
1252static PyObject *
1253map_next(mapobject *lz)
1254{
Victor Stinnerbc08ab42016-12-15 12:40:53 +01001255 PyObject *small_stack[_PY_FASTCALL_SMALL_STACK];
Victor Stinnercdb5cee2016-08-24 01:45:13 +02001256 PyObject **stack;
1257 Py_ssize_t niters, nargs, i;
1258 PyObject *result = NULL;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001259
Victor Stinnercdb5cee2016-08-24 01:45:13 +02001260 niters = PyTuple_GET_SIZE(lz->iters);
1261 if (niters <= (Py_ssize_t)Py_ARRAY_LENGTH(small_stack)) {
1262 stack = small_stack;
1263 }
1264 else {
1265 stack = PyMem_Malloc(niters * sizeof(stack[0]));
1266 if (stack == NULL) {
1267 PyErr_NoMemory();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001268 return NULL;
1269 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001270 }
Victor Stinnercdb5cee2016-08-24 01:45:13 +02001271
1272 nargs = 0;
1273 for (i=0; i < niters; i++) {
1274 PyObject *it = PyTuple_GET_ITEM(lz->iters, i);
1275 PyObject *val = Py_TYPE(it)->tp_iternext(it);
1276 if (val == NULL) {
1277 goto exit;
1278 }
1279 stack[i] = val;
1280 nargs++;
1281 }
1282
1283 result = _PyObject_FastCall(lz->func, stack, nargs);
1284
1285exit:
1286 for (i=0; i < nargs; i++) {
1287 Py_DECREF(stack[i]);
1288 }
1289 if (stack != small_stack) {
1290 PyMem_Free(stack);
1291 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001292 return result;
Guido van Rossum12d12c51993-10-26 17:58:25 +00001293}
1294
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001295static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05301296map_reduce(mapobject *lz, PyObject *Py_UNUSED(ignored))
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001297{
1298 Py_ssize_t numargs = PyTuple_GET_SIZE(lz->iters);
1299 PyObject *args = PyTuple_New(numargs+1);
1300 Py_ssize_t i;
1301 if (args == NULL)
1302 return NULL;
1303 Py_INCREF(lz->func);
1304 PyTuple_SET_ITEM(args, 0, lz->func);
1305 for (i = 0; i<numargs; i++){
1306 PyObject *it = PyTuple_GET_ITEM(lz->iters, i);
1307 Py_INCREF(it);
1308 PyTuple_SET_ITEM(args, i+1, it);
1309 }
1310
1311 return Py_BuildValue("ON", Py_TYPE(lz), args);
1312}
1313
1314static PyMethodDef map_methods[] = {
1315 {"__reduce__", (PyCFunction)map_reduce, METH_NOARGS, reduce_doc},
1316 {NULL, NULL} /* sentinel */
1317};
1318
1319
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001320PyDoc_STRVAR(map_doc,
Raymond Hettingera6c60372008-03-13 01:26:19 +00001321"map(func, *iterables) --> map object\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001322\n\
Raymond Hettingera6c60372008-03-13 01:26:19 +00001323Make an iterator that computes the function using arguments from\n\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001324each of the iterables. Stops when the shortest iterable is exhausted.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001325
Raymond Hettingera6c60372008-03-13 01:26:19 +00001326PyTypeObject PyMap_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001327 PyVarObject_HEAD_INIT(&PyType_Type, 0)
1328 "map", /* tp_name */
1329 sizeof(mapobject), /* tp_basicsize */
1330 0, /* tp_itemsize */
1331 /* methods */
1332 (destructor)map_dealloc, /* tp_dealloc */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02001333 0, /* tp_vectorcall_offset */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001334 0, /* tp_getattr */
1335 0, /* tp_setattr */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02001336 0, /* tp_as_async */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001337 0, /* tp_repr */
1338 0, /* tp_as_number */
1339 0, /* tp_as_sequence */
1340 0, /* tp_as_mapping */
1341 0, /* tp_hash */
1342 0, /* tp_call */
1343 0, /* tp_str */
1344 PyObject_GenericGetAttr, /* tp_getattro */
1345 0, /* tp_setattro */
1346 0, /* tp_as_buffer */
1347 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
1348 Py_TPFLAGS_BASETYPE, /* tp_flags */
1349 map_doc, /* tp_doc */
1350 (traverseproc)map_traverse, /* tp_traverse */
1351 0, /* tp_clear */
1352 0, /* tp_richcompare */
1353 0, /* tp_weaklistoffset */
1354 PyObject_SelfIter, /* tp_iter */
1355 (iternextfunc)map_next, /* tp_iternext */
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001356 map_methods, /* tp_methods */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001357 0, /* tp_members */
1358 0, /* tp_getset */
1359 0, /* tp_base */
1360 0, /* tp_dict */
1361 0, /* tp_descr_get */
1362 0, /* tp_descr_set */
1363 0, /* tp_dictoffset */
1364 0, /* tp_init */
1365 PyType_GenericAlloc, /* tp_alloc */
1366 map_new, /* tp_new */
1367 PyObject_GC_Del, /* tp_free */
Raymond Hettingera6c60372008-03-13 01:26:19 +00001368};
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001369
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001370
1371/* AC: cannot convert yet, as needs PEP 457 group support in inspect */
Guido van Rossum79f25d91997-04-29 20:08:16 +00001372static PyObject *
Serhiy Storchakaa5552f02017-12-15 13:11:11 +02001373builtin_next(PyObject *self, PyObject *const *args, Py_ssize_t nargs)
Georg Brandla18af4e2007-04-21 15:47:16 +00001374{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001375 PyObject *it, *res;
Georg Brandla18af4e2007-04-21 15:47:16 +00001376
Serhiy Storchaka79342662019-01-12 08:25:41 +02001377 if (!_PyArg_CheckPositional("next", nargs, 1, 2))
Sylvain96c7c062017-06-15 17:05:23 +02001378 return NULL;
1379
Serhiy Storchaka79342662019-01-12 08:25:41 +02001380 it = args[0];
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001381 if (!PyIter_Check(it)) {
1382 PyErr_Format(PyExc_TypeError,
Philip Jenvey50add042011-11-06 16:37:52 -08001383 "'%.200s' object is not an iterator",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001384 it->ob_type->tp_name);
1385 return NULL;
1386 }
1387
1388 res = (*it->ob_type->tp_iternext)(it);
1389 if (res != NULL) {
1390 return res;
Serhiy Storchaka79342662019-01-12 08:25:41 +02001391 } else if (nargs > 1) {
1392 PyObject *def = args[1];
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001393 if (PyErr_Occurred()) {
1394 if(!PyErr_ExceptionMatches(PyExc_StopIteration))
1395 return NULL;
1396 PyErr_Clear();
1397 }
1398 Py_INCREF(def);
1399 return def;
1400 } else if (PyErr_Occurred()) {
1401 return NULL;
1402 } else {
1403 PyErr_SetNone(PyExc_StopIteration);
1404 return NULL;
1405 }
Georg Brandla18af4e2007-04-21 15:47:16 +00001406}
1407
1408PyDoc_STRVAR(next_doc,
1409"next(iterator[, default])\n\
1410\n\
1411Return the next item from the iterator. If default is given and the iterator\n\
1412is exhausted, it is returned instead of raising StopIteration.");
1413
1414
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001415/*[clinic input]
1416setattr as builtin_setattr
1417
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001418 obj: object
1419 name: object
1420 value: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001421 /
1422
1423Sets the named attribute on the given object to the specified value.
1424
1425setattr(x, 'y', v) is equivalent to ``x.y = v''
1426[clinic start generated code]*/
1427
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001428static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001429builtin_setattr_impl(PyObject *module, PyObject *obj, PyObject *name,
Larry Hastings89964c42015-04-14 18:07:59 -04001430 PyObject *value)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001431/*[clinic end generated code: output=dc2ce1d1add9acb4 input=bd2b7ca6875a1899]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001432{
1433 if (PyObject_SetAttr(obj, name, value) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001434 return NULL;
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02001435 Py_RETURN_NONE;
Guido van Rossum33894be1992-01-27 16:53:09 +00001436}
1437
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001438
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001439/*[clinic input]
1440delattr as builtin_delattr
1441
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001442 obj: object
1443 name: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001444 /
1445
1446Deletes the named attribute from the given object.
1447
1448delattr(x, 'y') is equivalent to ``del x.y''
1449[clinic start generated code]*/
1450
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001451static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001452builtin_delattr_impl(PyObject *module, PyObject *obj, PyObject *name)
1453/*[clinic end generated code: output=85134bc58dff79fa input=db16685d6b4b9410]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001454{
1455 if (PyObject_SetAttr(obj, name, (PyObject *)NULL) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001456 return NULL;
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02001457 Py_RETURN_NONE;
Guido van Rossum14144fc1994-08-29 12:53:40 +00001458}
1459
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001460
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001461/*[clinic input]
1462hash as builtin_hash
1463
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001464 obj: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001465 /
1466
1467Return the hash value for the given object.
1468
1469Two objects that compare equal must also have the same hash value, but the
1470reverse is not necessarily true.
1471[clinic start generated code]*/
1472
Guido van Rossum79f25d91997-04-29 20:08:16 +00001473static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001474builtin_hash(PyObject *module, PyObject *obj)
1475/*[clinic end generated code: output=237668e9d7688db7 input=58c48be822bf9c54]*/
Guido van Rossum9bfef441993-03-29 10:43:31 +00001476{
Benjamin Peterson8f67d082010-10-17 20:54:53 +00001477 Py_hash_t x;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001478
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001479 x = PyObject_Hash(obj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001480 if (x == -1)
1481 return NULL;
Benjamin Peterson8f67d082010-10-17 20:54:53 +00001482 return PyLong_FromSsize_t(x);
Guido van Rossum9bfef441993-03-29 10:43:31 +00001483}
1484
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001485
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001486/*[clinic input]
1487hex as builtin_hex
1488
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001489 number: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001490 /
1491
1492Return the hexadecimal representation of an integer.
1493
1494 >>> hex(12648430)
1495 '0xc0ffee'
1496[clinic start generated code]*/
1497
Guido van Rossum79f25d91997-04-29 20:08:16 +00001498static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001499builtin_hex(PyObject *module, PyObject *number)
1500/*[clinic end generated code: output=e46b612169099408 input=e645aff5fc7d540e]*/
Guido van Rossum006bcd41991-10-24 14:54:44 +00001501{
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001502 return PyNumber_ToBase(number, 16);
Guido van Rossum006bcd41991-10-24 14:54:44 +00001503}
1504
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001505
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001506/* AC: cannot convert yet, as needs PEP 457 group support in inspect */
Guido van Rossum79f25d91997-04-29 20:08:16 +00001507static PyObject *
Serhiy Storchaka79342662019-01-12 08:25:41 +02001508builtin_iter(PyObject *self, PyObject *const *args, Py_ssize_t nargs)
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001509{
Serhiy Storchaka79342662019-01-12 08:25:41 +02001510 PyObject *v;
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001511
Serhiy Storchaka79342662019-01-12 08:25:41 +02001512 if (!_PyArg_CheckPositional("iter", nargs, 1, 2))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001513 return NULL;
Serhiy Storchaka79342662019-01-12 08:25:41 +02001514 v = args[0];
1515 if (nargs == 1)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001516 return PyObject_GetIter(v);
1517 if (!PyCallable_Check(v)) {
1518 PyErr_SetString(PyExc_TypeError,
1519 "iter(v, w): v must be callable");
1520 return NULL;
1521 }
Serhiy Storchaka79342662019-01-12 08:25:41 +02001522 PyObject *sentinel = args[1];
1523 return PyCallIter_New(v, sentinel);
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001524}
1525
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001526PyDoc_STRVAR(iter_doc,
Georg Brandld11ae5d2008-05-16 13:27:32 +00001527"iter(iterable) -> iterator\n\
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001528iter(callable, sentinel) -> iterator\n\
1529\n\
1530Get an iterator from an object. In the first form, the argument must\n\
1531supply its own iterator, or be a sequence.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001532In the second form, the callable is called until it returns the sentinel.");
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001533
1534
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001535/*[clinic input]
1536len as builtin_len
1537
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001538 obj: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001539 /
1540
1541Return the number of items in a container.
1542[clinic start generated code]*/
1543
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001544static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001545builtin_len(PyObject *module, PyObject *obj)
1546/*[clinic end generated code: output=fa7a270d314dfb6c input=bc55598da9e9c9b5]*/
Guido van Rossum3f5da241990-12-20 15:06:42 +00001547{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001548 Py_ssize_t res;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001549
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001550 res = PyObject_Size(obj);
Serhiy Storchaka813f9432017-04-16 09:21:44 +03001551 if (res < 0) {
1552 assert(PyErr_Occurred());
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001553 return NULL;
Serhiy Storchaka813f9432017-04-16 09:21:44 +03001554 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001555 return PyLong_FromSsize_t(res);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001556}
1557
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001558
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001559/*[clinic input]
1560locals as builtin_locals
1561
1562Return a dictionary containing the current scope's local variables.
1563
1564NOTE: Whether or not updates to this dictionary will affect name lookups in
1565the local scope and vice-versa is *implementation dependent* and not
1566covered by any backwards compatibility guarantees.
1567[clinic start generated code]*/
1568
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001569static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001570builtin_locals_impl(PyObject *module)
1571/*[clinic end generated code: output=b46c94015ce11448 input=7874018d478d5c4b]*/
Guido van Rossum872537c1995-07-07 22:43:42 +00001572{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001573 PyObject *d;
Guido van Rossum872537c1995-07-07 22:43:42 +00001574
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001575 d = PyEval_GetLocals();
1576 Py_XINCREF(d);
1577 return d;
Guido van Rossum872537c1995-07-07 22:43:42 +00001578}
1579
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001580
Guido van Rossum79f25d91997-04-29 20:08:16 +00001581static PyObject *
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001582min_max(PyObject *args, PyObject *kwds, int op)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001583{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001584 PyObject *v, *it, *item, *val, *maxitem, *maxval, *keyfunc=NULL;
Raymond Hettinger4d6018f2013-06-24 22:43:02 -07001585 PyObject *emptytuple, *defaultval = NULL;
1586 static char *kwlist[] = {"key", "default", NULL};
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001587 const char *name = op == Py_LT ? "min" : "max";
Raymond Hettinger4d6018f2013-06-24 22:43:02 -07001588 const int positional = PyTuple_Size(args) > 1;
1589 int ret;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001590
Raymond Hettinger4d6018f2013-06-24 22:43:02 -07001591 if (positional)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001592 v = args;
Serhiy Storchakac6792272013-10-19 21:03:34 +03001593 else if (!PyArg_UnpackTuple(args, name, 1, 1, &v))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001594 return NULL;
Tim Peters67d687a2002-04-29 21:27:32 +00001595
Raymond Hettinger4d6018f2013-06-24 22:43:02 -07001596 emptytuple = PyTuple_New(0);
1597 if (emptytuple == NULL)
1598 return NULL;
Oren Milman58cf7482017-08-21 20:19:07 +03001599 ret = PyArg_ParseTupleAndKeywords(emptytuple, kwds,
1600 (op == Py_LT) ? "|$OO:min" : "|$OO:max",
1601 kwlist, &keyfunc, &defaultval);
Raymond Hettinger4d6018f2013-06-24 22:43:02 -07001602 Py_DECREF(emptytuple);
1603 if (!ret)
1604 return NULL;
1605
1606 if (positional && defaultval != NULL) {
1607 PyErr_Format(PyExc_TypeError,
1608 "Cannot specify a default for %s() with multiple "
1609 "positional arguments", name);
1610 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001611 }
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001612
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001613 it = PyObject_GetIter(v);
1614 if (it == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001615 return NULL;
1616 }
Tim Petersc3074532001-05-03 07:00:32 +00001617
Alexander Marshalove22072f2018-07-24 10:58:21 +07001618 if (keyfunc == Py_None) {
1619 keyfunc = NULL;
1620 }
1621
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001622 maxitem = NULL; /* the result */
1623 maxval = NULL; /* the value associated with the result */
1624 while (( item = PyIter_Next(it) )) {
1625 /* get the value from the key function */
1626 if (keyfunc != NULL) {
Jeroen Demeyer196a5302019-07-04 12:31:34 +02001627 val = _PyObject_CallOneArg(keyfunc, item);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001628 if (val == NULL)
1629 goto Fail_it_item;
1630 }
1631 /* no key function; the value is the item */
1632 else {
1633 val = item;
1634 Py_INCREF(val);
1635 }
Tim Petersc3074532001-05-03 07:00:32 +00001636
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001637 /* maximum value and item are unset; set them */
1638 if (maxval == NULL) {
1639 maxitem = item;
1640 maxval = val;
1641 }
1642 /* maximum value and item are set; update them as necessary */
1643 else {
1644 int cmp = PyObject_RichCompareBool(val, maxval, op);
1645 if (cmp < 0)
1646 goto Fail_it_item_and_val;
1647 else if (cmp > 0) {
1648 Py_DECREF(maxval);
1649 Py_DECREF(maxitem);
1650 maxval = val;
1651 maxitem = item;
1652 }
1653 else {
1654 Py_DECREF(item);
1655 Py_DECREF(val);
1656 }
1657 }
1658 }
1659 if (PyErr_Occurred())
1660 goto Fail_it;
1661 if (maxval == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001662 assert(maxitem == NULL);
Raymond Hettinger4d6018f2013-06-24 22:43:02 -07001663 if (defaultval != NULL) {
1664 Py_INCREF(defaultval);
1665 maxitem = defaultval;
1666 } else {
1667 PyErr_Format(PyExc_ValueError,
1668 "%s() arg is an empty sequence", name);
1669 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001670 }
1671 else
1672 Py_DECREF(maxval);
1673 Py_DECREF(it);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001674 return maxitem;
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001675
1676Fail_it_item_and_val:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001677 Py_DECREF(val);
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001678Fail_it_item:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001679 Py_DECREF(item);
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001680Fail_it:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001681 Py_XDECREF(maxval);
1682 Py_XDECREF(maxitem);
1683 Py_DECREF(it);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001684 return NULL;
Guido van Rossum3f5da241990-12-20 15:06:42 +00001685}
1686
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001687/* AC: cannot convert yet, waiting for *args support */
Guido van Rossum79f25d91997-04-29 20:08:16 +00001688static PyObject *
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001689builtin_min(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001690{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001691 return min_max(args, kwds, Py_LT);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001692}
1693
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001694PyDoc_STRVAR(min_doc,
Raymond Hettinger2a545822014-05-19 22:20:52 +01001695"min(iterable, *[, default=obj, key=func]) -> value\n\
1696min(arg1, arg2, *args, *[, key=func]) -> value\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001697\n\
Raymond Hettinger2a545822014-05-19 22:20:52 +01001698With a single iterable argument, return its smallest item. The\n\
1699default keyword-only argument specifies an object to return if\n\
1700the provided iterable is empty.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001701With two or more arguments, return the smallest argument.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001702
1703
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001704/* AC: cannot convert yet, waiting for *args support */
Guido van Rossum79f25d91997-04-29 20:08:16 +00001705static PyObject *
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001706builtin_max(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001707{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001708 return min_max(args, kwds, Py_GT);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001709}
1710
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001711PyDoc_STRVAR(max_doc,
Raymond Hettinger2a545822014-05-19 22:20:52 +01001712"max(iterable, *[, default=obj, key=func]) -> value\n\
1713max(arg1, arg2, *args, *[, key=func]) -> value\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001714\n\
Raymond Hettinger2a545822014-05-19 22:20:52 +01001715With a single iterable argument, return its biggest item. The\n\
1716default keyword-only argument specifies an object to return if\n\
1717the provided iterable is empty.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001718With two or more arguments, return the largest argument.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001719
1720
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001721/*[clinic input]
1722oct as builtin_oct
1723
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001724 number: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001725 /
1726
1727Return the octal representation of an integer.
1728
1729 >>> oct(342391)
1730 '0o1234567'
1731[clinic start generated code]*/
1732
Guido van Rossum79f25d91997-04-29 20:08:16 +00001733static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001734builtin_oct(PyObject *module, PyObject *number)
1735/*[clinic end generated code: output=40a34656b6875352 input=ad6b274af4016c72]*/
Guido van Rossum006bcd41991-10-24 14:54:44 +00001736{
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001737 return PyNumber_ToBase(number, 8);
Guido van Rossum006bcd41991-10-24 14:54:44 +00001738}
1739
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001740
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001741/*[clinic input]
1742ord as builtin_ord
1743
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001744 c: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001745 /
1746
1747Return the Unicode code point for a one-character string.
1748[clinic start generated code]*/
1749
Guido van Rossum79f25d91997-04-29 20:08:16 +00001750static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001751builtin_ord(PyObject *module, PyObject *c)
1752/*[clinic end generated code: output=4fa5e87a323bae71 input=3064e5d6203ad012]*/
Guido van Rossum3f5da241990-12-20 15:06:42 +00001753{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001754 long ord;
1755 Py_ssize_t size;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001756
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001757 if (PyBytes_Check(c)) {
1758 size = PyBytes_GET_SIZE(c);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001759 if (size == 1) {
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001760 ord = (long)((unsigned char)*PyBytes_AS_STRING(c));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001761 return PyLong_FromLong(ord);
1762 }
1763 }
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001764 else if (PyUnicode_Check(c)) {
1765 if (PyUnicode_READY(c) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001766 return NULL;
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001767 size = PyUnicode_GET_LENGTH(c);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001768 if (size == 1) {
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001769 ord = (long)PyUnicode_READ_CHAR(c, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001770 return PyLong_FromLong(ord);
1771 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001772 }
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001773 else if (PyByteArray_Check(c)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001774 /* XXX Hopefully this is temporary */
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001775 size = PyByteArray_GET_SIZE(c);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001776 if (size == 1) {
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001777 ord = (long)((unsigned char)*PyByteArray_AS_STRING(c));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001778 return PyLong_FromLong(ord);
1779 }
1780 }
1781 else {
1782 PyErr_Format(PyExc_TypeError,
1783 "ord() expected string of length 1, but " \
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001784 "%.200s found", c->ob_type->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001785 return NULL;
1786 }
Guido van Rossum09095f32000-03-10 23:00:52 +00001787
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001788 PyErr_Format(PyExc_TypeError,
1789 "ord() expected a character, "
1790 "but string of length %zd found",
1791 size);
1792 return NULL;
Guido van Rossum3f5da241990-12-20 15:06:42 +00001793}
1794
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001795
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001796/*[clinic input]
1797pow as builtin_pow
1798
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001799 x: object
1800 y: object
1801 z: object = None
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001802 /
1803
1804Equivalent to x**y (with two arguments) or x**y % z (with three arguments)
1805
1806Some types, such as ints, are able to use a more efficient algorithm when
1807invoked using the three argument form.
1808[clinic start generated code]*/
1809
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001810static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001811builtin_pow_impl(PyObject *module, PyObject *x, PyObject *y, PyObject *z)
1812/*[clinic end generated code: output=50a14d5d130d404b input=653d57d38d41fc07]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001813{
1814 return PyNumber_Power(x, y, z);
1815}
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001816
1817
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001818/* AC: cannot convert yet, waiting for *args support */
Guido van Rossum34343512006-11-30 22:13:52 +00001819static PyObject *
Serhiy Storchakaa5552f02017-12-15 13:11:11 +02001820builtin_print(PyObject *self, PyObject *const *args, Py_ssize_t nargs, PyObject *kwnames)
Guido van Rossum34343512006-11-30 22:13:52 +00001821{
INADA Naokibd584f12017-01-19 12:50:34 +01001822 static const char * const _keywords[] = {"sep", "end", "file", "flush", 0};
Serhiy Storchaka1f21eaa2019-09-01 12:16:51 +03001823 static struct _PyArg_Parser _parser = {"|OOOp:print", _keywords, 0};
1824 PyObject *sep = NULL, *end = NULL, *file = NULL;
1825 int flush = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001826 int i, err;
Guido van Rossum34343512006-11-30 22:13:52 +00001827
INADA Naokibd584f12017-01-19 12:50:34 +01001828 if (kwnames != NULL &&
1829 !_PyArg_ParseStackAndKeywords(args + nargs, 0, kwnames, &_parser,
1830 &sep, &end, &file, &flush)) {
Georg Brandlbc3b6822012-01-13 19:41:25 +01001831 return NULL;
INADA Naokibd584f12017-01-19 12:50:34 +01001832 }
1833
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001834 if (file == NULL || file == Py_None) {
Victor Stinnerbd303c12013-11-07 23:07:29 +01001835 file = _PySys_GetObjectId(&PyId_stdout);
Victor Stinner1e53bba2013-07-16 22:26:05 +02001836 if (file == NULL) {
1837 PyErr_SetString(PyExc_RuntimeError, "lost sys.stdout");
1838 return NULL;
1839 }
1840
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001841 /* sys.stdout may be None when FILE* stdout isn't connected */
1842 if (file == Py_None)
1843 Py_RETURN_NONE;
1844 }
Guido van Rossum34343512006-11-30 22:13:52 +00001845
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001846 if (sep == Py_None) {
1847 sep = NULL;
1848 }
1849 else if (sep && !PyUnicode_Check(sep)) {
1850 PyErr_Format(PyExc_TypeError,
1851 "sep must be None or a string, not %.200s",
1852 sep->ob_type->tp_name);
1853 return NULL;
1854 }
1855 if (end == Py_None) {
1856 end = NULL;
1857 }
1858 else if (end && !PyUnicode_Check(end)) {
1859 PyErr_Format(PyExc_TypeError,
1860 "end must be None or a string, not %.200s",
1861 end->ob_type->tp_name);
1862 return NULL;
1863 }
Guido van Rossum34343512006-11-30 22:13:52 +00001864
INADA Naokibd584f12017-01-19 12:50:34 +01001865 for (i = 0; i < nargs; i++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001866 if (i > 0) {
1867 if (sep == NULL)
1868 err = PyFile_WriteString(" ", file);
1869 else
1870 err = PyFile_WriteObject(sep, file,
1871 Py_PRINT_RAW);
1872 if (err)
1873 return NULL;
1874 }
INADA Naokibd584f12017-01-19 12:50:34 +01001875 err = PyFile_WriteObject(args[i], file, Py_PRINT_RAW);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001876 if (err)
1877 return NULL;
1878 }
Guido van Rossum34343512006-11-30 22:13:52 +00001879
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001880 if (end == NULL)
1881 err = PyFile_WriteString("\n", file);
1882 else
1883 err = PyFile_WriteObject(end, file, Py_PRINT_RAW);
1884 if (err)
1885 return NULL;
Guido van Rossum34343512006-11-30 22:13:52 +00001886
Serhiy Storchaka1f21eaa2019-09-01 12:16:51 +03001887 if (flush) {
1888 PyObject *tmp = _PyObject_CallMethodIdNoArgs(file, &PyId_flush);
1889 if (tmp == NULL)
Georg Brandlbc3b6822012-01-13 19:41:25 +01001890 return NULL;
Serhiy Storchaka1f21eaa2019-09-01 12:16:51 +03001891 Py_DECREF(tmp);
Georg Brandlbc3b6822012-01-13 19:41:25 +01001892 }
1893
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001894 Py_RETURN_NONE;
Guido van Rossum34343512006-11-30 22:13:52 +00001895}
1896
1897PyDoc_STRVAR(print_doc,
Senthil Kumarane9175bd2012-08-10 13:53:45 -07001898"print(value, ..., sep=' ', end='\\n', file=sys.stdout, flush=False)\n\
Guido van Rossum34343512006-11-30 22:13:52 +00001899\n\
1900Prints the values to a stream, or to sys.stdout by default.\n\
1901Optional keyword arguments:\n\
Senthil Kumarane9175bd2012-08-10 13:53:45 -07001902file: a file-like object (stream); defaults to the current sys.stdout.\n\
1903sep: string inserted between values, default a space.\n\
1904end: string appended after the last value, default a newline.\n\
1905flush: whether to forcibly flush the stream.");
Guido van Rossum34343512006-11-30 22:13:52 +00001906
1907
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001908/*[clinic input]
1909input as builtin_input
1910
1911 prompt: object(c_default="NULL") = None
1912 /
1913
1914Read a string from standard input. The trailing newline is stripped.
1915
1916The prompt string, if given, is printed to standard output without a
1917trailing newline before reading input.
1918
1919If the user hits EOF (*nix: Ctrl-D, Windows: Ctrl-Z+Return), raise EOFError.
1920On *nix systems, readline is used if available.
1921[clinic start generated code]*/
1922
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001923static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001924builtin_input_impl(PyObject *module, PyObject *prompt)
1925/*[clinic end generated code: output=83db5a191e7a0d60 input=5e8bb70c2908fe3c]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001926{
Victor Stinnerbd303c12013-11-07 23:07:29 +01001927 PyObject *fin = _PySys_GetObjectId(&PyId_stdin);
1928 PyObject *fout = _PySys_GetObjectId(&PyId_stdout);
1929 PyObject *ferr = _PySys_GetObjectId(&PyId_stderr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001930 PyObject *tmp;
1931 long fd;
1932 int tty;
Guido van Rossuma88a0332007-02-26 16:59:55 +00001933
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001934 /* Check that stdin/out/err are intact */
1935 if (fin == NULL || fin == Py_None) {
1936 PyErr_SetString(PyExc_RuntimeError,
1937 "input(): lost sys.stdin");
1938 return NULL;
1939 }
1940 if (fout == NULL || fout == Py_None) {
1941 PyErr_SetString(PyExc_RuntimeError,
1942 "input(): lost sys.stdout");
1943 return NULL;
1944 }
1945 if (ferr == NULL || ferr == Py_None) {
1946 PyErr_SetString(PyExc_RuntimeError,
1947 "input(): lost sys.stderr");
1948 return NULL;
1949 }
Guido van Rossumeba76962007-05-27 09:13:28 +00001950
Steve Dowerb82e17e2019-05-23 08:45:22 -07001951 if (PySys_Audit("builtins.input", "O", prompt ? prompt : Py_None) < 0) {
1952 return NULL;
1953 }
1954
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001955 /* First of all, flush stderr */
Jeroen Demeyer762f93f2019-07-08 10:19:25 +02001956 tmp = _PyObject_CallMethodIdNoArgs(ferr, &PyId_flush);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001957 if (tmp == NULL)
1958 PyErr_Clear();
1959 else
1960 Py_DECREF(tmp);
Guido van Rossumeba76962007-05-27 09:13:28 +00001961
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001962 /* We should only use (GNU) readline if Python's sys.stdin and
1963 sys.stdout are the same as C's stdin and stdout, because we
1964 need to pass it those. */
Jeroen Demeyer762f93f2019-07-08 10:19:25 +02001965 tmp = _PyObject_CallMethodIdNoArgs(fin, &PyId_fileno);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001966 if (tmp == NULL) {
1967 PyErr_Clear();
1968 tty = 0;
1969 }
1970 else {
1971 fd = PyLong_AsLong(tmp);
1972 Py_DECREF(tmp);
1973 if (fd < 0 && PyErr_Occurred())
1974 return NULL;
1975 tty = fd == fileno(stdin) && isatty(fd);
1976 }
1977 if (tty) {
Jeroen Demeyer762f93f2019-07-08 10:19:25 +02001978 tmp = _PyObject_CallMethodIdNoArgs(fout, &PyId_fileno);
Martin Panterc9a6ab52015-10-10 01:25:38 +00001979 if (tmp == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001980 PyErr_Clear();
Martin Panterc9a6ab52015-10-10 01:25:38 +00001981 tty = 0;
1982 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001983 else {
1984 fd = PyLong_AsLong(tmp);
1985 Py_DECREF(tmp);
1986 if (fd < 0 && PyErr_Occurred())
1987 return NULL;
1988 tty = fd == fileno(stdout) && isatty(fd);
1989 }
1990 }
Guido van Rossumeba76962007-05-27 09:13:28 +00001991
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001992 /* If we're interactive, use (GNU) readline */
1993 if (tty) {
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001994 PyObject *po = NULL;
Serhiy Storchakae2f92de2017-11-11 13:06:26 +02001995 const char *promptstr;
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001996 char *s = NULL;
1997 PyObject *stdin_encoding = NULL, *stdin_errors = NULL;
1998 PyObject *stdout_encoding = NULL, *stdout_errors = NULL;
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +02001999 const char *stdin_encoding_str, *stdin_errors_str;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002000 PyObject *result;
Victor Stinnerc0f1a1a2011-02-23 12:07:37 +00002001 size_t len;
Martin v. Löwis4a7b5d52007-09-04 05:24:49 +00002002
Serhiy Storchakac2cf1282017-03-12 13:50:36 +02002003 /* stdin is a text stream, so it must have an encoding. */
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02002004 stdin_encoding = _PyObject_GetAttrId(fin, &PyId_encoding);
Antoine Pitrou5ee9d8a2011-11-06 00:38:45 +01002005 stdin_errors = _PyObject_GetAttrId(fin, &PyId_errors);
Serhiy Storchakac2cf1282017-03-12 13:50:36 +02002006 if (!stdin_encoding || !stdin_errors ||
2007 !PyUnicode_Check(stdin_encoding) ||
2008 !PyUnicode_Check(stdin_errors)) {
2009 tty = 0;
Antoine Pitrou0d776b12011-11-06 00:34:26 +01002010 goto _readline_errors;
Serhiy Storchakac2cf1282017-03-12 13:50:36 +02002011 }
Serhiy Storchaka06515832016-11-20 09:13:07 +02002012 stdin_encoding_str = PyUnicode_AsUTF8(stdin_encoding);
2013 stdin_errors_str = PyUnicode_AsUTF8(stdin_errors);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01002014 if (!stdin_encoding_str || !stdin_errors_str)
2015 goto _readline_errors;
Jeroen Demeyer762f93f2019-07-08 10:19:25 +02002016 tmp = _PyObject_CallMethodIdNoArgs(fout, &PyId_flush);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002017 if (tmp == NULL)
2018 PyErr_Clear();
2019 else
2020 Py_DECREF(tmp);
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002021 if (prompt != NULL) {
Antoine Pitrou0d776b12011-11-06 00:34:26 +01002022 /* We have a prompt, encode it as stdout would */
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +02002023 const char *stdout_encoding_str, *stdout_errors_str;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002024 PyObject *stringpo;
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02002025 stdout_encoding = _PyObject_GetAttrId(fout, &PyId_encoding);
Antoine Pitrou5ee9d8a2011-11-06 00:38:45 +01002026 stdout_errors = _PyObject_GetAttrId(fout, &PyId_errors);
Serhiy Storchakac2cf1282017-03-12 13:50:36 +02002027 if (!stdout_encoding || !stdout_errors ||
2028 !PyUnicode_Check(stdout_encoding) ||
2029 !PyUnicode_Check(stdout_errors)) {
2030 tty = 0;
Antoine Pitrou0d776b12011-11-06 00:34:26 +01002031 goto _readline_errors;
Serhiy Storchakac2cf1282017-03-12 13:50:36 +02002032 }
Serhiy Storchaka06515832016-11-20 09:13:07 +02002033 stdout_encoding_str = PyUnicode_AsUTF8(stdout_encoding);
2034 stdout_errors_str = PyUnicode_AsUTF8(stdout_errors);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01002035 if (!stdout_encoding_str || !stdout_errors_str)
2036 goto _readline_errors;
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002037 stringpo = PyObject_Str(prompt);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01002038 if (stringpo == NULL)
2039 goto _readline_errors;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002040 po = PyUnicode_AsEncodedString(stringpo,
Antoine Pitrou0d776b12011-11-06 00:34:26 +01002041 stdout_encoding_str, stdout_errors_str);
2042 Py_CLEAR(stdout_encoding);
2043 Py_CLEAR(stdout_errors);
2044 Py_CLEAR(stringpo);
2045 if (po == NULL)
2046 goto _readline_errors;
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03002047 assert(PyBytes_Check(po));
2048 promptstr = PyBytes_AS_STRING(po);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002049 }
2050 else {
2051 po = NULL;
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002052 promptstr = "";
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002053 }
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002054 s = PyOS_Readline(stdin, stdout, promptstr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002055 if (s == NULL) {
Richard Oudkerk614c5782013-04-03 13:44:50 +01002056 PyErr_CheckSignals();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002057 if (!PyErr_Occurred())
2058 PyErr_SetNone(PyExc_KeyboardInterrupt);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01002059 goto _readline_errors;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002060 }
Victor Stinnerc0f1a1a2011-02-23 12:07:37 +00002061
2062 len = strlen(s);
2063 if (len == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002064 PyErr_SetNone(PyExc_EOFError);
2065 result = NULL;
2066 }
Victor Stinnerc0f1a1a2011-02-23 12:07:37 +00002067 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002068 if (len > PY_SSIZE_T_MAX) {
2069 PyErr_SetString(PyExc_OverflowError,
2070 "input: input too long");
2071 result = NULL;
2072 }
2073 else {
Victor Stinnerc0f1a1a2011-02-23 12:07:37 +00002074 len--; /* strip trailing '\n' */
2075 if (len != 0 && s[len-1] == '\r')
2076 len--; /* strip trailing '\r' */
Antoine Pitrou0d776b12011-11-06 00:34:26 +01002077 result = PyUnicode_Decode(s, len, stdin_encoding_str,
2078 stdin_errors_str);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002079 }
2080 }
2081 Py_DECREF(stdin_encoding);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01002082 Py_DECREF(stdin_errors);
2083 Py_XDECREF(po);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002084 PyMem_FREE(s);
Steve Dowerb82e17e2019-05-23 08:45:22 -07002085
2086 if (result != NULL) {
2087 if (PySys_Audit("builtins.input/result", "O", result) < 0) {
2088 return NULL;
2089 }
2090 }
2091
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002092 return result;
Serhiy Storchakac2cf1282017-03-12 13:50:36 +02002093
Antoine Pitrou0d776b12011-11-06 00:34:26 +01002094 _readline_errors:
2095 Py_XDECREF(stdin_encoding);
2096 Py_XDECREF(stdout_encoding);
2097 Py_XDECREF(stdin_errors);
2098 Py_XDECREF(stdout_errors);
2099 Py_XDECREF(po);
Serhiy Storchakac2cf1282017-03-12 13:50:36 +02002100 if (tty)
2101 return NULL;
2102
2103 PyErr_Clear();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002104 }
Guido van Rossumeba76962007-05-27 09:13:28 +00002105
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002106 /* Fallback if we're not interactive */
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002107 if (prompt != NULL) {
2108 if (PyFile_WriteObject(prompt, fout, Py_PRINT_RAW) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002109 return NULL;
2110 }
Jeroen Demeyer762f93f2019-07-08 10:19:25 +02002111 tmp = _PyObject_CallMethodIdNoArgs(fout, &PyId_flush);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002112 if (tmp == NULL)
2113 PyErr_Clear();
2114 else
2115 Py_DECREF(tmp);
2116 return PyFile_GetLine(fin, -1);
Guido van Rossuma88a0332007-02-26 16:59:55 +00002117}
2118
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002119
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002120/*[clinic input]
2121repr as builtin_repr
2122
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03002123 obj: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002124 /
2125
2126Return the canonical string representation of the object.
2127
2128For many object types, including most builtins, eval(repr(obj)) == obj.
2129[clinic start generated code]*/
2130
Guido van Rossum79f25d91997-04-29 20:08:16 +00002131static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002132builtin_repr(PyObject *module, PyObject *obj)
2133/*[clinic end generated code: output=7ed3778c44fd0194 input=1c9e6d66d3e3be04]*/
Guido van Rossumc89705d1992-11-26 08:54:07 +00002134{
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002135 return PyObject_Repr(obj);
Guido van Rossumc89705d1992-11-26 08:54:07 +00002136}
2137
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002138
Serhiy Storchakaaca7f572017-11-15 17:51:14 +02002139/*[clinic input]
2140round as builtin_round
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002141
Serhiy Storchakaaca7f572017-11-15 17:51:14 +02002142 number: object
2143 ndigits: object = NULL
2144
2145Round a number to a given precision in decimal digits.
2146
2147The return value is an integer if ndigits is omitted or None. Otherwise
2148the return value has the same type as the number. ndigits may be negative.
2149[clinic start generated code]*/
2150
2151static PyObject *
2152builtin_round_impl(PyObject *module, PyObject *number, PyObject *ndigits)
2153/*[clinic end generated code: output=ff0d9dd176c02ede input=854bc3a217530c3d]*/
2154{
2155 PyObject *round, *result;
Alex Martelliae211f92007-08-22 23:21:33 +00002156
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002157 if (Py_TYPE(number)->tp_dict == NULL) {
2158 if (PyType_Ready(Py_TYPE(number)) < 0)
2159 return NULL;
2160 }
Guido van Rossum15d3d042007-08-24 02:02:45 +00002161
Benjamin Peterson214a7d22013-04-13 17:19:01 -04002162 round = _PyObject_LookupSpecial(number, &PyId___round__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002163 if (round == NULL) {
Benjamin Peterson214a7d22013-04-13 17:19:01 -04002164 if (!PyErr_Occurred())
2165 PyErr_Format(PyExc_TypeError,
2166 "type %.100s doesn't define __round__ method",
2167 Py_TYPE(number)->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002168 return NULL;
2169 }
Alex Martelliae211f92007-08-22 23:21:33 +00002170
Raymond Hettingerf0f1c232016-09-03 01:55:11 -07002171 if (ndigits == NULL || ndigits == Py_None)
Victor Stinnerf17c3de2016-12-06 18:46:19 +01002172 result = _PyObject_CallNoArg(round);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002173 else
Jeroen Demeyer196a5302019-07-04 12:31:34 +02002174 result = _PyObject_CallOneArg(round, ndigits);
Benjamin Peterson214a7d22013-04-13 17:19:01 -04002175 Py_DECREF(round);
2176 return result;
Guido van Rossum9e51f9b1993-02-12 16:29:05 +00002177}
2178
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002179
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002180/*AC: we need to keep the kwds dict intact to easily call into the
2181 * list.sort method, which isn't currently supported in AC. So we just use
2182 * the initially generated signature with a custom implementation.
2183 */
2184/* [disabled clinic input]
2185sorted as builtin_sorted
2186
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03002187 iterable as seq: object
2188 key as keyfunc: object = None
2189 reverse: object = False
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002190
2191Return a new list containing all items from the iterable in ascending order.
2192
Raymond Hettinger7ea386e2016-08-25 21:11:50 -07002193A custom key function can be supplied to customize the sort order, and the
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002194reverse flag can be set to request the result in descending order.
2195[end disabled clinic input]*/
2196
2197PyDoc_STRVAR(builtin_sorted__doc__,
Serhiy Storchaka3a104252017-01-23 12:29:47 +02002198"sorted($module, iterable, /, *, key=None, reverse=False)\n"
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002199"--\n"
2200"\n"
2201"Return a new list containing all items from the iterable in ascending order.\n"
2202"\n"
Raymond Hettinger7ea386e2016-08-25 21:11:50 -07002203"A custom key function can be supplied to customize the sort order, and the\n"
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002204"reverse flag can be set to request the result in descending order.");
2205
2206#define BUILTIN_SORTED_METHODDEF \
Serhiy Storchaka62be7422018-11-27 13:27:31 +02002207 {"sorted", (PyCFunction)(void(*)(void))builtin_sorted, METH_FASTCALL | METH_KEYWORDS, builtin_sorted__doc__},
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002208
Raymond Hettinger64958a12003-12-17 20:43:33 +00002209static PyObject *
Serhiy Storchakaa5552f02017-12-15 13:11:11 +02002210builtin_sorted(PyObject *self, PyObject *const *args, Py_ssize_t nargs, PyObject *kwnames)
Raymond Hettinger64958a12003-12-17 20:43:33 +00002211{
Serhiy Storchaka7cf8beb2017-01-21 23:05:00 +02002212 PyObject *newlist, *v, *seq, *callable;
Victor Stinner5a60eca2017-01-17 15:17:49 +01002213
Serhiy Storchaka7cf8beb2017-01-21 23:05:00 +02002214 /* Keyword arguments are passed through list.sort() which will check
2215 them. */
2216 if (!_PyArg_UnpackStack(args, nargs, "sorted", 1, 1, &seq))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002217 return NULL;
Raymond Hettinger64958a12003-12-17 20:43:33 +00002218
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002219 newlist = PySequence_List(seq);
2220 if (newlist == NULL)
2221 return NULL;
Raymond Hettinger64958a12003-12-17 20:43:33 +00002222
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02002223 callable = _PyObject_GetAttrId(newlist, &PyId_sort);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002224 if (callable == NULL) {
2225 Py_DECREF(newlist);
2226 return NULL;
2227 }
Georg Brandl99d7e4e2005-08-31 22:21:15 +00002228
Serhiy Storchaka299dc232017-01-20 08:35:18 +02002229 assert(nargs >= 1);
Jeroen Demeyeraacc77f2019-05-29 20:31:52 +02002230 v = _PyObject_Vectorcall(callable, args + 1, nargs - 1, kwnames);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002231 Py_DECREF(callable);
2232 if (v == NULL) {
2233 Py_DECREF(newlist);
2234 return NULL;
2235 }
2236 Py_DECREF(v);
2237 return newlist;
Raymond Hettinger64958a12003-12-17 20:43:33 +00002238}
2239
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002240
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002241/* AC: cannot convert yet, as needs PEP 457 group support in inspect */
Guido van Rossum79f25d91997-04-29 20:08:16 +00002242static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002243builtin_vars(PyObject *self, PyObject *args)
Guido van Rossum2d951851994-08-29 12:52:16 +00002244{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002245 PyObject *v = NULL;
2246 PyObject *d;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002247
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002248 if (!PyArg_UnpackTuple(args, "vars", 0, 1, &v))
2249 return NULL;
2250 if (v == NULL) {
2251 d = PyEval_GetLocals();
Serhiy Storchaka41c57b32019-09-01 12:03:39 +03002252 Py_XINCREF(d);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002253 }
2254 else {
Serhiy Storchaka41c57b32019-09-01 12:03:39 +03002255 if (_PyObject_LookupAttrId(v, &PyId___dict__, &d) == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002256 PyErr_SetString(PyExc_TypeError,
2257 "vars() argument must have __dict__ attribute");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002258 }
2259 }
2260 return d;
Guido van Rossum2d951851994-08-29 12:52:16 +00002261}
2262
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002263PyDoc_STRVAR(vars_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002264"vars([object]) -> dictionary\n\
2265\n\
2266Without arguments, equivalent to locals().\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002267With an argument, equivalent to object.__dict__.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002268
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002269
2270/*[clinic input]
2271sum as builtin_sum
2272
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03002273 iterable: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002274 /
Raymond Hettinger9dfa0fe2018-09-12 10:54:06 -07002275 start: object(c_default="NULL") = 0
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002276
2277Return the sum of a 'start' value (default: 0) plus an iterable of numbers
2278
2279When the iterable is empty, return the start value.
2280This function is intended specifically for use with numeric values and may
2281reject non-numeric types.
2282[clinic start generated code]*/
2283
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002284static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002285builtin_sum_impl(PyObject *module, PyObject *iterable, PyObject *start)
Raymond Hettinger9dfa0fe2018-09-12 10:54:06 -07002286/*[clinic end generated code: output=df758cec7d1d302f input=162b50765250d222]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002287{
2288 PyObject *result = start;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002289 PyObject *temp, *item, *iter;
Alex Martellia70b1912003-04-22 08:12:33 +00002290
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002291 iter = PyObject_GetIter(iterable);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002292 if (iter == NULL)
2293 return NULL;
Alex Martellia70b1912003-04-22 08:12:33 +00002294
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002295 if (result == NULL) {
2296 result = PyLong_FromLong(0);
2297 if (result == NULL) {
2298 Py_DECREF(iter);
2299 return NULL;
2300 }
2301 } else {
2302 /* reject string values for 'start' parameter */
2303 if (PyUnicode_Check(result)) {
2304 PyErr_SetString(PyExc_TypeError,
2305 "sum() can't sum strings [use ''.join(seq) instead]");
2306 Py_DECREF(iter);
2307 return NULL;
2308 }
Benjamin Petersonce071ca2011-07-29 14:23:47 -05002309 if (PyBytes_Check(result)) {
2310 PyErr_SetString(PyExc_TypeError,
2311 "sum() can't sum bytes [use b''.join(seq) instead]");
Benjamin Peterson405f32c2011-07-29 22:43:45 -05002312 Py_DECREF(iter);
Benjamin Petersonce071ca2011-07-29 14:23:47 -05002313 return NULL;
2314 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002315 if (PyByteArray_Check(result)) {
2316 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson4f921c22011-07-29 14:24:29 -05002317 "sum() can't sum bytearray [use b''.join(seq) instead]");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002318 Py_DECREF(iter);
2319 return NULL;
2320 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002321 Py_INCREF(result);
2322 }
Alex Martellia70b1912003-04-22 08:12:33 +00002323
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002324#ifndef SLOW_SUM
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002325 /* Fast addition by keeping temporary sums in C instead of new Python objects.
2326 Assumes all inputs are the same type. If the assumption fails, default
2327 to the more general routine.
2328 */
2329 if (PyLong_CheckExact(result)) {
2330 int overflow;
2331 long i_result = PyLong_AsLongAndOverflow(result, &overflow);
2332 /* If this already overflowed, don't even enter the loop. */
2333 if (overflow == 0) {
2334 Py_DECREF(result);
2335 result = NULL;
2336 }
2337 while(result == NULL) {
2338 item = PyIter_Next(iter);
2339 if (item == NULL) {
2340 Py_DECREF(iter);
2341 if (PyErr_Occurred())
2342 return NULL;
2343 return PyLong_FromLong(i_result);
2344 }
Serhiy Storchaka88bdb922019-09-10 16:31:01 +03002345 if (PyLong_CheckExact(item) || PyBool_Check(item)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002346 long b = PyLong_AsLongAndOverflow(item, &overflow);
Serhiy Storchaka29500732019-05-05 14:26:23 +03002347 if (overflow == 0 &&
2348 (i_result >= 0 ? (b <= LONG_MAX - i_result)
2349 : (b >= LONG_MIN - i_result)))
2350 {
2351 i_result += b;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002352 Py_DECREF(item);
2353 continue;
2354 }
2355 }
2356 /* Either overflowed or is not an int. Restore real objects and process normally */
2357 result = PyLong_FromLong(i_result);
Christian Heimes704e2d32013-07-26 22:49:26 +02002358 if (result == NULL) {
2359 Py_DECREF(item);
2360 Py_DECREF(iter);
2361 return NULL;
2362 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002363 temp = PyNumber_Add(result, item);
2364 Py_DECREF(result);
2365 Py_DECREF(item);
2366 result = temp;
2367 if (result == NULL) {
2368 Py_DECREF(iter);
2369 return NULL;
2370 }
2371 }
2372 }
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002373
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002374 if (PyFloat_CheckExact(result)) {
2375 double f_result = PyFloat_AS_DOUBLE(result);
2376 Py_DECREF(result);
2377 result = NULL;
2378 while(result == NULL) {
2379 item = PyIter_Next(iter);
2380 if (item == NULL) {
2381 Py_DECREF(iter);
2382 if (PyErr_Occurred())
2383 return NULL;
2384 return PyFloat_FromDouble(f_result);
2385 }
2386 if (PyFloat_CheckExact(item)) {
2387 PyFPE_START_PROTECT("add", Py_DECREF(item); Py_DECREF(iter); return 0)
2388 f_result += PyFloat_AS_DOUBLE(item);
2389 PyFPE_END_PROTECT(f_result)
2390 Py_DECREF(item);
2391 continue;
2392 }
Serhiy Storchaka88bdb922019-09-10 16:31:01 +03002393 if (PyLong_Check(item)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002394 long value;
2395 int overflow;
2396 value = PyLong_AsLongAndOverflow(item, &overflow);
2397 if (!overflow) {
2398 PyFPE_START_PROTECT("add", Py_DECREF(item); Py_DECREF(iter); return 0)
2399 f_result += (double)value;
2400 PyFPE_END_PROTECT(f_result)
2401 Py_DECREF(item);
2402 continue;
2403 }
2404 }
2405 result = PyFloat_FromDouble(f_result);
Alexey Izbyshev2b824b22018-08-24 07:27:52 +03002406 if (result == NULL) {
2407 Py_DECREF(item);
2408 Py_DECREF(iter);
2409 return NULL;
2410 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002411 temp = PyNumber_Add(result, item);
2412 Py_DECREF(result);
2413 Py_DECREF(item);
2414 result = temp;
2415 if (result == NULL) {
2416 Py_DECREF(iter);
2417 return NULL;
2418 }
2419 }
2420 }
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002421#endif
2422
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002423 for(;;) {
2424 item = PyIter_Next(iter);
2425 if (item == NULL) {
2426 /* error, or end-of-sequence */
2427 if (PyErr_Occurred()) {
2428 Py_DECREF(result);
2429 result = NULL;
2430 }
2431 break;
2432 }
2433 /* It's tempting to use PyNumber_InPlaceAdd instead of
2434 PyNumber_Add here, to avoid quadratic running time
2435 when doing 'sum(list_of_lists, [])'. However, this
2436 would produce a change in behaviour: a snippet like
Mark Dickinson9acadc52009-10-26 14:19:42 +00002437
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002438 empty = []
2439 sum([[x] for x in range(10)], empty)
Mark Dickinson9acadc52009-10-26 14:19:42 +00002440
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002441 would change the value of empty. */
2442 temp = PyNumber_Add(result, item);
2443 Py_DECREF(result);
2444 Py_DECREF(item);
2445 result = temp;
2446 if (result == NULL)
2447 break;
2448 }
2449 Py_DECREF(iter);
2450 return result;
Alex Martellia70b1912003-04-22 08:12:33 +00002451}
2452
Alex Martellia70b1912003-04-22 08:12:33 +00002453
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002454/*[clinic input]
2455isinstance as builtin_isinstance
2456
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03002457 obj: object
2458 class_or_tuple: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002459 /
2460
2461Return whether an object is an instance of a class or of a subclass thereof.
2462
2463A tuple, as in ``isinstance(x, (A, B, ...))``, may be given as the target to
2464check against. This is equivalent to ``isinstance(x, A) or isinstance(x, B)
2465or ...`` etc.
2466[clinic start generated code]*/
2467
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002468static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002469builtin_isinstance_impl(PyObject *module, PyObject *obj,
Larry Hastings89964c42015-04-14 18:07:59 -04002470 PyObject *class_or_tuple)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002471/*[clinic end generated code: output=6faf01472c13b003 input=ffa743db1daf7549]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002472{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002473 int retval;
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002474
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002475 retval = PyObject_IsInstance(obj, class_or_tuple);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002476 if (retval < 0)
2477 return NULL;
2478 return PyBool_FromLong(retval);
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002479}
2480
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002481
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002482/*[clinic input]
2483issubclass as builtin_issubclass
2484
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03002485 cls: object
2486 class_or_tuple: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002487 /
2488
2489Return whether 'cls' is a derived from another class or is the same class.
2490
2491A tuple, as in ``issubclass(x, (A, B, ...))``, may be given as the target to
2492check against. This is equivalent to ``issubclass(x, A) or issubclass(x, B)
2493or ...`` etc.
2494[clinic start generated code]*/
2495
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002496static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002497builtin_issubclass_impl(PyObject *module, PyObject *cls,
Larry Hastings89964c42015-04-14 18:07:59 -04002498 PyObject *class_or_tuple)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002499/*[clinic end generated code: output=358412410cd7a250 input=af5f35e9ceaddaf6]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002500{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002501 int retval;
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002502
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002503 retval = PyObject_IsSubclass(cls, class_or_tuple);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002504 if (retval < 0)
2505 return NULL;
2506 return PyBool_FromLong(retval);
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002507}
2508
2509
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002510typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002511 PyObject_HEAD
2512 Py_ssize_t tuplesize;
2513 PyObject *ittuple; /* tuple of iterators */
2514 PyObject *result;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002515} zipobject;
2516
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002517static PyObject *
2518zip_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
Barry Warsawbd599b52000-08-03 15:45:29 +00002519{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002520 zipobject *lz;
2521 Py_ssize_t i;
2522 PyObject *ittuple; /* tuple of iterators */
2523 PyObject *result;
Serhiy Storchakabf623ae2017-04-19 20:03:52 +03002524 Py_ssize_t tuplesize;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002525
Serhiy Storchaka6cca5c82017-06-08 14:41:19 +03002526 if (type == &PyZip_Type && !_PyArg_NoKeywords("zip", kwds))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002527 return NULL;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002528
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002529 /* args must be a tuple */
2530 assert(PyTuple_Check(args));
Serhiy Storchakabf623ae2017-04-19 20:03:52 +03002531 tuplesize = PyTuple_GET_SIZE(args);
Barry Warsawbd599b52000-08-03 15:45:29 +00002532
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002533 /* obtain iterators */
2534 ittuple = PyTuple_New(tuplesize);
2535 if (ittuple == NULL)
2536 return NULL;
2537 for (i=0; i < tuplesize; ++i) {
2538 PyObject *item = PyTuple_GET_ITEM(args, i);
2539 PyObject *it = PyObject_GetIter(item);
2540 if (it == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002541 Py_DECREF(ittuple);
2542 return NULL;
2543 }
2544 PyTuple_SET_ITEM(ittuple, i, it);
2545 }
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002546
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002547 /* create a result holder */
2548 result = PyTuple_New(tuplesize);
2549 if (result == NULL) {
2550 Py_DECREF(ittuple);
2551 return NULL;
2552 }
2553 for (i=0 ; i < tuplesize ; i++) {
2554 Py_INCREF(Py_None);
2555 PyTuple_SET_ITEM(result, i, Py_None);
2556 }
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002557
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002558 /* create zipobject structure */
2559 lz = (zipobject *)type->tp_alloc(type, 0);
2560 if (lz == NULL) {
2561 Py_DECREF(ittuple);
2562 Py_DECREF(result);
2563 return NULL;
2564 }
2565 lz->ittuple = ittuple;
2566 lz->tuplesize = tuplesize;
2567 lz->result = result;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002568
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002569 return (PyObject *)lz;
Barry Warsawbd599b52000-08-03 15:45:29 +00002570}
2571
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002572static void
2573zip_dealloc(zipobject *lz)
2574{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002575 PyObject_GC_UnTrack(lz);
2576 Py_XDECREF(lz->ittuple);
2577 Py_XDECREF(lz->result);
2578 Py_TYPE(lz)->tp_free(lz);
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002579}
2580
2581static int
2582zip_traverse(zipobject *lz, visitproc visit, void *arg)
2583{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002584 Py_VISIT(lz->ittuple);
2585 Py_VISIT(lz->result);
2586 return 0;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002587}
2588
2589static PyObject *
2590zip_next(zipobject *lz)
2591{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002592 Py_ssize_t i;
2593 Py_ssize_t tuplesize = lz->tuplesize;
2594 PyObject *result = lz->result;
2595 PyObject *it;
2596 PyObject *item;
2597 PyObject *olditem;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002598
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002599 if (tuplesize == 0)
2600 return NULL;
2601 if (Py_REFCNT(result) == 1) {
2602 Py_INCREF(result);
2603 for (i=0 ; i < tuplesize ; i++) {
2604 it = PyTuple_GET_ITEM(lz->ittuple, i);
2605 item = (*Py_TYPE(it)->tp_iternext)(it);
Serhiy Storchaka278d03b2013-04-06 22:52:34 +03002606 if (item == NULL) {
2607 Py_DECREF(result);
2608 return NULL;
2609 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002610 olditem = PyTuple_GET_ITEM(result, i);
2611 PyTuple_SET_ITEM(result, i, item);
2612 Py_DECREF(olditem);
2613 }
2614 } else {
2615 result = PyTuple_New(tuplesize);
2616 if (result == NULL)
Serhiy Storchaka278d03b2013-04-06 22:52:34 +03002617 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002618 for (i=0 ; i < tuplesize ; i++) {
2619 it = PyTuple_GET_ITEM(lz->ittuple, i);
2620 item = (*Py_TYPE(it)->tp_iternext)(it);
Serhiy Storchaka278d03b2013-04-06 22:52:34 +03002621 if (item == NULL) {
2622 Py_DECREF(result);
2623 return NULL;
2624 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002625 PyTuple_SET_ITEM(result, i, item);
2626 }
2627 }
2628 return result;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002629}
Barry Warsawbd599b52000-08-03 15:45:29 +00002630
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002631static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05302632zip_reduce(zipobject *lz, PyObject *Py_UNUSED(ignored))
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002633{
2634 /* Just recreate the zip with the internal iterator tuple */
2635 return Py_BuildValue("OO", Py_TYPE(lz), lz->ittuple);
2636}
2637
2638static PyMethodDef zip_methods[] = {
2639 {"__reduce__", (PyCFunction)zip_reduce, METH_NOARGS, reduce_doc},
2640 {NULL, NULL} /* sentinel */
2641};
2642
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002643PyDoc_STRVAR(zip_doc,
Sergey Fedoseevaf2f5b12019-07-18 23:19:25 +05002644"zip(*iterables) --> zip object\n\
Barry Warsawbd599b52000-08-03 15:45:29 +00002645\n\
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002646Return a zip object whose .__next__() method returns a tuple where\n\
2647the i-th element comes from the i-th iterable argument. The .__next__()\n\
2648method continues until the shortest iterable in the argument sequence\n\
Georg Brandlced51db2008-12-04 18:28:38 +00002649is exhausted and then it raises StopIteration.");
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002650
2651PyTypeObject PyZip_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002652 PyVarObject_HEAD_INIT(&PyType_Type, 0)
2653 "zip", /* tp_name */
2654 sizeof(zipobject), /* tp_basicsize */
2655 0, /* tp_itemsize */
2656 /* methods */
2657 (destructor)zip_dealloc, /* tp_dealloc */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02002658 0, /* tp_vectorcall_offset */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002659 0, /* tp_getattr */
2660 0, /* tp_setattr */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02002661 0, /* tp_as_async */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002662 0, /* tp_repr */
2663 0, /* tp_as_number */
2664 0, /* tp_as_sequence */
2665 0, /* tp_as_mapping */
2666 0, /* tp_hash */
2667 0, /* tp_call */
2668 0, /* tp_str */
2669 PyObject_GenericGetAttr, /* tp_getattro */
2670 0, /* tp_setattro */
2671 0, /* tp_as_buffer */
2672 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
2673 Py_TPFLAGS_BASETYPE, /* tp_flags */
2674 zip_doc, /* tp_doc */
2675 (traverseproc)zip_traverse, /* tp_traverse */
2676 0, /* tp_clear */
2677 0, /* tp_richcompare */
2678 0, /* tp_weaklistoffset */
2679 PyObject_SelfIter, /* tp_iter */
2680 (iternextfunc)zip_next, /* tp_iternext */
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002681 zip_methods, /* tp_methods */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002682 0, /* tp_members */
2683 0, /* tp_getset */
2684 0, /* tp_base */
2685 0, /* tp_dict */
2686 0, /* tp_descr_get */
2687 0, /* tp_descr_set */
2688 0, /* tp_dictoffset */
2689 0, /* tp_init */
2690 PyType_GenericAlloc, /* tp_alloc */
2691 zip_new, /* tp_new */
2692 PyObject_GC_Del, /* tp_free */
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002693};
Barry Warsawbd599b52000-08-03 15:45:29 +00002694
2695
Guido van Rossum79f25d91997-04-29 20:08:16 +00002696static PyMethodDef builtin_methods[] = {
Serhiy Storchaka62be7422018-11-27 13:27:31 +02002697 {"__build_class__", (PyCFunction)(void(*)(void))builtin___build_class__,
Serhiy Storchaka6969eaf2017-07-03 21:20:15 +03002698 METH_FASTCALL | METH_KEYWORDS, build_class_doc},
Serhiy Storchaka62be7422018-11-27 13:27:31 +02002699 {"__import__", (PyCFunction)(void(*)(void))builtin___import__, METH_VARARGS | METH_KEYWORDS, import_doc},
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002700 BUILTIN_ABS_METHODDEF
2701 BUILTIN_ALL_METHODDEF
2702 BUILTIN_ANY_METHODDEF
2703 BUILTIN_ASCII_METHODDEF
2704 BUILTIN_BIN_METHODDEF
Serhiy Storchaka62be7422018-11-27 13:27:31 +02002705 {"breakpoint", (PyCFunction)(void(*)(void))builtin_breakpoint, METH_FASTCALL | METH_KEYWORDS, breakpoint_doc},
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002706 BUILTIN_CALLABLE_METHODDEF
2707 BUILTIN_CHR_METHODDEF
2708 BUILTIN_COMPILE_METHODDEF
2709 BUILTIN_DELATTR_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002710 {"dir", builtin_dir, METH_VARARGS, dir_doc},
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002711 BUILTIN_DIVMOD_METHODDEF
2712 BUILTIN_EVAL_METHODDEF
2713 BUILTIN_EXEC_METHODDEF
2714 BUILTIN_FORMAT_METHODDEF
Serhiy Storchaka62be7422018-11-27 13:27:31 +02002715 {"getattr", (PyCFunction)(void(*)(void))builtin_getattr, METH_FASTCALL, getattr_doc},
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002716 BUILTIN_GLOBALS_METHODDEF
2717 BUILTIN_HASATTR_METHODDEF
2718 BUILTIN_HASH_METHODDEF
2719 BUILTIN_HEX_METHODDEF
2720 BUILTIN_ID_METHODDEF
2721 BUILTIN_INPUT_METHODDEF
2722 BUILTIN_ISINSTANCE_METHODDEF
2723 BUILTIN_ISSUBCLASS_METHODDEF
Serhiy Storchaka79342662019-01-12 08:25:41 +02002724 {"iter", (PyCFunction)(void(*)(void))builtin_iter, METH_FASTCALL, iter_doc},
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002725 BUILTIN_LEN_METHODDEF
2726 BUILTIN_LOCALS_METHODDEF
Serhiy Storchaka62be7422018-11-27 13:27:31 +02002727 {"max", (PyCFunction)(void(*)(void))builtin_max, METH_VARARGS | METH_KEYWORDS, max_doc},
2728 {"min", (PyCFunction)(void(*)(void))builtin_min, METH_VARARGS | METH_KEYWORDS, min_doc},
2729 {"next", (PyCFunction)(void(*)(void))builtin_next, METH_FASTCALL, next_doc},
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002730 BUILTIN_OCT_METHODDEF
2731 BUILTIN_ORD_METHODDEF
2732 BUILTIN_POW_METHODDEF
Serhiy Storchaka62be7422018-11-27 13:27:31 +02002733 {"print", (PyCFunction)(void(*)(void))builtin_print, METH_FASTCALL | METH_KEYWORDS, print_doc},
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002734 BUILTIN_REPR_METHODDEF
Serhiy Storchakaaca7f572017-11-15 17:51:14 +02002735 BUILTIN_ROUND_METHODDEF
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002736 BUILTIN_SETATTR_METHODDEF
2737 BUILTIN_SORTED_METHODDEF
2738 BUILTIN_SUM_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002739 {"vars", builtin_vars, METH_VARARGS, vars_doc},
2740 {NULL, NULL},
Guido van Rossum3f5da241990-12-20 15:06:42 +00002741};
2742
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002743PyDoc_STRVAR(builtin_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002744"Built-in functions, exceptions, and other objects.\n\
2745\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002746Noteworthy: None is the `nil' object; Ellipsis represents `...' in slices.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002747
Martin v. Löwis1a214512008-06-11 05:26:20 +00002748static struct PyModuleDef builtinsmodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002749 PyModuleDef_HEAD_INIT,
2750 "builtins",
2751 builtin_doc,
2752 -1, /* multiple "initialization" just copies the module dict. */
2753 builtin_methods,
2754 NULL,
2755 NULL,
2756 NULL,
2757 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00002758};
2759
2760
Guido van Rossum25ce5661997-08-02 03:10:38 +00002761PyObject *
Victor Stinnerb45d2592019-06-20 00:05:23 +02002762_PyBuiltin_Init(PyThreadState *tstate)
Guido van Rossum25ce5661997-08-02 03:10:38 +00002763{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002764 PyObject *mod, *dict, *debug;
Benjamin Peterson42124a72012-10-30 23:41:54 -04002765
Victor Stinnerb45d2592019-06-20 00:05:23 +02002766 const PyConfig *config = &tstate->interp->config;
Victor Stinnerfbca9082018-08-30 00:50:45 +02002767
Benjamin Peterson42124a72012-10-30 23:41:54 -04002768 if (PyType_Ready(&PyFilter_Type) < 0 ||
2769 PyType_Ready(&PyMap_Type) < 0 ||
2770 PyType_Ready(&PyZip_Type) < 0)
2771 return NULL;
2772
Eric Snowd393c1b2017-09-14 12:18:12 -06002773 mod = _PyModule_CreateInitialized(&builtinsmodule, PYTHON_API_VERSION);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002774 if (mod == NULL)
2775 return NULL;
2776 dict = PyModule_GetDict(mod);
Tim Peters4b7625e2001-09-13 21:37:17 +00002777
Tim Peters7571a0f2003-03-23 17:52:28 +00002778#ifdef Py_TRACE_REFS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002779 /* "builtins" exposes a number of statically allocated objects
2780 * that, before this code was added in 2.3, never showed up in
2781 * the list of "all objects" maintained by Py_TRACE_REFS. As a
2782 * result, programs leaking references to None and False (etc)
2783 * couldn't be diagnosed by examining sys.getobjects(0).
2784 */
Tim Peters7571a0f2003-03-23 17:52:28 +00002785#define ADD_TO_ALL(OBJECT) _Py_AddToAllObjects((PyObject *)(OBJECT), 0)
2786#else
2787#define ADD_TO_ALL(OBJECT) (void)0
2788#endif
2789
Tim Peters4b7625e2001-09-13 21:37:17 +00002790#define SETBUILTIN(NAME, OBJECT) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002791 if (PyDict_SetItemString(dict, NAME, (PyObject *)OBJECT) < 0) \
2792 return NULL; \
2793 ADD_TO_ALL(OBJECT)
Tim Peters4b7625e2001-09-13 21:37:17 +00002794
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002795 SETBUILTIN("None", Py_None);
2796 SETBUILTIN("Ellipsis", Py_Ellipsis);
2797 SETBUILTIN("NotImplemented", Py_NotImplemented);
2798 SETBUILTIN("False", Py_False);
2799 SETBUILTIN("True", Py_True);
2800 SETBUILTIN("bool", &PyBool_Type);
2801 SETBUILTIN("memoryview", &PyMemoryView_Type);
2802 SETBUILTIN("bytearray", &PyByteArray_Type);
2803 SETBUILTIN("bytes", &PyBytes_Type);
2804 SETBUILTIN("classmethod", &PyClassMethod_Type);
2805 SETBUILTIN("complex", &PyComplex_Type);
2806 SETBUILTIN("dict", &PyDict_Type);
2807 SETBUILTIN("enumerate", &PyEnum_Type);
2808 SETBUILTIN("filter", &PyFilter_Type);
2809 SETBUILTIN("float", &PyFloat_Type);
2810 SETBUILTIN("frozenset", &PyFrozenSet_Type);
2811 SETBUILTIN("property", &PyProperty_Type);
2812 SETBUILTIN("int", &PyLong_Type);
2813 SETBUILTIN("list", &PyList_Type);
2814 SETBUILTIN("map", &PyMap_Type);
2815 SETBUILTIN("object", &PyBaseObject_Type);
2816 SETBUILTIN("range", &PyRange_Type);
2817 SETBUILTIN("reversed", &PyReversed_Type);
2818 SETBUILTIN("set", &PySet_Type);
2819 SETBUILTIN("slice", &PySlice_Type);
2820 SETBUILTIN("staticmethod", &PyStaticMethod_Type);
2821 SETBUILTIN("str", &PyUnicode_Type);
2822 SETBUILTIN("super", &PySuper_Type);
2823 SETBUILTIN("tuple", &PyTuple_Type);
2824 SETBUILTIN("type", &PyType_Type);
2825 SETBUILTIN("zip", &PyZip_Type);
Victor Stinnerfbca9082018-08-30 00:50:45 +02002826 debug = PyBool_FromLong(config->optimization_level == 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002827 if (PyDict_SetItemString(dict, "__debug__", debug) < 0) {
Serhiy Storchakacfdfbb42016-06-18 09:44:03 +03002828 Py_DECREF(debug);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002829 return NULL;
2830 }
Serhiy Storchakacfdfbb42016-06-18 09:44:03 +03002831 Py_DECREF(debug);
Barry Warsaw757af0e1997-08-29 22:13:51 +00002832
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002833 return mod;
Tim Peters7571a0f2003-03-23 17:52:28 +00002834#undef ADD_TO_ALL
Tim Peters4b7625e2001-09-13 21:37:17 +00002835#undef SETBUILTIN
Guido van Rossum3f5da241990-12-20 15:06:42 +00002836}