blob: ce3561e4c089858f2ce09e228ad491b65ccfb537 [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 Stinnere5014be2020-04-14 17:52:15 +02009#include "pycore_pystate.h" // _PyThreadState_GET()
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 &
Batuhan Taşkaya44540572020-04-22 19:09:03 +0300742 ~(PyCF_MASK | PyCF_MASK_OBSOLETE | PyCF_COMPILE_MASK))
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
Victor Stinner1def7752020-04-23 03:03:24 +0200819 int current_use_peg = PyInterpreterState_Get()->config._use_peg_parser;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100820 if (flags & PyCF_TYPE_COMMENTS || feature_version >= 0) {
Victor Stinner1def7752020-04-23 03:03:24 +0200821 PyInterpreterState_Get()->config._use_peg_parser = 0;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100822 }
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000823 result = Py_CompileStringObject(str, filename, start[compile_mode], &cf, optimize);
Victor Stinner1def7752020-04-23 03:03:24 +0200824 PyInterpreterState_Get()->config._use_peg_parser = current_use_peg;
Martin Panter61d6e4a2015-11-07 02:56:11 +0000825 Py_XDECREF(source_copy);
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000826 goto finally;
827
828error:
829 result = NULL;
830finally:
Victor Stinner14e461d2013-08-26 22:28:21 +0200831 Py_DECREF(filename);
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000832 return result;
Guido van Rossum5b722181993-03-30 17:46:03 +0000833}
834
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000835/* AC: cannot convert yet, as needs PEP 457 group support in inspect */
Guido van Rossum79f25d91997-04-29 20:08:16 +0000836static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000837builtin_dir(PyObject *self, PyObject *args)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000838{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000839 PyObject *arg = NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000840
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000841 if (!PyArg_UnpackTuple(args, "dir", 0, 1, &arg))
842 return NULL;
843 return PyObject_Dir(arg);
Guido van Rossum3f5da241990-12-20 15:06:42 +0000844}
845
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000846PyDoc_STRVAR(dir_doc,
Tim Peters5d2b77c2001-09-03 05:47:38 +0000847"dir([object]) -> list of strings\n"
848"\n"
Georg Brandle32b4222007-03-10 22:13:27 +0000849"If called without an argument, return the names in the current scope.\n"
850"Else, return an alphabetized list of names comprising (some of) the attributes\n"
851"of the given object, and of attributes reachable from it.\n"
852"If the object supplies a method named __dir__, it will be used; otherwise\n"
853"the default dir() logic is used and returns:\n"
854" for a module object: the module's attributes.\n"
855" for a class object: its attributes, and recursively the attributes\n"
856" of its bases.\n"
Guido van Rossumd8faa362007-04-27 19:54:29 +0000857" for any other object: its attributes, its class's attributes, and\n"
Georg Brandle32b4222007-03-10 22:13:27 +0000858" recursively the attributes of its class's base classes.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000859
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000860/*[clinic input]
861divmod as builtin_divmod
Guido van Rossum6a00cd81995-01-07 12:39:01 +0000862
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300863 x: object
864 y: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000865 /
866
Zachary Ware7f227d92016-04-28 14:39:50 -0500867Return the tuple (x//y, x%y). Invariant: div*y + mod == x.
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000868[clinic start generated code]*/
869
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000870static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300871builtin_divmod_impl(PyObject *module, PyObject *x, PyObject *y)
872/*[clinic end generated code: output=b06d8a5f6e0c745e input=175ad9c84ff41a85]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000873{
874 return PyNumber_Divmod(x, y);
875}
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000876
877
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000878/*[clinic input]
879eval as builtin_eval
880
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300881 source: object
882 globals: object = None
883 locals: object = None
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000884 /
885
886Evaluate the given source in the context of globals and locals.
887
888The source may be a string representing a Python expression
889or a code object as returned by compile().
890The globals must be a dictionary and locals can be any mapping,
891defaulting to the current globals and locals.
892If only globals is given, locals defaults to it.
893[clinic start generated code]*/
894
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000895static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300896builtin_eval_impl(PyObject *module, PyObject *source, PyObject *globals,
Larry Hastings89964c42015-04-14 18:07:59 -0400897 PyObject *locals)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300898/*[clinic end generated code: output=0a0824aa70093116 input=11ee718a8640e527]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000899{
Martin Panter61d6e4a2015-11-07 02:56:11 +0000900 PyObject *result, *source_copy;
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +0200901 const char *str;
Guido van Rossum590baa41993-11-30 13:40:46 +0000902
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000903 if (locals != Py_None && !PyMapping_Check(locals)) {
904 PyErr_SetString(PyExc_TypeError, "locals must be a mapping");
905 return NULL;
906 }
907 if (globals != Py_None && !PyDict_Check(globals)) {
908 PyErr_SetString(PyExc_TypeError, PyMapping_Check(globals) ?
909 "globals must be a real dict; try eval(expr, {}, mapping)"
910 : "globals must be a dict");
911 return NULL;
912 }
913 if (globals == Py_None) {
914 globals = PyEval_GetGlobals();
Victor Stinner41bb43a2013-10-29 01:19:37 +0100915 if (locals == Py_None) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000916 locals = PyEval_GetLocals();
Victor Stinner41bb43a2013-10-29 01:19:37 +0100917 if (locals == NULL)
918 return NULL;
919 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000920 }
921 else if (locals == Py_None)
922 locals = globals;
Tim Peters9fa96be2001-08-17 23:04:59 +0000923
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000924 if (globals == NULL || locals == NULL) {
925 PyErr_SetString(PyExc_TypeError,
926 "eval must be given globals and locals "
927 "when called without a frame");
928 return NULL;
929 }
Georg Brandl77c85e62005-09-15 10:46:13 +0000930
Serhiy Storchakaa24107b2019-02-25 17:59:46 +0200931 if (_PyDict_GetItemIdWithError(globals, &PyId___builtins__) == NULL) {
Victor Stinnerb44562b2013-11-06 19:03:11 +0100932 if (_PyDict_SetItemId(globals, &PyId___builtins__,
933 PyEval_GetBuiltins()) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000934 return NULL;
935 }
Serhiy Storchakaa24107b2019-02-25 17:59:46 +0200936 else if (PyErr_Occurred()) {
937 return NULL;
938 }
Tim Peters9fa96be2001-08-17 23:04:59 +0000939
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000940 if (PyCode_Check(source)) {
Steve Dowerb82e17e2019-05-23 08:45:22 -0700941 if (PySys_Audit("exec", "O", source) < 0) {
942 return NULL;
943 }
944
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000945 if (PyCode_GetNumFree((PyCodeObject *)source) > 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000946 PyErr_SetString(PyExc_TypeError,
Steve Dowerb82e17e2019-05-23 08:45:22 -0700947 "code object passed to eval() may not contain free variables");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000948 return NULL;
949 }
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000950 return PyEval_EvalCode(source, globals, locals);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000951 }
Tim Peters9fa96be2001-08-17 23:04:59 +0000952
Victor Stinner37d66d72019-06-13 02:16:41 +0200953 PyCompilerFlags cf = _PyCompilerFlags_INIT;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000954 cf.cf_flags = PyCF_SOURCE_IS_UTF8;
Dino Viehland41540692019-05-28 16:21:17 -0700955 str = _Py_SourceAsString(source, "eval", "string, bytes or code", &cf, &source_copy);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000956 if (str == NULL)
957 return NULL;
Just van Rossum3aaf42c2003-02-10 08:21:10 +0000958
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000959 while (*str == ' ' || *str == '\t')
960 str++;
Tim Peters9fa96be2001-08-17 23:04:59 +0000961
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000962 (void)PyEval_MergeCompilerFlags(&cf);
963 result = PyRun_StringFlags(str, Py_eval_input, globals, locals, &cf);
Martin Panter61d6e4a2015-11-07 02:56:11 +0000964 Py_XDECREF(source_copy);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000965 return result;
Guido van Rossum3f5da241990-12-20 15:06:42 +0000966}
967
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000968/*[clinic input]
969exec as builtin_exec
970
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300971 source: object
972 globals: object = None
973 locals: object = None
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000974 /
975
976Execute the given source in the context of globals and locals.
977
978The source may be a string representing one or more Python statements
979or a code object as returned by compile().
980The globals must be a dictionary and locals can be any mapping,
981defaulting to the current globals and locals.
982If only globals is given, locals defaults to it.
983[clinic start generated code]*/
984
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000985static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300986builtin_exec_impl(PyObject *module, PyObject *source, PyObject *globals,
Larry Hastings89964c42015-04-14 18:07:59 -0400987 PyObject *locals)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300988/*[clinic end generated code: output=3c90efc6ab68ef5d input=01ca3e1c01692829]*/
Georg Brandl7cae87c2006-09-06 06:51:57 +0000989{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000990 PyObject *v;
Georg Brandl2cabc562008-08-28 07:57:16 +0000991
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000992 if (globals == Py_None) {
993 globals = PyEval_GetGlobals();
994 if (locals == Py_None) {
995 locals = PyEval_GetLocals();
Victor Stinner41bb43a2013-10-29 01:19:37 +0100996 if (locals == NULL)
997 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000998 }
999 if (!globals || !locals) {
1000 PyErr_SetString(PyExc_SystemError,
1001 "globals and locals cannot be NULL");
1002 return NULL;
1003 }
1004 }
1005 else if (locals == Py_None)
1006 locals = globals;
Georg Brandl7cae87c2006-09-06 06:51:57 +00001007
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001008 if (!PyDict_Check(globals)) {
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001009 PyErr_Format(PyExc_TypeError, "exec() globals must be a dict, not %.100s",
Victor Stinnera102ed72020-02-07 02:24:48 +01001010 Py_TYPE(globals)->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001011 return NULL;
1012 }
1013 if (!PyMapping_Check(locals)) {
1014 PyErr_Format(PyExc_TypeError,
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001015 "locals must be a mapping or None, not %.100s",
Victor Stinnera102ed72020-02-07 02:24:48 +01001016 Py_TYPE(locals)->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001017 return NULL;
1018 }
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02001019 if (_PyDict_GetItemIdWithError(globals, &PyId___builtins__) == NULL) {
Victor Stinnerb44562b2013-11-06 19:03:11 +01001020 if (_PyDict_SetItemId(globals, &PyId___builtins__,
1021 PyEval_GetBuiltins()) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001022 return NULL;
1023 }
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02001024 else if (PyErr_Occurred()) {
1025 return NULL;
1026 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001027
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001028 if (PyCode_Check(source)) {
Steve Dowerb82e17e2019-05-23 08:45:22 -07001029 if (PySys_Audit("exec", "O", source) < 0) {
1030 return NULL;
1031 }
1032
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001033 if (PyCode_GetNumFree((PyCodeObject *)source) > 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001034 PyErr_SetString(PyExc_TypeError,
1035 "code object passed to exec() may not "
1036 "contain free variables");
1037 return NULL;
1038 }
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001039 v = PyEval_EvalCode(source, globals, locals);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001040 }
1041 else {
Martin Panter61d6e4a2015-11-07 02:56:11 +00001042 PyObject *source_copy;
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +02001043 const char *str;
Victor Stinner37d66d72019-06-13 02:16:41 +02001044 PyCompilerFlags cf = _PyCompilerFlags_INIT;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001045 cf.cf_flags = PyCF_SOURCE_IS_UTF8;
Dino Viehland41540692019-05-28 16:21:17 -07001046 str = _Py_SourceAsString(source, "exec",
Martin Panter61d6e4a2015-11-07 02:56:11 +00001047 "string, bytes or code", &cf,
1048 &source_copy);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001049 if (str == NULL)
1050 return NULL;
1051 if (PyEval_MergeCompilerFlags(&cf))
1052 v = PyRun_StringFlags(str, Py_file_input, globals,
1053 locals, &cf);
1054 else
1055 v = PyRun_String(str, Py_file_input, globals, locals);
Martin Panter61d6e4a2015-11-07 02:56:11 +00001056 Py_XDECREF(source_copy);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001057 }
1058 if (v == NULL)
1059 return NULL;
1060 Py_DECREF(v);
1061 Py_RETURN_NONE;
Georg Brandl7cae87c2006-09-06 06:51:57 +00001062}
1063
Georg Brandl7cae87c2006-09-06 06:51:57 +00001064
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001065/* AC: cannot convert yet, as needs PEP 457 group support in inspect */
Guido van Rossum79f25d91997-04-29 20:08:16 +00001066static PyObject *
Serhiy Storchakaa5552f02017-12-15 13:11:11 +02001067builtin_getattr(PyObject *self, PyObject *const *args, Py_ssize_t nargs)
Guido van Rossum33894be1992-01-27 16:53:09 +00001068{
Serhiy Storchaka79342662019-01-12 08:25:41 +02001069 PyObject *v, *name, *result;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001070
Serhiy Storchaka79342662019-01-12 08:25:41 +02001071 if (!_PyArg_CheckPositional("getattr", nargs, 2, 3))
Sylvain96c7c062017-06-15 17:05:23 +02001072 return NULL;
1073
Serhiy Storchaka79342662019-01-12 08:25:41 +02001074 v = args[0];
1075 name = args[1];
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001076 if (!PyUnicode_Check(name)) {
1077 PyErr_SetString(PyExc_TypeError,
1078 "getattr(): attribute name must be string");
1079 return NULL;
1080 }
Serhiy Storchaka79342662019-01-12 08:25:41 +02001081 if (nargs > 2) {
Serhiy Storchakaf320be72018-01-25 10:49:40 +02001082 if (_PyObject_LookupAttr(v, name, &result) == 0) {
Serhiy Storchaka79342662019-01-12 08:25:41 +02001083 PyObject *dflt = args[2];
INADA Naoki378edee2018-01-16 20:52:41 +09001084 Py_INCREF(dflt);
1085 return dflt;
1086 }
1087 }
1088 else {
1089 result = PyObject_GetAttr(v, name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001090 }
1091 return result;
Guido van Rossum9bfef441993-03-29 10:43:31 +00001092}
1093
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001094PyDoc_STRVAR(getattr_doc,
Guido van Rossum950ff291998-06-29 13:38:57 +00001095"getattr(object, name[, default]) -> value\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001096\n\
Guido van Rossum950ff291998-06-29 13:38:57 +00001097Get a named attribute from an object; getattr(x, 'y') is equivalent to x.y.\n\
1098When a default argument is given, it is returned when the attribute doesn't\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001099exist; without it, an exception is raised in that case.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001100
1101
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001102/*[clinic input]
1103globals as builtin_globals
1104
1105Return the dictionary containing the current scope's global variables.
1106
1107NOTE: Updates to this dictionary *will* affect name lookups in the current
1108global scope and vice-versa.
1109[clinic start generated code]*/
1110
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001111static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001112builtin_globals_impl(PyObject *module)
1113/*[clinic end generated code: output=e5dd1527067b94d2 input=9327576f92bb48ba]*/
Guido van Rossum872537c1995-07-07 22:43:42 +00001114{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001115 PyObject *d;
Guido van Rossum872537c1995-07-07 22:43:42 +00001116
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001117 d = PyEval_GetGlobals();
1118 Py_XINCREF(d);
1119 return d;
Guido van Rossum872537c1995-07-07 22:43:42 +00001120}
1121
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001122
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001123/*[clinic input]
1124hasattr as builtin_hasattr
1125
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001126 obj: object
1127 name: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001128 /
1129
1130Return whether the object has an attribute with the given name.
1131
1132This is done by calling getattr(obj, name) and catching AttributeError.
1133[clinic start generated code]*/
1134
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001135static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001136builtin_hasattr_impl(PyObject *module, PyObject *obj, PyObject *name)
1137/*[clinic end generated code: output=a7aff2090a4151e5 input=0faec9787d979542]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001138{
1139 PyObject *v;
1140
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001141 if (!PyUnicode_Check(name)) {
1142 PyErr_SetString(PyExc_TypeError,
1143 "hasattr(): attribute name must be string");
1144 return NULL;
1145 }
Serhiy Storchakaf320be72018-01-25 10:49:40 +02001146 if (_PyObject_LookupAttr(obj, name, &v) < 0) {
Benjamin Peterson17689992010-08-24 03:26:23 +00001147 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001148 }
Serhiy Storchakaf320be72018-01-25 10:49:40 +02001149 if (v == NULL) {
1150 Py_RETURN_FALSE;
1151 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001152 Py_DECREF(v);
Benjamin Peterson17689992010-08-24 03:26:23 +00001153 Py_RETURN_TRUE;
Guido van Rossum33894be1992-01-27 16:53:09 +00001154}
1155
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001156
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001157/* AC: gdb's integration with CPython relies on builtin_id having
1158 * the *exact* parameter names of "self" and "v", so we ensure we
1159 * preserve those name rather than using the AC defaults.
1160 */
1161/*[clinic input]
1162id as builtin_id
1163
Serhiy Storchaka24182a32016-05-05 16:21:35 +03001164 self: self(type="PyModuleDef *")
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001165 obj as v: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001166 /
1167
1168Return the identity of an object.
1169
1170This is guaranteed to be unique among simultaneously existing objects.
1171(CPython uses the object's memory address.)
1172[clinic start generated code]*/
1173
Guido van Rossum79f25d91997-04-29 20:08:16 +00001174static PyObject *
Serhiy Storchaka24182a32016-05-05 16:21:35 +03001175builtin_id(PyModuleDef *self, PyObject *v)
1176/*[clinic end generated code: output=0aa640785f697f65 input=5a534136419631f4]*/
Guido van Rossum5b722181993-03-30 17:46:03 +00001177{
Steve Dowerb82e17e2019-05-23 08:45:22 -07001178 PyObject *id = PyLong_FromVoidPtr(v);
1179
1180 if (id && PySys_Audit("builtins.id", "O", id) < 0) {
1181 Py_DECREF(id);
1182 return NULL;
1183 }
1184
1185 return id;
Guido van Rossum5b722181993-03-30 17:46:03 +00001186}
1187
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001188
Raymond Hettingera6c60372008-03-13 01:26:19 +00001189/* map object ************************************************************/
1190
1191typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001192 PyObject_HEAD
1193 PyObject *iters;
1194 PyObject *func;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001195} mapobject;
1196
Guido van Rossum79f25d91997-04-29 20:08:16 +00001197static PyObject *
Raymond Hettingera6c60372008-03-13 01:26:19 +00001198map_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
Guido van Rossum12d12c51993-10-26 17:58:25 +00001199{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001200 PyObject *it, *iters, *func;
1201 mapobject *lz;
1202 Py_ssize_t numargs, i;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001203
Serhiy Storchaka6cca5c82017-06-08 14:41:19 +03001204 if (type == &PyMap_Type && !_PyArg_NoKeywords("map", kwds))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001205 return NULL;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001206
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001207 numargs = PyTuple_Size(args);
1208 if (numargs < 2) {
1209 PyErr_SetString(PyExc_TypeError,
1210 "map() must have at least two arguments.");
1211 return NULL;
1212 }
Raymond Hettingera6c60372008-03-13 01:26:19 +00001213
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001214 iters = PyTuple_New(numargs-1);
1215 if (iters == NULL)
1216 return NULL;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001217
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001218 for (i=1 ; i<numargs ; i++) {
1219 /* Get iterator. */
1220 it = PyObject_GetIter(PyTuple_GET_ITEM(args, i));
1221 if (it == NULL) {
1222 Py_DECREF(iters);
1223 return NULL;
1224 }
1225 PyTuple_SET_ITEM(iters, i-1, it);
1226 }
Raymond Hettingera6c60372008-03-13 01:26:19 +00001227
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001228 /* create mapobject structure */
1229 lz = (mapobject *)type->tp_alloc(type, 0);
1230 if (lz == NULL) {
1231 Py_DECREF(iters);
1232 return NULL;
1233 }
1234 lz->iters = iters;
1235 func = PyTuple_GET_ITEM(args, 0);
1236 Py_INCREF(func);
1237 lz->func = func;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001238
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001239 return (PyObject *)lz;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001240}
1241
1242static void
1243map_dealloc(mapobject *lz)
1244{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001245 PyObject_GC_UnTrack(lz);
1246 Py_XDECREF(lz->iters);
1247 Py_XDECREF(lz->func);
1248 Py_TYPE(lz)->tp_free(lz);
Raymond Hettingera6c60372008-03-13 01:26:19 +00001249}
1250
1251static int
1252map_traverse(mapobject *lz, visitproc visit, void *arg)
1253{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001254 Py_VISIT(lz->iters);
1255 Py_VISIT(lz->func);
1256 return 0;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001257}
1258
1259static PyObject *
1260map_next(mapobject *lz)
1261{
Victor Stinnerbc08ab42016-12-15 12:40:53 +01001262 PyObject *small_stack[_PY_FASTCALL_SMALL_STACK];
Victor Stinnercdb5cee2016-08-24 01:45:13 +02001263 PyObject **stack;
Victor Stinnercdb5cee2016-08-24 01:45:13 +02001264 PyObject *result = NULL;
Victor Stinner4d231bc2019-11-14 13:36:21 +01001265 PyThreadState *tstate = _PyThreadState_GET();
Raymond Hettingera6c60372008-03-13 01:26:19 +00001266
Victor Stinner4d231bc2019-11-14 13:36:21 +01001267 const Py_ssize_t niters = PyTuple_GET_SIZE(lz->iters);
Victor Stinnercdb5cee2016-08-24 01:45:13 +02001268 if (niters <= (Py_ssize_t)Py_ARRAY_LENGTH(small_stack)) {
1269 stack = small_stack;
1270 }
1271 else {
1272 stack = PyMem_Malloc(niters * sizeof(stack[0]));
1273 if (stack == NULL) {
Victor Stinner4d231bc2019-11-14 13:36:21 +01001274 _PyErr_NoMemory(tstate);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001275 return NULL;
1276 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001277 }
Victor Stinnercdb5cee2016-08-24 01:45:13 +02001278
Victor Stinner4d231bc2019-11-14 13:36:21 +01001279 Py_ssize_t nargs = 0;
1280 for (Py_ssize_t i=0; i < niters; i++) {
Victor Stinnercdb5cee2016-08-24 01:45:13 +02001281 PyObject *it = PyTuple_GET_ITEM(lz->iters, i);
1282 PyObject *val = Py_TYPE(it)->tp_iternext(it);
1283 if (val == NULL) {
1284 goto exit;
1285 }
1286 stack[i] = val;
1287 nargs++;
1288 }
1289
Victor Stinner4d231bc2019-11-14 13:36:21 +01001290 result = _PyObject_VectorcallTstate(tstate, lz->func, stack, nargs, NULL);
Victor Stinnercdb5cee2016-08-24 01:45:13 +02001291
1292exit:
Victor Stinner4d231bc2019-11-14 13:36:21 +01001293 for (Py_ssize_t i=0; i < nargs; i++) {
Victor Stinnercdb5cee2016-08-24 01:45:13 +02001294 Py_DECREF(stack[i]);
1295 }
1296 if (stack != small_stack) {
1297 PyMem_Free(stack);
1298 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001299 return result;
Guido van Rossum12d12c51993-10-26 17:58:25 +00001300}
1301
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001302static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05301303map_reduce(mapobject *lz, PyObject *Py_UNUSED(ignored))
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001304{
1305 Py_ssize_t numargs = PyTuple_GET_SIZE(lz->iters);
1306 PyObject *args = PyTuple_New(numargs+1);
1307 Py_ssize_t i;
1308 if (args == NULL)
1309 return NULL;
1310 Py_INCREF(lz->func);
1311 PyTuple_SET_ITEM(args, 0, lz->func);
1312 for (i = 0; i<numargs; i++){
1313 PyObject *it = PyTuple_GET_ITEM(lz->iters, i);
1314 Py_INCREF(it);
1315 PyTuple_SET_ITEM(args, i+1, it);
1316 }
1317
1318 return Py_BuildValue("ON", Py_TYPE(lz), args);
1319}
1320
1321static PyMethodDef map_methods[] = {
1322 {"__reduce__", (PyCFunction)map_reduce, METH_NOARGS, reduce_doc},
1323 {NULL, NULL} /* sentinel */
1324};
1325
1326
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001327PyDoc_STRVAR(map_doc,
Raymond Hettingera6c60372008-03-13 01:26:19 +00001328"map(func, *iterables) --> map object\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001329\n\
Raymond Hettingera6c60372008-03-13 01:26:19 +00001330Make an iterator that computes the function using arguments from\n\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001331each of the iterables. Stops when the shortest iterable is exhausted.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001332
Raymond Hettingera6c60372008-03-13 01:26:19 +00001333PyTypeObject PyMap_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001334 PyVarObject_HEAD_INIT(&PyType_Type, 0)
1335 "map", /* tp_name */
1336 sizeof(mapobject), /* tp_basicsize */
1337 0, /* tp_itemsize */
1338 /* methods */
1339 (destructor)map_dealloc, /* tp_dealloc */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02001340 0, /* tp_vectorcall_offset */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001341 0, /* tp_getattr */
1342 0, /* tp_setattr */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02001343 0, /* tp_as_async */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001344 0, /* tp_repr */
1345 0, /* tp_as_number */
1346 0, /* tp_as_sequence */
1347 0, /* tp_as_mapping */
1348 0, /* tp_hash */
1349 0, /* tp_call */
1350 0, /* tp_str */
1351 PyObject_GenericGetAttr, /* tp_getattro */
1352 0, /* tp_setattro */
1353 0, /* tp_as_buffer */
1354 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
1355 Py_TPFLAGS_BASETYPE, /* tp_flags */
1356 map_doc, /* tp_doc */
1357 (traverseproc)map_traverse, /* tp_traverse */
1358 0, /* tp_clear */
1359 0, /* tp_richcompare */
1360 0, /* tp_weaklistoffset */
1361 PyObject_SelfIter, /* tp_iter */
1362 (iternextfunc)map_next, /* tp_iternext */
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001363 map_methods, /* tp_methods */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001364 0, /* tp_members */
1365 0, /* tp_getset */
1366 0, /* tp_base */
1367 0, /* tp_dict */
1368 0, /* tp_descr_get */
1369 0, /* tp_descr_set */
1370 0, /* tp_dictoffset */
1371 0, /* tp_init */
1372 PyType_GenericAlloc, /* tp_alloc */
1373 map_new, /* tp_new */
1374 PyObject_GC_Del, /* tp_free */
Raymond Hettingera6c60372008-03-13 01:26:19 +00001375};
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001376
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001377
1378/* AC: cannot convert yet, as needs PEP 457 group support in inspect */
Guido van Rossum79f25d91997-04-29 20:08:16 +00001379static PyObject *
Serhiy Storchakaa5552f02017-12-15 13:11:11 +02001380builtin_next(PyObject *self, PyObject *const *args, Py_ssize_t nargs)
Georg Brandla18af4e2007-04-21 15:47:16 +00001381{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001382 PyObject *it, *res;
Georg Brandla18af4e2007-04-21 15:47:16 +00001383
Serhiy Storchaka79342662019-01-12 08:25:41 +02001384 if (!_PyArg_CheckPositional("next", nargs, 1, 2))
Sylvain96c7c062017-06-15 17:05:23 +02001385 return NULL;
1386
Serhiy Storchaka79342662019-01-12 08:25:41 +02001387 it = args[0];
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001388 if (!PyIter_Check(it)) {
1389 PyErr_Format(PyExc_TypeError,
Philip Jenvey50add042011-11-06 16:37:52 -08001390 "'%.200s' object is not an iterator",
Victor Stinnera102ed72020-02-07 02:24:48 +01001391 Py_TYPE(it)->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001392 return NULL;
1393 }
1394
Victor Stinnera102ed72020-02-07 02:24:48 +01001395 res = (*Py_TYPE(it)->tp_iternext)(it);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001396 if (res != NULL) {
1397 return res;
Serhiy Storchaka79342662019-01-12 08:25:41 +02001398 } else if (nargs > 1) {
1399 PyObject *def = args[1];
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001400 if (PyErr_Occurred()) {
1401 if(!PyErr_ExceptionMatches(PyExc_StopIteration))
1402 return NULL;
1403 PyErr_Clear();
1404 }
1405 Py_INCREF(def);
1406 return def;
1407 } else if (PyErr_Occurred()) {
1408 return NULL;
1409 } else {
1410 PyErr_SetNone(PyExc_StopIteration);
1411 return NULL;
1412 }
Georg Brandla18af4e2007-04-21 15:47:16 +00001413}
1414
1415PyDoc_STRVAR(next_doc,
1416"next(iterator[, default])\n\
1417\n\
1418Return the next item from the iterator. If default is given and the iterator\n\
1419is exhausted, it is returned instead of raising StopIteration.");
1420
1421
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001422/*[clinic input]
1423setattr as builtin_setattr
1424
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001425 obj: object
1426 name: object
1427 value: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001428 /
1429
1430Sets the named attribute on the given object to the specified value.
1431
1432setattr(x, 'y', v) is equivalent to ``x.y = v''
1433[clinic start generated code]*/
1434
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001435static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001436builtin_setattr_impl(PyObject *module, PyObject *obj, PyObject *name,
Larry Hastings89964c42015-04-14 18:07:59 -04001437 PyObject *value)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001438/*[clinic end generated code: output=dc2ce1d1add9acb4 input=bd2b7ca6875a1899]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001439{
1440 if (PyObject_SetAttr(obj, name, value) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001441 return NULL;
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02001442 Py_RETURN_NONE;
Guido van Rossum33894be1992-01-27 16:53:09 +00001443}
1444
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001445
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001446/*[clinic input]
1447delattr as builtin_delattr
1448
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001449 obj: object
1450 name: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001451 /
1452
1453Deletes the named attribute from the given object.
1454
1455delattr(x, 'y') is equivalent to ``del x.y''
1456[clinic start generated code]*/
1457
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001458static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001459builtin_delattr_impl(PyObject *module, PyObject *obj, PyObject *name)
1460/*[clinic end generated code: output=85134bc58dff79fa input=db16685d6b4b9410]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001461{
1462 if (PyObject_SetAttr(obj, name, (PyObject *)NULL) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001463 return NULL;
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02001464 Py_RETURN_NONE;
Guido van Rossum14144fc1994-08-29 12:53:40 +00001465}
1466
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001467
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001468/*[clinic input]
1469hash as builtin_hash
1470
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001471 obj: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001472 /
1473
1474Return the hash value for the given object.
1475
1476Two objects that compare equal must also have the same hash value, but the
1477reverse is not necessarily true.
1478[clinic start generated code]*/
1479
Guido van Rossum79f25d91997-04-29 20:08:16 +00001480static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001481builtin_hash(PyObject *module, PyObject *obj)
1482/*[clinic end generated code: output=237668e9d7688db7 input=58c48be822bf9c54]*/
Guido van Rossum9bfef441993-03-29 10:43:31 +00001483{
Benjamin Peterson8f67d082010-10-17 20:54:53 +00001484 Py_hash_t x;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001485
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001486 x = PyObject_Hash(obj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001487 if (x == -1)
1488 return NULL;
Benjamin Peterson8f67d082010-10-17 20:54:53 +00001489 return PyLong_FromSsize_t(x);
Guido van Rossum9bfef441993-03-29 10:43:31 +00001490}
1491
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001492
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001493/*[clinic input]
1494hex as builtin_hex
1495
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001496 number: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001497 /
1498
1499Return the hexadecimal representation of an integer.
1500
1501 >>> hex(12648430)
1502 '0xc0ffee'
1503[clinic start generated code]*/
1504
Guido van Rossum79f25d91997-04-29 20:08:16 +00001505static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001506builtin_hex(PyObject *module, PyObject *number)
1507/*[clinic end generated code: output=e46b612169099408 input=e645aff5fc7d540e]*/
Guido van Rossum006bcd41991-10-24 14:54:44 +00001508{
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001509 return PyNumber_ToBase(number, 16);
Guido van Rossum006bcd41991-10-24 14:54:44 +00001510}
1511
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001512
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001513/* AC: cannot convert yet, as needs PEP 457 group support in inspect */
Guido van Rossum79f25d91997-04-29 20:08:16 +00001514static PyObject *
Serhiy Storchaka79342662019-01-12 08:25:41 +02001515builtin_iter(PyObject *self, PyObject *const *args, Py_ssize_t nargs)
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001516{
Serhiy Storchaka79342662019-01-12 08:25:41 +02001517 PyObject *v;
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001518
Serhiy Storchaka79342662019-01-12 08:25:41 +02001519 if (!_PyArg_CheckPositional("iter", nargs, 1, 2))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001520 return NULL;
Serhiy Storchaka79342662019-01-12 08:25:41 +02001521 v = args[0];
1522 if (nargs == 1)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001523 return PyObject_GetIter(v);
1524 if (!PyCallable_Check(v)) {
1525 PyErr_SetString(PyExc_TypeError,
1526 "iter(v, w): v must be callable");
1527 return NULL;
1528 }
Serhiy Storchaka79342662019-01-12 08:25:41 +02001529 PyObject *sentinel = args[1];
1530 return PyCallIter_New(v, sentinel);
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001531}
1532
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001533PyDoc_STRVAR(iter_doc,
Georg Brandld11ae5d2008-05-16 13:27:32 +00001534"iter(iterable) -> iterator\n\
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001535iter(callable, sentinel) -> iterator\n\
1536\n\
1537Get an iterator from an object. In the first form, the argument must\n\
1538supply its own iterator, or be a sequence.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001539In the second form, the callable is called until it returns the sentinel.");
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001540
1541
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001542/*[clinic input]
1543len as builtin_len
1544
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001545 obj: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001546 /
1547
1548Return the number of items in a container.
1549[clinic start generated code]*/
1550
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001551static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001552builtin_len(PyObject *module, PyObject *obj)
1553/*[clinic end generated code: output=fa7a270d314dfb6c input=bc55598da9e9c9b5]*/
Guido van Rossum3f5da241990-12-20 15:06:42 +00001554{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001555 Py_ssize_t res;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001556
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001557 res = PyObject_Size(obj);
Serhiy Storchaka813f9432017-04-16 09:21:44 +03001558 if (res < 0) {
1559 assert(PyErr_Occurred());
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001560 return NULL;
Serhiy Storchaka813f9432017-04-16 09:21:44 +03001561 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001562 return PyLong_FromSsize_t(res);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001563}
1564
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001565
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001566/*[clinic input]
1567locals as builtin_locals
1568
1569Return a dictionary containing the current scope's local variables.
1570
1571NOTE: Whether or not updates to this dictionary will affect name lookups in
1572the local scope and vice-versa is *implementation dependent* and not
1573covered by any backwards compatibility guarantees.
1574[clinic start generated code]*/
1575
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001576static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001577builtin_locals_impl(PyObject *module)
1578/*[clinic end generated code: output=b46c94015ce11448 input=7874018d478d5c4b]*/
Guido van Rossum872537c1995-07-07 22:43:42 +00001579{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001580 PyObject *d;
Guido van Rossum872537c1995-07-07 22:43:42 +00001581
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001582 d = PyEval_GetLocals();
1583 Py_XINCREF(d);
1584 return d;
Guido van Rossum872537c1995-07-07 22:43:42 +00001585}
1586
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001587
Guido van Rossum79f25d91997-04-29 20:08:16 +00001588static PyObject *
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001589min_max(PyObject *args, PyObject *kwds, int op)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001590{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001591 PyObject *v, *it, *item, *val, *maxitem, *maxval, *keyfunc=NULL;
Raymond Hettinger4d6018f2013-06-24 22:43:02 -07001592 PyObject *emptytuple, *defaultval = NULL;
1593 static char *kwlist[] = {"key", "default", NULL};
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001594 const char *name = op == Py_LT ? "min" : "max";
Raymond Hettinger4d6018f2013-06-24 22:43:02 -07001595 const int positional = PyTuple_Size(args) > 1;
1596 int ret;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001597
Dong-hee Naabdc6342020-01-11 01:31:43 +09001598 if (positional) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001599 v = args;
Dong-hee Naabdc6342020-01-11 01:31:43 +09001600 }
1601 else if (!PyArg_UnpackTuple(args, name, 1, 1, &v)) {
1602 if (PyExceptionClass_Check(PyExc_TypeError)) {
1603 PyErr_Format(PyExc_TypeError, "%s expected at least 1 argument, got 0", name);
1604 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001605 return NULL;
Dong-hee Naabdc6342020-01-11 01:31:43 +09001606 }
Tim Peters67d687a2002-04-29 21:27:32 +00001607
Raymond Hettinger4d6018f2013-06-24 22:43:02 -07001608 emptytuple = PyTuple_New(0);
1609 if (emptytuple == NULL)
1610 return NULL;
Oren Milman58cf7482017-08-21 20:19:07 +03001611 ret = PyArg_ParseTupleAndKeywords(emptytuple, kwds,
1612 (op == Py_LT) ? "|$OO:min" : "|$OO:max",
1613 kwlist, &keyfunc, &defaultval);
Raymond Hettinger4d6018f2013-06-24 22:43:02 -07001614 Py_DECREF(emptytuple);
1615 if (!ret)
1616 return NULL;
1617
1618 if (positional && defaultval != NULL) {
1619 PyErr_Format(PyExc_TypeError,
1620 "Cannot specify a default for %s() with multiple "
1621 "positional arguments", name);
1622 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001623 }
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001624
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001625 it = PyObject_GetIter(v);
1626 if (it == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001627 return NULL;
1628 }
Tim Petersc3074532001-05-03 07:00:32 +00001629
Alexander Marshalove22072f2018-07-24 10:58:21 +07001630 if (keyfunc == Py_None) {
1631 keyfunc = NULL;
1632 }
1633
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001634 maxitem = NULL; /* the result */
1635 maxval = NULL; /* the value associated with the result */
1636 while (( item = PyIter_Next(it) )) {
1637 /* get the value from the key function */
1638 if (keyfunc != NULL) {
Petr Viktorinffd97532020-02-11 17:46:57 +01001639 val = PyObject_CallOneArg(keyfunc, item);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001640 if (val == NULL)
1641 goto Fail_it_item;
1642 }
1643 /* no key function; the value is the item */
1644 else {
1645 val = item;
1646 Py_INCREF(val);
1647 }
Tim Petersc3074532001-05-03 07:00:32 +00001648
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001649 /* maximum value and item are unset; set them */
1650 if (maxval == NULL) {
1651 maxitem = item;
1652 maxval = val;
1653 }
1654 /* maximum value and item are set; update them as necessary */
1655 else {
1656 int cmp = PyObject_RichCompareBool(val, maxval, op);
1657 if (cmp < 0)
1658 goto Fail_it_item_and_val;
1659 else if (cmp > 0) {
1660 Py_DECREF(maxval);
1661 Py_DECREF(maxitem);
1662 maxval = val;
1663 maxitem = item;
1664 }
1665 else {
1666 Py_DECREF(item);
1667 Py_DECREF(val);
1668 }
1669 }
1670 }
1671 if (PyErr_Occurred())
1672 goto Fail_it;
1673 if (maxval == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001674 assert(maxitem == NULL);
Raymond Hettinger4d6018f2013-06-24 22:43:02 -07001675 if (defaultval != NULL) {
1676 Py_INCREF(defaultval);
1677 maxitem = defaultval;
1678 } else {
1679 PyErr_Format(PyExc_ValueError,
1680 "%s() arg is an empty sequence", name);
1681 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001682 }
1683 else
1684 Py_DECREF(maxval);
1685 Py_DECREF(it);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001686 return maxitem;
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001687
1688Fail_it_item_and_val:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001689 Py_DECREF(val);
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001690Fail_it_item:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001691 Py_DECREF(item);
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001692Fail_it:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001693 Py_XDECREF(maxval);
1694 Py_XDECREF(maxitem);
1695 Py_DECREF(it);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001696 return NULL;
Guido van Rossum3f5da241990-12-20 15:06:42 +00001697}
1698
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001699/* AC: cannot convert yet, waiting for *args support */
Guido van Rossum79f25d91997-04-29 20:08:16 +00001700static PyObject *
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001701builtin_min(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001702{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001703 return min_max(args, kwds, Py_LT);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001704}
1705
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001706PyDoc_STRVAR(min_doc,
Raymond Hettinger2a545822014-05-19 22:20:52 +01001707"min(iterable, *[, default=obj, key=func]) -> value\n\
1708min(arg1, arg2, *args, *[, key=func]) -> value\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001709\n\
Raymond Hettinger2a545822014-05-19 22:20:52 +01001710With a single iterable argument, return its smallest item. The\n\
1711default keyword-only argument specifies an object to return if\n\
1712the provided iterable is empty.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001713With two or more arguments, return the smallest argument.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001714
1715
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001716/* AC: cannot convert yet, waiting for *args support */
Guido van Rossum79f25d91997-04-29 20:08:16 +00001717static PyObject *
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001718builtin_max(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001719{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001720 return min_max(args, kwds, Py_GT);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001721}
1722
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001723PyDoc_STRVAR(max_doc,
Raymond Hettinger2a545822014-05-19 22:20:52 +01001724"max(iterable, *[, default=obj, key=func]) -> value\n\
1725max(arg1, arg2, *args, *[, key=func]) -> value\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001726\n\
Raymond Hettinger2a545822014-05-19 22:20:52 +01001727With a single iterable argument, return its biggest item. The\n\
1728default keyword-only argument specifies an object to return if\n\
1729the provided iterable is empty.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001730With two or more arguments, return the largest argument.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001731
1732
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001733/*[clinic input]
1734oct as builtin_oct
1735
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001736 number: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001737 /
1738
1739Return the octal representation of an integer.
1740
1741 >>> oct(342391)
1742 '0o1234567'
1743[clinic start generated code]*/
1744
Guido van Rossum79f25d91997-04-29 20:08:16 +00001745static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001746builtin_oct(PyObject *module, PyObject *number)
1747/*[clinic end generated code: output=40a34656b6875352 input=ad6b274af4016c72]*/
Guido van Rossum006bcd41991-10-24 14:54:44 +00001748{
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001749 return PyNumber_ToBase(number, 8);
Guido van Rossum006bcd41991-10-24 14:54:44 +00001750}
1751
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001752
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001753/*[clinic input]
1754ord as builtin_ord
1755
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001756 c: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001757 /
1758
1759Return the Unicode code point for a one-character string.
1760[clinic start generated code]*/
1761
Guido van Rossum79f25d91997-04-29 20:08:16 +00001762static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001763builtin_ord(PyObject *module, PyObject *c)
1764/*[clinic end generated code: output=4fa5e87a323bae71 input=3064e5d6203ad012]*/
Guido van Rossum3f5da241990-12-20 15:06:42 +00001765{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001766 long ord;
1767 Py_ssize_t size;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001768
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001769 if (PyBytes_Check(c)) {
1770 size = PyBytes_GET_SIZE(c);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001771 if (size == 1) {
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001772 ord = (long)((unsigned char)*PyBytes_AS_STRING(c));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001773 return PyLong_FromLong(ord);
1774 }
1775 }
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001776 else if (PyUnicode_Check(c)) {
1777 if (PyUnicode_READY(c) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001778 return NULL;
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001779 size = PyUnicode_GET_LENGTH(c);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001780 if (size == 1) {
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001781 ord = (long)PyUnicode_READ_CHAR(c, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001782 return PyLong_FromLong(ord);
1783 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001784 }
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001785 else if (PyByteArray_Check(c)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001786 /* XXX Hopefully this is temporary */
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001787 size = PyByteArray_GET_SIZE(c);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001788 if (size == 1) {
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001789 ord = (long)((unsigned char)*PyByteArray_AS_STRING(c));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001790 return PyLong_FromLong(ord);
1791 }
1792 }
1793 else {
1794 PyErr_Format(PyExc_TypeError,
1795 "ord() expected string of length 1, but " \
Victor Stinnera102ed72020-02-07 02:24:48 +01001796 "%.200s found", Py_TYPE(c)->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001797 return NULL;
1798 }
Guido van Rossum09095f32000-03-10 23:00:52 +00001799
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001800 PyErr_Format(PyExc_TypeError,
1801 "ord() expected a character, "
1802 "but string of length %zd found",
1803 size);
1804 return NULL;
Guido van Rossum3f5da241990-12-20 15:06:42 +00001805}
1806
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001807
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001808/*[clinic input]
1809pow as builtin_pow
1810
Ammar Askar87d6cd32019-09-21 00:28:49 -04001811 base: object
1812 exp: object
1813 mod: object = None
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001814
Raymond Hettingerb104ecb2019-09-21 12:57:44 -07001815Equivalent to base**exp with 2 arguments or base**exp % mod with 3 arguments
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001816
1817Some types, such as ints, are able to use a more efficient algorithm when
1818invoked using the three argument form.
1819[clinic start generated code]*/
1820
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001821static PyObject *
Ammar Askar87d6cd32019-09-21 00:28:49 -04001822builtin_pow_impl(PyObject *module, PyObject *base, PyObject *exp,
1823 PyObject *mod)
Raymond Hettingerb104ecb2019-09-21 12:57:44 -07001824/*[clinic end generated code: output=3ca1538221bbf15f input=435dbd48a12efb23]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001825{
Ammar Askar87d6cd32019-09-21 00:28:49 -04001826 return PyNumber_Power(base, exp, mod);
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001827}
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001828
1829
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001830/* AC: cannot convert yet, waiting for *args support */
Guido van Rossum34343512006-11-30 22:13:52 +00001831static PyObject *
Serhiy Storchakaa5552f02017-12-15 13:11:11 +02001832builtin_print(PyObject *self, PyObject *const *args, Py_ssize_t nargs, PyObject *kwnames)
Guido van Rossum34343512006-11-30 22:13:52 +00001833{
INADA Naokibd584f12017-01-19 12:50:34 +01001834 static const char * const _keywords[] = {"sep", "end", "file", "flush", 0};
Serhiy Storchaka1f21eaa2019-09-01 12:16:51 +03001835 static struct _PyArg_Parser _parser = {"|OOOp:print", _keywords, 0};
1836 PyObject *sep = NULL, *end = NULL, *file = NULL;
1837 int flush = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001838 int i, err;
Guido van Rossum34343512006-11-30 22:13:52 +00001839
INADA Naokibd584f12017-01-19 12:50:34 +01001840 if (kwnames != NULL &&
1841 !_PyArg_ParseStackAndKeywords(args + nargs, 0, kwnames, &_parser,
1842 &sep, &end, &file, &flush)) {
Georg Brandlbc3b6822012-01-13 19:41:25 +01001843 return NULL;
INADA Naokibd584f12017-01-19 12:50:34 +01001844 }
1845
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001846 if (file == NULL || file == Py_None) {
Victor Stinnerbd303c12013-11-07 23:07:29 +01001847 file = _PySys_GetObjectId(&PyId_stdout);
Victor Stinner1e53bba2013-07-16 22:26:05 +02001848 if (file == NULL) {
1849 PyErr_SetString(PyExc_RuntimeError, "lost sys.stdout");
1850 return NULL;
1851 }
1852
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001853 /* sys.stdout may be None when FILE* stdout isn't connected */
1854 if (file == Py_None)
1855 Py_RETURN_NONE;
1856 }
Guido van Rossum34343512006-11-30 22:13:52 +00001857
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001858 if (sep == Py_None) {
1859 sep = NULL;
1860 }
1861 else if (sep && !PyUnicode_Check(sep)) {
1862 PyErr_Format(PyExc_TypeError,
1863 "sep must be None or a string, not %.200s",
Victor Stinnera102ed72020-02-07 02:24:48 +01001864 Py_TYPE(sep)->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001865 return NULL;
1866 }
1867 if (end == Py_None) {
1868 end = NULL;
1869 }
1870 else if (end && !PyUnicode_Check(end)) {
1871 PyErr_Format(PyExc_TypeError,
1872 "end must be None or a string, not %.200s",
Victor Stinnera102ed72020-02-07 02:24:48 +01001873 Py_TYPE(end)->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001874 return NULL;
1875 }
Guido van Rossum34343512006-11-30 22:13:52 +00001876
INADA Naokibd584f12017-01-19 12:50:34 +01001877 for (i = 0; i < nargs; i++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001878 if (i > 0) {
1879 if (sep == NULL)
1880 err = PyFile_WriteString(" ", file);
1881 else
1882 err = PyFile_WriteObject(sep, file,
1883 Py_PRINT_RAW);
1884 if (err)
1885 return NULL;
1886 }
INADA Naokibd584f12017-01-19 12:50:34 +01001887 err = PyFile_WriteObject(args[i], file, Py_PRINT_RAW);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001888 if (err)
1889 return NULL;
1890 }
Guido van Rossum34343512006-11-30 22:13:52 +00001891
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001892 if (end == NULL)
1893 err = PyFile_WriteString("\n", file);
1894 else
1895 err = PyFile_WriteObject(end, file, Py_PRINT_RAW);
1896 if (err)
1897 return NULL;
Guido van Rossum34343512006-11-30 22:13:52 +00001898
Serhiy Storchaka1f21eaa2019-09-01 12:16:51 +03001899 if (flush) {
1900 PyObject *tmp = _PyObject_CallMethodIdNoArgs(file, &PyId_flush);
1901 if (tmp == NULL)
Georg Brandlbc3b6822012-01-13 19:41:25 +01001902 return NULL;
Serhiy Storchaka1f21eaa2019-09-01 12:16:51 +03001903 Py_DECREF(tmp);
Georg Brandlbc3b6822012-01-13 19:41:25 +01001904 }
1905
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001906 Py_RETURN_NONE;
Guido van Rossum34343512006-11-30 22:13:52 +00001907}
1908
1909PyDoc_STRVAR(print_doc,
Senthil Kumarane9175bd2012-08-10 13:53:45 -07001910"print(value, ..., sep=' ', end='\\n', file=sys.stdout, flush=False)\n\
Guido van Rossum34343512006-11-30 22:13:52 +00001911\n\
1912Prints the values to a stream, or to sys.stdout by default.\n\
1913Optional keyword arguments:\n\
Senthil Kumarane9175bd2012-08-10 13:53:45 -07001914file: a file-like object (stream); defaults to the current sys.stdout.\n\
1915sep: string inserted between values, default a space.\n\
1916end: string appended after the last value, default a newline.\n\
1917flush: whether to forcibly flush the stream.");
Guido van Rossum34343512006-11-30 22:13:52 +00001918
1919
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001920/*[clinic input]
1921input as builtin_input
1922
1923 prompt: object(c_default="NULL") = None
1924 /
1925
1926Read a string from standard input. The trailing newline is stripped.
1927
1928The prompt string, if given, is printed to standard output without a
1929trailing newline before reading input.
1930
1931If the user hits EOF (*nix: Ctrl-D, Windows: Ctrl-Z+Return), raise EOFError.
1932On *nix systems, readline is used if available.
1933[clinic start generated code]*/
1934
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001935static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001936builtin_input_impl(PyObject *module, PyObject *prompt)
1937/*[clinic end generated code: output=83db5a191e7a0d60 input=5e8bb70c2908fe3c]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001938{
Victor Stinnerbd303c12013-11-07 23:07:29 +01001939 PyObject *fin = _PySys_GetObjectId(&PyId_stdin);
1940 PyObject *fout = _PySys_GetObjectId(&PyId_stdout);
1941 PyObject *ferr = _PySys_GetObjectId(&PyId_stderr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001942 PyObject *tmp;
1943 long fd;
1944 int tty;
Guido van Rossuma88a0332007-02-26 16:59:55 +00001945
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001946 /* Check that stdin/out/err are intact */
1947 if (fin == NULL || fin == Py_None) {
1948 PyErr_SetString(PyExc_RuntimeError,
1949 "input(): lost sys.stdin");
1950 return NULL;
1951 }
1952 if (fout == NULL || fout == Py_None) {
1953 PyErr_SetString(PyExc_RuntimeError,
1954 "input(): lost sys.stdout");
1955 return NULL;
1956 }
1957 if (ferr == NULL || ferr == Py_None) {
1958 PyErr_SetString(PyExc_RuntimeError,
1959 "input(): lost sys.stderr");
1960 return NULL;
1961 }
Guido van Rossumeba76962007-05-27 09:13:28 +00001962
Steve Dowerb82e17e2019-05-23 08:45:22 -07001963 if (PySys_Audit("builtins.input", "O", prompt ? prompt : Py_None) < 0) {
1964 return NULL;
1965 }
1966
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001967 /* First of all, flush stderr */
Jeroen Demeyer762f93f2019-07-08 10:19:25 +02001968 tmp = _PyObject_CallMethodIdNoArgs(ferr, &PyId_flush);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001969 if (tmp == NULL)
1970 PyErr_Clear();
1971 else
1972 Py_DECREF(tmp);
Guido van Rossumeba76962007-05-27 09:13:28 +00001973
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001974 /* We should only use (GNU) readline if Python's sys.stdin and
1975 sys.stdout are the same as C's stdin and stdout, because we
1976 need to pass it those. */
Jeroen Demeyer762f93f2019-07-08 10:19:25 +02001977 tmp = _PyObject_CallMethodIdNoArgs(fin, &PyId_fileno);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001978 if (tmp == NULL) {
1979 PyErr_Clear();
1980 tty = 0;
1981 }
1982 else {
1983 fd = PyLong_AsLong(tmp);
1984 Py_DECREF(tmp);
1985 if (fd < 0 && PyErr_Occurred())
1986 return NULL;
1987 tty = fd == fileno(stdin) && isatty(fd);
1988 }
1989 if (tty) {
Jeroen Demeyer762f93f2019-07-08 10:19:25 +02001990 tmp = _PyObject_CallMethodIdNoArgs(fout, &PyId_fileno);
Martin Panterc9a6ab52015-10-10 01:25:38 +00001991 if (tmp == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001992 PyErr_Clear();
Martin Panterc9a6ab52015-10-10 01:25:38 +00001993 tty = 0;
1994 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001995 else {
1996 fd = PyLong_AsLong(tmp);
1997 Py_DECREF(tmp);
1998 if (fd < 0 && PyErr_Occurred())
1999 return NULL;
2000 tty = fd == fileno(stdout) && isatty(fd);
2001 }
2002 }
Guido van Rossumeba76962007-05-27 09:13:28 +00002003
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002004 /* If we're interactive, use (GNU) readline */
2005 if (tty) {
Antoine Pitrou0d776b12011-11-06 00:34:26 +01002006 PyObject *po = NULL;
Serhiy Storchakae2f92de2017-11-11 13:06:26 +02002007 const char *promptstr;
Antoine Pitrou0d776b12011-11-06 00:34:26 +01002008 char *s = NULL;
2009 PyObject *stdin_encoding = NULL, *stdin_errors = NULL;
2010 PyObject *stdout_encoding = NULL, *stdout_errors = NULL;
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +02002011 const char *stdin_encoding_str, *stdin_errors_str;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002012 PyObject *result;
Victor Stinnerc0f1a1a2011-02-23 12:07:37 +00002013 size_t len;
Martin v. Löwis4a7b5d52007-09-04 05:24:49 +00002014
Serhiy Storchakac2cf1282017-03-12 13:50:36 +02002015 /* stdin is a text stream, so it must have an encoding. */
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02002016 stdin_encoding = _PyObject_GetAttrId(fin, &PyId_encoding);
Antoine Pitrou5ee9d8a2011-11-06 00:38:45 +01002017 stdin_errors = _PyObject_GetAttrId(fin, &PyId_errors);
Serhiy Storchakac2cf1282017-03-12 13:50:36 +02002018 if (!stdin_encoding || !stdin_errors ||
2019 !PyUnicode_Check(stdin_encoding) ||
2020 !PyUnicode_Check(stdin_errors)) {
2021 tty = 0;
Antoine Pitrou0d776b12011-11-06 00:34:26 +01002022 goto _readline_errors;
Serhiy Storchakac2cf1282017-03-12 13:50:36 +02002023 }
Serhiy Storchaka06515832016-11-20 09:13:07 +02002024 stdin_encoding_str = PyUnicode_AsUTF8(stdin_encoding);
2025 stdin_errors_str = PyUnicode_AsUTF8(stdin_errors);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01002026 if (!stdin_encoding_str || !stdin_errors_str)
2027 goto _readline_errors;
Jeroen Demeyer762f93f2019-07-08 10:19:25 +02002028 tmp = _PyObject_CallMethodIdNoArgs(fout, &PyId_flush);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002029 if (tmp == NULL)
2030 PyErr_Clear();
2031 else
2032 Py_DECREF(tmp);
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002033 if (prompt != NULL) {
Antoine Pitrou0d776b12011-11-06 00:34:26 +01002034 /* We have a prompt, encode it as stdout would */
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +02002035 const char *stdout_encoding_str, *stdout_errors_str;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002036 PyObject *stringpo;
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02002037 stdout_encoding = _PyObject_GetAttrId(fout, &PyId_encoding);
Antoine Pitrou5ee9d8a2011-11-06 00:38:45 +01002038 stdout_errors = _PyObject_GetAttrId(fout, &PyId_errors);
Serhiy Storchakac2cf1282017-03-12 13:50:36 +02002039 if (!stdout_encoding || !stdout_errors ||
2040 !PyUnicode_Check(stdout_encoding) ||
2041 !PyUnicode_Check(stdout_errors)) {
2042 tty = 0;
Antoine Pitrou0d776b12011-11-06 00:34:26 +01002043 goto _readline_errors;
Serhiy Storchakac2cf1282017-03-12 13:50:36 +02002044 }
Serhiy Storchaka06515832016-11-20 09:13:07 +02002045 stdout_encoding_str = PyUnicode_AsUTF8(stdout_encoding);
2046 stdout_errors_str = PyUnicode_AsUTF8(stdout_errors);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01002047 if (!stdout_encoding_str || !stdout_errors_str)
2048 goto _readline_errors;
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002049 stringpo = PyObject_Str(prompt);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01002050 if (stringpo == NULL)
2051 goto _readline_errors;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002052 po = PyUnicode_AsEncodedString(stringpo,
Antoine Pitrou0d776b12011-11-06 00:34:26 +01002053 stdout_encoding_str, stdout_errors_str);
2054 Py_CLEAR(stdout_encoding);
2055 Py_CLEAR(stdout_errors);
2056 Py_CLEAR(stringpo);
2057 if (po == NULL)
2058 goto _readline_errors;
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03002059 assert(PyBytes_Check(po));
2060 promptstr = PyBytes_AS_STRING(po);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002061 }
2062 else {
2063 po = NULL;
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002064 promptstr = "";
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002065 }
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002066 s = PyOS_Readline(stdin, stdout, promptstr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002067 if (s == NULL) {
Richard Oudkerk614c5782013-04-03 13:44:50 +01002068 PyErr_CheckSignals();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002069 if (!PyErr_Occurred())
2070 PyErr_SetNone(PyExc_KeyboardInterrupt);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01002071 goto _readline_errors;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002072 }
Victor Stinnerc0f1a1a2011-02-23 12:07:37 +00002073
2074 len = strlen(s);
2075 if (len == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002076 PyErr_SetNone(PyExc_EOFError);
2077 result = NULL;
2078 }
Victor Stinnerc0f1a1a2011-02-23 12:07:37 +00002079 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002080 if (len > PY_SSIZE_T_MAX) {
2081 PyErr_SetString(PyExc_OverflowError,
2082 "input: input too long");
2083 result = NULL;
2084 }
2085 else {
Victor Stinnerc0f1a1a2011-02-23 12:07:37 +00002086 len--; /* strip trailing '\n' */
2087 if (len != 0 && s[len-1] == '\r')
2088 len--; /* strip trailing '\r' */
Antoine Pitrou0d776b12011-11-06 00:34:26 +01002089 result = PyUnicode_Decode(s, len, stdin_encoding_str,
2090 stdin_errors_str);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002091 }
2092 }
2093 Py_DECREF(stdin_encoding);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01002094 Py_DECREF(stdin_errors);
2095 Py_XDECREF(po);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002096 PyMem_FREE(s);
Steve Dowerb82e17e2019-05-23 08:45:22 -07002097
2098 if (result != NULL) {
2099 if (PySys_Audit("builtins.input/result", "O", result) < 0) {
2100 return NULL;
2101 }
2102 }
2103
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002104 return result;
Serhiy Storchakac2cf1282017-03-12 13:50:36 +02002105
Antoine Pitrou0d776b12011-11-06 00:34:26 +01002106 _readline_errors:
2107 Py_XDECREF(stdin_encoding);
2108 Py_XDECREF(stdout_encoding);
2109 Py_XDECREF(stdin_errors);
2110 Py_XDECREF(stdout_errors);
2111 Py_XDECREF(po);
Serhiy Storchakac2cf1282017-03-12 13:50:36 +02002112 if (tty)
2113 return NULL;
2114
2115 PyErr_Clear();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002116 }
Guido van Rossumeba76962007-05-27 09:13:28 +00002117
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002118 /* Fallback if we're not interactive */
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002119 if (prompt != NULL) {
2120 if (PyFile_WriteObject(prompt, fout, Py_PRINT_RAW) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002121 return NULL;
2122 }
Jeroen Demeyer762f93f2019-07-08 10:19:25 +02002123 tmp = _PyObject_CallMethodIdNoArgs(fout, &PyId_flush);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002124 if (tmp == NULL)
2125 PyErr_Clear();
2126 else
2127 Py_DECREF(tmp);
2128 return PyFile_GetLine(fin, -1);
Guido van Rossuma88a0332007-02-26 16:59:55 +00002129}
2130
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002131
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002132/*[clinic input]
2133repr as builtin_repr
2134
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03002135 obj: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002136 /
2137
2138Return the canonical string representation of the object.
2139
2140For many object types, including most builtins, eval(repr(obj)) == obj.
2141[clinic start generated code]*/
2142
Guido van Rossum79f25d91997-04-29 20:08:16 +00002143static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002144builtin_repr(PyObject *module, PyObject *obj)
2145/*[clinic end generated code: output=7ed3778c44fd0194 input=1c9e6d66d3e3be04]*/
Guido van Rossumc89705d1992-11-26 08:54:07 +00002146{
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002147 return PyObject_Repr(obj);
Guido van Rossumc89705d1992-11-26 08:54:07 +00002148}
2149
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002150
Serhiy Storchakaaca7f572017-11-15 17:51:14 +02002151/*[clinic input]
2152round as builtin_round
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002153
Serhiy Storchakaaca7f572017-11-15 17:51:14 +02002154 number: object
Serhiy Storchaka279f4462019-09-14 12:24:05 +03002155 ndigits: object = None
Serhiy Storchakaaca7f572017-11-15 17:51:14 +02002156
2157Round a number to a given precision in decimal digits.
2158
2159The return value is an integer if ndigits is omitted or None. Otherwise
2160the return value has the same type as the number. ndigits may be negative.
2161[clinic start generated code]*/
2162
2163static PyObject *
2164builtin_round_impl(PyObject *module, PyObject *number, PyObject *ndigits)
Serhiy Storchaka279f4462019-09-14 12:24:05 +03002165/*[clinic end generated code: output=ff0d9dd176c02ede input=275678471d7aca15]*/
Serhiy Storchakaaca7f572017-11-15 17:51:14 +02002166{
2167 PyObject *round, *result;
Alex Martelliae211f92007-08-22 23:21:33 +00002168
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002169 if (Py_TYPE(number)->tp_dict == NULL) {
2170 if (PyType_Ready(Py_TYPE(number)) < 0)
2171 return NULL;
2172 }
Guido van Rossum15d3d042007-08-24 02:02:45 +00002173
Benjamin Peterson214a7d22013-04-13 17:19:01 -04002174 round = _PyObject_LookupSpecial(number, &PyId___round__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002175 if (round == NULL) {
Benjamin Peterson214a7d22013-04-13 17:19:01 -04002176 if (!PyErr_Occurred())
2177 PyErr_Format(PyExc_TypeError,
2178 "type %.100s doesn't define __round__ method",
2179 Py_TYPE(number)->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002180 return NULL;
2181 }
Alex Martelliae211f92007-08-22 23:21:33 +00002182
Serhiy Storchaka279f4462019-09-14 12:24:05 +03002183 if (ndigits == Py_None)
Victor Stinnerf17c3de2016-12-06 18:46:19 +01002184 result = _PyObject_CallNoArg(round);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002185 else
Petr Viktorinffd97532020-02-11 17:46:57 +01002186 result = PyObject_CallOneArg(round, ndigits);
Benjamin Peterson214a7d22013-04-13 17:19:01 -04002187 Py_DECREF(round);
2188 return result;
Guido van Rossum9e51f9b1993-02-12 16:29:05 +00002189}
2190
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002191
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002192/*AC: we need to keep the kwds dict intact to easily call into the
2193 * list.sort method, which isn't currently supported in AC. So we just use
2194 * the initially generated signature with a custom implementation.
2195 */
2196/* [disabled clinic input]
2197sorted as builtin_sorted
2198
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03002199 iterable as seq: object
2200 key as keyfunc: object = None
2201 reverse: object = False
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002202
2203Return a new list containing all items from the iterable in ascending order.
2204
Raymond Hettinger7ea386e2016-08-25 21:11:50 -07002205A custom key function can be supplied to customize the sort order, and the
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002206reverse flag can be set to request the result in descending order.
2207[end disabled clinic input]*/
2208
2209PyDoc_STRVAR(builtin_sorted__doc__,
Serhiy Storchaka3a104252017-01-23 12:29:47 +02002210"sorted($module, iterable, /, *, key=None, reverse=False)\n"
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002211"--\n"
2212"\n"
2213"Return a new list containing all items from the iterable in ascending order.\n"
2214"\n"
Raymond Hettinger7ea386e2016-08-25 21:11:50 -07002215"A custom key function can be supplied to customize the sort order, and the\n"
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002216"reverse flag can be set to request the result in descending order.");
2217
2218#define BUILTIN_SORTED_METHODDEF \
Serhiy Storchaka62be7422018-11-27 13:27:31 +02002219 {"sorted", (PyCFunction)(void(*)(void))builtin_sorted, METH_FASTCALL | METH_KEYWORDS, builtin_sorted__doc__},
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002220
Raymond Hettinger64958a12003-12-17 20:43:33 +00002221static PyObject *
Serhiy Storchakaa5552f02017-12-15 13:11:11 +02002222builtin_sorted(PyObject *self, PyObject *const *args, Py_ssize_t nargs, PyObject *kwnames)
Raymond Hettinger64958a12003-12-17 20:43:33 +00002223{
Serhiy Storchaka7cf8beb2017-01-21 23:05:00 +02002224 PyObject *newlist, *v, *seq, *callable;
Victor Stinner5a60eca2017-01-17 15:17:49 +01002225
Serhiy Storchaka7cf8beb2017-01-21 23:05:00 +02002226 /* Keyword arguments are passed through list.sort() which will check
2227 them. */
2228 if (!_PyArg_UnpackStack(args, nargs, "sorted", 1, 1, &seq))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002229 return NULL;
Raymond Hettinger64958a12003-12-17 20:43:33 +00002230
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002231 newlist = PySequence_List(seq);
2232 if (newlist == NULL)
2233 return NULL;
Raymond Hettinger64958a12003-12-17 20:43:33 +00002234
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02002235 callable = _PyObject_GetAttrId(newlist, &PyId_sort);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002236 if (callable == NULL) {
2237 Py_DECREF(newlist);
2238 return NULL;
2239 }
Georg Brandl99d7e4e2005-08-31 22:21:15 +00002240
Serhiy Storchaka299dc232017-01-20 08:35:18 +02002241 assert(nargs >= 1);
Petr Viktorinffd97532020-02-11 17:46:57 +01002242 v = PyObject_Vectorcall(callable, args + 1, nargs - 1, kwnames);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002243 Py_DECREF(callable);
2244 if (v == NULL) {
2245 Py_DECREF(newlist);
2246 return NULL;
2247 }
2248 Py_DECREF(v);
2249 return newlist;
Raymond Hettinger64958a12003-12-17 20:43:33 +00002250}
2251
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002252
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002253/* AC: cannot convert yet, as needs PEP 457 group support in inspect */
Guido van Rossum79f25d91997-04-29 20:08:16 +00002254static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002255builtin_vars(PyObject *self, PyObject *args)
Guido van Rossum2d951851994-08-29 12:52:16 +00002256{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002257 PyObject *v = NULL;
2258 PyObject *d;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002259
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002260 if (!PyArg_UnpackTuple(args, "vars", 0, 1, &v))
2261 return NULL;
2262 if (v == NULL) {
2263 d = PyEval_GetLocals();
Serhiy Storchaka41c57b32019-09-01 12:03:39 +03002264 Py_XINCREF(d);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002265 }
2266 else {
Serhiy Storchaka41c57b32019-09-01 12:03:39 +03002267 if (_PyObject_LookupAttrId(v, &PyId___dict__, &d) == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002268 PyErr_SetString(PyExc_TypeError,
2269 "vars() argument must have __dict__ attribute");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002270 }
2271 }
2272 return d;
Guido van Rossum2d951851994-08-29 12:52:16 +00002273}
2274
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002275PyDoc_STRVAR(vars_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002276"vars([object]) -> dictionary\n\
2277\n\
2278Without arguments, equivalent to locals().\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002279With an argument, equivalent to object.__dict__.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002280
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002281
2282/*[clinic input]
2283sum as builtin_sum
2284
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03002285 iterable: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002286 /
Raymond Hettinger9dfa0fe2018-09-12 10:54:06 -07002287 start: object(c_default="NULL") = 0
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002288
2289Return the sum of a 'start' value (default: 0) plus an iterable of numbers
2290
2291When the iterable is empty, return the start value.
2292This function is intended specifically for use with numeric values and may
2293reject non-numeric types.
2294[clinic start generated code]*/
2295
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002296static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002297builtin_sum_impl(PyObject *module, PyObject *iterable, PyObject *start)
Raymond Hettinger9dfa0fe2018-09-12 10:54:06 -07002298/*[clinic end generated code: output=df758cec7d1d302f input=162b50765250d222]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002299{
2300 PyObject *result = start;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002301 PyObject *temp, *item, *iter;
Alex Martellia70b1912003-04-22 08:12:33 +00002302
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002303 iter = PyObject_GetIter(iterable);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002304 if (iter == NULL)
2305 return NULL;
Alex Martellia70b1912003-04-22 08:12:33 +00002306
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002307 if (result == NULL) {
2308 result = PyLong_FromLong(0);
2309 if (result == NULL) {
2310 Py_DECREF(iter);
2311 return NULL;
2312 }
2313 } else {
2314 /* reject string values for 'start' parameter */
2315 if (PyUnicode_Check(result)) {
2316 PyErr_SetString(PyExc_TypeError,
2317 "sum() can't sum strings [use ''.join(seq) instead]");
2318 Py_DECREF(iter);
2319 return NULL;
2320 }
Benjamin Petersonce071ca2011-07-29 14:23:47 -05002321 if (PyBytes_Check(result)) {
2322 PyErr_SetString(PyExc_TypeError,
2323 "sum() can't sum bytes [use b''.join(seq) instead]");
Benjamin Peterson405f32c2011-07-29 22:43:45 -05002324 Py_DECREF(iter);
Benjamin Petersonce071ca2011-07-29 14:23:47 -05002325 return NULL;
2326 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002327 if (PyByteArray_Check(result)) {
2328 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson4f921c22011-07-29 14:24:29 -05002329 "sum() can't sum bytearray [use b''.join(seq) instead]");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002330 Py_DECREF(iter);
2331 return NULL;
2332 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002333 Py_INCREF(result);
2334 }
Alex Martellia70b1912003-04-22 08:12:33 +00002335
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002336#ifndef SLOW_SUM
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002337 /* Fast addition by keeping temporary sums in C instead of new Python objects.
2338 Assumes all inputs are the same type. If the assumption fails, default
2339 to the more general routine.
2340 */
2341 if (PyLong_CheckExact(result)) {
2342 int overflow;
2343 long i_result = PyLong_AsLongAndOverflow(result, &overflow);
2344 /* If this already overflowed, don't even enter the loop. */
2345 if (overflow == 0) {
2346 Py_DECREF(result);
2347 result = NULL;
2348 }
2349 while(result == NULL) {
2350 item = PyIter_Next(iter);
2351 if (item == NULL) {
2352 Py_DECREF(iter);
2353 if (PyErr_Occurred())
2354 return NULL;
2355 return PyLong_FromLong(i_result);
2356 }
Serhiy Storchaka88bdb922019-09-10 16:31:01 +03002357 if (PyLong_CheckExact(item) || PyBool_Check(item)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002358 long b = PyLong_AsLongAndOverflow(item, &overflow);
Serhiy Storchaka29500732019-05-05 14:26:23 +03002359 if (overflow == 0 &&
2360 (i_result >= 0 ? (b <= LONG_MAX - i_result)
2361 : (b >= LONG_MIN - i_result)))
2362 {
2363 i_result += b;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002364 Py_DECREF(item);
2365 continue;
2366 }
2367 }
2368 /* Either overflowed or is not an int. Restore real objects and process normally */
2369 result = PyLong_FromLong(i_result);
Christian Heimes704e2d32013-07-26 22:49:26 +02002370 if (result == NULL) {
2371 Py_DECREF(item);
2372 Py_DECREF(iter);
2373 return NULL;
2374 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002375 temp = PyNumber_Add(result, item);
2376 Py_DECREF(result);
2377 Py_DECREF(item);
2378 result = temp;
2379 if (result == NULL) {
2380 Py_DECREF(iter);
2381 return NULL;
2382 }
2383 }
2384 }
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002385
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002386 if (PyFloat_CheckExact(result)) {
2387 double f_result = PyFloat_AS_DOUBLE(result);
2388 Py_DECREF(result);
2389 result = NULL;
2390 while(result == NULL) {
2391 item = PyIter_Next(iter);
2392 if (item == NULL) {
2393 Py_DECREF(iter);
2394 if (PyErr_Occurred())
2395 return NULL;
2396 return PyFloat_FromDouble(f_result);
2397 }
2398 if (PyFloat_CheckExact(item)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002399 f_result += PyFloat_AS_DOUBLE(item);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002400 Py_DECREF(item);
2401 continue;
2402 }
Serhiy Storchaka88bdb922019-09-10 16:31:01 +03002403 if (PyLong_Check(item)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002404 long value;
2405 int overflow;
2406 value = PyLong_AsLongAndOverflow(item, &overflow);
2407 if (!overflow) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002408 f_result += (double)value;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002409 Py_DECREF(item);
2410 continue;
2411 }
2412 }
2413 result = PyFloat_FromDouble(f_result);
Alexey Izbyshev2b824b22018-08-24 07:27:52 +03002414 if (result == NULL) {
2415 Py_DECREF(item);
2416 Py_DECREF(iter);
2417 return NULL;
2418 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002419 temp = PyNumber_Add(result, item);
2420 Py_DECREF(result);
2421 Py_DECREF(item);
2422 result = temp;
2423 if (result == NULL) {
2424 Py_DECREF(iter);
2425 return NULL;
2426 }
2427 }
2428 }
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002429#endif
2430
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002431 for(;;) {
2432 item = PyIter_Next(iter);
2433 if (item == NULL) {
2434 /* error, or end-of-sequence */
2435 if (PyErr_Occurred()) {
2436 Py_DECREF(result);
2437 result = NULL;
2438 }
2439 break;
2440 }
2441 /* It's tempting to use PyNumber_InPlaceAdd instead of
2442 PyNumber_Add here, to avoid quadratic running time
2443 when doing 'sum(list_of_lists, [])'. However, this
2444 would produce a change in behaviour: a snippet like
Mark Dickinson9acadc52009-10-26 14:19:42 +00002445
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002446 empty = []
2447 sum([[x] for x in range(10)], empty)
Mark Dickinson9acadc52009-10-26 14:19:42 +00002448
Brandt Bucherabb9a442020-02-01 03:08:34 -08002449 would change the value of empty. In fact, using
2450 in-place addition rather that binary addition for
2451 any of the steps introduces subtle behavior changes:
Victor Stinner58f4e1a2020-02-05 18:24:33 +01002452
Brandt Bucherabb9a442020-02-01 03:08:34 -08002453 https://bugs.python.org/issue18305 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002454 temp = PyNumber_Add(result, item);
2455 Py_DECREF(result);
2456 Py_DECREF(item);
2457 result = temp;
2458 if (result == NULL)
2459 break;
2460 }
2461 Py_DECREF(iter);
2462 return result;
Alex Martellia70b1912003-04-22 08:12:33 +00002463}
2464
Alex Martellia70b1912003-04-22 08:12:33 +00002465
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002466/*[clinic input]
2467isinstance as builtin_isinstance
2468
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03002469 obj: object
2470 class_or_tuple: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002471 /
2472
2473Return whether an object is an instance of a class or of a subclass thereof.
2474
2475A tuple, as in ``isinstance(x, (A, B, ...))``, may be given as the target to
2476check against. This is equivalent to ``isinstance(x, A) or isinstance(x, B)
2477or ...`` etc.
2478[clinic start generated code]*/
2479
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002480static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002481builtin_isinstance_impl(PyObject *module, PyObject *obj,
Larry Hastings89964c42015-04-14 18:07:59 -04002482 PyObject *class_or_tuple)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002483/*[clinic end generated code: output=6faf01472c13b003 input=ffa743db1daf7549]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002484{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002485 int retval;
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002486
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002487 retval = PyObject_IsInstance(obj, class_or_tuple);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002488 if (retval < 0)
2489 return NULL;
2490 return PyBool_FromLong(retval);
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002491}
2492
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002493
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002494/*[clinic input]
2495issubclass as builtin_issubclass
2496
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03002497 cls: object
2498 class_or_tuple: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002499 /
2500
2501Return whether 'cls' is a derived from another class or is the same class.
2502
2503A tuple, as in ``issubclass(x, (A, B, ...))``, may be given as the target to
2504check against. This is equivalent to ``issubclass(x, A) or issubclass(x, B)
2505or ...`` etc.
2506[clinic start generated code]*/
2507
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002508static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002509builtin_issubclass_impl(PyObject *module, PyObject *cls,
Larry Hastings89964c42015-04-14 18:07:59 -04002510 PyObject *class_or_tuple)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002511/*[clinic end generated code: output=358412410cd7a250 input=af5f35e9ceaddaf6]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002512{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002513 int retval;
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002514
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002515 retval = PyObject_IsSubclass(cls, class_or_tuple);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002516 if (retval < 0)
2517 return NULL;
2518 return PyBool_FromLong(retval);
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002519}
2520
2521
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002522typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002523 PyObject_HEAD
2524 Py_ssize_t tuplesize;
2525 PyObject *ittuple; /* tuple of iterators */
2526 PyObject *result;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002527} zipobject;
2528
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002529static PyObject *
2530zip_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
Barry Warsawbd599b52000-08-03 15:45:29 +00002531{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002532 zipobject *lz;
2533 Py_ssize_t i;
2534 PyObject *ittuple; /* tuple of iterators */
2535 PyObject *result;
Serhiy Storchakabf623ae2017-04-19 20:03:52 +03002536 Py_ssize_t tuplesize;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002537
Serhiy Storchaka6cca5c82017-06-08 14:41:19 +03002538 if (type == &PyZip_Type && !_PyArg_NoKeywords("zip", kwds))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002539 return NULL;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002540
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002541 /* args must be a tuple */
2542 assert(PyTuple_Check(args));
Serhiy Storchakabf623ae2017-04-19 20:03:52 +03002543 tuplesize = PyTuple_GET_SIZE(args);
Barry Warsawbd599b52000-08-03 15:45:29 +00002544
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002545 /* obtain iterators */
2546 ittuple = PyTuple_New(tuplesize);
2547 if (ittuple == NULL)
2548 return NULL;
2549 for (i=0; i < tuplesize; ++i) {
2550 PyObject *item = PyTuple_GET_ITEM(args, i);
2551 PyObject *it = PyObject_GetIter(item);
2552 if (it == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002553 Py_DECREF(ittuple);
2554 return NULL;
2555 }
2556 PyTuple_SET_ITEM(ittuple, i, it);
2557 }
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002558
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002559 /* create a result holder */
2560 result = PyTuple_New(tuplesize);
2561 if (result == NULL) {
2562 Py_DECREF(ittuple);
2563 return NULL;
2564 }
2565 for (i=0 ; i < tuplesize ; i++) {
2566 Py_INCREF(Py_None);
2567 PyTuple_SET_ITEM(result, i, Py_None);
2568 }
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002569
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002570 /* create zipobject structure */
2571 lz = (zipobject *)type->tp_alloc(type, 0);
2572 if (lz == NULL) {
2573 Py_DECREF(ittuple);
2574 Py_DECREF(result);
2575 return NULL;
2576 }
2577 lz->ittuple = ittuple;
2578 lz->tuplesize = tuplesize;
2579 lz->result = result;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002580
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002581 return (PyObject *)lz;
Barry Warsawbd599b52000-08-03 15:45:29 +00002582}
2583
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002584static void
2585zip_dealloc(zipobject *lz)
2586{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002587 PyObject_GC_UnTrack(lz);
2588 Py_XDECREF(lz->ittuple);
2589 Py_XDECREF(lz->result);
2590 Py_TYPE(lz)->tp_free(lz);
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002591}
2592
2593static int
2594zip_traverse(zipobject *lz, visitproc visit, void *arg)
2595{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002596 Py_VISIT(lz->ittuple);
2597 Py_VISIT(lz->result);
2598 return 0;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002599}
2600
2601static PyObject *
2602zip_next(zipobject *lz)
2603{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002604 Py_ssize_t i;
2605 Py_ssize_t tuplesize = lz->tuplesize;
2606 PyObject *result = lz->result;
2607 PyObject *it;
2608 PyObject *item;
2609 PyObject *olditem;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002610
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002611 if (tuplesize == 0)
2612 return NULL;
2613 if (Py_REFCNT(result) == 1) {
2614 Py_INCREF(result);
2615 for (i=0 ; i < tuplesize ; i++) {
2616 it = PyTuple_GET_ITEM(lz->ittuple, i);
2617 item = (*Py_TYPE(it)->tp_iternext)(it);
Serhiy Storchaka278d03b2013-04-06 22:52:34 +03002618 if (item == NULL) {
2619 Py_DECREF(result);
2620 return NULL;
2621 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002622 olditem = PyTuple_GET_ITEM(result, i);
2623 PyTuple_SET_ITEM(result, i, item);
2624 Py_DECREF(olditem);
2625 }
2626 } else {
2627 result = PyTuple_New(tuplesize);
2628 if (result == NULL)
Serhiy Storchaka278d03b2013-04-06 22:52:34 +03002629 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002630 for (i=0 ; i < tuplesize ; i++) {
2631 it = PyTuple_GET_ITEM(lz->ittuple, i);
2632 item = (*Py_TYPE(it)->tp_iternext)(it);
Serhiy Storchaka278d03b2013-04-06 22:52:34 +03002633 if (item == NULL) {
2634 Py_DECREF(result);
2635 return NULL;
2636 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002637 PyTuple_SET_ITEM(result, i, item);
2638 }
2639 }
2640 return result;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002641}
Barry Warsawbd599b52000-08-03 15:45:29 +00002642
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002643static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05302644zip_reduce(zipobject *lz, PyObject *Py_UNUSED(ignored))
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002645{
2646 /* Just recreate the zip with the internal iterator tuple */
2647 return Py_BuildValue("OO", Py_TYPE(lz), lz->ittuple);
2648}
2649
2650static PyMethodDef zip_methods[] = {
2651 {"__reduce__", (PyCFunction)zip_reduce, METH_NOARGS, reduce_doc},
2652 {NULL, NULL} /* sentinel */
2653};
2654
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002655PyDoc_STRVAR(zip_doc,
Sergey Fedoseevaf2f5b12019-07-18 23:19:25 +05002656"zip(*iterables) --> zip object\n\
Barry Warsawbd599b52000-08-03 15:45:29 +00002657\n\
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002658Return a zip object whose .__next__() method returns a tuple where\n\
2659the i-th element comes from the i-th iterable argument. The .__next__()\n\
2660method continues until the shortest iterable in the argument sequence\n\
Georg Brandlced51db2008-12-04 18:28:38 +00002661is exhausted and then it raises StopIteration.");
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002662
2663PyTypeObject PyZip_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002664 PyVarObject_HEAD_INIT(&PyType_Type, 0)
2665 "zip", /* tp_name */
2666 sizeof(zipobject), /* tp_basicsize */
2667 0, /* tp_itemsize */
2668 /* methods */
2669 (destructor)zip_dealloc, /* tp_dealloc */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02002670 0, /* tp_vectorcall_offset */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002671 0, /* tp_getattr */
2672 0, /* tp_setattr */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02002673 0, /* tp_as_async */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002674 0, /* tp_repr */
2675 0, /* tp_as_number */
2676 0, /* tp_as_sequence */
2677 0, /* tp_as_mapping */
2678 0, /* tp_hash */
2679 0, /* tp_call */
2680 0, /* tp_str */
2681 PyObject_GenericGetAttr, /* tp_getattro */
2682 0, /* tp_setattro */
2683 0, /* tp_as_buffer */
2684 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
2685 Py_TPFLAGS_BASETYPE, /* tp_flags */
2686 zip_doc, /* tp_doc */
2687 (traverseproc)zip_traverse, /* tp_traverse */
2688 0, /* tp_clear */
2689 0, /* tp_richcompare */
2690 0, /* tp_weaklistoffset */
2691 PyObject_SelfIter, /* tp_iter */
2692 (iternextfunc)zip_next, /* tp_iternext */
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002693 zip_methods, /* tp_methods */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002694 0, /* tp_members */
2695 0, /* tp_getset */
2696 0, /* tp_base */
2697 0, /* tp_dict */
2698 0, /* tp_descr_get */
2699 0, /* tp_descr_set */
2700 0, /* tp_dictoffset */
2701 0, /* tp_init */
2702 PyType_GenericAlloc, /* tp_alloc */
2703 zip_new, /* tp_new */
2704 PyObject_GC_Del, /* tp_free */
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002705};
Barry Warsawbd599b52000-08-03 15:45:29 +00002706
2707
Guido van Rossum79f25d91997-04-29 20:08:16 +00002708static PyMethodDef builtin_methods[] = {
Serhiy Storchaka62be7422018-11-27 13:27:31 +02002709 {"__build_class__", (PyCFunction)(void(*)(void))builtin___build_class__,
Serhiy Storchaka6969eaf2017-07-03 21:20:15 +03002710 METH_FASTCALL | METH_KEYWORDS, build_class_doc},
Serhiy Storchaka62be7422018-11-27 13:27:31 +02002711 {"__import__", (PyCFunction)(void(*)(void))builtin___import__, METH_VARARGS | METH_KEYWORDS, import_doc},
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002712 BUILTIN_ABS_METHODDEF
2713 BUILTIN_ALL_METHODDEF
2714 BUILTIN_ANY_METHODDEF
2715 BUILTIN_ASCII_METHODDEF
2716 BUILTIN_BIN_METHODDEF
Serhiy Storchaka62be7422018-11-27 13:27:31 +02002717 {"breakpoint", (PyCFunction)(void(*)(void))builtin_breakpoint, METH_FASTCALL | METH_KEYWORDS, breakpoint_doc},
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002718 BUILTIN_CALLABLE_METHODDEF
2719 BUILTIN_CHR_METHODDEF
2720 BUILTIN_COMPILE_METHODDEF
2721 BUILTIN_DELATTR_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002722 {"dir", builtin_dir, METH_VARARGS, dir_doc},
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002723 BUILTIN_DIVMOD_METHODDEF
2724 BUILTIN_EVAL_METHODDEF
2725 BUILTIN_EXEC_METHODDEF
2726 BUILTIN_FORMAT_METHODDEF
Serhiy Storchaka62be7422018-11-27 13:27:31 +02002727 {"getattr", (PyCFunction)(void(*)(void))builtin_getattr, METH_FASTCALL, getattr_doc},
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002728 BUILTIN_GLOBALS_METHODDEF
2729 BUILTIN_HASATTR_METHODDEF
2730 BUILTIN_HASH_METHODDEF
2731 BUILTIN_HEX_METHODDEF
2732 BUILTIN_ID_METHODDEF
2733 BUILTIN_INPUT_METHODDEF
2734 BUILTIN_ISINSTANCE_METHODDEF
2735 BUILTIN_ISSUBCLASS_METHODDEF
Serhiy Storchaka79342662019-01-12 08:25:41 +02002736 {"iter", (PyCFunction)(void(*)(void))builtin_iter, METH_FASTCALL, iter_doc},
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002737 BUILTIN_LEN_METHODDEF
2738 BUILTIN_LOCALS_METHODDEF
Serhiy Storchaka62be7422018-11-27 13:27:31 +02002739 {"max", (PyCFunction)(void(*)(void))builtin_max, METH_VARARGS | METH_KEYWORDS, max_doc},
2740 {"min", (PyCFunction)(void(*)(void))builtin_min, METH_VARARGS | METH_KEYWORDS, min_doc},
2741 {"next", (PyCFunction)(void(*)(void))builtin_next, METH_FASTCALL, next_doc},
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002742 BUILTIN_OCT_METHODDEF
2743 BUILTIN_ORD_METHODDEF
2744 BUILTIN_POW_METHODDEF
Serhiy Storchaka62be7422018-11-27 13:27:31 +02002745 {"print", (PyCFunction)(void(*)(void))builtin_print, METH_FASTCALL | METH_KEYWORDS, print_doc},
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002746 BUILTIN_REPR_METHODDEF
Serhiy Storchakaaca7f572017-11-15 17:51:14 +02002747 BUILTIN_ROUND_METHODDEF
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002748 BUILTIN_SETATTR_METHODDEF
2749 BUILTIN_SORTED_METHODDEF
2750 BUILTIN_SUM_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002751 {"vars", builtin_vars, METH_VARARGS, vars_doc},
2752 {NULL, NULL},
Guido van Rossum3f5da241990-12-20 15:06:42 +00002753};
2754
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002755PyDoc_STRVAR(builtin_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002756"Built-in functions, exceptions, and other objects.\n\
2757\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002758Noteworthy: None is the `nil' object; Ellipsis represents `...' in slices.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002759
Martin v. Löwis1a214512008-06-11 05:26:20 +00002760static struct PyModuleDef builtinsmodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002761 PyModuleDef_HEAD_INIT,
2762 "builtins",
2763 builtin_doc,
2764 -1, /* multiple "initialization" just copies the module dict. */
2765 builtin_methods,
2766 NULL,
2767 NULL,
2768 NULL,
2769 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00002770};
2771
2772
Guido van Rossum25ce5661997-08-02 03:10:38 +00002773PyObject *
Victor Stinnerb45d2592019-06-20 00:05:23 +02002774_PyBuiltin_Init(PyThreadState *tstate)
Guido van Rossum25ce5661997-08-02 03:10:38 +00002775{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002776 PyObject *mod, *dict, *debug;
Benjamin Peterson42124a72012-10-30 23:41:54 -04002777
Victor Stinnerda7933e2020-04-13 03:04:28 +02002778 const PyConfig *config = _PyInterpreterState_GetConfig(tstate->interp);
Victor Stinnerfbca9082018-08-30 00:50:45 +02002779
Benjamin Peterson42124a72012-10-30 23:41:54 -04002780 if (PyType_Ready(&PyFilter_Type) < 0 ||
2781 PyType_Ready(&PyMap_Type) < 0 ||
2782 PyType_Ready(&PyZip_Type) < 0)
2783 return NULL;
2784
Eric Snowd393c1b2017-09-14 12:18:12 -06002785 mod = _PyModule_CreateInitialized(&builtinsmodule, PYTHON_API_VERSION);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002786 if (mod == NULL)
2787 return NULL;
2788 dict = PyModule_GetDict(mod);
Tim Peters4b7625e2001-09-13 21:37:17 +00002789
Tim Peters7571a0f2003-03-23 17:52:28 +00002790#ifdef Py_TRACE_REFS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002791 /* "builtins" exposes a number of statically allocated objects
2792 * that, before this code was added in 2.3, never showed up in
2793 * the list of "all objects" maintained by Py_TRACE_REFS. As a
2794 * result, programs leaking references to None and False (etc)
2795 * couldn't be diagnosed by examining sys.getobjects(0).
2796 */
Tim Peters7571a0f2003-03-23 17:52:28 +00002797#define ADD_TO_ALL(OBJECT) _Py_AddToAllObjects((PyObject *)(OBJECT), 0)
2798#else
2799#define ADD_TO_ALL(OBJECT) (void)0
2800#endif
2801
Tim Peters4b7625e2001-09-13 21:37:17 +00002802#define SETBUILTIN(NAME, OBJECT) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002803 if (PyDict_SetItemString(dict, NAME, (PyObject *)OBJECT) < 0) \
2804 return NULL; \
2805 ADD_TO_ALL(OBJECT)
Tim Peters4b7625e2001-09-13 21:37:17 +00002806
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002807 SETBUILTIN("None", Py_None);
2808 SETBUILTIN("Ellipsis", Py_Ellipsis);
2809 SETBUILTIN("NotImplemented", Py_NotImplemented);
2810 SETBUILTIN("False", Py_False);
2811 SETBUILTIN("True", Py_True);
2812 SETBUILTIN("bool", &PyBool_Type);
2813 SETBUILTIN("memoryview", &PyMemoryView_Type);
2814 SETBUILTIN("bytearray", &PyByteArray_Type);
2815 SETBUILTIN("bytes", &PyBytes_Type);
2816 SETBUILTIN("classmethod", &PyClassMethod_Type);
2817 SETBUILTIN("complex", &PyComplex_Type);
2818 SETBUILTIN("dict", &PyDict_Type);
2819 SETBUILTIN("enumerate", &PyEnum_Type);
2820 SETBUILTIN("filter", &PyFilter_Type);
2821 SETBUILTIN("float", &PyFloat_Type);
2822 SETBUILTIN("frozenset", &PyFrozenSet_Type);
2823 SETBUILTIN("property", &PyProperty_Type);
2824 SETBUILTIN("int", &PyLong_Type);
2825 SETBUILTIN("list", &PyList_Type);
2826 SETBUILTIN("map", &PyMap_Type);
2827 SETBUILTIN("object", &PyBaseObject_Type);
2828 SETBUILTIN("range", &PyRange_Type);
2829 SETBUILTIN("reversed", &PyReversed_Type);
2830 SETBUILTIN("set", &PySet_Type);
2831 SETBUILTIN("slice", &PySlice_Type);
2832 SETBUILTIN("staticmethod", &PyStaticMethod_Type);
2833 SETBUILTIN("str", &PyUnicode_Type);
2834 SETBUILTIN("super", &PySuper_Type);
2835 SETBUILTIN("tuple", &PyTuple_Type);
2836 SETBUILTIN("type", &PyType_Type);
2837 SETBUILTIN("zip", &PyZip_Type);
Victor Stinnerfbca9082018-08-30 00:50:45 +02002838 debug = PyBool_FromLong(config->optimization_level == 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002839 if (PyDict_SetItemString(dict, "__debug__", debug) < 0) {
Serhiy Storchakacfdfbb42016-06-18 09:44:03 +03002840 Py_DECREF(debug);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002841 return NULL;
2842 }
Serhiy Storchakacfdfbb42016-06-18 09:44:03 +03002843 Py_DECREF(debug);
Barry Warsaw757af0e1997-08-29 22:13:51 +00002844
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002845 return mod;
Tim Peters7571a0f2003-03-23 17:52:28 +00002846#undef ADD_TO_ALL
Tim Peters4b7625e2001-09-13 21:37:17 +00002847#undef SETBUILTIN
Guido van Rossum3f5da241990-12-20 15:06:42 +00002848}