blob: cb048af97855fe72dbfadd252a1d8917a848c43b [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 Stinner58f4e1a2020-02-05 18:24:33 +01007#include "pycore_object.h"
Victor Stinner4d231bc2019-11-14 13:36:21 +01008#include "pycore_pyerrors.h"
Victor Stinner621cebe2018-11-12 16:53:38 +01009#include "pycore_pystate.h"
Sergey Fedoseevf1b9abe2019-02-26 02:37:26 +050010#include "pycore_tupleobject.h"
Guido van Rossum6bf62da1997-04-11 20:37:35 +000011
Victor Stinnerbd303c12013-11-07 23:07:29 +010012_Py_IDENTIFIER(__builtins__);
13_Py_IDENTIFIER(__dict__);
14_Py_IDENTIFIER(__prepare__);
15_Py_IDENTIFIER(__round__);
Ivan Levkivskyi2b5fd1e2017-12-14 23:32:56 +010016_Py_IDENTIFIER(__mro_entries__);
Victor Stinnerbd303c12013-11-07 23:07:29 +010017_Py_IDENTIFIER(encoding);
18_Py_IDENTIFIER(errors);
Martin v. Löwisbd928fe2011-10-14 10:20:37 +020019_Py_IDENTIFIER(fileno);
20_Py_IDENTIFIER(flush);
Victor Stinnerbd303c12013-11-07 23:07:29 +010021_Py_IDENTIFIER(metaclass);
22_Py_IDENTIFIER(sort);
23_Py_IDENTIFIER(stdin);
24_Py_IDENTIFIER(stdout);
25_Py_IDENTIFIER(stderr);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +020026
Serhiy Storchaka1009bf12015-04-03 23:53:51 +030027#include "clinic/bltinmodule.c.h"
28
Ivan Levkivskyi2b5fd1e2017-12-14 23:32:56 +010029static PyObject*
Victor Stinner05d68a82018-01-18 11:15:25 +010030update_bases(PyObject *bases, PyObject *const *args, Py_ssize_t nargs)
Ivan Levkivskyi2b5fd1e2017-12-14 23:32:56 +010031{
Victor Stinner05d68a82018-01-18 11:15:25 +010032 Py_ssize_t i, j;
Ivan Levkivskyi2b5fd1e2017-12-14 23:32:56 +010033 PyObject *base, *meth, *new_base, *result, *new_bases = NULL;
Ivan Levkivskyi2b5fd1e2017-12-14 23:32:56 +010034 assert(PyTuple_Check(bases));
35
36 for (i = 0; i < nargs; i++) {
37 base = args[i];
38 if (PyType_Check(base)) {
39 if (new_bases) {
40 /* If we already have made a replacement, then we append every normal base,
41 otherwise just skip it. */
42 if (PyList_Append(new_bases, base) < 0) {
43 goto error;
44 }
45 }
46 continue;
47 }
Serhiy Storchakaf320be72018-01-25 10:49:40 +020048 if (_PyObject_LookupAttrId(base, &PyId___mro_entries__, &meth) < 0) {
49 goto error;
50 }
Ivan Levkivskyi2b5fd1e2017-12-14 23:32:56 +010051 if (!meth) {
Ivan Levkivskyi2b5fd1e2017-12-14 23:32:56 +010052 if (new_bases) {
53 if (PyList_Append(new_bases, base) < 0) {
54 goto error;
55 }
56 }
57 continue;
58 }
Petr Viktorinffd97532020-02-11 17:46:57 +010059 new_base = PyObject_CallOneArg(meth, bases);
Ivan Levkivskyi2b5fd1e2017-12-14 23:32:56 +010060 Py_DECREF(meth);
61 if (!new_base) {
62 goto error;
63 }
64 if (!PyTuple_Check(new_base)) {
65 PyErr_SetString(PyExc_TypeError,
66 "__mro_entries__ must return a tuple");
67 Py_DECREF(new_base);
68 goto error;
69 }
70 if (!new_bases) {
71 /* If this is a first successful replacement, create new_bases list and
72 copy previously encountered bases. */
73 if (!(new_bases = PyList_New(i))) {
74 goto error;
75 }
76 for (j = 0; j < i; j++) {
77 base = args[j];
78 PyList_SET_ITEM(new_bases, j, base);
79 Py_INCREF(base);
80 }
81 }
82 j = PyList_GET_SIZE(new_bases);
83 if (PyList_SetSlice(new_bases, j, j, new_base) < 0) {
84 goto error;
85 }
86 Py_DECREF(new_base);
87 }
88 if (!new_bases) {
89 return bases;
90 }
91 result = PyList_AsTuple(new_bases);
92 Py_DECREF(new_bases);
93 return result;
94
95error:
96 Py_XDECREF(new_bases);
97 return NULL;
98}
99
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000100/* AC: cannot convert yet, waiting for *args support */
Guido van Rossum79f25d91997-04-29 20:08:16 +0000101static PyObject *
Serhiy Storchakaa5552f02017-12-15 13:11:11 +0200102builtin___build_class__(PyObject *self, PyObject *const *args, Py_ssize_t nargs,
Victor Stinner773dc6d2017-01-16 23:46:26 +0100103 PyObject *kwnames)
Guido van Rossum52cc1d82007-03-18 15:41:51 +0000104{
Ivan Levkivskyi2b5fd1e2017-12-14 23:32:56 +0100105 PyObject *func, *name, *bases, *mkw, *meta, *winner, *prep, *ns, *orig_bases;
Nick Coghlan19d24672016-12-05 16:47:55 +1000106 PyObject *cls = NULL, *cell = NULL;
Victor Stinner0c39b1b2015-03-18 15:02:06 +0100107 int isclass = 0; /* initialize to prevent gcc warning */
Guido van Rossum52cc1d82007-03-18 15:41:51 +0000108
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000109 if (nargs < 2) {
110 PyErr_SetString(PyExc_TypeError,
111 "__build_class__: not enough arguments");
112 return NULL;
113 }
Victor Stinner773dc6d2017-01-16 23:46:26 +0100114 func = args[0]; /* Better be callable */
Benjamin Petersone8e14592013-05-16 14:37:25 -0500115 if (!PyFunction_Check(func)) {
116 PyErr_SetString(PyExc_TypeError,
Zachary Ware9b338722014-08-05 14:01:10 -0500117 "__build_class__: func must be a function");
Benjamin Petersone8e14592013-05-16 14:37:25 -0500118 return NULL;
119 }
Victor Stinner773dc6d2017-01-16 23:46:26 +0100120 name = args[1];
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000121 if (!PyUnicode_Check(name)) {
122 PyErr_SetString(PyExc_TypeError,
123 "__build_class__: name is not a string");
124 return NULL;
125 }
Sergey Fedoseevf1b9abe2019-02-26 02:37:26 +0500126 orig_bases = _PyTuple_FromArray(args + 2, nargs - 2);
Ivan Levkivskyi2b5fd1e2017-12-14 23:32:56 +0100127 if (orig_bases == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000128 return NULL;
Guido van Rossum52cc1d82007-03-18 15:41:51 +0000129
Ivan Levkivskyi2b5fd1e2017-12-14 23:32:56 +0100130 bases = update_bases(orig_bases, args + 2, nargs - 2);
131 if (bases == NULL) {
132 Py_DECREF(orig_bases);
133 return NULL;
134 }
135
Victor Stinner773dc6d2017-01-16 23:46:26 +0100136 if (kwnames == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000137 meta = NULL;
138 mkw = NULL;
139 }
140 else {
Victor Stinner773dc6d2017-01-16 23:46:26 +0100141 mkw = _PyStack_AsDict(args + nargs, kwnames);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000142 if (mkw == NULL) {
143 Py_DECREF(bases);
144 return NULL;
Guido van Rossum52cc1d82007-03-18 15:41:51 +0000145 }
Victor Stinner773dc6d2017-01-16 23:46:26 +0100146
Serhiy Storchakaa24107b2019-02-25 17:59:46 +0200147 meta = _PyDict_GetItemIdWithError(mkw, &PyId_metaclass);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000148 if (meta != NULL) {
149 Py_INCREF(meta);
Victor Stinnerae9f1612013-11-06 22:46:51 +0100150 if (_PyDict_DelItemId(mkw, &PyId_metaclass) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000151 Py_DECREF(meta);
152 Py_DECREF(mkw);
153 Py_DECREF(bases);
154 return NULL;
155 }
Nick Coghlande31b192011-10-23 22:04:16 +1000156 /* metaclass is explicitly given, check if it's indeed a class */
157 isclass = PyType_Check(meta);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000158 }
Serhiy Storchakaa24107b2019-02-25 17:59:46 +0200159 else if (PyErr_Occurred()) {
160 Py_DECREF(mkw);
161 Py_DECREF(bases);
162 return NULL;
163 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000164 }
165 if (meta == NULL) {
Nick Coghlande31b192011-10-23 22:04:16 +1000166 /* if there are no bases, use type: */
167 if (PyTuple_GET_SIZE(bases) == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000168 meta = (PyObject *) (&PyType_Type);
Nick Coghlande31b192011-10-23 22:04:16 +1000169 }
170 /* else get the type of the first base */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000171 else {
172 PyObject *base0 = PyTuple_GET_ITEM(bases, 0);
Victor Stinnera102ed72020-02-07 02:24:48 +0100173 meta = (PyObject *)Py_TYPE(base0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000174 }
175 Py_INCREF(meta);
Nick Coghlande31b192011-10-23 22:04:16 +1000176 isclass = 1; /* meta is really a class */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000177 }
Nick Coghlan9715d262011-10-23 22:36:42 +1000178
Nick Coghlande31b192011-10-23 22:04:16 +1000179 if (isclass) {
180 /* meta is really a class, so check for a more derived
181 metaclass, or possible metaclass conflicts: */
182 winner = (PyObject *)_PyType_CalculateMetaclass((PyTypeObject *)meta,
183 bases);
184 if (winner == NULL) {
185 Py_DECREF(meta);
186 Py_XDECREF(mkw);
187 Py_DECREF(bases);
188 return NULL;
189 }
190 if (winner != meta) {
191 Py_DECREF(meta);
192 meta = winner;
193 Py_INCREF(meta);
194 }
195 }
196 /* else: meta is not a class, so we cannot do the metaclass
197 calculation, so we will use the explicitly given object as it is */
Serhiy Storchakaf320be72018-01-25 10:49:40 +0200198 if (_PyObject_LookupAttrId(meta, &PyId___prepare__, &prep) < 0) {
199 ns = NULL;
200 }
201 else if (prep == NULL) {
202 ns = PyDict_New();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000203 }
204 else {
Victor Stinner463b86a2016-08-22 23:33:13 +0200205 PyObject *pargs[2] = {name, bases};
Petr Viktorinffd97532020-02-11 17:46:57 +0100206 ns = PyObject_VectorcallDict(prep, pargs, 2, mkw);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000207 Py_DECREF(prep);
208 }
209 if (ns == NULL) {
210 Py_DECREF(meta);
211 Py_XDECREF(mkw);
212 Py_DECREF(bases);
213 return NULL;
214 }
Oren Milman5837d042017-09-27 17:04:37 +0300215 if (!PyMapping_Check(ns)) {
216 PyErr_Format(PyExc_TypeError,
217 "%.200s.__prepare__() must return a mapping, not %.200s",
218 isclass ? ((PyTypeObject *)meta)->tp_name : "<metaclass>",
219 Py_TYPE(ns)->tp_name);
220 goto error;
221 }
Nick Coghlan19d24672016-12-05 16:47:55 +1000222 cell = PyEval_EvalCodeEx(PyFunction_GET_CODE(func), PyFunction_GET_GLOBALS(func), ns,
Benjamin Petersone8e14592013-05-16 14:37:25 -0500223 NULL, 0, NULL, 0, NULL, 0, NULL,
224 PyFunction_GET_CLOSURE(func));
Nick Coghlan19d24672016-12-05 16:47:55 +1000225 if (cell != NULL) {
Ivan Levkivskyi2b5fd1e2017-12-14 23:32:56 +0100226 if (bases != orig_bases) {
227 if (PyMapping_SetItemString(ns, "__orig_bases__", orig_bases) < 0) {
228 goto error;
229 }
230 }
Victor Stinnerd1c2a8e2016-08-23 01:34:35 +0200231 PyObject *margs[3] = {name, bases, ns};
Petr Viktorinffd97532020-02-11 17:46:57 +0100232 cls = PyObject_VectorcallDict(meta, margs, 3, mkw);
Nick Coghlan19d24672016-12-05 16:47:55 +1000233 if (cls != NULL && PyType_Check(cls) && PyCell_Check(cell)) {
234 PyObject *cell_cls = PyCell_GET(cell);
235 if (cell_cls != cls) {
Nick Coghlan19d24672016-12-05 16:47:55 +1000236 if (cell_cls == NULL) {
237 const char *msg =
238 "__class__ not set defining %.200R as %.200R. "
239 "Was __classcell__ propagated to type.__new__?";
Serhiy Storchakaf5e7b192018-05-20 08:48:12 +0300240 PyErr_Format(PyExc_RuntimeError, msg, name, cls);
Nick Coghlan19d24672016-12-05 16:47:55 +1000241 } else {
242 const char *msg =
243 "__class__ set to %.200R defining %.200R as %.200R";
244 PyErr_Format(PyExc_TypeError, msg, cell_cls, name, cls);
Nick Coghlan19d24672016-12-05 16:47:55 +1000245 }
Serhiy Storchakaf5e7b192018-05-20 08:48:12 +0300246 Py_DECREF(cls);
247 cls = NULL;
248 goto error;
Nick Coghlan19d24672016-12-05 16:47:55 +1000249 }
250 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000251 }
Nick Coghlan19d24672016-12-05 16:47:55 +1000252error:
253 Py_XDECREF(cell);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000254 Py_DECREF(ns);
255 Py_DECREF(meta);
256 Py_XDECREF(mkw);
257 Py_DECREF(bases);
Ivan Levkivskyi2b5fd1e2017-12-14 23:32:56 +0100258 if (bases != orig_bases) {
259 Py_DECREF(orig_bases);
260 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000261 return cls;
Guido van Rossum52cc1d82007-03-18 15:41:51 +0000262}
263
264PyDoc_STRVAR(build_class_doc,
Pablo Galindoe3babbd2019-10-13 16:35:41 +0100265"__build_class__(func, name, /, *bases, [metaclass], **kwds) -> class\n\
Guido van Rossum52cc1d82007-03-18 15:41:51 +0000266\n\
267Internal helper function used by the class statement.");
268
269static PyObject *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000270builtin___import__(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000271{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000272 static char *kwlist[] = {"name", "globals", "locals", "fromlist",
273 "level", 0};
Victor Stinnerfe93faf2011-03-14 15:54:52 -0400274 PyObject *name, *globals = NULL, *locals = NULL, *fromlist = NULL;
Brett Cannonfd074152012-04-14 14:10:13 -0400275 int level = 0;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000276
Victor Stinnerfe93faf2011-03-14 15:54:52 -0400277 if (!PyArg_ParseTupleAndKeywords(args, kwds, "U|OOOi:__import__",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000278 kwlist, &name, &globals, &locals, &fromlist, &level))
279 return NULL;
Victor Stinnerfe93faf2011-03-14 15:54:52 -0400280 return PyImport_ImportModuleLevelObject(name, globals, locals,
281 fromlist, level);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000282}
283
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000284PyDoc_STRVAR(import_doc,
Brett Cannoncb4996a2012-08-06 16:34:44 -0400285"__import__(name, globals=None, locals=None, fromlist=(), level=0) -> module\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000286\n\
Brett Cannon5305a992010-09-27 21:08:38 +0000287Import a module. Because this function is meant for use by the Python\n\
oldk461d2252018-02-02 12:20:00 +0800288interpreter and not for general use, it is better to use\n\
Brett Cannon5305a992010-09-27 21:08:38 +0000289importlib.import_module() to programmatically import a module.\n\
290\n\
291The globals argument is only used to determine the context;\n\
292they are not modified. The locals argument is unused. The fromlist\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000293should be a list of names to emulate ``from name import ...'', or an\n\
294empty list to emulate ``import name''.\n\
295When importing a module from a package, note that __import__('A.B', ...)\n\
296returns package A when fromlist is empty, but its submodule B when\n\
oldk461d2252018-02-02 12:20:00 +0800297fromlist is not empty. The level argument is used to determine whether to\n\
298perform absolute or relative imports: 0 is absolute, while a positive number\n\
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000299is the number of parent directories to search relative to the current module.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000300
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000301
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000302/*[clinic input]
303abs as builtin_abs
304
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300305 x: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000306 /
307
308Return the absolute value of the argument.
309[clinic start generated code]*/
310
Guido van Rossum79f25d91997-04-29 20:08:16 +0000311static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300312builtin_abs(PyObject *module, PyObject *x)
313/*[clinic end generated code: output=b1b433b9e51356f5 input=bed4ca14e29c20d1]*/
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000314{
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000315 return PyNumber_Absolute(x);
Guido van Rossum3f5da241990-12-20 15:06:42 +0000316}
317
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000318/*[clinic input]
319all as builtin_all
320
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300321 iterable: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000322 /
323
324Return True if bool(x) is True for all values x in the iterable.
325
326If the iterable is empty, return True.
327[clinic start generated code]*/
328
Raymond Hettinger96229b12005-03-11 06:49:40 +0000329static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300330builtin_all(PyObject *module, PyObject *iterable)
331/*[clinic end generated code: output=ca2a7127276f79b3 input=1a7c5d1bc3438a21]*/
Raymond Hettinger96229b12005-03-11 06:49:40 +0000332{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000333 PyObject *it, *item;
334 PyObject *(*iternext)(PyObject *);
335 int cmp;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000336
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000337 it = PyObject_GetIter(iterable);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000338 if (it == NULL)
339 return NULL;
340 iternext = *Py_TYPE(it)->tp_iternext;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000341
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000342 for (;;) {
343 item = iternext(it);
344 if (item == NULL)
345 break;
346 cmp = PyObject_IsTrue(item);
347 Py_DECREF(item);
348 if (cmp < 0) {
349 Py_DECREF(it);
350 return NULL;
351 }
352 if (cmp == 0) {
353 Py_DECREF(it);
354 Py_RETURN_FALSE;
355 }
356 }
357 Py_DECREF(it);
358 if (PyErr_Occurred()) {
359 if (PyErr_ExceptionMatches(PyExc_StopIteration))
360 PyErr_Clear();
361 else
362 return NULL;
363 }
364 Py_RETURN_TRUE;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000365}
366
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000367/*[clinic input]
368any as builtin_any
369
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300370 iterable: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000371 /
372
373Return True if bool(x) is True for any x in the iterable.
374
375If the iterable is empty, return False.
376[clinic start generated code]*/
377
Raymond Hettinger96229b12005-03-11 06:49:40 +0000378static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300379builtin_any(PyObject *module, PyObject *iterable)
380/*[clinic end generated code: output=fa65684748caa60e input=41d7451c23384f24]*/
Raymond Hettinger96229b12005-03-11 06:49:40 +0000381{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000382 PyObject *it, *item;
383 PyObject *(*iternext)(PyObject *);
384 int cmp;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000385
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000386 it = PyObject_GetIter(iterable);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000387 if (it == NULL)
388 return NULL;
389 iternext = *Py_TYPE(it)->tp_iternext;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000390
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000391 for (;;) {
392 item = iternext(it);
393 if (item == NULL)
394 break;
395 cmp = PyObject_IsTrue(item);
396 Py_DECREF(item);
397 if (cmp < 0) {
398 Py_DECREF(it);
399 return NULL;
400 }
Raymond Hettinger5098b582015-10-09 00:42:47 -0400401 if (cmp > 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000402 Py_DECREF(it);
403 Py_RETURN_TRUE;
404 }
405 }
406 Py_DECREF(it);
407 if (PyErr_Occurred()) {
408 if (PyErr_ExceptionMatches(PyExc_StopIteration))
409 PyErr_Clear();
410 else
411 return NULL;
412 }
413 Py_RETURN_FALSE;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000414}
415
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000416/*[clinic input]
417ascii as builtin_ascii
418
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300419 obj: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000420 /
421
422Return an ASCII-only representation of an object.
423
424As repr(), return a string containing a printable representation of an
425object, but escape the non-ASCII characters in the string returned by
426repr() using \\x, \\u or \\U escapes. This generates a string similar
427to that returned by repr() in Python 2.
428[clinic start generated code]*/
429
Georg Brandl559e5d72008-06-11 18:37:52 +0000430static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300431builtin_ascii(PyObject *module, PyObject *obj)
432/*[clinic end generated code: output=6d37b3f0984c7eb9 input=4c62732e1b3a3cc9]*/
Georg Brandl559e5d72008-06-11 18:37:52 +0000433{
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000434 return PyObject_ASCII(obj);
Georg Brandl559e5d72008-06-11 18:37:52 +0000435}
436
Georg Brandl559e5d72008-06-11 18:37:52 +0000437
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000438/*[clinic input]
439bin as builtin_bin
440
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300441 number: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000442 /
443
444Return the binary representation of an integer.
445
446 >>> bin(2796202)
447 '0b1010101010101010101010'
448[clinic start generated code]*/
449
Guido van Rossum79f25d91997-04-29 20:08:16 +0000450static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300451builtin_bin(PyObject *module, PyObject *number)
452/*[clinic end generated code: output=b6fc4ad5e649f4f7 input=53f8a0264bacaf90]*/
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000453{
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000454 return PyNumber_ToBase(number, 2);
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000455}
456
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000457
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000458/*[clinic input]
459callable as builtin_callable
460
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300461 obj: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000462 /
463
464Return whether the object is callable (i.e., some kind of function).
465
466Note that classes are callable, as are instances of classes with a
467__call__() method.
468[clinic start generated code]*/
469
Antoine Pitroue71362d2010-11-27 22:00:11 +0000470static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300471builtin_callable(PyObject *module, PyObject *obj)
472/*[clinic end generated code: output=2b095d59d934cb7e input=1423bab99cc41f58]*/
Antoine Pitroue71362d2010-11-27 22:00:11 +0000473{
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000474 return PyBool_FromLong((long)PyCallable_Check(obj));
Antoine Pitroue71362d2010-11-27 22:00:11 +0000475}
476
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400477static PyObject *
Serhiy Storchakaa5552f02017-12-15 13:11:11 +0200478builtin_breakpoint(PyObject *self, PyObject *const *args, Py_ssize_t nargs, PyObject *keywords)
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400479{
480 PyObject *hook = PySys_GetObject("breakpointhook");
481
482 if (hook == NULL) {
483 PyErr_SetString(PyExc_RuntimeError, "lost sys.breakpointhook");
484 return NULL;
485 }
Steve Dower60419a72019-06-24 08:42:54 -0700486
487 if (PySys_Audit("builtins.breakpoint", "O", hook) < 0) {
488 return NULL;
489 }
490
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400491 Py_INCREF(hook);
Petr Viktorinffd97532020-02-11 17:46:57 +0100492 PyObject *retval = PyObject_Vectorcall(hook, args, nargs, keywords);
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400493 Py_DECREF(hook);
494 return retval;
495}
496
497PyDoc_STRVAR(breakpoint_doc,
498"breakpoint(*args, **kws)\n\
499\n\
500Call sys.breakpointhook(*args, **kws). sys.breakpointhook() must accept\n\
501whatever arguments are passed.\n\
502\n\
503By default, this drops you into the pdb debugger.");
Antoine Pitroue71362d2010-11-27 22:00:11 +0000504
Raymond Hettinger17301e92008-03-13 00:19:26 +0000505typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000506 PyObject_HEAD
507 PyObject *func;
508 PyObject *it;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000509} filterobject;
510
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000511static PyObject *
Raymond Hettinger17301e92008-03-13 00:19:26 +0000512filter_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
Guido van Rossum12d12c51993-10-26 17:58:25 +0000513{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000514 PyObject *func, *seq;
515 PyObject *it;
516 filterobject *lz;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000517
Serhiy Storchaka6cca5c82017-06-08 14:41:19 +0300518 if (type == &PyFilter_Type && !_PyArg_NoKeywords("filter", kwds))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000519 return NULL;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000520
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000521 if (!PyArg_UnpackTuple(args, "filter", 2, 2, &func, &seq))
522 return NULL;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000523
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000524 /* Get iterator. */
525 it = PyObject_GetIter(seq);
526 if (it == NULL)
527 return NULL;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000528
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000529 /* create filterobject structure */
530 lz = (filterobject *)type->tp_alloc(type, 0);
531 if (lz == NULL) {
532 Py_DECREF(it);
533 return NULL;
534 }
535 Py_INCREF(func);
536 lz->func = func;
537 lz->it = it;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000538
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000539 return (PyObject *)lz;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000540}
541
542static void
543filter_dealloc(filterobject *lz)
544{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000545 PyObject_GC_UnTrack(lz);
546 Py_XDECREF(lz->func);
547 Py_XDECREF(lz->it);
548 Py_TYPE(lz)->tp_free(lz);
Raymond Hettinger17301e92008-03-13 00:19:26 +0000549}
550
551static int
552filter_traverse(filterobject *lz, visitproc visit, void *arg)
553{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000554 Py_VISIT(lz->it);
555 Py_VISIT(lz->func);
556 return 0;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000557}
558
559static PyObject *
560filter_next(filterobject *lz)
561{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000562 PyObject *item;
563 PyObject *it = lz->it;
564 long ok;
565 PyObject *(*iternext)(PyObject *);
Raymond Hettingerbd5f0e82015-10-09 01:34:08 -0400566 int checktrue = lz->func == Py_None || lz->func == (PyObject *)&PyBool_Type;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000567
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000568 iternext = *Py_TYPE(it)->tp_iternext;
569 for (;;) {
570 item = iternext(it);
571 if (item == NULL)
572 return NULL;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000573
Raymond Hettingerbd5f0e82015-10-09 01:34:08 -0400574 if (checktrue) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000575 ok = PyObject_IsTrue(item);
576 } else {
577 PyObject *good;
Petr Viktorinffd97532020-02-11 17:46:57 +0100578 good = PyObject_CallOneArg(lz->func, item);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000579 if (good == NULL) {
580 Py_DECREF(item);
581 return NULL;
582 }
583 ok = PyObject_IsTrue(good);
584 Py_DECREF(good);
585 }
Antoine Pitrou6f430e42012-08-15 23:18:25 +0200586 if (ok > 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000587 return item;
588 Py_DECREF(item);
Antoine Pitrou6f430e42012-08-15 23:18:25 +0200589 if (ok < 0)
590 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000591 }
Guido van Rossum12d12c51993-10-26 17:58:25 +0000592}
593
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +0000594static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +0530595filter_reduce(filterobject *lz, PyObject *Py_UNUSED(ignored))
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +0000596{
597 return Py_BuildValue("O(OO)", Py_TYPE(lz), lz->func, lz->it);
598}
599
600PyDoc_STRVAR(reduce_doc, "Return state information for pickling.");
601
602static PyMethodDef filter_methods[] = {
603 {"__reduce__", (PyCFunction)filter_reduce, METH_NOARGS, reduce_doc},
604 {NULL, NULL} /* sentinel */
605};
606
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000607PyDoc_STRVAR(filter_doc,
Georg Brandld11ae5d2008-05-16 13:27:32 +0000608"filter(function or None, iterable) --> filter object\n\
Guido van Rossumc1f779c2007-07-03 08:25:58 +0000609\n\
Georg Brandld11ae5d2008-05-16 13:27:32 +0000610Return an iterator yielding those items of iterable for which function(item)\n\
Raymond Hettinger17301e92008-03-13 00:19:26 +0000611is true. If function is None, return the items that are true.");
612
613PyTypeObject PyFilter_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000614 PyVarObject_HEAD_INIT(&PyType_Type, 0)
615 "filter", /* tp_name */
616 sizeof(filterobject), /* tp_basicsize */
617 0, /* tp_itemsize */
618 /* methods */
619 (destructor)filter_dealloc, /* tp_dealloc */
Jeroen Demeyer530f5062019-05-31 04:13:39 +0200620 0, /* tp_vectorcall_offset */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000621 0, /* tp_getattr */
622 0, /* tp_setattr */
Jeroen Demeyer530f5062019-05-31 04:13:39 +0200623 0, /* tp_as_async */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000624 0, /* tp_repr */
625 0, /* tp_as_number */
626 0, /* tp_as_sequence */
627 0, /* tp_as_mapping */
628 0, /* tp_hash */
629 0, /* tp_call */
630 0, /* tp_str */
631 PyObject_GenericGetAttr, /* tp_getattro */
632 0, /* tp_setattro */
633 0, /* tp_as_buffer */
634 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
635 Py_TPFLAGS_BASETYPE, /* tp_flags */
636 filter_doc, /* tp_doc */
637 (traverseproc)filter_traverse, /* tp_traverse */
638 0, /* tp_clear */
639 0, /* tp_richcompare */
640 0, /* tp_weaklistoffset */
641 PyObject_SelfIter, /* tp_iter */
642 (iternextfunc)filter_next, /* tp_iternext */
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +0000643 filter_methods, /* tp_methods */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000644 0, /* tp_members */
645 0, /* tp_getset */
646 0, /* tp_base */
647 0, /* tp_dict */
648 0, /* tp_descr_get */
649 0, /* tp_descr_set */
650 0, /* tp_dictoffset */
651 0, /* tp_init */
652 PyType_GenericAlloc, /* tp_alloc */
653 filter_new, /* tp_new */
654 PyObject_GC_Del, /* tp_free */
Raymond Hettinger17301e92008-03-13 00:19:26 +0000655};
656
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000657
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000658/*[clinic input]
659format as builtin_format
660
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300661 value: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000662 format_spec: unicode(c_default="NULL") = ''
663 /
664
665Return value.__format__(format_spec)
666
Amit Kumar2e6bb442017-05-29 06:32:26 +0530667format_spec defaults to the empty string.
668See the Format Specification Mini-Language section of help('FORMATTING') for
669details.
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000670[clinic start generated code]*/
671
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000672static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300673builtin_format_impl(PyObject *module, PyObject *value, PyObject *format_spec)
Amit Kumar2e6bb442017-05-29 06:32:26 +0530674/*[clinic end generated code: output=2f40bdfa4954b077 input=88339c93ea522b33]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000675{
Eric Smith8fd3eba2008-02-17 19:48:00 +0000676 return PyObject_Format(value, format_spec);
Eric Smith8c663262007-08-25 02:26:07 +0000677}
678
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000679/*[clinic input]
680chr as builtin_chr
681
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300682 i: int
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000683 /
684
685Return a Unicode string of one character with ordinal i; 0 <= i <= 0x10ffff.
686[clinic start generated code]*/
687
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000688static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300689builtin_chr_impl(PyObject *module, int i)
690/*[clinic end generated code: output=c733afcd200afcb7 input=3f604ef45a70750d]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000691{
692 return PyUnicode_FromOrdinal(i);
693}
Guido van Rossum09095f32000-03-10 23:00:52 +0000694
695
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000696/*[clinic input]
697compile as builtin_compile
698
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300699 source: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000700 filename: object(converter="PyUnicode_FSDecoder")
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300701 mode: str
702 flags: int = 0
Serhiy Storchaka202fda52017-03-12 10:10:47 +0200703 dont_inherit: bool(accept={int}) = False
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300704 optimize: int = -1
Victor Stinnerefdf6ca2019-06-12 02:52:16 +0200705 *
706 _feature_version as feature_version: int = -1
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000707
708Compile source into a code object that can be executed by exec() or eval().
709
710The source code may represent a Python module, statement or expression.
711The filename will be used for run-time error messages.
712The mode must be 'exec' to compile a module, 'single' to compile a
713single (interactive) statement, or 'eval' to compile an expression.
714The flags argument, if present, controls which future statements influence
715the compilation of the code.
Serhiy Storchaka8b2e8b62015-05-30 11:30:39 +0300716The dont_inherit argument, if true, stops the compilation inheriting
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000717the effects of any future statements in effect in the code calling
Serhiy Storchaka8b2e8b62015-05-30 11:30:39 +0300718compile; if absent or false these statements do influence the compilation,
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000719in addition to any features explicitly specified.
720[clinic start generated code]*/
721
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000722static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300723builtin_compile_impl(PyObject *module, PyObject *source, PyObject *filename,
724 const char *mode, int flags, int dont_inherit,
Guido van Rossum495da292019-03-07 12:38:08 -0800725 int optimize, int feature_version)
Victor Stinnerefdf6ca2019-06-12 02:52:16 +0200726/*[clinic end generated code: output=b0c09c84f116d3d7 input=40171fb92c1d580d]*/
Guido van Rossum5b722181993-03-30 17:46:03 +0000727{
Martin Panter61d6e4a2015-11-07 02:56:11 +0000728 PyObject *source_copy;
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +0200729 const char *str;
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000730 int compile_mode = -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000731 int is_ast;
Guido van Rossumdcfcd142019-01-31 03:40:27 -0800732 int start[] = {Py_file_input, Py_eval_input, Py_single_input, Py_func_type_input};
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000733 PyObject *result;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000734
Victor Stinner37d66d72019-06-13 02:16:41 +0200735 PyCompilerFlags cf = _PyCompilerFlags_INIT;
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000736 cf.cf_flags = flags | PyCF_SOURCE_IS_UTF8;
Guido van Rossum495da292019-03-07 12:38:08 -0800737 if (feature_version >= 0 && (flags & PyCF_ONLY_AST)) {
738 cf.cf_feature_version = feature_version;
739 }
Tim Peters6cd6a822001-08-17 22:11:27 +0000740
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000741 if (flags &
Guido van Rossumdcfcd142019-01-31 03:40:27 -0800742 ~(PyCF_MASK | PyCF_MASK_OBSOLETE | PyCF_DONT_IMPLY_DEDENT | PyCF_ONLY_AST | PyCF_TYPE_COMMENTS))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000743 {
744 PyErr_SetString(PyExc_ValueError,
745 "compile(): unrecognised flags");
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000746 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000747 }
748 /* XXX Warn if (supplied_flags & PyCF_MASK_OBSOLETE) != 0? */
Tim Peters6cd6a822001-08-17 22:11:27 +0000749
Georg Brandl8334fd92010-12-04 10:26:46 +0000750 if (optimize < -1 || optimize > 2) {
751 PyErr_SetString(PyExc_ValueError,
752 "compile(): invalid optimize value");
753 goto error;
754 }
755
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000756 if (!dont_inherit) {
757 PyEval_MergeCompilerFlags(&cf);
758 }
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000759
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000760 if (strcmp(mode, "exec") == 0)
761 compile_mode = 0;
762 else if (strcmp(mode, "eval") == 0)
763 compile_mode = 1;
764 else if (strcmp(mode, "single") == 0)
765 compile_mode = 2;
Guido van Rossumdcfcd142019-01-31 03:40:27 -0800766 else if (strcmp(mode, "func_type") == 0) {
767 if (!(flags & PyCF_ONLY_AST)) {
768 PyErr_SetString(PyExc_ValueError,
769 "compile() mode 'func_type' requires flag PyCF_ONLY_AST");
770 goto error;
771 }
772 compile_mode = 3;
773 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000774 else {
Guido van Rossumdcfcd142019-01-31 03:40:27 -0800775 const char *msg;
776 if (flags & PyCF_ONLY_AST)
777 msg = "compile() mode must be 'exec', 'eval', 'single' or 'func_type'";
778 else
779 msg = "compile() mode must be 'exec', 'eval' or 'single'";
780 PyErr_SetString(PyExc_ValueError, msg);
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000781 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000782 }
Neal Norwitzdb4115f2008-03-31 04:20:05 +0000783
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000784 is_ast = PyAST_Check(source);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000785 if (is_ast == -1)
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000786 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000787 if (is_ast) {
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000788 if (flags & PyCF_ONLY_AST) {
789 Py_INCREF(source);
790 result = source;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000791 }
792 else {
793 PyArena *arena;
794 mod_ty mod;
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000795
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000796 arena = PyArena_New();
Stefan Krah07795df2012-08-20 17:19:50 +0200797 if (arena == NULL)
798 goto error;
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000799 mod = PyAST_obj2mod(source, arena, compile_mode);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000800 if (mod == NULL) {
801 PyArena_Free(arena);
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000802 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000803 }
Benjamin Peterson832bfe22011-08-09 16:15:04 -0500804 if (!PyAST_Validate(mod)) {
805 PyArena_Free(arena);
806 goto error;
807 }
Victor Stinner14e461d2013-08-26 22:28:21 +0200808 result = (PyObject*)PyAST_CompileObject(mod, filename,
809 &cf, optimize, arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000810 PyArena_Free(arena);
811 }
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000812 goto finally;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000813 }
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000814
Dino Viehland41540692019-05-28 16:21:17 -0700815 str = _Py_SourceAsString(source, "compile", "string, bytes or AST", &cf, &source_copy);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000816 if (str == NULL)
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000817 goto error;
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000818
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000819 result = Py_CompileStringObject(str, filename, start[compile_mode], &cf, optimize);
Martin Panter61d6e4a2015-11-07 02:56:11 +0000820 Py_XDECREF(source_copy);
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000821 goto finally;
822
823error:
824 result = NULL;
825finally:
Victor Stinner14e461d2013-08-26 22:28:21 +0200826 Py_DECREF(filename);
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000827 return result;
Guido van Rossum5b722181993-03-30 17:46:03 +0000828}
829
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000830/* AC: cannot convert yet, as needs PEP 457 group support in inspect */
Guido van Rossum79f25d91997-04-29 20:08:16 +0000831static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000832builtin_dir(PyObject *self, PyObject *args)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000833{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000834 PyObject *arg = NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000835
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000836 if (!PyArg_UnpackTuple(args, "dir", 0, 1, &arg))
837 return NULL;
838 return PyObject_Dir(arg);
Guido van Rossum3f5da241990-12-20 15:06:42 +0000839}
840
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000841PyDoc_STRVAR(dir_doc,
Tim Peters5d2b77c2001-09-03 05:47:38 +0000842"dir([object]) -> list of strings\n"
843"\n"
Georg Brandle32b4222007-03-10 22:13:27 +0000844"If called without an argument, return the names in the current scope.\n"
845"Else, return an alphabetized list of names comprising (some of) the attributes\n"
846"of the given object, and of attributes reachable from it.\n"
847"If the object supplies a method named __dir__, it will be used; otherwise\n"
848"the default dir() logic is used and returns:\n"
849" for a module object: the module's attributes.\n"
850" for a class object: its attributes, and recursively the attributes\n"
851" of its bases.\n"
Guido van Rossumd8faa362007-04-27 19:54:29 +0000852" for any other object: its attributes, its class's attributes, and\n"
Georg Brandle32b4222007-03-10 22:13:27 +0000853" recursively the attributes of its class's base classes.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000854
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000855/*[clinic input]
856divmod as builtin_divmod
Guido van Rossum6a00cd81995-01-07 12:39:01 +0000857
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300858 x: object
859 y: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000860 /
861
Zachary Ware7f227d92016-04-28 14:39:50 -0500862Return the tuple (x//y, x%y). Invariant: div*y + mod == x.
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000863[clinic start generated code]*/
864
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000865static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300866builtin_divmod_impl(PyObject *module, PyObject *x, PyObject *y)
867/*[clinic end generated code: output=b06d8a5f6e0c745e input=175ad9c84ff41a85]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000868{
869 return PyNumber_Divmod(x, y);
870}
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000871
872
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000873/*[clinic input]
874eval as builtin_eval
875
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300876 source: object
877 globals: object = None
878 locals: object = None
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000879 /
880
881Evaluate the given source in the context of globals and locals.
882
883The source may be a string representing a Python expression
884or a code object as returned by compile().
885The globals must be a dictionary and locals can be any mapping,
886defaulting to the current globals and locals.
887If only globals is given, locals defaults to it.
888[clinic start generated code]*/
889
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000890static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300891builtin_eval_impl(PyObject *module, PyObject *source, PyObject *globals,
Larry Hastings89964c42015-04-14 18:07:59 -0400892 PyObject *locals)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300893/*[clinic end generated code: output=0a0824aa70093116 input=11ee718a8640e527]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000894{
Martin Panter61d6e4a2015-11-07 02:56:11 +0000895 PyObject *result, *source_copy;
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +0200896 const char *str;
Guido van Rossum590baa41993-11-30 13:40:46 +0000897
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000898 if (locals != Py_None && !PyMapping_Check(locals)) {
899 PyErr_SetString(PyExc_TypeError, "locals must be a mapping");
900 return NULL;
901 }
902 if (globals != Py_None && !PyDict_Check(globals)) {
903 PyErr_SetString(PyExc_TypeError, PyMapping_Check(globals) ?
904 "globals must be a real dict; try eval(expr, {}, mapping)"
905 : "globals must be a dict");
906 return NULL;
907 }
908 if (globals == Py_None) {
909 globals = PyEval_GetGlobals();
Victor Stinner41bb43a2013-10-29 01:19:37 +0100910 if (locals == Py_None) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000911 locals = PyEval_GetLocals();
Victor Stinner41bb43a2013-10-29 01:19:37 +0100912 if (locals == NULL)
913 return NULL;
914 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000915 }
916 else if (locals == Py_None)
917 locals = globals;
Tim Peters9fa96be2001-08-17 23:04:59 +0000918
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000919 if (globals == NULL || locals == NULL) {
920 PyErr_SetString(PyExc_TypeError,
921 "eval must be given globals and locals "
922 "when called without a frame");
923 return NULL;
924 }
Georg Brandl77c85e62005-09-15 10:46:13 +0000925
Serhiy Storchakaa24107b2019-02-25 17:59:46 +0200926 if (_PyDict_GetItemIdWithError(globals, &PyId___builtins__) == NULL) {
Victor Stinnerb44562b2013-11-06 19:03:11 +0100927 if (_PyDict_SetItemId(globals, &PyId___builtins__,
928 PyEval_GetBuiltins()) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000929 return NULL;
930 }
Serhiy Storchakaa24107b2019-02-25 17:59:46 +0200931 else if (PyErr_Occurred()) {
932 return NULL;
933 }
Tim Peters9fa96be2001-08-17 23:04:59 +0000934
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000935 if (PyCode_Check(source)) {
Steve Dowerb82e17e2019-05-23 08:45:22 -0700936 if (PySys_Audit("exec", "O", source) < 0) {
937 return NULL;
938 }
939
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000940 if (PyCode_GetNumFree((PyCodeObject *)source) > 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000941 PyErr_SetString(PyExc_TypeError,
Steve Dowerb82e17e2019-05-23 08:45:22 -0700942 "code object passed to eval() may not contain free variables");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000943 return NULL;
944 }
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000945 return PyEval_EvalCode(source, globals, locals);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000946 }
Tim Peters9fa96be2001-08-17 23:04:59 +0000947
Victor Stinner37d66d72019-06-13 02:16:41 +0200948 PyCompilerFlags cf = _PyCompilerFlags_INIT;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000949 cf.cf_flags = PyCF_SOURCE_IS_UTF8;
Dino Viehland41540692019-05-28 16:21:17 -0700950 str = _Py_SourceAsString(source, "eval", "string, bytes or code", &cf, &source_copy);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000951 if (str == NULL)
952 return NULL;
Just van Rossum3aaf42c2003-02-10 08:21:10 +0000953
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000954 while (*str == ' ' || *str == '\t')
955 str++;
Tim Peters9fa96be2001-08-17 23:04:59 +0000956
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000957 (void)PyEval_MergeCompilerFlags(&cf);
958 result = PyRun_StringFlags(str, Py_eval_input, globals, locals, &cf);
Martin Panter61d6e4a2015-11-07 02:56:11 +0000959 Py_XDECREF(source_copy);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000960 return result;
Guido van Rossum3f5da241990-12-20 15:06:42 +0000961}
962
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000963/*[clinic input]
964exec as builtin_exec
965
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300966 source: object
967 globals: object = None
968 locals: object = None
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000969 /
970
971Execute the given source in the context of globals and locals.
972
973The source may be a string representing one or more Python statements
974or a code object as returned by compile().
975The globals must be a dictionary and locals can be any mapping,
976defaulting to the current globals and locals.
977If only globals is given, locals defaults to it.
978[clinic start generated code]*/
979
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000980static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300981builtin_exec_impl(PyObject *module, PyObject *source, PyObject *globals,
Larry Hastings89964c42015-04-14 18:07:59 -0400982 PyObject *locals)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300983/*[clinic end generated code: output=3c90efc6ab68ef5d input=01ca3e1c01692829]*/
Georg Brandl7cae87c2006-09-06 06:51:57 +0000984{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000985 PyObject *v;
Georg Brandl2cabc562008-08-28 07:57:16 +0000986
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000987 if (globals == Py_None) {
988 globals = PyEval_GetGlobals();
989 if (locals == Py_None) {
990 locals = PyEval_GetLocals();
Victor Stinner41bb43a2013-10-29 01:19:37 +0100991 if (locals == NULL)
992 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000993 }
994 if (!globals || !locals) {
995 PyErr_SetString(PyExc_SystemError,
996 "globals and locals cannot be NULL");
997 return NULL;
998 }
999 }
1000 else if (locals == Py_None)
1001 locals = globals;
Georg Brandl7cae87c2006-09-06 06:51:57 +00001002
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001003 if (!PyDict_Check(globals)) {
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001004 PyErr_Format(PyExc_TypeError, "exec() globals must be a dict, not %.100s",
Victor Stinnera102ed72020-02-07 02:24:48 +01001005 Py_TYPE(globals)->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001006 return NULL;
1007 }
1008 if (!PyMapping_Check(locals)) {
1009 PyErr_Format(PyExc_TypeError,
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001010 "locals must be a mapping or None, not %.100s",
Victor Stinnera102ed72020-02-07 02:24:48 +01001011 Py_TYPE(locals)->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001012 return NULL;
1013 }
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02001014 if (_PyDict_GetItemIdWithError(globals, &PyId___builtins__) == NULL) {
Victor Stinnerb44562b2013-11-06 19:03:11 +01001015 if (_PyDict_SetItemId(globals, &PyId___builtins__,
1016 PyEval_GetBuiltins()) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001017 return NULL;
1018 }
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02001019 else if (PyErr_Occurred()) {
1020 return NULL;
1021 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001022
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001023 if (PyCode_Check(source)) {
Steve Dowerb82e17e2019-05-23 08:45:22 -07001024 if (PySys_Audit("exec", "O", source) < 0) {
1025 return NULL;
1026 }
1027
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001028 if (PyCode_GetNumFree((PyCodeObject *)source) > 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001029 PyErr_SetString(PyExc_TypeError,
1030 "code object passed to exec() may not "
1031 "contain free variables");
1032 return NULL;
1033 }
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001034 v = PyEval_EvalCode(source, globals, locals);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001035 }
1036 else {
Martin Panter61d6e4a2015-11-07 02:56:11 +00001037 PyObject *source_copy;
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +02001038 const char *str;
Victor Stinner37d66d72019-06-13 02:16:41 +02001039 PyCompilerFlags cf = _PyCompilerFlags_INIT;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001040 cf.cf_flags = PyCF_SOURCE_IS_UTF8;
Dino Viehland41540692019-05-28 16:21:17 -07001041 str = _Py_SourceAsString(source, "exec",
Martin Panter61d6e4a2015-11-07 02:56:11 +00001042 "string, bytes or code", &cf,
1043 &source_copy);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001044 if (str == NULL)
1045 return NULL;
1046 if (PyEval_MergeCompilerFlags(&cf))
1047 v = PyRun_StringFlags(str, Py_file_input, globals,
1048 locals, &cf);
1049 else
1050 v = PyRun_String(str, Py_file_input, globals, locals);
Martin Panter61d6e4a2015-11-07 02:56:11 +00001051 Py_XDECREF(source_copy);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001052 }
1053 if (v == NULL)
1054 return NULL;
1055 Py_DECREF(v);
1056 Py_RETURN_NONE;
Georg Brandl7cae87c2006-09-06 06:51:57 +00001057}
1058
Georg Brandl7cae87c2006-09-06 06:51:57 +00001059
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001060/* AC: cannot convert yet, as needs PEP 457 group support in inspect */
Guido van Rossum79f25d91997-04-29 20:08:16 +00001061static PyObject *
Serhiy Storchakaa5552f02017-12-15 13:11:11 +02001062builtin_getattr(PyObject *self, PyObject *const *args, Py_ssize_t nargs)
Guido van Rossum33894be1992-01-27 16:53:09 +00001063{
Serhiy Storchaka79342662019-01-12 08:25:41 +02001064 PyObject *v, *name, *result;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001065
Serhiy Storchaka79342662019-01-12 08:25:41 +02001066 if (!_PyArg_CheckPositional("getattr", nargs, 2, 3))
Sylvain96c7c062017-06-15 17:05:23 +02001067 return NULL;
1068
Serhiy Storchaka79342662019-01-12 08:25:41 +02001069 v = args[0];
1070 name = args[1];
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001071 if (!PyUnicode_Check(name)) {
1072 PyErr_SetString(PyExc_TypeError,
1073 "getattr(): attribute name must be string");
1074 return NULL;
1075 }
Serhiy Storchaka79342662019-01-12 08:25:41 +02001076 if (nargs > 2) {
Serhiy Storchakaf320be72018-01-25 10:49:40 +02001077 if (_PyObject_LookupAttr(v, name, &result) == 0) {
Serhiy Storchaka79342662019-01-12 08:25:41 +02001078 PyObject *dflt = args[2];
INADA Naoki378edee2018-01-16 20:52:41 +09001079 Py_INCREF(dflt);
1080 return dflt;
1081 }
1082 }
1083 else {
1084 result = PyObject_GetAttr(v, name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001085 }
1086 return result;
Guido van Rossum9bfef441993-03-29 10:43:31 +00001087}
1088
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001089PyDoc_STRVAR(getattr_doc,
Guido van Rossum950ff291998-06-29 13:38:57 +00001090"getattr(object, name[, default]) -> value\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001091\n\
Guido van Rossum950ff291998-06-29 13:38:57 +00001092Get a named attribute from an object; getattr(x, 'y') is equivalent to x.y.\n\
1093When a default argument is given, it is returned when the attribute doesn't\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001094exist; without it, an exception is raised in that case.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001095
1096
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001097/*[clinic input]
1098globals as builtin_globals
1099
1100Return the dictionary containing the current scope's global variables.
1101
1102NOTE: Updates to this dictionary *will* affect name lookups in the current
1103global scope and vice-versa.
1104[clinic start generated code]*/
1105
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001106static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001107builtin_globals_impl(PyObject *module)
1108/*[clinic end generated code: output=e5dd1527067b94d2 input=9327576f92bb48ba]*/
Guido van Rossum872537c1995-07-07 22:43:42 +00001109{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001110 PyObject *d;
Guido van Rossum872537c1995-07-07 22:43:42 +00001111
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001112 d = PyEval_GetGlobals();
1113 Py_XINCREF(d);
1114 return d;
Guido van Rossum872537c1995-07-07 22:43:42 +00001115}
1116
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001117
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001118/*[clinic input]
1119hasattr as builtin_hasattr
1120
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001121 obj: object
1122 name: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001123 /
1124
1125Return whether the object has an attribute with the given name.
1126
1127This is done by calling getattr(obj, name) and catching AttributeError.
1128[clinic start generated code]*/
1129
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001130static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001131builtin_hasattr_impl(PyObject *module, PyObject *obj, PyObject *name)
1132/*[clinic end generated code: output=a7aff2090a4151e5 input=0faec9787d979542]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001133{
1134 PyObject *v;
1135
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001136 if (!PyUnicode_Check(name)) {
1137 PyErr_SetString(PyExc_TypeError,
1138 "hasattr(): attribute name must be string");
1139 return NULL;
1140 }
Serhiy Storchakaf320be72018-01-25 10:49:40 +02001141 if (_PyObject_LookupAttr(obj, name, &v) < 0) {
Benjamin Peterson17689992010-08-24 03:26:23 +00001142 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001143 }
Serhiy Storchakaf320be72018-01-25 10:49:40 +02001144 if (v == NULL) {
1145 Py_RETURN_FALSE;
1146 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001147 Py_DECREF(v);
Benjamin Peterson17689992010-08-24 03:26:23 +00001148 Py_RETURN_TRUE;
Guido van Rossum33894be1992-01-27 16:53:09 +00001149}
1150
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001151
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001152/* AC: gdb's integration with CPython relies on builtin_id having
1153 * the *exact* parameter names of "self" and "v", so we ensure we
1154 * preserve those name rather than using the AC defaults.
1155 */
1156/*[clinic input]
1157id as builtin_id
1158
Serhiy Storchaka24182a32016-05-05 16:21:35 +03001159 self: self(type="PyModuleDef *")
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001160 obj as v: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001161 /
1162
1163Return the identity of an object.
1164
1165This is guaranteed to be unique among simultaneously existing objects.
1166(CPython uses the object's memory address.)
1167[clinic start generated code]*/
1168
Guido van Rossum79f25d91997-04-29 20:08:16 +00001169static PyObject *
Serhiy Storchaka24182a32016-05-05 16:21:35 +03001170builtin_id(PyModuleDef *self, PyObject *v)
1171/*[clinic end generated code: output=0aa640785f697f65 input=5a534136419631f4]*/
Guido van Rossum5b722181993-03-30 17:46:03 +00001172{
Steve Dowerb82e17e2019-05-23 08:45:22 -07001173 PyObject *id = PyLong_FromVoidPtr(v);
1174
1175 if (id && PySys_Audit("builtins.id", "O", id) < 0) {
1176 Py_DECREF(id);
1177 return NULL;
1178 }
1179
1180 return id;
Guido van Rossum5b722181993-03-30 17:46:03 +00001181}
1182
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001183
Raymond Hettingera6c60372008-03-13 01:26:19 +00001184/* map object ************************************************************/
1185
1186typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001187 PyObject_HEAD
1188 PyObject *iters;
1189 PyObject *func;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001190} mapobject;
1191
Guido van Rossum79f25d91997-04-29 20:08:16 +00001192static PyObject *
Raymond Hettingera6c60372008-03-13 01:26:19 +00001193map_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
Guido van Rossum12d12c51993-10-26 17:58:25 +00001194{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001195 PyObject *it, *iters, *func;
1196 mapobject *lz;
1197 Py_ssize_t numargs, i;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001198
Serhiy Storchaka6cca5c82017-06-08 14:41:19 +03001199 if (type == &PyMap_Type && !_PyArg_NoKeywords("map", kwds))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001200 return NULL;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001201
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001202 numargs = PyTuple_Size(args);
1203 if (numargs < 2) {
1204 PyErr_SetString(PyExc_TypeError,
1205 "map() must have at least two arguments.");
1206 return NULL;
1207 }
Raymond Hettingera6c60372008-03-13 01:26:19 +00001208
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001209 iters = PyTuple_New(numargs-1);
1210 if (iters == NULL)
1211 return NULL;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001212
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001213 for (i=1 ; i<numargs ; i++) {
1214 /* Get iterator. */
1215 it = PyObject_GetIter(PyTuple_GET_ITEM(args, i));
1216 if (it == NULL) {
1217 Py_DECREF(iters);
1218 return NULL;
1219 }
1220 PyTuple_SET_ITEM(iters, i-1, it);
1221 }
Raymond Hettingera6c60372008-03-13 01:26:19 +00001222
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001223 /* create mapobject structure */
1224 lz = (mapobject *)type->tp_alloc(type, 0);
1225 if (lz == NULL) {
1226 Py_DECREF(iters);
1227 return NULL;
1228 }
1229 lz->iters = iters;
1230 func = PyTuple_GET_ITEM(args, 0);
1231 Py_INCREF(func);
1232 lz->func = func;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001233
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001234 return (PyObject *)lz;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001235}
1236
1237static void
1238map_dealloc(mapobject *lz)
1239{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001240 PyObject_GC_UnTrack(lz);
1241 Py_XDECREF(lz->iters);
1242 Py_XDECREF(lz->func);
1243 Py_TYPE(lz)->tp_free(lz);
Raymond Hettingera6c60372008-03-13 01:26:19 +00001244}
1245
1246static int
1247map_traverse(mapobject *lz, visitproc visit, void *arg)
1248{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001249 Py_VISIT(lz->iters);
1250 Py_VISIT(lz->func);
1251 return 0;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001252}
1253
1254static PyObject *
1255map_next(mapobject *lz)
1256{
Victor Stinnerbc08ab42016-12-15 12:40:53 +01001257 PyObject *small_stack[_PY_FASTCALL_SMALL_STACK];
Victor Stinnercdb5cee2016-08-24 01:45:13 +02001258 PyObject **stack;
Victor Stinnercdb5cee2016-08-24 01:45:13 +02001259 PyObject *result = NULL;
Victor Stinner4d231bc2019-11-14 13:36:21 +01001260 PyThreadState *tstate = _PyThreadState_GET();
Raymond Hettingera6c60372008-03-13 01:26:19 +00001261
Victor Stinner4d231bc2019-11-14 13:36:21 +01001262 const Py_ssize_t niters = PyTuple_GET_SIZE(lz->iters);
Victor Stinnercdb5cee2016-08-24 01:45:13 +02001263 if (niters <= (Py_ssize_t)Py_ARRAY_LENGTH(small_stack)) {
1264 stack = small_stack;
1265 }
1266 else {
1267 stack = PyMem_Malloc(niters * sizeof(stack[0]));
1268 if (stack == NULL) {
Victor Stinner4d231bc2019-11-14 13:36:21 +01001269 _PyErr_NoMemory(tstate);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001270 return NULL;
1271 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001272 }
Victor Stinnercdb5cee2016-08-24 01:45:13 +02001273
Victor Stinner4d231bc2019-11-14 13:36:21 +01001274 Py_ssize_t nargs = 0;
1275 for (Py_ssize_t i=0; i < niters; i++) {
Victor Stinnercdb5cee2016-08-24 01:45:13 +02001276 PyObject *it = PyTuple_GET_ITEM(lz->iters, i);
1277 PyObject *val = Py_TYPE(it)->tp_iternext(it);
1278 if (val == NULL) {
1279 goto exit;
1280 }
1281 stack[i] = val;
1282 nargs++;
1283 }
1284
Victor Stinner4d231bc2019-11-14 13:36:21 +01001285 result = _PyObject_VectorcallTstate(tstate, lz->func, stack, nargs, NULL);
Victor Stinnercdb5cee2016-08-24 01:45:13 +02001286
1287exit:
Victor Stinner4d231bc2019-11-14 13:36:21 +01001288 for (Py_ssize_t i=0; i < nargs; i++) {
Victor Stinnercdb5cee2016-08-24 01:45:13 +02001289 Py_DECREF(stack[i]);
1290 }
1291 if (stack != small_stack) {
1292 PyMem_Free(stack);
1293 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001294 return result;
Guido van Rossum12d12c51993-10-26 17:58:25 +00001295}
1296
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001297static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05301298map_reduce(mapobject *lz, PyObject *Py_UNUSED(ignored))
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001299{
1300 Py_ssize_t numargs = PyTuple_GET_SIZE(lz->iters);
1301 PyObject *args = PyTuple_New(numargs+1);
1302 Py_ssize_t i;
1303 if (args == NULL)
1304 return NULL;
1305 Py_INCREF(lz->func);
1306 PyTuple_SET_ITEM(args, 0, lz->func);
1307 for (i = 0; i<numargs; i++){
1308 PyObject *it = PyTuple_GET_ITEM(lz->iters, i);
1309 Py_INCREF(it);
1310 PyTuple_SET_ITEM(args, i+1, it);
1311 }
1312
1313 return Py_BuildValue("ON", Py_TYPE(lz), args);
1314}
1315
1316static PyMethodDef map_methods[] = {
1317 {"__reduce__", (PyCFunction)map_reduce, METH_NOARGS, reduce_doc},
1318 {NULL, NULL} /* sentinel */
1319};
1320
1321
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001322PyDoc_STRVAR(map_doc,
Raymond Hettingera6c60372008-03-13 01:26:19 +00001323"map(func, *iterables) --> map object\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001324\n\
Raymond Hettingera6c60372008-03-13 01:26:19 +00001325Make an iterator that computes the function using arguments from\n\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001326each of the iterables. Stops when the shortest iterable is exhausted.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001327
Raymond Hettingera6c60372008-03-13 01:26:19 +00001328PyTypeObject PyMap_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001329 PyVarObject_HEAD_INIT(&PyType_Type, 0)
1330 "map", /* tp_name */
1331 sizeof(mapobject), /* tp_basicsize */
1332 0, /* tp_itemsize */
1333 /* methods */
1334 (destructor)map_dealloc, /* tp_dealloc */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02001335 0, /* tp_vectorcall_offset */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001336 0, /* tp_getattr */
1337 0, /* tp_setattr */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02001338 0, /* tp_as_async */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001339 0, /* tp_repr */
1340 0, /* tp_as_number */
1341 0, /* tp_as_sequence */
1342 0, /* tp_as_mapping */
1343 0, /* tp_hash */
1344 0, /* tp_call */
1345 0, /* tp_str */
1346 PyObject_GenericGetAttr, /* tp_getattro */
1347 0, /* tp_setattro */
1348 0, /* tp_as_buffer */
1349 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
1350 Py_TPFLAGS_BASETYPE, /* tp_flags */
1351 map_doc, /* tp_doc */
1352 (traverseproc)map_traverse, /* tp_traverse */
1353 0, /* tp_clear */
1354 0, /* tp_richcompare */
1355 0, /* tp_weaklistoffset */
1356 PyObject_SelfIter, /* tp_iter */
1357 (iternextfunc)map_next, /* tp_iternext */
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001358 map_methods, /* tp_methods */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001359 0, /* tp_members */
1360 0, /* tp_getset */
1361 0, /* tp_base */
1362 0, /* tp_dict */
1363 0, /* tp_descr_get */
1364 0, /* tp_descr_set */
1365 0, /* tp_dictoffset */
1366 0, /* tp_init */
1367 PyType_GenericAlloc, /* tp_alloc */
1368 map_new, /* tp_new */
1369 PyObject_GC_Del, /* tp_free */
Raymond Hettingera6c60372008-03-13 01:26:19 +00001370};
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001371
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001372
1373/* AC: cannot convert yet, as needs PEP 457 group support in inspect */
Guido van Rossum79f25d91997-04-29 20:08:16 +00001374static PyObject *
Serhiy Storchakaa5552f02017-12-15 13:11:11 +02001375builtin_next(PyObject *self, PyObject *const *args, Py_ssize_t nargs)
Georg Brandla18af4e2007-04-21 15:47:16 +00001376{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001377 PyObject *it, *res;
Georg Brandla18af4e2007-04-21 15:47:16 +00001378
Serhiy Storchaka79342662019-01-12 08:25:41 +02001379 if (!_PyArg_CheckPositional("next", nargs, 1, 2))
Sylvain96c7c062017-06-15 17:05:23 +02001380 return NULL;
1381
Serhiy Storchaka79342662019-01-12 08:25:41 +02001382 it = args[0];
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001383 if (!PyIter_Check(it)) {
1384 PyErr_Format(PyExc_TypeError,
Philip Jenvey50add042011-11-06 16:37:52 -08001385 "'%.200s' object is not an iterator",
Victor Stinnera102ed72020-02-07 02:24:48 +01001386 Py_TYPE(it)->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001387 return NULL;
1388 }
1389
Victor Stinnera102ed72020-02-07 02:24:48 +01001390 res = (*Py_TYPE(it)->tp_iternext)(it);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001391 if (res != NULL) {
1392 return res;
Serhiy Storchaka79342662019-01-12 08:25:41 +02001393 } else if (nargs > 1) {
1394 PyObject *def = args[1];
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001395 if (PyErr_Occurred()) {
1396 if(!PyErr_ExceptionMatches(PyExc_StopIteration))
1397 return NULL;
1398 PyErr_Clear();
1399 }
1400 Py_INCREF(def);
1401 return def;
1402 } else if (PyErr_Occurred()) {
1403 return NULL;
1404 } else {
1405 PyErr_SetNone(PyExc_StopIteration);
1406 return NULL;
1407 }
Georg Brandla18af4e2007-04-21 15:47:16 +00001408}
1409
1410PyDoc_STRVAR(next_doc,
1411"next(iterator[, default])\n\
1412\n\
1413Return the next item from the iterator. If default is given and the iterator\n\
1414is exhausted, it is returned instead of raising StopIteration.");
1415
1416
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001417/*[clinic input]
1418setattr as builtin_setattr
1419
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001420 obj: object
1421 name: object
1422 value: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001423 /
1424
1425Sets the named attribute on the given object to the specified value.
1426
1427setattr(x, 'y', v) is equivalent to ``x.y = v''
1428[clinic start generated code]*/
1429
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001430static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001431builtin_setattr_impl(PyObject *module, PyObject *obj, PyObject *name,
Larry Hastings89964c42015-04-14 18:07:59 -04001432 PyObject *value)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001433/*[clinic end generated code: output=dc2ce1d1add9acb4 input=bd2b7ca6875a1899]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001434{
1435 if (PyObject_SetAttr(obj, name, value) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001436 return NULL;
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02001437 Py_RETURN_NONE;
Guido van Rossum33894be1992-01-27 16:53:09 +00001438}
1439
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001440
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001441/*[clinic input]
1442delattr as builtin_delattr
1443
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001444 obj: object
1445 name: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001446 /
1447
1448Deletes the named attribute from the given object.
1449
1450delattr(x, 'y') is equivalent to ``del x.y''
1451[clinic start generated code]*/
1452
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001453static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001454builtin_delattr_impl(PyObject *module, PyObject *obj, PyObject *name)
1455/*[clinic end generated code: output=85134bc58dff79fa input=db16685d6b4b9410]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001456{
1457 if (PyObject_SetAttr(obj, name, (PyObject *)NULL) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001458 return NULL;
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02001459 Py_RETURN_NONE;
Guido van Rossum14144fc1994-08-29 12:53:40 +00001460}
1461
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001462
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001463/*[clinic input]
1464hash as builtin_hash
1465
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001466 obj: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001467 /
1468
1469Return the hash value for the given object.
1470
1471Two objects that compare equal must also have the same hash value, but the
1472reverse is not necessarily true.
1473[clinic start generated code]*/
1474
Guido van Rossum79f25d91997-04-29 20:08:16 +00001475static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001476builtin_hash(PyObject *module, PyObject *obj)
1477/*[clinic end generated code: output=237668e9d7688db7 input=58c48be822bf9c54]*/
Guido van Rossum9bfef441993-03-29 10:43:31 +00001478{
Benjamin Peterson8f67d082010-10-17 20:54:53 +00001479 Py_hash_t x;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001480
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001481 x = PyObject_Hash(obj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001482 if (x == -1)
1483 return NULL;
Benjamin Peterson8f67d082010-10-17 20:54:53 +00001484 return PyLong_FromSsize_t(x);
Guido van Rossum9bfef441993-03-29 10:43:31 +00001485}
1486
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001487
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001488/*[clinic input]
1489hex as builtin_hex
1490
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001491 number: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001492 /
1493
1494Return the hexadecimal representation of an integer.
1495
1496 >>> hex(12648430)
1497 '0xc0ffee'
1498[clinic start generated code]*/
1499
Guido van Rossum79f25d91997-04-29 20:08:16 +00001500static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001501builtin_hex(PyObject *module, PyObject *number)
1502/*[clinic end generated code: output=e46b612169099408 input=e645aff5fc7d540e]*/
Guido van Rossum006bcd41991-10-24 14:54:44 +00001503{
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001504 return PyNumber_ToBase(number, 16);
Guido van Rossum006bcd41991-10-24 14:54:44 +00001505}
1506
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001507
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001508/* AC: cannot convert yet, as needs PEP 457 group support in inspect */
Guido van Rossum79f25d91997-04-29 20:08:16 +00001509static PyObject *
Serhiy Storchaka79342662019-01-12 08:25:41 +02001510builtin_iter(PyObject *self, PyObject *const *args, Py_ssize_t nargs)
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001511{
Serhiy Storchaka79342662019-01-12 08:25:41 +02001512 PyObject *v;
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001513
Serhiy Storchaka79342662019-01-12 08:25:41 +02001514 if (!_PyArg_CheckPositional("iter", nargs, 1, 2))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001515 return NULL;
Serhiy Storchaka79342662019-01-12 08:25:41 +02001516 v = args[0];
1517 if (nargs == 1)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001518 return PyObject_GetIter(v);
1519 if (!PyCallable_Check(v)) {
1520 PyErr_SetString(PyExc_TypeError,
1521 "iter(v, w): v must be callable");
1522 return NULL;
1523 }
Serhiy Storchaka79342662019-01-12 08:25:41 +02001524 PyObject *sentinel = args[1];
1525 return PyCallIter_New(v, sentinel);
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001526}
1527
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001528PyDoc_STRVAR(iter_doc,
Georg Brandld11ae5d2008-05-16 13:27:32 +00001529"iter(iterable) -> iterator\n\
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001530iter(callable, sentinel) -> iterator\n\
1531\n\
1532Get an iterator from an object. In the first form, the argument must\n\
1533supply its own iterator, or be a sequence.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001534In the second form, the callable is called until it returns the sentinel.");
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001535
1536
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001537/*[clinic input]
1538len as builtin_len
1539
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001540 obj: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001541 /
1542
1543Return the number of items in a container.
1544[clinic start generated code]*/
1545
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001546static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001547builtin_len(PyObject *module, PyObject *obj)
1548/*[clinic end generated code: output=fa7a270d314dfb6c input=bc55598da9e9c9b5]*/
Guido van Rossum3f5da241990-12-20 15:06:42 +00001549{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001550 Py_ssize_t res;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001551
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001552 res = PyObject_Size(obj);
Serhiy Storchaka813f9432017-04-16 09:21:44 +03001553 if (res < 0) {
1554 assert(PyErr_Occurred());
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001555 return NULL;
Serhiy Storchaka813f9432017-04-16 09:21:44 +03001556 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001557 return PyLong_FromSsize_t(res);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001558}
1559
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001560
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001561/*[clinic input]
1562locals as builtin_locals
1563
1564Return a dictionary containing the current scope's local variables.
1565
1566NOTE: Whether or not updates to this dictionary will affect name lookups in
1567the local scope and vice-versa is *implementation dependent* and not
1568covered by any backwards compatibility guarantees.
1569[clinic start generated code]*/
1570
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001571static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001572builtin_locals_impl(PyObject *module)
1573/*[clinic end generated code: output=b46c94015ce11448 input=7874018d478d5c4b]*/
Guido van Rossum872537c1995-07-07 22:43:42 +00001574{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001575 PyObject *d;
Guido van Rossum872537c1995-07-07 22:43:42 +00001576
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001577 d = PyEval_GetLocals();
1578 Py_XINCREF(d);
1579 return d;
Guido van Rossum872537c1995-07-07 22:43:42 +00001580}
1581
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001582
Guido van Rossum79f25d91997-04-29 20:08:16 +00001583static PyObject *
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001584min_max(PyObject *args, PyObject *kwds, int op)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001585{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001586 PyObject *v, *it, *item, *val, *maxitem, *maxval, *keyfunc=NULL;
Raymond Hettinger4d6018f2013-06-24 22:43:02 -07001587 PyObject *emptytuple, *defaultval = NULL;
1588 static char *kwlist[] = {"key", "default", NULL};
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001589 const char *name = op == Py_LT ? "min" : "max";
Raymond Hettinger4d6018f2013-06-24 22:43:02 -07001590 const int positional = PyTuple_Size(args) > 1;
1591 int ret;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001592
Dong-hee Naabdc6342020-01-11 01:31:43 +09001593 if (positional) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001594 v = args;
Dong-hee Naabdc6342020-01-11 01:31:43 +09001595 }
1596 else if (!PyArg_UnpackTuple(args, name, 1, 1, &v)) {
1597 if (PyExceptionClass_Check(PyExc_TypeError)) {
1598 PyErr_Format(PyExc_TypeError, "%s expected at least 1 argument, got 0", name);
1599 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001600 return NULL;
Dong-hee Naabdc6342020-01-11 01:31:43 +09001601 }
Tim Peters67d687a2002-04-29 21:27:32 +00001602
Raymond Hettinger4d6018f2013-06-24 22:43:02 -07001603 emptytuple = PyTuple_New(0);
1604 if (emptytuple == NULL)
1605 return NULL;
Oren Milman58cf7482017-08-21 20:19:07 +03001606 ret = PyArg_ParseTupleAndKeywords(emptytuple, kwds,
1607 (op == Py_LT) ? "|$OO:min" : "|$OO:max",
1608 kwlist, &keyfunc, &defaultval);
Raymond Hettinger4d6018f2013-06-24 22:43:02 -07001609 Py_DECREF(emptytuple);
1610 if (!ret)
1611 return NULL;
1612
1613 if (positional && defaultval != NULL) {
1614 PyErr_Format(PyExc_TypeError,
1615 "Cannot specify a default for %s() with multiple "
1616 "positional arguments", name);
1617 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001618 }
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001619
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001620 it = PyObject_GetIter(v);
1621 if (it == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001622 return NULL;
1623 }
Tim Petersc3074532001-05-03 07:00:32 +00001624
Alexander Marshalove22072f2018-07-24 10:58:21 +07001625 if (keyfunc == Py_None) {
1626 keyfunc = NULL;
1627 }
1628
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001629 maxitem = NULL; /* the result */
1630 maxval = NULL; /* the value associated with the result */
1631 while (( item = PyIter_Next(it) )) {
1632 /* get the value from the key function */
1633 if (keyfunc != NULL) {
Petr Viktorinffd97532020-02-11 17:46:57 +01001634 val = PyObject_CallOneArg(keyfunc, item);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001635 if (val == NULL)
1636 goto Fail_it_item;
1637 }
1638 /* no key function; the value is the item */
1639 else {
1640 val = item;
1641 Py_INCREF(val);
1642 }
Tim Petersc3074532001-05-03 07:00:32 +00001643
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001644 /* maximum value and item are unset; set them */
1645 if (maxval == NULL) {
1646 maxitem = item;
1647 maxval = val;
1648 }
1649 /* maximum value and item are set; update them as necessary */
1650 else {
1651 int cmp = PyObject_RichCompareBool(val, maxval, op);
1652 if (cmp < 0)
1653 goto Fail_it_item_and_val;
1654 else if (cmp > 0) {
1655 Py_DECREF(maxval);
1656 Py_DECREF(maxitem);
1657 maxval = val;
1658 maxitem = item;
1659 }
1660 else {
1661 Py_DECREF(item);
1662 Py_DECREF(val);
1663 }
1664 }
1665 }
1666 if (PyErr_Occurred())
1667 goto Fail_it;
1668 if (maxval == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001669 assert(maxitem == NULL);
Raymond Hettinger4d6018f2013-06-24 22:43:02 -07001670 if (defaultval != NULL) {
1671 Py_INCREF(defaultval);
1672 maxitem = defaultval;
1673 } else {
1674 PyErr_Format(PyExc_ValueError,
1675 "%s() arg is an empty sequence", name);
1676 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001677 }
1678 else
1679 Py_DECREF(maxval);
1680 Py_DECREF(it);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001681 return maxitem;
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001682
1683Fail_it_item_and_val:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001684 Py_DECREF(val);
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001685Fail_it_item:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001686 Py_DECREF(item);
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001687Fail_it:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001688 Py_XDECREF(maxval);
1689 Py_XDECREF(maxitem);
1690 Py_DECREF(it);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001691 return NULL;
Guido van Rossum3f5da241990-12-20 15:06:42 +00001692}
1693
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001694/* AC: cannot convert yet, waiting for *args support */
Guido van Rossum79f25d91997-04-29 20:08:16 +00001695static PyObject *
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001696builtin_min(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001697{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001698 return min_max(args, kwds, Py_LT);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001699}
1700
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001701PyDoc_STRVAR(min_doc,
Raymond Hettinger2a545822014-05-19 22:20:52 +01001702"min(iterable, *[, default=obj, key=func]) -> value\n\
1703min(arg1, arg2, *args, *[, key=func]) -> value\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001704\n\
Raymond Hettinger2a545822014-05-19 22:20:52 +01001705With a single iterable argument, return its smallest item. The\n\
1706default keyword-only argument specifies an object to return if\n\
1707the provided iterable is empty.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001708With two or more arguments, return the smallest argument.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001709
1710
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001711/* AC: cannot convert yet, waiting for *args support */
Guido van Rossum79f25d91997-04-29 20:08:16 +00001712static PyObject *
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001713builtin_max(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001714{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001715 return min_max(args, kwds, Py_GT);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001716}
1717
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001718PyDoc_STRVAR(max_doc,
Raymond Hettinger2a545822014-05-19 22:20:52 +01001719"max(iterable, *[, default=obj, key=func]) -> value\n\
1720max(arg1, arg2, *args, *[, key=func]) -> value\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001721\n\
Raymond Hettinger2a545822014-05-19 22:20:52 +01001722With a single iterable argument, return its biggest item. The\n\
1723default keyword-only argument specifies an object to return if\n\
1724the provided iterable is empty.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001725With two or more arguments, return the largest argument.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001726
1727
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001728/*[clinic input]
1729oct as builtin_oct
1730
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001731 number: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001732 /
1733
1734Return the octal representation of an integer.
1735
1736 >>> oct(342391)
1737 '0o1234567'
1738[clinic start generated code]*/
1739
Guido van Rossum79f25d91997-04-29 20:08:16 +00001740static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001741builtin_oct(PyObject *module, PyObject *number)
1742/*[clinic end generated code: output=40a34656b6875352 input=ad6b274af4016c72]*/
Guido van Rossum006bcd41991-10-24 14:54:44 +00001743{
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001744 return PyNumber_ToBase(number, 8);
Guido van Rossum006bcd41991-10-24 14:54:44 +00001745}
1746
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001747
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001748/*[clinic input]
1749ord as builtin_ord
1750
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001751 c: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001752 /
1753
1754Return the Unicode code point for a one-character string.
1755[clinic start generated code]*/
1756
Guido van Rossum79f25d91997-04-29 20:08:16 +00001757static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001758builtin_ord(PyObject *module, PyObject *c)
1759/*[clinic end generated code: output=4fa5e87a323bae71 input=3064e5d6203ad012]*/
Guido van Rossum3f5da241990-12-20 15:06:42 +00001760{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001761 long ord;
1762 Py_ssize_t size;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001763
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001764 if (PyBytes_Check(c)) {
1765 size = PyBytes_GET_SIZE(c);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001766 if (size == 1) {
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001767 ord = (long)((unsigned char)*PyBytes_AS_STRING(c));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001768 return PyLong_FromLong(ord);
1769 }
1770 }
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001771 else if (PyUnicode_Check(c)) {
1772 if (PyUnicode_READY(c) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001773 return NULL;
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001774 size = PyUnicode_GET_LENGTH(c);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001775 if (size == 1) {
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001776 ord = (long)PyUnicode_READ_CHAR(c, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001777 return PyLong_FromLong(ord);
1778 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001779 }
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001780 else if (PyByteArray_Check(c)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001781 /* XXX Hopefully this is temporary */
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001782 size = PyByteArray_GET_SIZE(c);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001783 if (size == 1) {
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001784 ord = (long)((unsigned char)*PyByteArray_AS_STRING(c));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001785 return PyLong_FromLong(ord);
1786 }
1787 }
1788 else {
1789 PyErr_Format(PyExc_TypeError,
1790 "ord() expected string of length 1, but " \
Victor Stinnera102ed72020-02-07 02:24:48 +01001791 "%.200s found", Py_TYPE(c)->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001792 return NULL;
1793 }
Guido van Rossum09095f32000-03-10 23:00:52 +00001794
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001795 PyErr_Format(PyExc_TypeError,
1796 "ord() expected a character, "
1797 "but string of length %zd found",
1798 size);
1799 return NULL;
Guido van Rossum3f5da241990-12-20 15:06:42 +00001800}
1801
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001802
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001803/*[clinic input]
1804pow as builtin_pow
1805
Ammar Askar87d6cd32019-09-21 00:28:49 -04001806 base: object
1807 exp: object
1808 mod: object = None
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001809
Raymond Hettingerb104ecb2019-09-21 12:57:44 -07001810Equivalent to base**exp with 2 arguments or base**exp % mod with 3 arguments
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001811
1812Some types, such as ints, are able to use a more efficient algorithm when
1813invoked using the three argument form.
1814[clinic start generated code]*/
1815
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001816static PyObject *
Ammar Askar87d6cd32019-09-21 00:28:49 -04001817builtin_pow_impl(PyObject *module, PyObject *base, PyObject *exp,
1818 PyObject *mod)
Raymond Hettingerb104ecb2019-09-21 12:57:44 -07001819/*[clinic end generated code: output=3ca1538221bbf15f input=435dbd48a12efb23]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001820{
Ammar Askar87d6cd32019-09-21 00:28:49 -04001821 return PyNumber_Power(base, exp, mod);
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001822}
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001823
1824
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001825/* AC: cannot convert yet, waiting for *args support */
Guido van Rossum34343512006-11-30 22:13:52 +00001826static PyObject *
Serhiy Storchakaa5552f02017-12-15 13:11:11 +02001827builtin_print(PyObject *self, PyObject *const *args, Py_ssize_t nargs, PyObject *kwnames)
Guido van Rossum34343512006-11-30 22:13:52 +00001828{
INADA Naokibd584f12017-01-19 12:50:34 +01001829 static const char * const _keywords[] = {"sep", "end", "file", "flush", 0};
Serhiy Storchaka1f21eaa2019-09-01 12:16:51 +03001830 static struct _PyArg_Parser _parser = {"|OOOp:print", _keywords, 0};
1831 PyObject *sep = NULL, *end = NULL, *file = NULL;
1832 int flush = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001833 int i, err;
Guido van Rossum34343512006-11-30 22:13:52 +00001834
INADA Naokibd584f12017-01-19 12:50:34 +01001835 if (kwnames != NULL &&
1836 !_PyArg_ParseStackAndKeywords(args + nargs, 0, kwnames, &_parser,
1837 &sep, &end, &file, &flush)) {
Georg Brandlbc3b6822012-01-13 19:41:25 +01001838 return NULL;
INADA Naokibd584f12017-01-19 12:50:34 +01001839 }
1840
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001841 if (file == NULL || file == Py_None) {
Victor Stinnerbd303c12013-11-07 23:07:29 +01001842 file = _PySys_GetObjectId(&PyId_stdout);
Victor Stinner1e53bba2013-07-16 22:26:05 +02001843 if (file == NULL) {
1844 PyErr_SetString(PyExc_RuntimeError, "lost sys.stdout");
1845 return NULL;
1846 }
1847
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001848 /* sys.stdout may be None when FILE* stdout isn't connected */
1849 if (file == Py_None)
1850 Py_RETURN_NONE;
1851 }
Guido van Rossum34343512006-11-30 22:13:52 +00001852
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001853 if (sep == Py_None) {
1854 sep = NULL;
1855 }
1856 else if (sep && !PyUnicode_Check(sep)) {
1857 PyErr_Format(PyExc_TypeError,
1858 "sep must be None or a string, not %.200s",
Victor Stinnera102ed72020-02-07 02:24:48 +01001859 Py_TYPE(sep)->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001860 return NULL;
1861 }
1862 if (end == Py_None) {
1863 end = NULL;
1864 }
1865 else if (end && !PyUnicode_Check(end)) {
1866 PyErr_Format(PyExc_TypeError,
1867 "end must be None or a string, not %.200s",
Victor Stinnera102ed72020-02-07 02:24:48 +01001868 Py_TYPE(end)->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001869 return NULL;
1870 }
Guido van Rossum34343512006-11-30 22:13:52 +00001871
INADA Naokibd584f12017-01-19 12:50:34 +01001872 for (i = 0; i < nargs; i++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001873 if (i > 0) {
1874 if (sep == NULL)
1875 err = PyFile_WriteString(" ", file);
1876 else
1877 err = PyFile_WriteObject(sep, file,
1878 Py_PRINT_RAW);
1879 if (err)
1880 return NULL;
1881 }
INADA Naokibd584f12017-01-19 12:50:34 +01001882 err = PyFile_WriteObject(args[i], file, Py_PRINT_RAW);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001883 if (err)
1884 return NULL;
1885 }
Guido van Rossum34343512006-11-30 22:13:52 +00001886
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001887 if (end == NULL)
1888 err = PyFile_WriteString("\n", file);
1889 else
1890 err = PyFile_WriteObject(end, file, Py_PRINT_RAW);
1891 if (err)
1892 return NULL;
Guido van Rossum34343512006-11-30 22:13:52 +00001893
Serhiy Storchaka1f21eaa2019-09-01 12:16:51 +03001894 if (flush) {
1895 PyObject *tmp = _PyObject_CallMethodIdNoArgs(file, &PyId_flush);
1896 if (tmp == NULL)
Georg Brandlbc3b6822012-01-13 19:41:25 +01001897 return NULL;
Serhiy Storchaka1f21eaa2019-09-01 12:16:51 +03001898 Py_DECREF(tmp);
Georg Brandlbc3b6822012-01-13 19:41:25 +01001899 }
1900
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001901 Py_RETURN_NONE;
Guido van Rossum34343512006-11-30 22:13:52 +00001902}
1903
1904PyDoc_STRVAR(print_doc,
Senthil Kumarane9175bd2012-08-10 13:53:45 -07001905"print(value, ..., sep=' ', end='\\n', file=sys.stdout, flush=False)\n\
Guido van Rossum34343512006-11-30 22:13:52 +00001906\n\
1907Prints the values to a stream, or to sys.stdout by default.\n\
1908Optional keyword arguments:\n\
Senthil Kumarane9175bd2012-08-10 13:53:45 -07001909file: a file-like object (stream); defaults to the current sys.stdout.\n\
1910sep: string inserted between values, default a space.\n\
1911end: string appended after the last value, default a newline.\n\
1912flush: whether to forcibly flush the stream.");
Guido van Rossum34343512006-11-30 22:13:52 +00001913
1914
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001915/*[clinic input]
1916input as builtin_input
1917
1918 prompt: object(c_default="NULL") = None
1919 /
1920
1921Read a string from standard input. The trailing newline is stripped.
1922
1923The prompt string, if given, is printed to standard output without a
1924trailing newline before reading input.
1925
1926If the user hits EOF (*nix: Ctrl-D, Windows: Ctrl-Z+Return), raise EOFError.
1927On *nix systems, readline is used if available.
1928[clinic start generated code]*/
1929
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001930static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001931builtin_input_impl(PyObject *module, PyObject *prompt)
1932/*[clinic end generated code: output=83db5a191e7a0d60 input=5e8bb70c2908fe3c]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001933{
Victor Stinnerbd303c12013-11-07 23:07:29 +01001934 PyObject *fin = _PySys_GetObjectId(&PyId_stdin);
1935 PyObject *fout = _PySys_GetObjectId(&PyId_stdout);
1936 PyObject *ferr = _PySys_GetObjectId(&PyId_stderr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001937 PyObject *tmp;
1938 long fd;
1939 int tty;
Guido van Rossuma88a0332007-02-26 16:59:55 +00001940
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001941 /* Check that stdin/out/err are intact */
1942 if (fin == NULL || fin == Py_None) {
1943 PyErr_SetString(PyExc_RuntimeError,
1944 "input(): lost sys.stdin");
1945 return NULL;
1946 }
1947 if (fout == NULL || fout == Py_None) {
1948 PyErr_SetString(PyExc_RuntimeError,
1949 "input(): lost sys.stdout");
1950 return NULL;
1951 }
1952 if (ferr == NULL || ferr == Py_None) {
1953 PyErr_SetString(PyExc_RuntimeError,
1954 "input(): lost sys.stderr");
1955 return NULL;
1956 }
Guido van Rossumeba76962007-05-27 09:13:28 +00001957
Steve Dowerb82e17e2019-05-23 08:45:22 -07001958 if (PySys_Audit("builtins.input", "O", prompt ? prompt : Py_None) < 0) {
1959 return NULL;
1960 }
1961
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001962 /* First of all, flush stderr */
Jeroen Demeyer762f93f2019-07-08 10:19:25 +02001963 tmp = _PyObject_CallMethodIdNoArgs(ferr, &PyId_flush);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001964 if (tmp == NULL)
1965 PyErr_Clear();
1966 else
1967 Py_DECREF(tmp);
Guido van Rossumeba76962007-05-27 09:13:28 +00001968
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001969 /* We should only use (GNU) readline if Python's sys.stdin and
1970 sys.stdout are the same as C's stdin and stdout, because we
1971 need to pass it those. */
Jeroen Demeyer762f93f2019-07-08 10:19:25 +02001972 tmp = _PyObject_CallMethodIdNoArgs(fin, &PyId_fileno);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001973 if (tmp == NULL) {
1974 PyErr_Clear();
1975 tty = 0;
1976 }
1977 else {
1978 fd = PyLong_AsLong(tmp);
1979 Py_DECREF(tmp);
1980 if (fd < 0 && PyErr_Occurred())
1981 return NULL;
1982 tty = fd == fileno(stdin) && isatty(fd);
1983 }
1984 if (tty) {
Jeroen Demeyer762f93f2019-07-08 10:19:25 +02001985 tmp = _PyObject_CallMethodIdNoArgs(fout, &PyId_fileno);
Martin Panterc9a6ab52015-10-10 01:25:38 +00001986 if (tmp == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001987 PyErr_Clear();
Martin Panterc9a6ab52015-10-10 01:25:38 +00001988 tty = 0;
1989 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001990 else {
1991 fd = PyLong_AsLong(tmp);
1992 Py_DECREF(tmp);
1993 if (fd < 0 && PyErr_Occurred())
1994 return NULL;
1995 tty = fd == fileno(stdout) && isatty(fd);
1996 }
1997 }
Guido van Rossumeba76962007-05-27 09:13:28 +00001998
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001999 /* If we're interactive, use (GNU) readline */
2000 if (tty) {
Antoine Pitrou0d776b12011-11-06 00:34:26 +01002001 PyObject *po = NULL;
Serhiy Storchakae2f92de2017-11-11 13:06:26 +02002002 const char *promptstr;
Antoine Pitrou0d776b12011-11-06 00:34:26 +01002003 char *s = NULL;
2004 PyObject *stdin_encoding = NULL, *stdin_errors = NULL;
2005 PyObject *stdout_encoding = NULL, *stdout_errors = NULL;
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +02002006 const char *stdin_encoding_str, *stdin_errors_str;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002007 PyObject *result;
Victor Stinnerc0f1a1a2011-02-23 12:07:37 +00002008 size_t len;
Martin v. Löwis4a7b5d52007-09-04 05:24:49 +00002009
Serhiy Storchakac2cf1282017-03-12 13:50:36 +02002010 /* stdin is a text stream, so it must have an encoding. */
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02002011 stdin_encoding = _PyObject_GetAttrId(fin, &PyId_encoding);
Antoine Pitrou5ee9d8a2011-11-06 00:38:45 +01002012 stdin_errors = _PyObject_GetAttrId(fin, &PyId_errors);
Serhiy Storchakac2cf1282017-03-12 13:50:36 +02002013 if (!stdin_encoding || !stdin_errors ||
2014 !PyUnicode_Check(stdin_encoding) ||
2015 !PyUnicode_Check(stdin_errors)) {
2016 tty = 0;
Antoine Pitrou0d776b12011-11-06 00:34:26 +01002017 goto _readline_errors;
Serhiy Storchakac2cf1282017-03-12 13:50:36 +02002018 }
Serhiy Storchaka06515832016-11-20 09:13:07 +02002019 stdin_encoding_str = PyUnicode_AsUTF8(stdin_encoding);
2020 stdin_errors_str = PyUnicode_AsUTF8(stdin_errors);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01002021 if (!stdin_encoding_str || !stdin_errors_str)
2022 goto _readline_errors;
Jeroen Demeyer762f93f2019-07-08 10:19:25 +02002023 tmp = _PyObject_CallMethodIdNoArgs(fout, &PyId_flush);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002024 if (tmp == NULL)
2025 PyErr_Clear();
2026 else
2027 Py_DECREF(tmp);
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002028 if (prompt != NULL) {
Antoine Pitrou0d776b12011-11-06 00:34:26 +01002029 /* We have a prompt, encode it as stdout would */
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +02002030 const char *stdout_encoding_str, *stdout_errors_str;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002031 PyObject *stringpo;
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02002032 stdout_encoding = _PyObject_GetAttrId(fout, &PyId_encoding);
Antoine Pitrou5ee9d8a2011-11-06 00:38:45 +01002033 stdout_errors = _PyObject_GetAttrId(fout, &PyId_errors);
Serhiy Storchakac2cf1282017-03-12 13:50:36 +02002034 if (!stdout_encoding || !stdout_errors ||
2035 !PyUnicode_Check(stdout_encoding) ||
2036 !PyUnicode_Check(stdout_errors)) {
2037 tty = 0;
Antoine Pitrou0d776b12011-11-06 00:34:26 +01002038 goto _readline_errors;
Serhiy Storchakac2cf1282017-03-12 13:50:36 +02002039 }
Serhiy Storchaka06515832016-11-20 09:13:07 +02002040 stdout_encoding_str = PyUnicode_AsUTF8(stdout_encoding);
2041 stdout_errors_str = PyUnicode_AsUTF8(stdout_errors);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01002042 if (!stdout_encoding_str || !stdout_errors_str)
2043 goto _readline_errors;
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002044 stringpo = PyObject_Str(prompt);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01002045 if (stringpo == NULL)
2046 goto _readline_errors;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002047 po = PyUnicode_AsEncodedString(stringpo,
Antoine Pitrou0d776b12011-11-06 00:34:26 +01002048 stdout_encoding_str, stdout_errors_str);
2049 Py_CLEAR(stdout_encoding);
2050 Py_CLEAR(stdout_errors);
2051 Py_CLEAR(stringpo);
2052 if (po == NULL)
2053 goto _readline_errors;
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03002054 assert(PyBytes_Check(po));
2055 promptstr = PyBytes_AS_STRING(po);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002056 }
2057 else {
2058 po = NULL;
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002059 promptstr = "";
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002060 }
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002061 s = PyOS_Readline(stdin, stdout, promptstr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002062 if (s == NULL) {
Richard Oudkerk614c5782013-04-03 13:44:50 +01002063 PyErr_CheckSignals();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002064 if (!PyErr_Occurred())
2065 PyErr_SetNone(PyExc_KeyboardInterrupt);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01002066 goto _readline_errors;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002067 }
Victor Stinnerc0f1a1a2011-02-23 12:07:37 +00002068
2069 len = strlen(s);
2070 if (len == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002071 PyErr_SetNone(PyExc_EOFError);
2072 result = NULL;
2073 }
Victor Stinnerc0f1a1a2011-02-23 12:07:37 +00002074 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002075 if (len > PY_SSIZE_T_MAX) {
2076 PyErr_SetString(PyExc_OverflowError,
2077 "input: input too long");
2078 result = NULL;
2079 }
2080 else {
Victor Stinnerc0f1a1a2011-02-23 12:07:37 +00002081 len--; /* strip trailing '\n' */
2082 if (len != 0 && s[len-1] == '\r')
2083 len--; /* strip trailing '\r' */
Antoine Pitrou0d776b12011-11-06 00:34:26 +01002084 result = PyUnicode_Decode(s, len, stdin_encoding_str,
2085 stdin_errors_str);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002086 }
2087 }
2088 Py_DECREF(stdin_encoding);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01002089 Py_DECREF(stdin_errors);
2090 Py_XDECREF(po);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002091 PyMem_FREE(s);
Steve Dowerb82e17e2019-05-23 08:45:22 -07002092
2093 if (result != NULL) {
2094 if (PySys_Audit("builtins.input/result", "O", result) < 0) {
2095 return NULL;
2096 }
2097 }
2098
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002099 return result;
Serhiy Storchakac2cf1282017-03-12 13:50:36 +02002100
Antoine Pitrou0d776b12011-11-06 00:34:26 +01002101 _readline_errors:
2102 Py_XDECREF(stdin_encoding);
2103 Py_XDECREF(stdout_encoding);
2104 Py_XDECREF(stdin_errors);
2105 Py_XDECREF(stdout_errors);
2106 Py_XDECREF(po);
Serhiy Storchakac2cf1282017-03-12 13:50:36 +02002107 if (tty)
2108 return NULL;
2109
2110 PyErr_Clear();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002111 }
Guido van Rossumeba76962007-05-27 09:13:28 +00002112
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002113 /* Fallback if we're not interactive */
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002114 if (prompt != NULL) {
2115 if (PyFile_WriteObject(prompt, fout, Py_PRINT_RAW) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002116 return NULL;
2117 }
Jeroen Demeyer762f93f2019-07-08 10:19:25 +02002118 tmp = _PyObject_CallMethodIdNoArgs(fout, &PyId_flush);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002119 if (tmp == NULL)
2120 PyErr_Clear();
2121 else
2122 Py_DECREF(tmp);
2123 return PyFile_GetLine(fin, -1);
Guido van Rossuma88a0332007-02-26 16:59:55 +00002124}
2125
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002126
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002127/*[clinic input]
2128repr as builtin_repr
2129
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03002130 obj: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002131 /
2132
2133Return the canonical string representation of the object.
2134
2135For many object types, including most builtins, eval(repr(obj)) == obj.
2136[clinic start generated code]*/
2137
Guido van Rossum79f25d91997-04-29 20:08:16 +00002138static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002139builtin_repr(PyObject *module, PyObject *obj)
2140/*[clinic end generated code: output=7ed3778c44fd0194 input=1c9e6d66d3e3be04]*/
Guido van Rossumc89705d1992-11-26 08:54:07 +00002141{
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002142 return PyObject_Repr(obj);
Guido van Rossumc89705d1992-11-26 08:54:07 +00002143}
2144
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002145
Serhiy Storchakaaca7f572017-11-15 17:51:14 +02002146/*[clinic input]
2147round as builtin_round
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002148
Serhiy Storchakaaca7f572017-11-15 17:51:14 +02002149 number: object
Serhiy Storchaka279f4462019-09-14 12:24:05 +03002150 ndigits: object = None
Serhiy Storchakaaca7f572017-11-15 17:51:14 +02002151
2152Round a number to a given precision in decimal digits.
2153
2154The return value is an integer if ndigits is omitted or None. Otherwise
2155the return value has the same type as the number. ndigits may be negative.
2156[clinic start generated code]*/
2157
2158static PyObject *
2159builtin_round_impl(PyObject *module, PyObject *number, PyObject *ndigits)
Serhiy Storchaka279f4462019-09-14 12:24:05 +03002160/*[clinic end generated code: output=ff0d9dd176c02ede input=275678471d7aca15]*/
Serhiy Storchakaaca7f572017-11-15 17:51:14 +02002161{
2162 PyObject *round, *result;
Alex Martelliae211f92007-08-22 23:21:33 +00002163
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002164 if (Py_TYPE(number)->tp_dict == NULL) {
2165 if (PyType_Ready(Py_TYPE(number)) < 0)
2166 return NULL;
2167 }
Guido van Rossum15d3d042007-08-24 02:02:45 +00002168
Benjamin Peterson214a7d22013-04-13 17:19:01 -04002169 round = _PyObject_LookupSpecial(number, &PyId___round__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002170 if (round == NULL) {
Benjamin Peterson214a7d22013-04-13 17:19:01 -04002171 if (!PyErr_Occurred())
2172 PyErr_Format(PyExc_TypeError,
2173 "type %.100s doesn't define __round__ method",
2174 Py_TYPE(number)->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002175 return NULL;
2176 }
Alex Martelliae211f92007-08-22 23:21:33 +00002177
Serhiy Storchaka279f4462019-09-14 12:24:05 +03002178 if (ndigits == Py_None)
Victor Stinnerf17c3de2016-12-06 18:46:19 +01002179 result = _PyObject_CallNoArg(round);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002180 else
Petr Viktorinffd97532020-02-11 17:46:57 +01002181 result = PyObject_CallOneArg(round, ndigits);
Benjamin Peterson214a7d22013-04-13 17:19:01 -04002182 Py_DECREF(round);
2183 return result;
Guido van Rossum9e51f9b1993-02-12 16:29:05 +00002184}
2185
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002186
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002187/*AC: we need to keep the kwds dict intact to easily call into the
2188 * list.sort method, which isn't currently supported in AC. So we just use
2189 * the initially generated signature with a custom implementation.
2190 */
2191/* [disabled clinic input]
2192sorted as builtin_sorted
2193
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03002194 iterable as seq: object
2195 key as keyfunc: object = None
2196 reverse: object = False
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002197
2198Return a new list containing all items from the iterable in ascending order.
2199
Raymond Hettinger7ea386e2016-08-25 21:11:50 -07002200A custom key function can be supplied to customize the sort order, and the
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002201reverse flag can be set to request the result in descending order.
2202[end disabled clinic input]*/
2203
2204PyDoc_STRVAR(builtin_sorted__doc__,
Serhiy Storchaka3a104252017-01-23 12:29:47 +02002205"sorted($module, iterable, /, *, key=None, reverse=False)\n"
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002206"--\n"
2207"\n"
2208"Return a new list containing all items from the iterable in ascending order.\n"
2209"\n"
Raymond Hettinger7ea386e2016-08-25 21:11:50 -07002210"A custom key function can be supplied to customize the sort order, and the\n"
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002211"reverse flag can be set to request the result in descending order.");
2212
2213#define BUILTIN_SORTED_METHODDEF \
Serhiy Storchaka62be7422018-11-27 13:27:31 +02002214 {"sorted", (PyCFunction)(void(*)(void))builtin_sorted, METH_FASTCALL | METH_KEYWORDS, builtin_sorted__doc__},
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002215
Raymond Hettinger64958a12003-12-17 20:43:33 +00002216static PyObject *
Serhiy Storchakaa5552f02017-12-15 13:11:11 +02002217builtin_sorted(PyObject *self, PyObject *const *args, Py_ssize_t nargs, PyObject *kwnames)
Raymond Hettinger64958a12003-12-17 20:43:33 +00002218{
Serhiy Storchaka7cf8beb2017-01-21 23:05:00 +02002219 PyObject *newlist, *v, *seq, *callable;
Victor Stinner5a60eca2017-01-17 15:17:49 +01002220
Serhiy Storchaka7cf8beb2017-01-21 23:05:00 +02002221 /* Keyword arguments are passed through list.sort() which will check
2222 them. */
2223 if (!_PyArg_UnpackStack(args, nargs, "sorted", 1, 1, &seq))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002224 return NULL;
Raymond Hettinger64958a12003-12-17 20:43:33 +00002225
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002226 newlist = PySequence_List(seq);
2227 if (newlist == NULL)
2228 return NULL;
Raymond Hettinger64958a12003-12-17 20:43:33 +00002229
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02002230 callable = _PyObject_GetAttrId(newlist, &PyId_sort);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002231 if (callable == NULL) {
2232 Py_DECREF(newlist);
2233 return NULL;
2234 }
Georg Brandl99d7e4e2005-08-31 22:21:15 +00002235
Serhiy Storchaka299dc232017-01-20 08:35:18 +02002236 assert(nargs >= 1);
Petr Viktorinffd97532020-02-11 17:46:57 +01002237 v = PyObject_Vectorcall(callable, args + 1, nargs - 1, kwnames);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002238 Py_DECREF(callable);
2239 if (v == NULL) {
2240 Py_DECREF(newlist);
2241 return NULL;
2242 }
2243 Py_DECREF(v);
2244 return newlist;
Raymond Hettinger64958a12003-12-17 20:43:33 +00002245}
2246
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002247
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002248/* AC: cannot convert yet, as needs PEP 457 group support in inspect */
Guido van Rossum79f25d91997-04-29 20:08:16 +00002249static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002250builtin_vars(PyObject *self, PyObject *args)
Guido van Rossum2d951851994-08-29 12:52:16 +00002251{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002252 PyObject *v = NULL;
2253 PyObject *d;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002254
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002255 if (!PyArg_UnpackTuple(args, "vars", 0, 1, &v))
2256 return NULL;
2257 if (v == NULL) {
2258 d = PyEval_GetLocals();
Serhiy Storchaka41c57b32019-09-01 12:03:39 +03002259 Py_XINCREF(d);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002260 }
2261 else {
Serhiy Storchaka41c57b32019-09-01 12:03:39 +03002262 if (_PyObject_LookupAttrId(v, &PyId___dict__, &d) == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002263 PyErr_SetString(PyExc_TypeError,
2264 "vars() argument must have __dict__ attribute");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002265 }
2266 }
2267 return d;
Guido van Rossum2d951851994-08-29 12:52:16 +00002268}
2269
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002270PyDoc_STRVAR(vars_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002271"vars([object]) -> dictionary\n\
2272\n\
2273Without arguments, equivalent to locals().\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002274With an argument, equivalent to object.__dict__.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002275
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002276
2277/*[clinic input]
2278sum as builtin_sum
2279
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03002280 iterable: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002281 /
Raymond Hettinger9dfa0fe2018-09-12 10:54:06 -07002282 start: object(c_default="NULL") = 0
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002283
2284Return the sum of a 'start' value (default: 0) plus an iterable of numbers
2285
2286When the iterable is empty, return the start value.
2287This function is intended specifically for use with numeric values and may
2288reject non-numeric types.
2289[clinic start generated code]*/
2290
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002291static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002292builtin_sum_impl(PyObject *module, PyObject *iterable, PyObject *start)
Raymond Hettinger9dfa0fe2018-09-12 10:54:06 -07002293/*[clinic end generated code: output=df758cec7d1d302f input=162b50765250d222]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002294{
2295 PyObject *result = start;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002296 PyObject *temp, *item, *iter;
Alex Martellia70b1912003-04-22 08:12:33 +00002297
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002298 iter = PyObject_GetIter(iterable);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002299 if (iter == NULL)
2300 return NULL;
Alex Martellia70b1912003-04-22 08:12:33 +00002301
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002302 if (result == NULL) {
2303 result = PyLong_FromLong(0);
2304 if (result == NULL) {
2305 Py_DECREF(iter);
2306 return NULL;
2307 }
2308 } else {
2309 /* reject string values for 'start' parameter */
2310 if (PyUnicode_Check(result)) {
2311 PyErr_SetString(PyExc_TypeError,
2312 "sum() can't sum strings [use ''.join(seq) instead]");
2313 Py_DECREF(iter);
2314 return NULL;
2315 }
Benjamin Petersonce071ca2011-07-29 14:23:47 -05002316 if (PyBytes_Check(result)) {
2317 PyErr_SetString(PyExc_TypeError,
2318 "sum() can't sum bytes [use b''.join(seq) instead]");
Benjamin Peterson405f32c2011-07-29 22:43:45 -05002319 Py_DECREF(iter);
Benjamin Petersonce071ca2011-07-29 14:23:47 -05002320 return NULL;
2321 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002322 if (PyByteArray_Check(result)) {
2323 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson4f921c22011-07-29 14:24:29 -05002324 "sum() can't sum bytearray [use b''.join(seq) instead]");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002325 Py_DECREF(iter);
2326 return NULL;
2327 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002328 Py_INCREF(result);
2329 }
Alex Martellia70b1912003-04-22 08:12:33 +00002330
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002331#ifndef SLOW_SUM
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002332 /* Fast addition by keeping temporary sums in C instead of new Python objects.
2333 Assumes all inputs are the same type. If the assumption fails, default
2334 to the more general routine.
2335 */
2336 if (PyLong_CheckExact(result)) {
2337 int overflow;
2338 long i_result = PyLong_AsLongAndOverflow(result, &overflow);
2339 /* If this already overflowed, don't even enter the loop. */
2340 if (overflow == 0) {
2341 Py_DECREF(result);
2342 result = NULL;
2343 }
2344 while(result == NULL) {
2345 item = PyIter_Next(iter);
2346 if (item == NULL) {
2347 Py_DECREF(iter);
2348 if (PyErr_Occurred())
2349 return NULL;
2350 return PyLong_FromLong(i_result);
2351 }
Serhiy Storchaka88bdb922019-09-10 16:31:01 +03002352 if (PyLong_CheckExact(item) || PyBool_Check(item)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002353 long b = PyLong_AsLongAndOverflow(item, &overflow);
Serhiy Storchaka29500732019-05-05 14:26:23 +03002354 if (overflow == 0 &&
2355 (i_result >= 0 ? (b <= LONG_MAX - i_result)
2356 : (b >= LONG_MIN - i_result)))
2357 {
2358 i_result += b;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002359 Py_DECREF(item);
2360 continue;
2361 }
2362 }
2363 /* Either overflowed or is not an int. Restore real objects and process normally */
2364 result = PyLong_FromLong(i_result);
Christian Heimes704e2d32013-07-26 22:49:26 +02002365 if (result == NULL) {
2366 Py_DECREF(item);
2367 Py_DECREF(iter);
2368 return NULL;
2369 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002370 temp = PyNumber_Add(result, item);
2371 Py_DECREF(result);
2372 Py_DECREF(item);
2373 result = temp;
2374 if (result == NULL) {
2375 Py_DECREF(iter);
2376 return NULL;
2377 }
2378 }
2379 }
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002380
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002381 if (PyFloat_CheckExact(result)) {
2382 double f_result = PyFloat_AS_DOUBLE(result);
2383 Py_DECREF(result);
2384 result = NULL;
2385 while(result == NULL) {
2386 item = PyIter_Next(iter);
2387 if (item == NULL) {
2388 Py_DECREF(iter);
2389 if (PyErr_Occurred())
2390 return NULL;
2391 return PyFloat_FromDouble(f_result);
2392 }
2393 if (PyFloat_CheckExact(item)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002394 f_result += PyFloat_AS_DOUBLE(item);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002395 Py_DECREF(item);
2396 continue;
2397 }
Serhiy Storchaka88bdb922019-09-10 16:31:01 +03002398 if (PyLong_Check(item)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002399 long value;
2400 int overflow;
2401 value = PyLong_AsLongAndOverflow(item, &overflow);
2402 if (!overflow) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002403 f_result += (double)value;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002404 Py_DECREF(item);
2405 continue;
2406 }
2407 }
2408 result = PyFloat_FromDouble(f_result);
Alexey Izbyshev2b824b22018-08-24 07:27:52 +03002409 if (result == NULL) {
2410 Py_DECREF(item);
2411 Py_DECREF(iter);
2412 return NULL;
2413 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002414 temp = PyNumber_Add(result, item);
2415 Py_DECREF(result);
2416 Py_DECREF(item);
2417 result = temp;
2418 if (result == NULL) {
2419 Py_DECREF(iter);
2420 return NULL;
2421 }
2422 }
2423 }
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002424#endif
2425
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002426 for(;;) {
2427 item = PyIter_Next(iter);
2428 if (item == NULL) {
2429 /* error, or end-of-sequence */
2430 if (PyErr_Occurred()) {
2431 Py_DECREF(result);
2432 result = NULL;
2433 }
2434 break;
2435 }
2436 /* It's tempting to use PyNumber_InPlaceAdd instead of
2437 PyNumber_Add here, to avoid quadratic running time
2438 when doing 'sum(list_of_lists, [])'. However, this
2439 would produce a change in behaviour: a snippet like
Mark Dickinson9acadc52009-10-26 14:19:42 +00002440
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002441 empty = []
2442 sum([[x] for x in range(10)], empty)
Mark Dickinson9acadc52009-10-26 14:19:42 +00002443
Brandt Bucherabb9a442020-02-01 03:08:34 -08002444 would change the value of empty. In fact, using
2445 in-place addition rather that binary addition for
2446 any of the steps introduces subtle behavior changes:
Victor Stinner58f4e1a2020-02-05 18:24:33 +01002447
Brandt Bucherabb9a442020-02-01 03:08:34 -08002448 https://bugs.python.org/issue18305 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002449 temp = PyNumber_Add(result, item);
2450 Py_DECREF(result);
2451 Py_DECREF(item);
2452 result = temp;
2453 if (result == NULL)
2454 break;
2455 }
2456 Py_DECREF(iter);
2457 return result;
Alex Martellia70b1912003-04-22 08:12:33 +00002458}
2459
Alex Martellia70b1912003-04-22 08:12:33 +00002460
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002461/*[clinic input]
2462isinstance as builtin_isinstance
2463
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03002464 obj: object
2465 class_or_tuple: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002466 /
2467
2468Return whether an object is an instance of a class or of a subclass thereof.
2469
2470A tuple, as in ``isinstance(x, (A, B, ...))``, may be given as the target to
2471check against. This is equivalent to ``isinstance(x, A) or isinstance(x, B)
2472or ...`` etc.
2473[clinic start generated code]*/
2474
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002475static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002476builtin_isinstance_impl(PyObject *module, PyObject *obj,
Larry Hastings89964c42015-04-14 18:07:59 -04002477 PyObject *class_or_tuple)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002478/*[clinic end generated code: output=6faf01472c13b003 input=ffa743db1daf7549]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002479{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002480 int retval;
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002481
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002482 retval = PyObject_IsInstance(obj, class_or_tuple);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002483 if (retval < 0)
2484 return NULL;
2485 return PyBool_FromLong(retval);
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002486}
2487
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002488
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002489/*[clinic input]
2490issubclass as builtin_issubclass
2491
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03002492 cls: object
2493 class_or_tuple: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002494 /
2495
2496Return whether 'cls' is a derived from another class or is the same class.
2497
2498A tuple, as in ``issubclass(x, (A, B, ...))``, may be given as the target to
2499check against. This is equivalent to ``issubclass(x, A) or issubclass(x, B)
2500or ...`` etc.
2501[clinic start generated code]*/
2502
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002503static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002504builtin_issubclass_impl(PyObject *module, PyObject *cls,
Larry Hastings89964c42015-04-14 18:07:59 -04002505 PyObject *class_or_tuple)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002506/*[clinic end generated code: output=358412410cd7a250 input=af5f35e9ceaddaf6]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002507{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002508 int retval;
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002509
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002510 retval = PyObject_IsSubclass(cls, class_or_tuple);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002511 if (retval < 0)
2512 return NULL;
2513 return PyBool_FromLong(retval);
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002514}
2515
2516
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002517typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002518 PyObject_HEAD
2519 Py_ssize_t tuplesize;
2520 PyObject *ittuple; /* tuple of iterators */
2521 PyObject *result;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002522} zipobject;
2523
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002524static PyObject *
2525zip_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
Barry Warsawbd599b52000-08-03 15:45:29 +00002526{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002527 zipobject *lz;
2528 Py_ssize_t i;
2529 PyObject *ittuple; /* tuple of iterators */
2530 PyObject *result;
Serhiy Storchakabf623ae2017-04-19 20:03:52 +03002531 Py_ssize_t tuplesize;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002532
Serhiy Storchaka6cca5c82017-06-08 14:41:19 +03002533 if (type == &PyZip_Type && !_PyArg_NoKeywords("zip", kwds))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002534 return NULL;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002535
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002536 /* args must be a tuple */
2537 assert(PyTuple_Check(args));
Serhiy Storchakabf623ae2017-04-19 20:03:52 +03002538 tuplesize = PyTuple_GET_SIZE(args);
Barry Warsawbd599b52000-08-03 15:45:29 +00002539
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002540 /* obtain iterators */
2541 ittuple = PyTuple_New(tuplesize);
2542 if (ittuple == NULL)
2543 return NULL;
2544 for (i=0; i < tuplesize; ++i) {
2545 PyObject *item = PyTuple_GET_ITEM(args, i);
2546 PyObject *it = PyObject_GetIter(item);
2547 if (it == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002548 Py_DECREF(ittuple);
2549 return NULL;
2550 }
2551 PyTuple_SET_ITEM(ittuple, i, it);
2552 }
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002553
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002554 /* create a result holder */
2555 result = PyTuple_New(tuplesize);
2556 if (result == NULL) {
2557 Py_DECREF(ittuple);
2558 return NULL;
2559 }
2560 for (i=0 ; i < tuplesize ; i++) {
2561 Py_INCREF(Py_None);
2562 PyTuple_SET_ITEM(result, i, Py_None);
2563 }
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002564
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002565 /* create zipobject structure */
2566 lz = (zipobject *)type->tp_alloc(type, 0);
2567 if (lz == NULL) {
2568 Py_DECREF(ittuple);
2569 Py_DECREF(result);
2570 return NULL;
2571 }
2572 lz->ittuple = ittuple;
2573 lz->tuplesize = tuplesize;
2574 lz->result = result;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002575
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002576 return (PyObject *)lz;
Barry Warsawbd599b52000-08-03 15:45:29 +00002577}
2578
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002579static void
2580zip_dealloc(zipobject *lz)
2581{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002582 PyObject_GC_UnTrack(lz);
2583 Py_XDECREF(lz->ittuple);
2584 Py_XDECREF(lz->result);
2585 Py_TYPE(lz)->tp_free(lz);
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002586}
2587
2588static int
2589zip_traverse(zipobject *lz, visitproc visit, void *arg)
2590{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002591 Py_VISIT(lz->ittuple);
2592 Py_VISIT(lz->result);
2593 return 0;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002594}
2595
2596static PyObject *
2597zip_next(zipobject *lz)
2598{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002599 Py_ssize_t i;
2600 Py_ssize_t tuplesize = lz->tuplesize;
2601 PyObject *result = lz->result;
2602 PyObject *it;
2603 PyObject *item;
2604 PyObject *olditem;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002605
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002606 if (tuplesize == 0)
2607 return NULL;
2608 if (Py_REFCNT(result) == 1) {
2609 Py_INCREF(result);
2610 for (i=0 ; i < tuplesize ; i++) {
2611 it = PyTuple_GET_ITEM(lz->ittuple, i);
2612 item = (*Py_TYPE(it)->tp_iternext)(it);
Serhiy Storchaka278d03b2013-04-06 22:52:34 +03002613 if (item == NULL) {
2614 Py_DECREF(result);
2615 return NULL;
2616 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002617 olditem = PyTuple_GET_ITEM(result, i);
2618 PyTuple_SET_ITEM(result, i, item);
2619 Py_DECREF(olditem);
2620 }
2621 } else {
2622 result = PyTuple_New(tuplesize);
2623 if (result == NULL)
Serhiy Storchaka278d03b2013-04-06 22:52:34 +03002624 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002625 for (i=0 ; i < tuplesize ; i++) {
2626 it = PyTuple_GET_ITEM(lz->ittuple, i);
2627 item = (*Py_TYPE(it)->tp_iternext)(it);
Serhiy Storchaka278d03b2013-04-06 22:52:34 +03002628 if (item == NULL) {
2629 Py_DECREF(result);
2630 return NULL;
2631 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002632 PyTuple_SET_ITEM(result, i, item);
2633 }
2634 }
2635 return result;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002636}
Barry Warsawbd599b52000-08-03 15:45:29 +00002637
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002638static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05302639zip_reduce(zipobject *lz, PyObject *Py_UNUSED(ignored))
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002640{
2641 /* Just recreate the zip with the internal iterator tuple */
2642 return Py_BuildValue("OO", Py_TYPE(lz), lz->ittuple);
2643}
2644
2645static PyMethodDef zip_methods[] = {
2646 {"__reduce__", (PyCFunction)zip_reduce, METH_NOARGS, reduce_doc},
2647 {NULL, NULL} /* sentinel */
2648};
2649
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002650PyDoc_STRVAR(zip_doc,
Sergey Fedoseevaf2f5b12019-07-18 23:19:25 +05002651"zip(*iterables) --> zip object\n\
Barry Warsawbd599b52000-08-03 15:45:29 +00002652\n\
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002653Return a zip object whose .__next__() method returns a tuple where\n\
2654the i-th element comes from the i-th iterable argument. The .__next__()\n\
2655method continues until the shortest iterable in the argument sequence\n\
Georg Brandlced51db2008-12-04 18:28:38 +00002656is exhausted and then it raises StopIteration.");
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002657
2658PyTypeObject PyZip_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002659 PyVarObject_HEAD_INIT(&PyType_Type, 0)
2660 "zip", /* tp_name */
2661 sizeof(zipobject), /* tp_basicsize */
2662 0, /* tp_itemsize */
2663 /* methods */
2664 (destructor)zip_dealloc, /* tp_dealloc */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02002665 0, /* tp_vectorcall_offset */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002666 0, /* tp_getattr */
2667 0, /* tp_setattr */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02002668 0, /* tp_as_async */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002669 0, /* tp_repr */
2670 0, /* tp_as_number */
2671 0, /* tp_as_sequence */
2672 0, /* tp_as_mapping */
2673 0, /* tp_hash */
2674 0, /* tp_call */
2675 0, /* tp_str */
2676 PyObject_GenericGetAttr, /* tp_getattro */
2677 0, /* tp_setattro */
2678 0, /* tp_as_buffer */
2679 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
2680 Py_TPFLAGS_BASETYPE, /* tp_flags */
2681 zip_doc, /* tp_doc */
2682 (traverseproc)zip_traverse, /* tp_traverse */
2683 0, /* tp_clear */
2684 0, /* tp_richcompare */
2685 0, /* tp_weaklistoffset */
2686 PyObject_SelfIter, /* tp_iter */
2687 (iternextfunc)zip_next, /* tp_iternext */
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002688 zip_methods, /* tp_methods */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002689 0, /* tp_members */
2690 0, /* tp_getset */
2691 0, /* tp_base */
2692 0, /* tp_dict */
2693 0, /* tp_descr_get */
2694 0, /* tp_descr_set */
2695 0, /* tp_dictoffset */
2696 0, /* tp_init */
2697 PyType_GenericAlloc, /* tp_alloc */
2698 zip_new, /* tp_new */
2699 PyObject_GC_Del, /* tp_free */
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002700};
Barry Warsawbd599b52000-08-03 15:45:29 +00002701
2702
Guido van Rossum79f25d91997-04-29 20:08:16 +00002703static PyMethodDef builtin_methods[] = {
Serhiy Storchaka62be7422018-11-27 13:27:31 +02002704 {"__build_class__", (PyCFunction)(void(*)(void))builtin___build_class__,
Serhiy Storchaka6969eaf2017-07-03 21:20:15 +03002705 METH_FASTCALL | METH_KEYWORDS, build_class_doc},
Serhiy Storchaka62be7422018-11-27 13:27:31 +02002706 {"__import__", (PyCFunction)(void(*)(void))builtin___import__, METH_VARARGS | METH_KEYWORDS, import_doc},
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002707 BUILTIN_ABS_METHODDEF
2708 BUILTIN_ALL_METHODDEF
2709 BUILTIN_ANY_METHODDEF
2710 BUILTIN_ASCII_METHODDEF
2711 BUILTIN_BIN_METHODDEF
Serhiy Storchaka62be7422018-11-27 13:27:31 +02002712 {"breakpoint", (PyCFunction)(void(*)(void))builtin_breakpoint, METH_FASTCALL | METH_KEYWORDS, breakpoint_doc},
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002713 BUILTIN_CALLABLE_METHODDEF
2714 BUILTIN_CHR_METHODDEF
2715 BUILTIN_COMPILE_METHODDEF
2716 BUILTIN_DELATTR_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002717 {"dir", builtin_dir, METH_VARARGS, dir_doc},
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002718 BUILTIN_DIVMOD_METHODDEF
2719 BUILTIN_EVAL_METHODDEF
2720 BUILTIN_EXEC_METHODDEF
2721 BUILTIN_FORMAT_METHODDEF
Serhiy Storchaka62be7422018-11-27 13:27:31 +02002722 {"getattr", (PyCFunction)(void(*)(void))builtin_getattr, METH_FASTCALL, getattr_doc},
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002723 BUILTIN_GLOBALS_METHODDEF
2724 BUILTIN_HASATTR_METHODDEF
2725 BUILTIN_HASH_METHODDEF
2726 BUILTIN_HEX_METHODDEF
2727 BUILTIN_ID_METHODDEF
2728 BUILTIN_INPUT_METHODDEF
2729 BUILTIN_ISINSTANCE_METHODDEF
2730 BUILTIN_ISSUBCLASS_METHODDEF
Serhiy Storchaka79342662019-01-12 08:25:41 +02002731 {"iter", (PyCFunction)(void(*)(void))builtin_iter, METH_FASTCALL, iter_doc},
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002732 BUILTIN_LEN_METHODDEF
2733 BUILTIN_LOCALS_METHODDEF
Serhiy Storchaka62be7422018-11-27 13:27:31 +02002734 {"max", (PyCFunction)(void(*)(void))builtin_max, METH_VARARGS | METH_KEYWORDS, max_doc},
2735 {"min", (PyCFunction)(void(*)(void))builtin_min, METH_VARARGS | METH_KEYWORDS, min_doc},
2736 {"next", (PyCFunction)(void(*)(void))builtin_next, METH_FASTCALL, next_doc},
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002737 BUILTIN_OCT_METHODDEF
2738 BUILTIN_ORD_METHODDEF
2739 BUILTIN_POW_METHODDEF
Serhiy Storchaka62be7422018-11-27 13:27:31 +02002740 {"print", (PyCFunction)(void(*)(void))builtin_print, METH_FASTCALL | METH_KEYWORDS, print_doc},
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002741 BUILTIN_REPR_METHODDEF
Serhiy Storchakaaca7f572017-11-15 17:51:14 +02002742 BUILTIN_ROUND_METHODDEF
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002743 BUILTIN_SETATTR_METHODDEF
2744 BUILTIN_SORTED_METHODDEF
2745 BUILTIN_SUM_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002746 {"vars", builtin_vars, METH_VARARGS, vars_doc},
2747 {NULL, NULL},
Guido van Rossum3f5da241990-12-20 15:06:42 +00002748};
2749
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002750PyDoc_STRVAR(builtin_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002751"Built-in functions, exceptions, and other objects.\n\
2752\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002753Noteworthy: None is the `nil' object; Ellipsis represents `...' in slices.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002754
Martin v. Löwis1a214512008-06-11 05:26:20 +00002755static struct PyModuleDef builtinsmodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002756 PyModuleDef_HEAD_INIT,
2757 "builtins",
2758 builtin_doc,
2759 -1, /* multiple "initialization" just copies the module dict. */
2760 builtin_methods,
2761 NULL,
2762 NULL,
2763 NULL,
2764 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00002765};
2766
2767
Guido van Rossum25ce5661997-08-02 03:10:38 +00002768PyObject *
Victor Stinnerb45d2592019-06-20 00:05:23 +02002769_PyBuiltin_Init(PyThreadState *tstate)
Guido van Rossum25ce5661997-08-02 03:10:38 +00002770{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002771 PyObject *mod, *dict, *debug;
Benjamin Peterson42124a72012-10-30 23:41:54 -04002772
Victor Stinnerb45d2592019-06-20 00:05:23 +02002773 const PyConfig *config = &tstate->interp->config;
Victor Stinnerfbca9082018-08-30 00:50:45 +02002774
Benjamin Peterson42124a72012-10-30 23:41:54 -04002775 if (PyType_Ready(&PyFilter_Type) < 0 ||
2776 PyType_Ready(&PyMap_Type) < 0 ||
2777 PyType_Ready(&PyZip_Type) < 0)
2778 return NULL;
2779
Eric Snowd393c1b2017-09-14 12:18:12 -06002780 mod = _PyModule_CreateInitialized(&builtinsmodule, PYTHON_API_VERSION);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002781 if (mod == NULL)
2782 return NULL;
2783 dict = PyModule_GetDict(mod);
Tim Peters4b7625e2001-09-13 21:37:17 +00002784
Tim Peters7571a0f2003-03-23 17:52:28 +00002785#ifdef Py_TRACE_REFS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002786 /* "builtins" exposes a number of statically allocated objects
2787 * that, before this code was added in 2.3, never showed up in
2788 * the list of "all objects" maintained by Py_TRACE_REFS. As a
2789 * result, programs leaking references to None and False (etc)
2790 * couldn't be diagnosed by examining sys.getobjects(0).
2791 */
Tim Peters7571a0f2003-03-23 17:52:28 +00002792#define ADD_TO_ALL(OBJECT) _Py_AddToAllObjects((PyObject *)(OBJECT), 0)
2793#else
2794#define ADD_TO_ALL(OBJECT) (void)0
2795#endif
2796
Tim Peters4b7625e2001-09-13 21:37:17 +00002797#define SETBUILTIN(NAME, OBJECT) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002798 if (PyDict_SetItemString(dict, NAME, (PyObject *)OBJECT) < 0) \
2799 return NULL; \
2800 ADD_TO_ALL(OBJECT)
Tim Peters4b7625e2001-09-13 21:37:17 +00002801
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002802 SETBUILTIN("None", Py_None);
2803 SETBUILTIN("Ellipsis", Py_Ellipsis);
2804 SETBUILTIN("NotImplemented", Py_NotImplemented);
2805 SETBUILTIN("False", Py_False);
2806 SETBUILTIN("True", Py_True);
2807 SETBUILTIN("bool", &PyBool_Type);
2808 SETBUILTIN("memoryview", &PyMemoryView_Type);
2809 SETBUILTIN("bytearray", &PyByteArray_Type);
2810 SETBUILTIN("bytes", &PyBytes_Type);
2811 SETBUILTIN("classmethod", &PyClassMethod_Type);
2812 SETBUILTIN("complex", &PyComplex_Type);
2813 SETBUILTIN("dict", &PyDict_Type);
2814 SETBUILTIN("enumerate", &PyEnum_Type);
2815 SETBUILTIN("filter", &PyFilter_Type);
2816 SETBUILTIN("float", &PyFloat_Type);
2817 SETBUILTIN("frozenset", &PyFrozenSet_Type);
2818 SETBUILTIN("property", &PyProperty_Type);
2819 SETBUILTIN("int", &PyLong_Type);
2820 SETBUILTIN("list", &PyList_Type);
2821 SETBUILTIN("map", &PyMap_Type);
2822 SETBUILTIN("object", &PyBaseObject_Type);
2823 SETBUILTIN("range", &PyRange_Type);
2824 SETBUILTIN("reversed", &PyReversed_Type);
2825 SETBUILTIN("set", &PySet_Type);
2826 SETBUILTIN("slice", &PySlice_Type);
2827 SETBUILTIN("staticmethod", &PyStaticMethod_Type);
2828 SETBUILTIN("str", &PyUnicode_Type);
2829 SETBUILTIN("super", &PySuper_Type);
2830 SETBUILTIN("tuple", &PyTuple_Type);
2831 SETBUILTIN("type", &PyType_Type);
2832 SETBUILTIN("zip", &PyZip_Type);
Victor Stinnerfbca9082018-08-30 00:50:45 +02002833 debug = PyBool_FromLong(config->optimization_level == 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002834 if (PyDict_SetItemString(dict, "__debug__", debug) < 0) {
Serhiy Storchakacfdfbb42016-06-18 09:44:03 +03002835 Py_DECREF(debug);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002836 return NULL;
2837 }
Serhiy Storchakacfdfbb42016-06-18 09:44:03 +03002838 Py_DECREF(debug);
Barry Warsaw757af0e1997-08-29 22:13:51 +00002839
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002840 return mod;
Tim Peters7571a0f2003-03-23 17:52:28 +00002841#undef ADD_TO_ALL
Tim Peters4b7625e2001-09-13 21:37:17 +00002842#undef SETBUILTIN
Guido van Rossum3f5da241990-12-20 15:06:42 +00002843}