blob: 5818eb9e38f6ad50ca76969051e47220466f8e66 [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 Stinner4d231bc2019-11-14 13:36:21 +01007#include "pycore_pyerrors.h"
Victor Stinner621cebe2018-11-12 16:53:38 +01008#include "pycore_pystate.h"
Sergey Fedoseevf1b9abe2019-02-26 02:37:26 +05009#include "pycore_tupleobject.h"
Guido van Rossum6bf62da1997-04-11 20:37:35 +000010
Victor Stinnerbd303c12013-11-07 23:07:29 +010011_Py_IDENTIFIER(__builtins__);
12_Py_IDENTIFIER(__dict__);
13_Py_IDENTIFIER(__prepare__);
14_Py_IDENTIFIER(__round__);
Ivan Levkivskyi2b5fd1e2017-12-14 23:32:56 +010015_Py_IDENTIFIER(__mro_entries__);
Victor Stinnerbd303c12013-11-07 23:07:29 +010016_Py_IDENTIFIER(encoding);
17_Py_IDENTIFIER(errors);
Martin v. Löwisbd928fe2011-10-14 10:20:37 +020018_Py_IDENTIFIER(fileno);
19_Py_IDENTIFIER(flush);
Victor Stinnerbd303c12013-11-07 23:07:29 +010020_Py_IDENTIFIER(metaclass);
21_Py_IDENTIFIER(sort);
22_Py_IDENTIFIER(stdin);
23_Py_IDENTIFIER(stdout);
24_Py_IDENTIFIER(stderr);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +020025
Serhiy Storchaka1009bf12015-04-03 23:53:51 +030026#include "clinic/bltinmodule.c.h"
27
Ivan Levkivskyi2b5fd1e2017-12-14 23:32:56 +010028static PyObject*
Victor Stinner05d68a82018-01-18 11:15:25 +010029update_bases(PyObject *bases, PyObject *const *args, Py_ssize_t nargs)
Ivan Levkivskyi2b5fd1e2017-12-14 23:32:56 +010030{
Victor Stinner05d68a82018-01-18 11:15:25 +010031 Py_ssize_t i, j;
Ivan Levkivskyi2b5fd1e2017-12-14 23:32:56 +010032 PyObject *base, *meth, *new_base, *result, *new_bases = NULL;
Ivan Levkivskyi2b5fd1e2017-12-14 23:32:56 +010033 assert(PyTuple_Check(bases));
34
35 for (i = 0; i < nargs; i++) {
36 base = args[i];
37 if (PyType_Check(base)) {
38 if (new_bases) {
39 /* If we already have made a replacement, then we append every normal base,
40 otherwise just skip it. */
41 if (PyList_Append(new_bases, base) < 0) {
42 goto error;
43 }
44 }
45 continue;
46 }
Serhiy Storchakaf320be72018-01-25 10:49:40 +020047 if (_PyObject_LookupAttrId(base, &PyId___mro_entries__, &meth) < 0) {
48 goto error;
49 }
Ivan Levkivskyi2b5fd1e2017-12-14 23:32:56 +010050 if (!meth) {
Ivan Levkivskyi2b5fd1e2017-12-14 23:32:56 +010051 if (new_bases) {
52 if (PyList_Append(new_bases, base) < 0) {
53 goto error;
54 }
55 }
56 continue;
57 }
Jeroen Demeyer196a5302019-07-04 12:31:34 +020058 new_base = _PyObject_CallOneArg(meth, bases);
Ivan Levkivskyi2b5fd1e2017-12-14 23:32:56 +010059 Py_DECREF(meth);
60 if (!new_base) {
61 goto error;
62 }
63 if (!PyTuple_Check(new_base)) {
64 PyErr_SetString(PyExc_TypeError,
65 "__mro_entries__ must return a tuple");
66 Py_DECREF(new_base);
67 goto error;
68 }
69 if (!new_bases) {
70 /* If this is a first successful replacement, create new_bases list and
71 copy previously encountered bases. */
72 if (!(new_bases = PyList_New(i))) {
73 goto error;
74 }
75 for (j = 0; j < i; j++) {
76 base = args[j];
77 PyList_SET_ITEM(new_bases, j, base);
78 Py_INCREF(base);
79 }
80 }
81 j = PyList_GET_SIZE(new_bases);
82 if (PyList_SetSlice(new_bases, j, j, new_base) < 0) {
83 goto error;
84 }
85 Py_DECREF(new_base);
86 }
87 if (!new_bases) {
88 return bases;
89 }
90 result = PyList_AsTuple(new_bases);
91 Py_DECREF(new_bases);
92 return result;
93
94error:
95 Py_XDECREF(new_bases);
96 return NULL;
97}
98
Nick Coghlanf9e227e2014-08-17 14:01:19 +100099/* AC: cannot convert yet, waiting for *args support */
Guido van Rossum79f25d91997-04-29 20:08:16 +0000100static PyObject *
Serhiy Storchakaa5552f02017-12-15 13:11:11 +0200101builtin___build_class__(PyObject *self, PyObject *const *args, Py_ssize_t nargs,
Victor Stinner773dc6d2017-01-16 23:46:26 +0100102 PyObject *kwnames)
Guido van Rossum52cc1d82007-03-18 15:41:51 +0000103{
Ivan Levkivskyi2b5fd1e2017-12-14 23:32:56 +0100104 PyObject *func, *name, *bases, *mkw, *meta, *winner, *prep, *ns, *orig_bases;
Nick Coghlan19d24672016-12-05 16:47:55 +1000105 PyObject *cls = NULL, *cell = NULL;
Victor Stinner0c39b1b2015-03-18 15:02:06 +0100106 int isclass = 0; /* initialize to prevent gcc warning */
Guido van Rossum52cc1d82007-03-18 15:41:51 +0000107
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000108 if (nargs < 2) {
109 PyErr_SetString(PyExc_TypeError,
110 "__build_class__: not enough arguments");
111 return NULL;
112 }
Victor Stinner773dc6d2017-01-16 23:46:26 +0100113 func = args[0]; /* Better be callable */
Benjamin Petersone8e14592013-05-16 14:37:25 -0500114 if (!PyFunction_Check(func)) {
115 PyErr_SetString(PyExc_TypeError,
Zachary Ware9b338722014-08-05 14:01:10 -0500116 "__build_class__: func must be a function");
Benjamin Petersone8e14592013-05-16 14:37:25 -0500117 return NULL;
118 }
Victor Stinner773dc6d2017-01-16 23:46:26 +0100119 name = args[1];
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000120 if (!PyUnicode_Check(name)) {
121 PyErr_SetString(PyExc_TypeError,
122 "__build_class__: name is not a string");
123 return NULL;
124 }
Sergey Fedoseevf1b9abe2019-02-26 02:37:26 +0500125 orig_bases = _PyTuple_FromArray(args + 2, nargs - 2);
Ivan Levkivskyi2b5fd1e2017-12-14 23:32:56 +0100126 if (orig_bases == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000127 return NULL;
Guido van Rossum52cc1d82007-03-18 15:41:51 +0000128
Ivan Levkivskyi2b5fd1e2017-12-14 23:32:56 +0100129 bases = update_bases(orig_bases, args + 2, nargs - 2);
130 if (bases == NULL) {
131 Py_DECREF(orig_bases);
132 return NULL;
133 }
134
Victor Stinner773dc6d2017-01-16 23:46:26 +0100135 if (kwnames == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000136 meta = NULL;
137 mkw = NULL;
138 }
139 else {
Victor Stinner773dc6d2017-01-16 23:46:26 +0100140 mkw = _PyStack_AsDict(args + nargs, kwnames);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000141 if (mkw == NULL) {
142 Py_DECREF(bases);
143 return NULL;
Guido van Rossum52cc1d82007-03-18 15:41:51 +0000144 }
Victor Stinner773dc6d2017-01-16 23:46:26 +0100145
Serhiy Storchakaa24107b2019-02-25 17:59:46 +0200146 meta = _PyDict_GetItemIdWithError(mkw, &PyId_metaclass);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000147 if (meta != NULL) {
148 Py_INCREF(meta);
Victor Stinnerae9f1612013-11-06 22:46:51 +0100149 if (_PyDict_DelItemId(mkw, &PyId_metaclass) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000150 Py_DECREF(meta);
151 Py_DECREF(mkw);
152 Py_DECREF(bases);
153 return NULL;
154 }
Nick Coghlande31b192011-10-23 22:04:16 +1000155 /* metaclass is explicitly given, check if it's indeed a class */
156 isclass = PyType_Check(meta);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000157 }
Serhiy Storchakaa24107b2019-02-25 17:59:46 +0200158 else if (PyErr_Occurred()) {
159 Py_DECREF(mkw);
160 Py_DECREF(bases);
161 return NULL;
162 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000163 }
164 if (meta == NULL) {
Nick Coghlande31b192011-10-23 22:04:16 +1000165 /* if there are no bases, use type: */
166 if (PyTuple_GET_SIZE(bases) == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000167 meta = (PyObject *) (&PyType_Type);
Nick Coghlande31b192011-10-23 22:04:16 +1000168 }
169 /* else get the type of the first base */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000170 else {
171 PyObject *base0 = PyTuple_GET_ITEM(bases, 0);
172 meta = (PyObject *) (base0->ob_type);
173 }
174 Py_INCREF(meta);
Nick Coghlande31b192011-10-23 22:04:16 +1000175 isclass = 1; /* meta is really a class */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000176 }
Nick Coghlan9715d262011-10-23 22:36:42 +1000177
Nick Coghlande31b192011-10-23 22:04:16 +1000178 if (isclass) {
179 /* meta is really a class, so check for a more derived
180 metaclass, or possible metaclass conflicts: */
181 winner = (PyObject *)_PyType_CalculateMetaclass((PyTypeObject *)meta,
182 bases);
183 if (winner == NULL) {
184 Py_DECREF(meta);
185 Py_XDECREF(mkw);
186 Py_DECREF(bases);
187 return NULL;
188 }
189 if (winner != meta) {
190 Py_DECREF(meta);
191 meta = winner;
192 Py_INCREF(meta);
193 }
194 }
195 /* else: meta is not a class, so we cannot do the metaclass
196 calculation, so we will use the explicitly given object as it is */
Serhiy Storchakaf320be72018-01-25 10:49:40 +0200197 if (_PyObject_LookupAttrId(meta, &PyId___prepare__, &prep) < 0) {
198 ns = NULL;
199 }
200 else if (prep == NULL) {
201 ns = PyDict_New();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000202 }
203 else {
Victor Stinner463b86a2016-08-22 23:33:13 +0200204 PyObject *pargs[2] = {name, bases};
205 ns = _PyObject_FastCallDict(prep, pargs, 2, mkw);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000206 Py_DECREF(prep);
207 }
208 if (ns == NULL) {
209 Py_DECREF(meta);
210 Py_XDECREF(mkw);
211 Py_DECREF(bases);
212 return NULL;
213 }
Oren Milman5837d042017-09-27 17:04:37 +0300214 if (!PyMapping_Check(ns)) {
215 PyErr_Format(PyExc_TypeError,
216 "%.200s.__prepare__() must return a mapping, not %.200s",
217 isclass ? ((PyTypeObject *)meta)->tp_name : "<metaclass>",
218 Py_TYPE(ns)->tp_name);
219 goto error;
220 }
Nick Coghlan19d24672016-12-05 16:47:55 +1000221 cell = PyEval_EvalCodeEx(PyFunction_GET_CODE(func), PyFunction_GET_GLOBALS(func), ns,
Benjamin Petersone8e14592013-05-16 14:37:25 -0500222 NULL, 0, NULL, 0, NULL, 0, NULL,
223 PyFunction_GET_CLOSURE(func));
Nick Coghlan19d24672016-12-05 16:47:55 +1000224 if (cell != NULL) {
Ivan Levkivskyi2b5fd1e2017-12-14 23:32:56 +0100225 if (bases != orig_bases) {
226 if (PyMapping_SetItemString(ns, "__orig_bases__", orig_bases) < 0) {
227 goto error;
228 }
229 }
Victor Stinnerd1c2a8e2016-08-23 01:34:35 +0200230 PyObject *margs[3] = {name, bases, ns};
231 cls = _PyObject_FastCallDict(meta, margs, 3, mkw);
Nick Coghlan19d24672016-12-05 16:47:55 +1000232 if (cls != NULL && PyType_Check(cls) && PyCell_Check(cell)) {
233 PyObject *cell_cls = PyCell_GET(cell);
234 if (cell_cls != cls) {
Nick Coghlan19d24672016-12-05 16:47:55 +1000235 if (cell_cls == NULL) {
236 const char *msg =
237 "__class__ not set defining %.200R as %.200R. "
238 "Was __classcell__ propagated to type.__new__?";
Serhiy Storchakaf5e7b192018-05-20 08:48:12 +0300239 PyErr_Format(PyExc_RuntimeError, msg, name, cls);
Nick Coghlan19d24672016-12-05 16:47:55 +1000240 } else {
241 const char *msg =
242 "__class__ set to %.200R defining %.200R as %.200R";
243 PyErr_Format(PyExc_TypeError, msg, cell_cls, name, cls);
Nick Coghlan19d24672016-12-05 16:47:55 +1000244 }
Serhiy Storchakaf5e7b192018-05-20 08:48:12 +0300245 Py_DECREF(cls);
246 cls = NULL;
247 goto error;
Nick Coghlan19d24672016-12-05 16:47:55 +1000248 }
249 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000250 }
Nick Coghlan19d24672016-12-05 16:47:55 +1000251error:
252 Py_XDECREF(cell);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000253 Py_DECREF(ns);
254 Py_DECREF(meta);
255 Py_XDECREF(mkw);
256 Py_DECREF(bases);
Ivan Levkivskyi2b5fd1e2017-12-14 23:32:56 +0100257 if (bases != orig_bases) {
258 Py_DECREF(orig_bases);
259 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000260 return cls;
Guido van Rossum52cc1d82007-03-18 15:41:51 +0000261}
262
263PyDoc_STRVAR(build_class_doc,
Pablo Galindoe3babbd2019-10-13 16:35:41 +0100264"__build_class__(func, name, /, *bases, [metaclass], **kwds) -> class\n\
Guido van Rossum52cc1d82007-03-18 15:41:51 +0000265\n\
266Internal helper function used by the class statement.");
267
268static PyObject *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000269builtin___import__(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000270{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000271 static char *kwlist[] = {"name", "globals", "locals", "fromlist",
272 "level", 0};
Victor Stinnerfe93faf2011-03-14 15:54:52 -0400273 PyObject *name, *globals = NULL, *locals = NULL, *fromlist = NULL;
Brett Cannonfd074152012-04-14 14:10:13 -0400274 int level = 0;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000275
Victor Stinnerfe93faf2011-03-14 15:54:52 -0400276 if (!PyArg_ParseTupleAndKeywords(args, kwds, "U|OOOi:__import__",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000277 kwlist, &name, &globals, &locals, &fromlist, &level))
278 return NULL;
Victor Stinnerfe93faf2011-03-14 15:54:52 -0400279 return PyImport_ImportModuleLevelObject(name, globals, locals,
280 fromlist, level);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000281}
282
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000283PyDoc_STRVAR(import_doc,
Brett Cannoncb4996a2012-08-06 16:34:44 -0400284"__import__(name, globals=None, locals=None, fromlist=(), level=0) -> module\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000285\n\
Brett Cannon5305a992010-09-27 21:08:38 +0000286Import a module. Because this function is meant for use by the Python\n\
oldk461d2252018-02-02 12:20:00 +0800287interpreter and not for general use, it is better to use\n\
Brett Cannon5305a992010-09-27 21:08:38 +0000288importlib.import_module() to programmatically import a module.\n\
289\n\
290The globals argument is only used to determine the context;\n\
291they are not modified. The locals argument is unused. The fromlist\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000292should be a list of names to emulate ``from name import ...'', or an\n\
293empty list to emulate ``import name''.\n\
294When importing a module from a package, note that __import__('A.B', ...)\n\
295returns package A when fromlist is empty, but its submodule B when\n\
oldk461d2252018-02-02 12:20:00 +0800296fromlist is not empty. The level argument is used to determine whether to\n\
297perform absolute or relative imports: 0 is absolute, while a positive number\n\
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000298is the number of parent directories to search relative to the current module.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000299
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000300
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000301/*[clinic input]
302abs as builtin_abs
303
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300304 x: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000305 /
306
307Return the absolute value of the argument.
308[clinic start generated code]*/
309
Guido van Rossum79f25d91997-04-29 20:08:16 +0000310static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300311builtin_abs(PyObject *module, PyObject *x)
312/*[clinic end generated code: output=b1b433b9e51356f5 input=bed4ca14e29c20d1]*/
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000313{
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000314 return PyNumber_Absolute(x);
Guido van Rossum3f5da241990-12-20 15:06:42 +0000315}
316
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000317/*[clinic input]
318all as builtin_all
319
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300320 iterable: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000321 /
322
323Return True if bool(x) is True for all values x in the iterable.
324
325If the iterable is empty, return True.
326[clinic start generated code]*/
327
Raymond Hettinger96229b12005-03-11 06:49:40 +0000328static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300329builtin_all(PyObject *module, PyObject *iterable)
330/*[clinic end generated code: output=ca2a7127276f79b3 input=1a7c5d1bc3438a21]*/
Raymond Hettinger96229b12005-03-11 06:49:40 +0000331{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000332 PyObject *it, *item;
333 PyObject *(*iternext)(PyObject *);
334 int cmp;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000335
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000336 it = PyObject_GetIter(iterable);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000337 if (it == NULL)
338 return NULL;
339 iternext = *Py_TYPE(it)->tp_iternext;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000340
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000341 for (;;) {
342 item = iternext(it);
343 if (item == NULL)
344 break;
345 cmp = PyObject_IsTrue(item);
346 Py_DECREF(item);
347 if (cmp < 0) {
348 Py_DECREF(it);
349 return NULL;
350 }
351 if (cmp == 0) {
352 Py_DECREF(it);
353 Py_RETURN_FALSE;
354 }
355 }
356 Py_DECREF(it);
357 if (PyErr_Occurred()) {
358 if (PyErr_ExceptionMatches(PyExc_StopIteration))
359 PyErr_Clear();
360 else
361 return NULL;
362 }
363 Py_RETURN_TRUE;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000364}
365
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000366/*[clinic input]
367any as builtin_any
368
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300369 iterable: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000370 /
371
372Return True if bool(x) is True for any x in the iterable.
373
374If the iterable is empty, return False.
375[clinic start generated code]*/
376
Raymond Hettinger96229b12005-03-11 06:49:40 +0000377static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300378builtin_any(PyObject *module, PyObject *iterable)
379/*[clinic end generated code: output=fa65684748caa60e input=41d7451c23384f24]*/
Raymond Hettinger96229b12005-03-11 06:49:40 +0000380{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000381 PyObject *it, *item;
382 PyObject *(*iternext)(PyObject *);
383 int cmp;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000384
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000385 it = PyObject_GetIter(iterable);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000386 if (it == NULL)
387 return NULL;
388 iternext = *Py_TYPE(it)->tp_iternext;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000389
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000390 for (;;) {
391 item = iternext(it);
392 if (item == NULL)
393 break;
394 cmp = PyObject_IsTrue(item);
395 Py_DECREF(item);
396 if (cmp < 0) {
397 Py_DECREF(it);
398 return NULL;
399 }
Raymond Hettinger5098b582015-10-09 00:42:47 -0400400 if (cmp > 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000401 Py_DECREF(it);
402 Py_RETURN_TRUE;
403 }
404 }
405 Py_DECREF(it);
406 if (PyErr_Occurred()) {
407 if (PyErr_ExceptionMatches(PyExc_StopIteration))
408 PyErr_Clear();
409 else
410 return NULL;
411 }
412 Py_RETURN_FALSE;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000413}
414
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000415/*[clinic input]
416ascii as builtin_ascii
417
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300418 obj: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000419 /
420
421Return an ASCII-only representation of an object.
422
423As repr(), return a string containing a printable representation of an
424object, but escape the non-ASCII characters in the string returned by
425repr() using \\x, \\u or \\U escapes. This generates a string similar
426to that returned by repr() in Python 2.
427[clinic start generated code]*/
428
Georg Brandl559e5d72008-06-11 18:37:52 +0000429static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300430builtin_ascii(PyObject *module, PyObject *obj)
431/*[clinic end generated code: output=6d37b3f0984c7eb9 input=4c62732e1b3a3cc9]*/
Georg Brandl559e5d72008-06-11 18:37:52 +0000432{
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000433 return PyObject_ASCII(obj);
Georg Brandl559e5d72008-06-11 18:37:52 +0000434}
435
Georg Brandl559e5d72008-06-11 18:37:52 +0000436
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000437/*[clinic input]
438bin as builtin_bin
439
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300440 number: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000441 /
442
443Return the binary representation of an integer.
444
445 >>> bin(2796202)
446 '0b1010101010101010101010'
447[clinic start generated code]*/
448
Guido van Rossum79f25d91997-04-29 20:08:16 +0000449static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300450builtin_bin(PyObject *module, PyObject *number)
451/*[clinic end generated code: output=b6fc4ad5e649f4f7 input=53f8a0264bacaf90]*/
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000452{
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000453 return PyNumber_ToBase(number, 2);
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000454}
455
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000456
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000457/*[clinic input]
458callable as builtin_callable
459
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300460 obj: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000461 /
462
463Return whether the object is callable (i.e., some kind of function).
464
465Note that classes are callable, as are instances of classes with a
466__call__() method.
467[clinic start generated code]*/
468
Antoine Pitroue71362d2010-11-27 22:00:11 +0000469static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300470builtin_callable(PyObject *module, PyObject *obj)
471/*[clinic end generated code: output=2b095d59d934cb7e input=1423bab99cc41f58]*/
Antoine Pitroue71362d2010-11-27 22:00:11 +0000472{
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000473 return PyBool_FromLong((long)PyCallable_Check(obj));
Antoine Pitroue71362d2010-11-27 22:00:11 +0000474}
475
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400476static PyObject *
Serhiy Storchakaa5552f02017-12-15 13:11:11 +0200477builtin_breakpoint(PyObject *self, PyObject *const *args, Py_ssize_t nargs, PyObject *keywords)
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400478{
479 PyObject *hook = PySys_GetObject("breakpointhook");
480
481 if (hook == NULL) {
482 PyErr_SetString(PyExc_RuntimeError, "lost sys.breakpointhook");
483 return NULL;
484 }
Steve Dower60419a72019-06-24 08:42:54 -0700485
486 if (PySys_Audit("builtins.breakpoint", "O", hook) < 0) {
487 return NULL;
488 }
489
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400490 Py_INCREF(hook);
Jeroen Demeyeraacc77f2019-05-29 20:31:52 +0200491 PyObject *retval = _PyObject_Vectorcall(hook, args, nargs, keywords);
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400492 Py_DECREF(hook);
493 return retval;
494}
495
496PyDoc_STRVAR(breakpoint_doc,
497"breakpoint(*args, **kws)\n\
498\n\
499Call sys.breakpointhook(*args, **kws). sys.breakpointhook() must accept\n\
500whatever arguments are passed.\n\
501\n\
502By default, this drops you into the pdb debugger.");
Antoine Pitroue71362d2010-11-27 22:00:11 +0000503
Raymond Hettinger17301e92008-03-13 00:19:26 +0000504typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000505 PyObject_HEAD
506 PyObject *func;
507 PyObject *it;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000508} filterobject;
509
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000510static PyObject *
Raymond Hettinger17301e92008-03-13 00:19:26 +0000511filter_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
Guido van Rossum12d12c51993-10-26 17:58:25 +0000512{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000513 PyObject *func, *seq;
514 PyObject *it;
515 filterobject *lz;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000516
Serhiy Storchaka6cca5c82017-06-08 14:41:19 +0300517 if (type == &PyFilter_Type && !_PyArg_NoKeywords("filter", kwds))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000518 return NULL;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000519
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000520 if (!PyArg_UnpackTuple(args, "filter", 2, 2, &func, &seq))
521 return NULL;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000522
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000523 /* Get iterator. */
524 it = PyObject_GetIter(seq);
525 if (it == NULL)
526 return NULL;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000527
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000528 /* create filterobject structure */
529 lz = (filterobject *)type->tp_alloc(type, 0);
530 if (lz == NULL) {
531 Py_DECREF(it);
532 return NULL;
533 }
534 Py_INCREF(func);
535 lz->func = func;
536 lz->it = it;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000537
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000538 return (PyObject *)lz;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000539}
540
541static void
542filter_dealloc(filterobject *lz)
543{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000544 PyObject_GC_UnTrack(lz);
545 Py_XDECREF(lz->func);
546 Py_XDECREF(lz->it);
547 Py_TYPE(lz)->tp_free(lz);
Raymond Hettinger17301e92008-03-13 00:19:26 +0000548}
549
550static int
551filter_traverse(filterobject *lz, visitproc visit, void *arg)
552{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000553 Py_VISIT(lz->it);
554 Py_VISIT(lz->func);
555 return 0;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000556}
557
558static PyObject *
559filter_next(filterobject *lz)
560{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000561 PyObject *item;
562 PyObject *it = lz->it;
563 long ok;
564 PyObject *(*iternext)(PyObject *);
Raymond Hettingerbd5f0e82015-10-09 01:34:08 -0400565 int checktrue = lz->func == Py_None || lz->func == (PyObject *)&PyBool_Type;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000566
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000567 iternext = *Py_TYPE(it)->tp_iternext;
568 for (;;) {
569 item = iternext(it);
570 if (item == NULL)
571 return NULL;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000572
Raymond Hettingerbd5f0e82015-10-09 01:34:08 -0400573 if (checktrue) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000574 ok = PyObject_IsTrue(item);
575 } else {
576 PyObject *good;
Jeroen Demeyer196a5302019-07-04 12:31:34 +0200577 good = _PyObject_CallOneArg(lz->func, item);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000578 if (good == NULL) {
579 Py_DECREF(item);
580 return NULL;
581 }
582 ok = PyObject_IsTrue(good);
583 Py_DECREF(good);
584 }
Antoine Pitrou6f430e42012-08-15 23:18:25 +0200585 if (ok > 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000586 return item;
587 Py_DECREF(item);
Antoine Pitrou6f430e42012-08-15 23:18:25 +0200588 if (ok < 0)
589 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000590 }
Guido van Rossum12d12c51993-10-26 17:58:25 +0000591}
592
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +0000593static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +0530594filter_reduce(filterobject *lz, PyObject *Py_UNUSED(ignored))
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +0000595{
596 return Py_BuildValue("O(OO)", Py_TYPE(lz), lz->func, lz->it);
597}
598
599PyDoc_STRVAR(reduce_doc, "Return state information for pickling.");
600
601static PyMethodDef filter_methods[] = {
602 {"__reduce__", (PyCFunction)filter_reduce, METH_NOARGS, reduce_doc},
603 {NULL, NULL} /* sentinel */
604};
605
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000606PyDoc_STRVAR(filter_doc,
Georg Brandld11ae5d2008-05-16 13:27:32 +0000607"filter(function or None, iterable) --> filter object\n\
Guido van Rossumc1f779c2007-07-03 08:25:58 +0000608\n\
Georg Brandld11ae5d2008-05-16 13:27:32 +0000609Return an iterator yielding those items of iterable for which function(item)\n\
Raymond Hettinger17301e92008-03-13 00:19:26 +0000610is true. If function is None, return the items that are true.");
611
612PyTypeObject PyFilter_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000613 PyVarObject_HEAD_INIT(&PyType_Type, 0)
614 "filter", /* tp_name */
615 sizeof(filterobject), /* tp_basicsize */
616 0, /* tp_itemsize */
617 /* methods */
618 (destructor)filter_dealloc, /* tp_dealloc */
Jeroen Demeyer530f5062019-05-31 04:13:39 +0200619 0, /* tp_vectorcall_offset */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000620 0, /* tp_getattr */
621 0, /* tp_setattr */
Jeroen Demeyer530f5062019-05-31 04:13:39 +0200622 0, /* tp_as_async */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000623 0, /* tp_repr */
624 0, /* tp_as_number */
625 0, /* tp_as_sequence */
626 0, /* tp_as_mapping */
627 0, /* tp_hash */
628 0, /* tp_call */
629 0, /* tp_str */
630 PyObject_GenericGetAttr, /* tp_getattro */
631 0, /* tp_setattro */
632 0, /* tp_as_buffer */
633 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
634 Py_TPFLAGS_BASETYPE, /* tp_flags */
635 filter_doc, /* tp_doc */
636 (traverseproc)filter_traverse, /* tp_traverse */
637 0, /* tp_clear */
638 0, /* tp_richcompare */
639 0, /* tp_weaklistoffset */
640 PyObject_SelfIter, /* tp_iter */
641 (iternextfunc)filter_next, /* tp_iternext */
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +0000642 filter_methods, /* tp_methods */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000643 0, /* tp_members */
644 0, /* tp_getset */
645 0, /* tp_base */
646 0, /* tp_dict */
647 0, /* tp_descr_get */
648 0, /* tp_descr_set */
649 0, /* tp_dictoffset */
650 0, /* tp_init */
651 PyType_GenericAlloc, /* tp_alloc */
652 filter_new, /* tp_new */
653 PyObject_GC_Del, /* tp_free */
Raymond Hettinger17301e92008-03-13 00:19:26 +0000654};
655
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000656
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000657/*[clinic input]
658format as builtin_format
659
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300660 value: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000661 format_spec: unicode(c_default="NULL") = ''
662 /
663
664Return value.__format__(format_spec)
665
Amit Kumar2e6bb442017-05-29 06:32:26 +0530666format_spec defaults to the empty string.
667See the Format Specification Mini-Language section of help('FORMATTING') for
668details.
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000669[clinic start generated code]*/
670
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000671static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300672builtin_format_impl(PyObject *module, PyObject *value, PyObject *format_spec)
Amit Kumar2e6bb442017-05-29 06:32:26 +0530673/*[clinic end generated code: output=2f40bdfa4954b077 input=88339c93ea522b33]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000674{
Eric Smith8fd3eba2008-02-17 19:48:00 +0000675 return PyObject_Format(value, format_spec);
Eric Smith8c663262007-08-25 02:26:07 +0000676}
677
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000678/*[clinic input]
679chr as builtin_chr
680
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300681 i: int
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000682 /
683
684Return a Unicode string of one character with ordinal i; 0 <= i <= 0x10ffff.
685[clinic start generated code]*/
686
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000687static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300688builtin_chr_impl(PyObject *module, int i)
689/*[clinic end generated code: output=c733afcd200afcb7 input=3f604ef45a70750d]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000690{
691 return PyUnicode_FromOrdinal(i);
692}
Guido van Rossum09095f32000-03-10 23:00:52 +0000693
694
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000695/*[clinic input]
696compile as builtin_compile
697
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300698 source: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000699 filename: object(converter="PyUnicode_FSDecoder")
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300700 mode: str
701 flags: int = 0
Serhiy Storchaka202fda52017-03-12 10:10:47 +0200702 dont_inherit: bool(accept={int}) = False
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300703 optimize: int = -1
Victor Stinnerefdf6ca2019-06-12 02:52:16 +0200704 *
705 _feature_version as feature_version: int = -1
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000706
707Compile source into a code object that can be executed by exec() or eval().
708
709The source code may represent a Python module, statement or expression.
710The filename will be used for run-time error messages.
711The mode must be 'exec' to compile a module, 'single' to compile a
712single (interactive) statement, or 'eval' to compile an expression.
713The flags argument, if present, controls which future statements influence
714the compilation of the code.
Serhiy Storchaka8b2e8b62015-05-30 11:30:39 +0300715The dont_inherit argument, if true, stops the compilation inheriting
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000716the effects of any future statements in effect in the code calling
Serhiy Storchaka8b2e8b62015-05-30 11:30:39 +0300717compile; if absent or false these statements do influence the compilation,
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000718in addition to any features explicitly specified.
719[clinic start generated code]*/
720
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000721static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300722builtin_compile_impl(PyObject *module, PyObject *source, PyObject *filename,
723 const char *mode, int flags, int dont_inherit,
Guido van Rossum495da292019-03-07 12:38:08 -0800724 int optimize, int feature_version)
Victor Stinnerefdf6ca2019-06-12 02:52:16 +0200725/*[clinic end generated code: output=b0c09c84f116d3d7 input=40171fb92c1d580d]*/
Guido van Rossum5b722181993-03-30 17:46:03 +0000726{
Martin Panter61d6e4a2015-11-07 02:56:11 +0000727 PyObject *source_copy;
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +0200728 const char *str;
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000729 int compile_mode = -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000730 int is_ast;
Guido van Rossumdcfcd142019-01-31 03:40:27 -0800731 int start[] = {Py_file_input, Py_eval_input, Py_single_input, Py_func_type_input};
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000732 PyObject *result;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000733
Victor Stinner37d66d72019-06-13 02:16:41 +0200734 PyCompilerFlags cf = _PyCompilerFlags_INIT;
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000735 cf.cf_flags = flags | PyCF_SOURCE_IS_UTF8;
Guido van Rossum495da292019-03-07 12:38:08 -0800736 if (feature_version >= 0 && (flags & PyCF_ONLY_AST)) {
737 cf.cf_feature_version = feature_version;
738 }
Tim Peters6cd6a822001-08-17 22:11:27 +0000739
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000740 if (flags &
Guido van Rossumdcfcd142019-01-31 03:40:27 -0800741 ~(PyCF_MASK | PyCF_MASK_OBSOLETE | PyCF_DONT_IMPLY_DEDENT | PyCF_ONLY_AST | PyCF_TYPE_COMMENTS))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000742 {
743 PyErr_SetString(PyExc_ValueError,
744 "compile(): unrecognised flags");
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000745 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000746 }
747 /* XXX Warn if (supplied_flags & PyCF_MASK_OBSOLETE) != 0? */
Tim Peters6cd6a822001-08-17 22:11:27 +0000748
Georg Brandl8334fd92010-12-04 10:26:46 +0000749 if (optimize < -1 || optimize > 2) {
750 PyErr_SetString(PyExc_ValueError,
751 "compile(): invalid optimize value");
752 goto error;
753 }
754
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000755 if (!dont_inherit) {
756 PyEval_MergeCompilerFlags(&cf);
757 }
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000758
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000759 if (strcmp(mode, "exec") == 0)
760 compile_mode = 0;
761 else if (strcmp(mode, "eval") == 0)
762 compile_mode = 1;
763 else if (strcmp(mode, "single") == 0)
764 compile_mode = 2;
Guido van Rossumdcfcd142019-01-31 03:40:27 -0800765 else if (strcmp(mode, "func_type") == 0) {
766 if (!(flags & PyCF_ONLY_AST)) {
767 PyErr_SetString(PyExc_ValueError,
768 "compile() mode 'func_type' requires flag PyCF_ONLY_AST");
769 goto error;
770 }
771 compile_mode = 3;
772 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000773 else {
Guido van Rossumdcfcd142019-01-31 03:40:27 -0800774 const char *msg;
775 if (flags & PyCF_ONLY_AST)
776 msg = "compile() mode must be 'exec', 'eval', 'single' or 'func_type'";
777 else
778 msg = "compile() mode must be 'exec', 'eval' or 'single'";
779 PyErr_SetString(PyExc_ValueError, msg);
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000780 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000781 }
Neal Norwitzdb4115f2008-03-31 04:20:05 +0000782
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000783 is_ast = PyAST_Check(source);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000784 if (is_ast == -1)
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000785 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000786 if (is_ast) {
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000787 if (flags & PyCF_ONLY_AST) {
788 Py_INCREF(source);
789 result = source;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000790 }
791 else {
792 PyArena *arena;
793 mod_ty mod;
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000794
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000795 arena = PyArena_New();
Stefan Krah07795df2012-08-20 17:19:50 +0200796 if (arena == NULL)
797 goto error;
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000798 mod = PyAST_obj2mod(source, arena, compile_mode);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000799 if (mod == NULL) {
800 PyArena_Free(arena);
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000801 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000802 }
Benjamin Peterson832bfe22011-08-09 16:15:04 -0500803 if (!PyAST_Validate(mod)) {
804 PyArena_Free(arena);
805 goto error;
806 }
Victor Stinner14e461d2013-08-26 22:28:21 +0200807 result = (PyObject*)PyAST_CompileObject(mod, filename,
808 &cf, optimize, arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000809 PyArena_Free(arena);
810 }
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000811 goto finally;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000812 }
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000813
Dino Viehland41540692019-05-28 16:21:17 -0700814 str = _Py_SourceAsString(source, "compile", "string, bytes or AST", &cf, &source_copy);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000815 if (str == NULL)
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000816 goto error;
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000817
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000818 result = Py_CompileStringObject(str, filename, start[compile_mode], &cf, optimize);
Martin Panter61d6e4a2015-11-07 02:56:11 +0000819 Py_XDECREF(source_copy);
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000820 goto finally;
821
822error:
823 result = NULL;
824finally:
Victor Stinner14e461d2013-08-26 22:28:21 +0200825 Py_DECREF(filename);
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000826 return result;
Guido van Rossum5b722181993-03-30 17:46:03 +0000827}
828
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000829/* AC: cannot convert yet, as needs PEP 457 group support in inspect */
Guido van Rossum79f25d91997-04-29 20:08:16 +0000830static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000831builtin_dir(PyObject *self, PyObject *args)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000832{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000833 PyObject *arg = NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000834
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000835 if (!PyArg_UnpackTuple(args, "dir", 0, 1, &arg))
836 return NULL;
837 return PyObject_Dir(arg);
Guido van Rossum3f5da241990-12-20 15:06:42 +0000838}
839
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000840PyDoc_STRVAR(dir_doc,
Tim Peters5d2b77c2001-09-03 05:47:38 +0000841"dir([object]) -> list of strings\n"
842"\n"
Georg Brandle32b4222007-03-10 22:13:27 +0000843"If called without an argument, return the names in the current scope.\n"
844"Else, return an alphabetized list of names comprising (some of) the attributes\n"
845"of the given object, and of attributes reachable from it.\n"
846"If the object supplies a method named __dir__, it will be used; otherwise\n"
847"the default dir() logic is used and returns:\n"
848" for a module object: the module's attributes.\n"
849" for a class object: its attributes, and recursively the attributes\n"
850" of its bases.\n"
Guido van Rossumd8faa362007-04-27 19:54:29 +0000851" for any other object: its attributes, its class's attributes, and\n"
Georg Brandle32b4222007-03-10 22:13:27 +0000852" recursively the attributes of its class's base classes.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000853
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000854/*[clinic input]
855divmod as builtin_divmod
Guido van Rossum6a00cd81995-01-07 12:39:01 +0000856
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300857 x: object
858 y: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000859 /
860
Zachary Ware7f227d92016-04-28 14:39:50 -0500861Return the tuple (x//y, x%y). Invariant: div*y + mod == x.
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000862[clinic start generated code]*/
863
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000864static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300865builtin_divmod_impl(PyObject *module, PyObject *x, PyObject *y)
866/*[clinic end generated code: output=b06d8a5f6e0c745e input=175ad9c84ff41a85]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000867{
868 return PyNumber_Divmod(x, y);
869}
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000870
871
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000872/*[clinic input]
873eval as builtin_eval
874
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300875 source: object
876 globals: object = None
877 locals: object = None
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000878 /
879
880Evaluate the given source in the context of globals and locals.
881
882The source may be a string representing a Python expression
883or a code object as returned by compile().
884The globals must be a dictionary and locals can be any mapping,
885defaulting to the current globals and locals.
886If only globals is given, locals defaults to it.
887[clinic start generated code]*/
888
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000889static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300890builtin_eval_impl(PyObject *module, PyObject *source, PyObject *globals,
Larry Hastings89964c42015-04-14 18:07:59 -0400891 PyObject *locals)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300892/*[clinic end generated code: output=0a0824aa70093116 input=11ee718a8640e527]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000893{
Martin Panter61d6e4a2015-11-07 02:56:11 +0000894 PyObject *result, *source_copy;
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +0200895 const char *str;
Guido van Rossum590baa41993-11-30 13:40:46 +0000896
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000897 if (locals != Py_None && !PyMapping_Check(locals)) {
898 PyErr_SetString(PyExc_TypeError, "locals must be a mapping");
899 return NULL;
900 }
901 if (globals != Py_None && !PyDict_Check(globals)) {
902 PyErr_SetString(PyExc_TypeError, PyMapping_Check(globals) ?
903 "globals must be a real dict; try eval(expr, {}, mapping)"
904 : "globals must be a dict");
905 return NULL;
906 }
907 if (globals == Py_None) {
908 globals = PyEval_GetGlobals();
Victor Stinner41bb43a2013-10-29 01:19:37 +0100909 if (locals == Py_None) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000910 locals = PyEval_GetLocals();
Victor Stinner41bb43a2013-10-29 01:19:37 +0100911 if (locals == NULL)
912 return NULL;
913 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000914 }
915 else if (locals == Py_None)
916 locals = globals;
Tim Peters9fa96be2001-08-17 23:04:59 +0000917
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000918 if (globals == NULL || locals == NULL) {
919 PyErr_SetString(PyExc_TypeError,
920 "eval must be given globals and locals "
921 "when called without a frame");
922 return NULL;
923 }
Georg Brandl77c85e62005-09-15 10:46:13 +0000924
Serhiy Storchakaa24107b2019-02-25 17:59:46 +0200925 if (_PyDict_GetItemIdWithError(globals, &PyId___builtins__) == NULL) {
Victor Stinnerb44562b2013-11-06 19:03:11 +0100926 if (_PyDict_SetItemId(globals, &PyId___builtins__,
927 PyEval_GetBuiltins()) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000928 return NULL;
929 }
Serhiy Storchakaa24107b2019-02-25 17:59:46 +0200930 else if (PyErr_Occurred()) {
931 return NULL;
932 }
Tim Peters9fa96be2001-08-17 23:04:59 +0000933
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000934 if (PyCode_Check(source)) {
Steve Dowerb82e17e2019-05-23 08:45:22 -0700935 if (PySys_Audit("exec", "O", source) < 0) {
936 return NULL;
937 }
938
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000939 if (PyCode_GetNumFree((PyCodeObject *)source) > 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000940 PyErr_SetString(PyExc_TypeError,
Steve Dowerb82e17e2019-05-23 08:45:22 -0700941 "code object passed to eval() may not contain free variables");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000942 return NULL;
943 }
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000944 return PyEval_EvalCode(source, globals, locals);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000945 }
Tim Peters9fa96be2001-08-17 23:04:59 +0000946
Victor Stinner37d66d72019-06-13 02:16:41 +0200947 PyCompilerFlags cf = _PyCompilerFlags_INIT;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000948 cf.cf_flags = PyCF_SOURCE_IS_UTF8;
Dino Viehland41540692019-05-28 16:21:17 -0700949 str = _Py_SourceAsString(source, "eval", "string, bytes or code", &cf, &source_copy);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000950 if (str == NULL)
951 return NULL;
Just van Rossum3aaf42c2003-02-10 08:21:10 +0000952
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000953 while (*str == ' ' || *str == '\t')
954 str++;
Tim Peters9fa96be2001-08-17 23:04:59 +0000955
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000956 (void)PyEval_MergeCompilerFlags(&cf);
957 result = PyRun_StringFlags(str, Py_eval_input, globals, locals, &cf);
Martin Panter61d6e4a2015-11-07 02:56:11 +0000958 Py_XDECREF(source_copy);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000959 return result;
Guido van Rossum3f5da241990-12-20 15:06:42 +0000960}
961
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000962/*[clinic input]
963exec as builtin_exec
964
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300965 source: object
966 globals: object = None
967 locals: object = None
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000968 /
969
970Execute the given source in the context of globals and locals.
971
972The source may be a string representing one or more Python statements
973or a code object as returned by compile().
974The globals must be a dictionary and locals can be any mapping,
975defaulting to the current globals and locals.
976If only globals is given, locals defaults to it.
977[clinic start generated code]*/
978
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000979static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300980builtin_exec_impl(PyObject *module, PyObject *source, PyObject *globals,
Larry Hastings89964c42015-04-14 18:07:59 -0400981 PyObject *locals)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300982/*[clinic end generated code: output=3c90efc6ab68ef5d input=01ca3e1c01692829]*/
Georg Brandl7cae87c2006-09-06 06:51:57 +0000983{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000984 PyObject *v;
Georg Brandl2cabc562008-08-28 07:57:16 +0000985
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000986 if (globals == Py_None) {
987 globals = PyEval_GetGlobals();
988 if (locals == Py_None) {
989 locals = PyEval_GetLocals();
Victor Stinner41bb43a2013-10-29 01:19:37 +0100990 if (locals == NULL)
991 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000992 }
993 if (!globals || !locals) {
994 PyErr_SetString(PyExc_SystemError,
995 "globals and locals cannot be NULL");
996 return NULL;
997 }
998 }
999 else if (locals == Py_None)
1000 locals = globals;
Georg Brandl7cae87c2006-09-06 06:51:57 +00001001
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001002 if (!PyDict_Check(globals)) {
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001003 PyErr_Format(PyExc_TypeError, "exec() globals must be a dict, not %.100s",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001004 globals->ob_type->tp_name);
1005 return NULL;
1006 }
1007 if (!PyMapping_Check(locals)) {
1008 PyErr_Format(PyExc_TypeError,
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001009 "locals must be a mapping or None, not %.100s",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001010 locals->ob_type->tp_name);
1011 return NULL;
1012 }
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02001013 if (_PyDict_GetItemIdWithError(globals, &PyId___builtins__) == NULL) {
Victor Stinnerb44562b2013-11-06 19:03:11 +01001014 if (_PyDict_SetItemId(globals, &PyId___builtins__,
1015 PyEval_GetBuiltins()) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001016 return NULL;
1017 }
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02001018 else if (PyErr_Occurred()) {
1019 return NULL;
1020 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001021
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001022 if (PyCode_Check(source)) {
Steve Dowerb82e17e2019-05-23 08:45:22 -07001023 if (PySys_Audit("exec", "O", source) < 0) {
1024 return NULL;
1025 }
1026
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001027 if (PyCode_GetNumFree((PyCodeObject *)source) > 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001028 PyErr_SetString(PyExc_TypeError,
1029 "code object passed to exec() may not "
1030 "contain free variables");
1031 return NULL;
1032 }
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001033 v = PyEval_EvalCode(source, globals, locals);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001034 }
1035 else {
Martin Panter61d6e4a2015-11-07 02:56:11 +00001036 PyObject *source_copy;
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +02001037 const char *str;
Victor Stinner37d66d72019-06-13 02:16:41 +02001038 PyCompilerFlags cf = _PyCompilerFlags_INIT;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001039 cf.cf_flags = PyCF_SOURCE_IS_UTF8;
Dino Viehland41540692019-05-28 16:21:17 -07001040 str = _Py_SourceAsString(source, "exec",
Martin Panter61d6e4a2015-11-07 02:56:11 +00001041 "string, bytes or code", &cf,
1042 &source_copy);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001043 if (str == NULL)
1044 return NULL;
1045 if (PyEval_MergeCompilerFlags(&cf))
1046 v = PyRun_StringFlags(str, Py_file_input, globals,
1047 locals, &cf);
1048 else
1049 v = PyRun_String(str, Py_file_input, globals, locals);
Martin Panter61d6e4a2015-11-07 02:56:11 +00001050 Py_XDECREF(source_copy);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001051 }
1052 if (v == NULL)
1053 return NULL;
1054 Py_DECREF(v);
1055 Py_RETURN_NONE;
Georg Brandl7cae87c2006-09-06 06:51:57 +00001056}
1057
Georg Brandl7cae87c2006-09-06 06:51:57 +00001058
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001059/* AC: cannot convert yet, as needs PEP 457 group support in inspect */
Guido van Rossum79f25d91997-04-29 20:08:16 +00001060static PyObject *
Serhiy Storchakaa5552f02017-12-15 13:11:11 +02001061builtin_getattr(PyObject *self, PyObject *const *args, Py_ssize_t nargs)
Guido van Rossum33894be1992-01-27 16:53:09 +00001062{
Serhiy Storchaka79342662019-01-12 08:25:41 +02001063 PyObject *v, *name, *result;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001064
Serhiy Storchaka79342662019-01-12 08:25:41 +02001065 if (!_PyArg_CheckPositional("getattr", nargs, 2, 3))
Sylvain96c7c062017-06-15 17:05:23 +02001066 return NULL;
1067
Serhiy Storchaka79342662019-01-12 08:25:41 +02001068 v = args[0];
1069 name = args[1];
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001070 if (!PyUnicode_Check(name)) {
1071 PyErr_SetString(PyExc_TypeError,
1072 "getattr(): attribute name must be string");
1073 return NULL;
1074 }
Serhiy Storchaka79342662019-01-12 08:25:41 +02001075 if (nargs > 2) {
Serhiy Storchakaf320be72018-01-25 10:49:40 +02001076 if (_PyObject_LookupAttr(v, name, &result) == 0) {
Serhiy Storchaka79342662019-01-12 08:25:41 +02001077 PyObject *dflt = args[2];
INADA Naoki378edee2018-01-16 20:52:41 +09001078 Py_INCREF(dflt);
1079 return dflt;
1080 }
1081 }
1082 else {
1083 result = PyObject_GetAttr(v, name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001084 }
1085 return result;
Guido van Rossum9bfef441993-03-29 10:43:31 +00001086}
1087
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001088PyDoc_STRVAR(getattr_doc,
Guido van Rossum950ff291998-06-29 13:38:57 +00001089"getattr(object, name[, default]) -> value\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001090\n\
Guido van Rossum950ff291998-06-29 13:38:57 +00001091Get a named attribute from an object; getattr(x, 'y') is equivalent to x.y.\n\
1092When a default argument is given, it is returned when the attribute doesn't\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001093exist; without it, an exception is raised in that case.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001094
1095
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001096/*[clinic input]
1097globals as builtin_globals
1098
1099Return the dictionary containing the current scope's global variables.
1100
1101NOTE: Updates to this dictionary *will* affect name lookups in the current
1102global scope and vice-versa.
1103[clinic start generated code]*/
1104
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001105static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001106builtin_globals_impl(PyObject *module)
1107/*[clinic end generated code: output=e5dd1527067b94d2 input=9327576f92bb48ba]*/
Guido van Rossum872537c1995-07-07 22:43:42 +00001108{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001109 PyObject *d;
Guido van Rossum872537c1995-07-07 22:43:42 +00001110
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001111 d = PyEval_GetGlobals();
1112 Py_XINCREF(d);
1113 return d;
Guido van Rossum872537c1995-07-07 22:43:42 +00001114}
1115
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001116
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001117/*[clinic input]
1118hasattr as builtin_hasattr
1119
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001120 obj: object
1121 name: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001122 /
1123
1124Return whether the object has an attribute with the given name.
1125
1126This is done by calling getattr(obj, name) and catching AttributeError.
1127[clinic start generated code]*/
1128
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001129static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001130builtin_hasattr_impl(PyObject *module, PyObject *obj, PyObject *name)
1131/*[clinic end generated code: output=a7aff2090a4151e5 input=0faec9787d979542]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001132{
1133 PyObject *v;
1134
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001135 if (!PyUnicode_Check(name)) {
1136 PyErr_SetString(PyExc_TypeError,
1137 "hasattr(): attribute name must be string");
1138 return NULL;
1139 }
Serhiy Storchakaf320be72018-01-25 10:49:40 +02001140 if (_PyObject_LookupAttr(obj, name, &v) < 0) {
Benjamin Peterson17689992010-08-24 03:26:23 +00001141 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001142 }
Serhiy Storchakaf320be72018-01-25 10:49:40 +02001143 if (v == NULL) {
1144 Py_RETURN_FALSE;
1145 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001146 Py_DECREF(v);
Benjamin Peterson17689992010-08-24 03:26:23 +00001147 Py_RETURN_TRUE;
Guido van Rossum33894be1992-01-27 16:53:09 +00001148}
1149
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001150
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001151/* AC: gdb's integration with CPython relies on builtin_id having
1152 * the *exact* parameter names of "self" and "v", so we ensure we
1153 * preserve those name rather than using the AC defaults.
1154 */
1155/*[clinic input]
1156id as builtin_id
1157
Serhiy Storchaka24182a32016-05-05 16:21:35 +03001158 self: self(type="PyModuleDef *")
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001159 obj as v: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001160 /
1161
1162Return the identity of an object.
1163
1164This is guaranteed to be unique among simultaneously existing objects.
1165(CPython uses the object's memory address.)
1166[clinic start generated code]*/
1167
Guido van Rossum79f25d91997-04-29 20:08:16 +00001168static PyObject *
Serhiy Storchaka24182a32016-05-05 16:21:35 +03001169builtin_id(PyModuleDef *self, PyObject *v)
1170/*[clinic end generated code: output=0aa640785f697f65 input=5a534136419631f4]*/
Guido van Rossum5b722181993-03-30 17:46:03 +00001171{
Steve Dowerb82e17e2019-05-23 08:45:22 -07001172 PyObject *id = PyLong_FromVoidPtr(v);
1173
1174 if (id && PySys_Audit("builtins.id", "O", id) < 0) {
1175 Py_DECREF(id);
1176 return NULL;
1177 }
1178
1179 return id;
Guido van Rossum5b722181993-03-30 17:46:03 +00001180}
1181
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001182
Raymond Hettingera6c60372008-03-13 01:26:19 +00001183/* map object ************************************************************/
1184
1185typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001186 PyObject_HEAD
1187 PyObject *iters;
1188 PyObject *func;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001189} mapobject;
1190
Guido van Rossum79f25d91997-04-29 20:08:16 +00001191static PyObject *
Raymond Hettingera6c60372008-03-13 01:26:19 +00001192map_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
Guido van Rossum12d12c51993-10-26 17:58:25 +00001193{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001194 PyObject *it, *iters, *func;
1195 mapobject *lz;
1196 Py_ssize_t numargs, i;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001197
Serhiy Storchaka6cca5c82017-06-08 14:41:19 +03001198 if (type == &PyMap_Type && !_PyArg_NoKeywords("map", kwds))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001199 return NULL;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001200
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001201 numargs = PyTuple_Size(args);
1202 if (numargs < 2) {
1203 PyErr_SetString(PyExc_TypeError,
1204 "map() must have at least two arguments.");
1205 return NULL;
1206 }
Raymond Hettingera6c60372008-03-13 01:26:19 +00001207
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001208 iters = PyTuple_New(numargs-1);
1209 if (iters == NULL)
1210 return NULL;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001211
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001212 for (i=1 ; i<numargs ; i++) {
1213 /* Get iterator. */
1214 it = PyObject_GetIter(PyTuple_GET_ITEM(args, i));
1215 if (it == NULL) {
1216 Py_DECREF(iters);
1217 return NULL;
1218 }
1219 PyTuple_SET_ITEM(iters, i-1, it);
1220 }
Raymond Hettingera6c60372008-03-13 01:26:19 +00001221
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001222 /* create mapobject structure */
1223 lz = (mapobject *)type->tp_alloc(type, 0);
1224 if (lz == NULL) {
1225 Py_DECREF(iters);
1226 return NULL;
1227 }
1228 lz->iters = iters;
1229 func = PyTuple_GET_ITEM(args, 0);
1230 Py_INCREF(func);
1231 lz->func = func;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001232
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001233 return (PyObject *)lz;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001234}
1235
1236static void
1237map_dealloc(mapobject *lz)
1238{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001239 PyObject_GC_UnTrack(lz);
1240 Py_XDECREF(lz->iters);
1241 Py_XDECREF(lz->func);
1242 Py_TYPE(lz)->tp_free(lz);
Raymond Hettingera6c60372008-03-13 01:26:19 +00001243}
1244
1245static int
1246map_traverse(mapobject *lz, visitproc visit, void *arg)
1247{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001248 Py_VISIT(lz->iters);
1249 Py_VISIT(lz->func);
1250 return 0;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001251}
1252
1253static PyObject *
1254map_next(mapobject *lz)
1255{
Victor Stinnerbc08ab42016-12-15 12:40:53 +01001256 PyObject *small_stack[_PY_FASTCALL_SMALL_STACK];
Victor Stinnercdb5cee2016-08-24 01:45:13 +02001257 PyObject **stack;
Victor Stinnercdb5cee2016-08-24 01:45:13 +02001258 PyObject *result = NULL;
Victor Stinner4d231bc2019-11-14 13:36:21 +01001259 PyThreadState *tstate = _PyThreadState_GET();
Raymond Hettingera6c60372008-03-13 01:26:19 +00001260
Victor Stinner4d231bc2019-11-14 13:36:21 +01001261 const Py_ssize_t niters = PyTuple_GET_SIZE(lz->iters);
Victor Stinnercdb5cee2016-08-24 01:45:13 +02001262 if (niters <= (Py_ssize_t)Py_ARRAY_LENGTH(small_stack)) {
1263 stack = small_stack;
1264 }
1265 else {
1266 stack = PyMem_Malloc(niters * sizeof(stack[0]));
1267 if (stack == NULL) {
Victor Stinner4d231bc2019-11-14 13:36:21 +01001268 _PyErr_NoMemory(tstate);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001269 return NULL;
1270 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001271 }
Victor Stinnercdb5cee2016-08-24 01:45:13 +02001272
Victor Stinner4d231bc2019-11-14 13:36:21 +01001273 Py_ssize_t nargs = 0;
1274 for (Py_ssize_t i=0; i < niters; i++) {
Victor Stinnercdb5cee2016-08-24 01:45:13 +02001275 PyObject *it = PyTuple_GET_ITEM(lz->iters, i);
1276 PyObject *val = Py_TYPE(it)->tp_iternext(it);
1277 if (val == NULL) {
1278 goto exit;
1279 }
1280 stack[i] = val;
1281 nargs++;
1282 }
1283
Victor Stinner4d231bc2019-11-14 13:36:21 +01001284 result = _PyObject_VectorcallTstate(tstate, lz->func, stack, nargs, NULL);
Victor Stinnercdb5cee2016-08-24 01:45:13 +02001285
1286exit:
Victor Stinner4d231bc2019-11-14 13:36:21 +01001287 for (Py_ssize_t i=0; i < nargs; i++) {
Victor Stinnercdb5cee2016-08-24 01:45:13 +02001288 Py_DECREF(stack[i]);
1289 }
1290 if (stack != small_stack) {
1291 PyMem_Free(stack);
1292 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001293 return result;
Guido van Rossum12d12c51993-10-26 17:58:25 +00001294}
1295
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001296static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05301297map_reduce(mapobject *lz, PyObject *Py_UNUSED(ignored))
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001298{
1299 Py_ssize_t numargs = PyTuple_GET_SIZE(lz->iters);
1300 PyObject *args = PyTuple_New(numargs+1);
1301 Py_ssize_t i;
1302 if (args == NULL)
1303 return NULL;
1304 Py_INCREF(lz->func);
1305 PyTuple_SET_ITEM(args, 0, lz->func);
1306 for (i = 0; i<numargs; i++){
1307 PyObject *it = PyTuple_GET_ITEM(lz->iters, i);
1308 Py_INCREF(it);
1309 PyTuple_SET_ITEM(args, i+1, it);
1310 }
1311
1312 return Py_BuildValue("ON", Py_TYPE(lz), args);
1313}
1314
1315static PyMethodDef map_methods[] = {
1316 {"__reduce__", (PyCFunction)map_reduce, METH_NOARGS, reduce_doc},
1317 {NULL, NULL} /* sentinel */
1318};
1319
1320
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001321PyDoc_STRVAR(map_doc,
Raymond Hettingera6c60372008-03-13 01:26:19 +00001322"map(func, *iterables) --> map object\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001323\n\
Raymond Hettingera6c60372008-03-13 01:26:19 +00001324Make an iterator that computes the function using arguments from\n\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001325each of the iterables. Stops when the shortest iterable is exhausted.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001326
Raymond Hettingera6c60372008-03-13 01:26:19 +00001327PyTypeObject PyMap_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001328 PyVarObject_HEAD_INIT(&PyType_Type, 0)
1329 "map", /* tp_name */
1330 sizeof(mapobject), /* tp_basicsize */
1331 0, /* tp_itemsize */
1332 /* methods */
1333 (destructor)map_dealloc, /* tp_dealloc */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02001334 0, /* tp_vectorcall_offset */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001335 0, /* tp_getattr */
1336 0, /* tp_setattr */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02001337 0, /* tp_as_async */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001338 0, /* tp_repr */
1339 0, /* tp_as_number */
1340 0, /* tp_as_sequence */
1341 0, /* tp_as_mapping */
1342 0, /* tp_hash */
1343 0, /* tp_call */
1344 0, /* tp_str */
1345 PyObject_GenericGetAttr, /* tp_getattro */
1346 0, /* tp_setattro */
1347 0, /* tp_as_buffer */
1348 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
1349 Py_TPFLAGS_BASETYPE, /* tp_flags */
1350 map_doc, /* tp_doc */
1351 (traverseproc)map_traverse, /* tp_traverse */
1352 0, /* tp_clear */
1353 0, /* tp_richcompare */
1354 0, /* tp_weaklistoffset */
1355 PyObject_SelfIter, /* tp_iter */
1356 (iternextfunc)map_next, /* tp_iternext */
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001357 map_methods, /* tp_methods */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001358 0, /* tp_members */
1359 0, /* tp_getset */
1360 0, /* tp_base */
1361 0, /* tp_dict */
1362 0, /* tp_descr_get */
1363 0, /* tp_descr_set */
1364 0, /* tp_dictoffset */
1365 0, /* tp_init */
1366 PyType_GenericAlloc, /* tp_alloc */
1367 map_new, /* tp_new */
1368 PyObject_GC_Del, /* tp_free */
Raymond Hettingera6c60372008-03-13 01:26:19 +00001369};
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001370
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001371
1372/* AC: cannot convert yet, as needs PEP 457 group support in inspect */
Guido van Rossum79f25d91997-04-29 20:08:16 +00001373static PyObject *
Serhiy Storchakaa5552f02017-12-15 13:11:11 +02001374builtin_next(PyObject *self, PyObject *const *args, Py_ssize_t nargs)
Georg Brandla18af4e2007-04-21 15:47:16 +00001375{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001376 PyObject *it, *res;
Georg Brandla18af4e2007-04-21 15:47:16 +00001377
Serhiy Storchaka79342662019-01-12 08:25:41 +02001378 if (!_PyArg_CheckPositional("next", nargs, 1, 2))
Sylvain96c7c062017-06-15 17:05:23 +02001379 return NULL;
1380
Serhiy Storchaka79342662019-01-12 08:25:41 +02001381 it = args[0];
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001382 if (!PyIter_Check(it)) {
1383 PyErr_Format(PyExc_TypeError,
Philip Jenvey50add042011-11-06 16:37:52 -08001384 "'%.200s' object is not an iterator",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001385 it->ob_type->tp_name);
1386 return NULL;
1387 }
1388
1389 res = (*it->ob_type->tp_iternext)(it);
1390 if (res != NULL) {
1391 return res;
Serhiy Storchaka79342662019-01-12 08:25:41 +02001392 } else if (nargs > 1) {
1393 PyObject *def = args[1];
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001394 if (PyErr_Occurred()) {
1395 if(!PyErr_ExceptionMatches(PyExc_StopIteration))
1396 return NULL;
1397 PyErr_Clear();
1398 }
1399 Py_INCREF(def);
1400 return def;
1401 } else if (PyErr_Occurred()) {
1402 return NULL;
1403 } else {
1404 PyErr_SetNone(PyExc_StopIteration);
1405 return NULL;
1406 }
Georg Brandla18af4e2007-04-21 15:47:16 +00001407}
1408
1409PyDoc_STRVAR(next_doc,
1410"next(iterator[, default])\n\
1411\n\
1412Return the next item from the iterator. If default is given and the iterator\n\
1413is exhausted, it is returned instead of raising StopIteration.");
1414
1415
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001416/*[clinic input]
1417setattr as builtin_setattr
1418
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001419 obj: object
1420 name: object
1421 value: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001422 /
1423
1424Sets the named attribute on the given object to the specified value.
1425
1426setattr(x, 'y', v) is equivalent to ``x.y = v''
1427[clinic start generated code]*/
1428
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001429static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001430builtin_setattr_impl(PyObject *module, PyObject *obj, PyObject *name,
Larry Hastings89964c42015-04-14 18:07:59 -04001431 PyObject *value)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001432/*[clinic end generated code: output=dc2ce1d1add9acb4 input=bd2b7ca6875a1899]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001433{
1434 if (PyObject_SetAttr(obj, name, value) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001435 return NULL;
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02001436 Py_RETURN_NONE;
Guido van Rossum33894be1992-01-27 16:53:09 +00001437}
1438
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001439
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001440/*[clinic input]
1441delattr as builtin_delattr
1442
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001443 obj: object
1444 name: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001445 /
1446
1447Deletes the named attribute from the given object.
1448
1449delattr(x, 'y') is equivalent to ``del x.y''
1450[clinic start generated code]*/
1451
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001452static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001453builtin_delattr_impl(PyObject *module, PyObject *obj, PyObject *name)
1454/*[clinic end generated code: output=85134bc58dff79fa input=db16685d6b4b9410]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001455{
1456 if (PyObject_SetAttr(obj, name, (PyObject *)NULL) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001457 return NULL;
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02001458 Py_RETURN_NONE;
Guido van Rossum14144fc1994-08-29 12:53:40 +00001459}
1460
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001461
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001462/*[clinic input]
1463hash as builtin_hash
1464
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001465 obj: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001466 /
1467
1468Return the hash value for the given object.
1469
1470Two objects that compare equal must also have the same hash value, but the
1471reverse is not necessarily true.
1472[clinic start generated code]*/
1473
Guido van Rossum79f25d91997-04-29 20:08:16 +00001474static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001475builtin_hash(PyObject *module, PyObject *obj)
1476/*[clinic end generated code: output=237668e9d7688db7 input=58c48be822bf9c54]*/
Guido van Rossum9bfef441993-03-29 10:43:31 +00001477{
Benjamin Peterson8f67d082010-10-17 20:54:53 +00001478 Py_hash_t x;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001479
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001480 x = PyObject_Hash(obj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001481 if (x == -1)
1482 return NULL;
Benjamin Peterson8f67d082010-10-17 20:54:53 +00001483 return PyLong_FromSsize_t(x);
Guido van Rossum9bfef441993-03-29 10:43:31 +00001484}
1485
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001486
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001487/*[clinic input]
1488hex as builtin_hex
1489
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001490 number: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001491 /
1492
1493Return the hexadecimal representation of an integer.
1494
1495 >>> hex(12648430)
1496 '0xc0ffee'
1497[clinic start generated code]*/
1498
Guido van Rossum79f25d91997-04-29 20:08:16 +00001499static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001500builtin_hex(PyObject *module, PyObject *number)
1501/*[clinic end generated code: output=e46b612169099408 input=e645aff5fc7d540e]*/
Guido van Rossum006bcd41991-10-24 14:54:44 +00001502{
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001503 return PyNumber_ToBase(number, 16);
Guido van Rossum006bcd41991-10-24 14:54:44 +00001504}
1505
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001506
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001507/* AC: cannot convert yet, as needs PEP 457 group support in inspect */
Guido van Rossum79f25d91997-04-29 20:08:16 +00001508static PyObject *
Serhiy Storchaka79342662019-01-12 08:25:41 +02001509builtin_iter(PyObject *self, PyObject *const *args, Py_ssize_t nargs)
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001510{
Serhiy Storchaka79342662019-01-12 08:25:41 +02001511 PyObject *v;
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001512
Serhiy Storchaka79342662019-01-12 08:25:41 +02001513 if (!_PyArg_CheckPositional("iter", nargs, 1, 2))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001514 return NULL;
Serhiy Storchaka79342662019-01-12 08:25:41 +02001515 v = args[0];
1516 if (nargs == 1)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001517 return PyObject_GetIter(v);
1518 if (!PyCallable_Check(v)) {
1519 PyErr_SetString(PyExc_TypeError,
1520 "iter(v, w): v must be callable");
1521 return NULL;
1522 }
Serhiy Storchaka79342662019-01-12 08:25:41 +02001523 PyObject *sentinel = args[1];
1524 return PyCallIter_New(v, sentinel);
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001525}
1526
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001527PyDoc_STRVAR(iter_doc,
Georg Brandld11ae5d2008-05-16 13:27:32 +00001528"iter(iterable) -> iterator\n\
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001529iter(callable, sentinel) -> iterator\n\
1530\n\
1531Get an iterator from an object. In the first form, the argument must\n\
1532supply its own iterator, or be a sequence.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001533In the second form, the callable is called until it returns the sentinel.");
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001534
1535
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001536/*[clinic input]
1537len as builtin_len
1538
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001539 obj: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001540 /
1541
1542Return the number of items in a container.
1543[clinic start generated code]*/
1544
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001545static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001546builtin_len(PyObject *module, PyObject *obj)
1547/*[clinic end generated code: output=fa7a270d314dfb6c input=bc55598da9e9c9b5]*/
Guido van Rossum3f5da241990-12-20 15:06:42 +00001548{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001549 Py_ssize_t res;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001550
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001551 res = PyObject_Size(obj);
Serhiy Storchaka813f9432017-04-16 09:21:44 +03001552 if (res < 0) {
1553 assert(PyErr_Occurred());
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001554 return NULL;
Serhiy Storchaka813f9432017-04-16 09:21:44 +03001555 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001556 return PyLong_FromSsize_t(res);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001557}
1558
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001559
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001560/*[clinic input]
1561locals as builtin_locals
1562
1563Return a dictionary containing the current scope's local variables.
1564
1565NOTE: Whether or not updates to this dictionary will affect name lookups in
1566the local scope and vice-versa is *implementation dependent* and not
1567covered by any backwards compatibility guarantees.
1568[clinic start generated code]*/
1569
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001570static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001571builtin_locals_impl(PyObject *module)
1572/*[clinic end generated code: output=b46c94015ce11448 input=7874018d478d5c4b]*/
Guido van Rossum872537c1995-07-07 22:43:42 +00001573{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001574 PyObject *d;
Guido van Rossum872537c1995-07-07 22:43:42 +00001575
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001576 d = PyEval_GetLocals();
1577 Py_XINCREF(d);
1578 return d;
Guido van Rossum872537c1995-07-07 22:43:42 +00001579}
1580
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001581
Guido van Rossum79f25d91997-04-29 20:08:16 +00001582static PyObject *
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001583min_max(PyObject *args, PyObject *kwds, int op)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001584{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001585 PyObject *v, *it, *item, *val, *maxitem, *maxval, *keyfunc=NULL;
Raymond Hettinger4d6018f2013-06-24 22:43:02 -07001586 PyObject *emptytuple, *defaultval = NULL;
1587 static char *kwlist[] = {"key", "default", NULL};
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001588 const char *name = op == Py_LT ? "min" : "max";
Raymond Hettinger4d6018f2013-06-24 22:43:02 -07001589 const int positional = PyTuple_Size(args) > 1;
1590 int ret;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001591
Dong-hee Naabdc6342020-01-11 01:31:43 +09001592 if (positional) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001593 v = args;
Dong-hee Naabdc6342020-01-11 01:31:43 +09001594 }
1595 else if (!PyArg_UnpackTuple(args, name, 1, 1, &v)) {
1596 if (PyExceptionClass_Check(PyExc_TypeError)) {
1597 PyErr_Format(PyExc_TypeError, "%s expected at least 1 argument, got 0", name);
1598 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001599 return NULL;
Dong-hee Naabdc6342020-01-11 01:31:43 +09001600 }
Tim Peters67d687a2002-04-29 21:27:32 +00001601
Raymond Hettinger4d6018f2013-06-24 22:43:02 -07001602 emptytuple = PyTuple_New(0);
1603 if (emptytuple == NULL)
1604 return NULL;
Oren Milman58cf7482017-08-21 20:19:07 +03001605 ret = PyArg_ParseTupleAndKeywords(emptytuple, kwds,
1606 (op == Py_LT) ? "|$OO:min" : "|$OO:max",
1607 kwlist, &keyfunc, &defaultval);
Raymond Hettinger4d6018f2013-06-24 22:43:02 -07001608 Py_DECREF(emptytuple);
1609 if (!ret)
1610 return NULL;
1611
1612 if (positional && defaultval != NULL) {
1613 PyErr_Format(PyExc_TypeError,
1614 "Cannot specify a default for %s() with multiple "
1615 "positional arguments", name);
1616 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001617 }
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001618
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001619 it = PyObject_GetIter(v);
1620 if (it == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001621 return NULL;
1622 }
Tim Petersc3074532001-05-03 07:00:32 +00001623
Alexander Marshalove22072f2018-07-24 10:58:21 +07001624 if (keyfunc == Py_None) {
1625 keyfunc = NULL;
1626 }
1627
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001628 maxitem = NULL; /* the result */
1629 maxval = NULL; /* the value associated with the result */
1630 while (( item = PyIter_Next(it) )) {
1631 /* get the value from the key function */
1632 if (keyfunc != NULL) {
Jeroen Demeyer196a5302019-07-04 12:31:34 +02001633 val = _PyObject_CallOneArg(keyfunc, item);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001634 if (val == NULL)
1635 goto Fail_it_item;
1636 }
1637 /* no key function; the value is the item */
1638 else {
1639 val = item;
1640 Py_INCREF(val);
1641 }
Tim Petersc3074532001-05-03 07:00:32 +00001642
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001643 /* maximum value and item are unset; set them */
1644 if (maxval == NULL) {
1645 maxitem = item;
1646 maxval = val;
1647 }
1648 /* maximum value and item are set; update them as necessary */
1649 else {
1650 int cmp = PyObject_RichCompareBool(val, maxval, op);
1651 if (cmp < 0)
1652 goto Fail_it_item_and_val;
1653 else if (cmp > 0) {
1654 Py_DECREF(maxval);
1655 Py_DECREF(maxitem);
1656 maxval = val;
1657 maxitem = item;
1658 }
1659 else {
1660 Py_DECREF(item);
1661 Py_DECREF(val);
1662 }
1663 }
1664 }
1665 if (PyErr_Occurred())
1666 goto Fail_it;
1667 if (maxval == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001668 assert(maxitem == NULL);
Raymond Hettinger4d6018f2013-06-24 22:43:02 -07001669 if (defaultval != NULL) {
1670 Py_INCREF(defaultval);
1671 maxitem = defaultval;
1672 } else {
1673 PyErr_Format(PyExc_ValueError,
1674 "%s() arg is an empty sequence", name);
1675 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001676 }
1677 else
1678 Py_DECREF(maxval);
1679 Py_DECREF(it);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001680 return maxitem;
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001681
1682Fail_it_item_and_val:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001683 Py_DECREF(val);
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001684Fail_it_item:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001685 Py_DECREF(item);
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001686Fail_it:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001687 Py_XDECREF(maxval);
1688 Py_XDECREF(maxitem);
1689 Py_DECREF(it);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001690 return NULL;
Guido van Rossum3f5da241990-12-20 15:06:42 +00001691}
1692
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001693/* AC: cannot convert yet, waiting for *args support */
Guido van Rossum79f25d91997-04-29 20:08:16 +00001694static PyObject *
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001695builtin_min(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001696{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001697 return min_max(args, kwds, Py_LT);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001698}
1699
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001700PyDoc_STRVAR(min_doc,
Raymond Hettinger2a545822014-05-19 22:20:52 +01001701"min(iterable, *[, default=obj, key=func]) -> value\n\
1702min(arg1, arg2, *args, *[, key=func]) -> value\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001703\n\
Raymond Hettinger2a545822014-05-19 22:20:52 +01001704With a single iterable argument, return its smallest item. The\n\
1705default keyword-only argument specifies an object to return if\n\
1706the provided iterable is empty.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001707With two or more arguments, return the smallest argument.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001708
1709
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001710/* AC: cannot convert yet, waiting for *args support */
Guido van Rossum79f25d91997-04-29 20:08:16 +00001711static PyObject *
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001712builtin_max(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001713{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001714 return min_max(args, kwds, Py_GT);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001715}
1716
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001717PyDoc_STRVAR(max_doc,
Raymond Hettinger2a545822014-05-19 22:20:52 +01001718"max(iterable, *[, default=obj, key=func]) -> value\n\
1719max(arg1, arg2, *args, *[, key=func]) -> value\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001720\n\
Raymond Hettinger2a545822014-05-19 22:20:52 +01001721With a single iterable argument, return its biggest item. The\n\
1722default keyword-only argument specifies an object to return if\n\
1723the provided iterable is empty.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001724With two or more arguments, return the largest argument.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001725
1726
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001727/*[clinic input]
1728oct as builtin_oct
1729
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001730 number: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001731 /
1732
1733Return the octal representation of an integer.
1734
1735 >>> oct(342391)
1736 '0o1234567'
1737[clinic start generated code]*/
1738
Guido van Rossum79f25d91997-04-29 20:08:16 +00001739static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001740builtin_oct(PyObject *module, PyObject *number)
1741/*[clinic end generated code: output=40a34656b6875352 input=ad6b274af4016c72]*/
Guido van Rossum006bcd41991-10-24 14:54:44 +00001742{
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001743 return PyNumber_ToBase(number, 8);
Guido van Rossum006bcd41991-10-24 14:54:44 +00001744}
1745
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001746
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001747/*[clinic input]
1748ord as builtin_ord
1749
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001750 c: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001751 /
1752
1753Return the Unicode code point for a one-character string.
1754[clinic start generated code]*/
1755
Guido van Rossum79f25d91997-04-29 20:08:16 +00001756static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001757builtin_ord(PyObject *module, PyObject *c)
1758/*[clinic end generated code: output=4fa5e87a323bae71 input=3064e5d6203ad012]*/
Guido van Rossum3f5da241990-12-20 15:06:42 +00001759{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001760 long ord;
1761 Py_ssize_t size;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001762
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001763 if (PyBytes_Check(c)) {
1764 size = PyBytes_GET_SIZE(c);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001765 if (size == 1) {
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001766 ord = (long)((unsigned char)*PyBytes_AS_STRING(c));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001767 return PyLong_FromLong(ord);
1768 }
1769 }
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001770 else if (PyUnicode_Check(c)) {
1771 if (PyUnicode_READY(c) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001772 return NULL;
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001773 size = PyUnicode_GET_LENGTH(c);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001774 if (size == 1) {
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001775 ord = (long)PyUnicode_READ_CHAR(c, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001776 return PyLong_FromLong(ord);
1777 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001778 }
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001779 else if (PyByteArray_Check(c)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001780 /* XXX Hopefully this is temporary */
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001781 size = PyByteArray_GET_SIZE(c);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001782 if (size == 1) {
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001783 ord = (long)((unsigned char)*PyByteArray_AS_STRING(c));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001784 return PyLong_FromLong(ord);
1785 }
1786 }
1787 else {
1788 PyErr_Format(PyExc_TypeError,
1789 "ord() expected string of length 1, but " \
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001790 "%.200s found", c->ob_type->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001791 return NULL;
1792 }
Guido van Rossum09095f32000-03-10 23:00:52 +00001793
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001794 PyErr_Format(PyExc_TypeError,
1795 "ord() expected a character, "
1796 "but string of length %zd found",
1797 size);
1798 return NULL;
Guido van Rossum3f5da241990-12-20 15:06:42 +00001799}
1800
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001801
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001802/*[clinic input]
1803pow as builtin_pow
1804
Ammar Askar87d6cd32019-09-21 00:28:49 -04001805 base: object
1806 exp: object
1807 mod: object = None
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001808
Raymond Hettingerb104ecb2019-09-21 12:57:44 -07001809Equivalent to base**exp with 2 arguments or base**exp % mod with 3 arguments
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001810
1811Some types, such as ints, are able to use a more efficient algorithm when
1812invoked using the three argument form.
1813[clinic start generated code]*/
1814
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001815static PyObject *
Ammar Askar87d6cd32019-09-21 00:28:49 -04001816builtin_pow_impl(PyObject *module, PyObject *base, PyObject *exp,
1817 PyObject *mod)
Raymond Hettingerb104ecb2019-09-21 12:57:44 -07001818/*[clinic end generated code: output=3ca1538221bbf15f input=435dbd48a12efb23]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001819{
Ammar Askar87d6cd32019-09-21 00:28:49 -04001820 return PyNumber_Power(base, exp, mod);
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001821}
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001822
1823
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001824/* AC: cannot convert yet, waiting for *args support */
Guido van Rossum34343512006-11-30 22:13:52 +00001825static PyObject *
Serhiy Storchakaa5552f02017-12-15 13:11:11 +02001826builtin_print(PyObject *self, PyObject *const *args, Py_ssize_t nargs, PyObject *kwnames)
Guido van Rossum34343512006-11-30 22:13:52 +00001827{
INADA Naokibd584f12017-01-19 12:50:34 +01001828 static const char * const _keywords[] = {"sep", "end", "file", "flush", 0};
Serhiy Storchaka1f21eaa2019-09-01 12:16:51 +03001829 static struct _PyArg_Parser _parser = {"|OOOp:print", _keywords, 0};
1830 PyObject *sep = NULL, *end = NULL, *file = NULL;
1831 int flush = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001832 int i, err;
Guido van Rossum34343512006-11-30 22:13:52 +00001833
INADA Naokibd584f12017-01-19 12:50:34 +01001834 if (kwnames != NULL &&
1835 !_PyArg_ParseStackAndKeywords(args + nargs, 0, kwnames, &_parser,
1836 &sep, &end, &file, &flush)) {
Georg Brandlbc3b6822012-01-13 19:41:25 +01001837 return NULL;
INADA Naokibd584f12017-01-19 12:50:34 +01001838 }
1839
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001840 if (file == NULL || file == Py_None) {
Victor Stinnerbd303c12013-11-07 23:07:29 +01001841 file = _PySys_GetObjectId(&PyId_stdout);
Victor Stinner1e53bba2013-07-16 22:26:05 +02001842 if (file == NULL) {
1843 PyErr_SetString(PyExc_RuntimeError, "lost sys.stdout");
1844 return NULL;
1845 }
1846
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001847 /* sys.stdout may be None when FILE* stdout isn't connected */
1848 if (file == Py_None)
1849 Py_RETURN_NONE;
1850 }
Guido van Rossum34343512006-11-30 22:13:52 +00001851
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001852 if (sep == Py_None) {
1853 sep = NULL;
1854 }
1855 else if (sep && !PyUnicode_Check(sep)) {
1856 PyErr_Format(PyExc_TypeError,
1857 "sep must be None or a string, not %.200s",
1858 sep->ob_type->tp_name);
1859 return NULL;
1860 }
1861 if (end == Py_None) {
1862 end = NULL;
1863 }
1864 else if (end && !PyUnicode_Check(end)) {
1865 PyErr_Format(PyExc_TypeError,
1866 "end must be None or a string, not %.200s",
1867 end->ob_type->tp_name);
1868 return NULL;
1869 }
Guido van Rossum34343512006-11-30 22:13:52 +00001870
INADA Naokibd584f12017-01-19 12:50:34 +01001871 for (i = 0; i < nargs; i++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001872 if (i > 0) {
1873 if (sep == NULL)
1874 err = PyFile_WriteString(" ", file);
1875 else
1876 err = PyFile_WriteObject(sep, file,
1877 Py_PRINT_RAW);
1878 if (err)
1879 return NULL;
1880 }
INADA Naokibd584f12017-01-19 12:50:34 +01001881 err = PyFile_WriteObject(args[i], file, Py_PRINT_RAW);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001882 if (err)
1883 return NULL;
1884 }
Guido van Rossum34343512006-11-30 22:13:52 +00001885
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001886 if (end == NULL)
1887 err = PyFile_WriteString("\n", file);
1888 else
1889 err = PyFile_WriteObject(end, file, Py_PRINT_RAW);
1890 if (err)
1891 return NULL;
Guido van Rossum34343512006-11-30 22:13:52 +00001892
Serhiy Storchaka1f21eaa2019-09-01 12:16:51 +03001893 if (flush) {
1894 PyObject *tmp = _PyObject_CallMethodIdNoArgs(file, &PyId_flush);
1895 if (tmp == NULL)
Georg Brandlbc3b6822012-01-13 19:41:25 +01001896 return NULL;
Serhiy Storchaka1f21eaa2019-09-01 12:16:51 +03001897 Py_DECREF(tmp);
Georg Brandlbc3b6822012-01-13 19:41:25 +01001898 }
1899
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001900 Py_RETURN_NONE;
Guido van Rossum34343512006-11-30 22:13:52 +00001901}
1902
1903PyDoc_STRVAR(print_doc,
Senthil Kumarane9175bd2012-08-10 13:53:45 -07001904"print(value, ..., sep=' ', end='\\n', file=sys.stdout, flush=False)\n\
Guido van Rossum34343512006-11-30 22:13:52 +00001905\n\
1906Prints the values to a stream, or to sys.stdout by default.\n\
1907Optional keyword arguments:\n\
Senthil Kumarane9175bd2012-08-10 13:53:45 -07001908file: a file-like object (stream); defaults to the current sys.stdout.\n\
1909sep: string inserted between values, default a space.\n\
1910end: string appended after the last value, default a newline.\n\
1911flush: whether to forcibly flush the stream.");
Guido van Rossum34343512006-11-30 22:13:52 +00001912
1913
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001914/*[clinic input]
1915input as builtin_input
1916
1917 prompt: object(c_default="NULL") = None
1918 /
1919
1920Read a string from standard input. The trailing newline is stripped.
1921
1922The prompt string, if given, is printed to standard output without a
1923trailing newline before reading input.
1924
1925If the user hits EOF (*nix: Ctrl-D, Windows: Ctrl-Z+Return), raise EOFError.
1926On *nix systems, readline is used if available.
1927[clinic start generated code]*/
1928
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001929static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001930builtin_input_impl(PyObject *module, PyObject *prompt)
1931/*[clinic end generated code: output=83db5a191e7a0d60 input=5e8bb70c2908fe3c]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001932{
Victor Stinnerbd303c12013-11-07 23:07:29 +01001933 PyObject *fin = _PySys_GetObjectId(&PyId_stdin);
1934 PyObject *fout = _PySys_GetObjectId(&PyId_stdout);
1935 PyObject *ferr = _PySys_GetObjectId(&PyId_stderr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001936 PyObject *tmp;
1937 long fd;
1938 int tty;
Guido van Rossuma88a0332007-02-26 16:59:55 +00001939
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001940 /* Check that stdin/out/err are intact */
1941 if (fin == NULL || fin == Py_None) {
1942 PyErr_SetString(PyExc_RuntimeError,
1943 "input(): lost sys.stdin");
1944 return NULL;
1945 }
1946 if (fout == NULL || fout == Py_None) {
1947 PyErr_SetString(PyExc_RuntimeError,
1948 "input(): lost sys.stdout");
1949 return NULL;
1950 }
1951 if (ferr == NULL || ferr == Py_None) {
1952 PyErr_SetString(PyExc_RuntimeError,
1953 "input(): lost sys.stderr");
1954 return NULL;
1955 }
Guido van Rossumeba76962007-05-27 09:13:28 +00001956
Steve Dowerb82e17e2019-05-23 08:45:22 -07001957 if (PySys_Audit("builtins.input", "O", prompt ? prompt : Py_None) < 0) {
1958 return NULL;
1959 }
1960
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001961 /* First of all, flush stderr */
Jeroen Demeyer762f93f2019-07-08 10:19:25 +02001962 tmp = _PyObject_CallMethodIdNoArgs(ferr, &PyId_flush);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001963 if (tmp == NULL)
1964 PyErr_Clear();
1965 else
1966 Py_DECREF(tmp);
Guido van Rossumeba76962007-05-27 09:13:28 +00001967
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001968 /* We should only use (GNU) readline if Python's sys.stdin and
1969 sys.stdout are the same as C's stdin and stdout, because we
1970 need to pass it those. */
Jeroen Demeyer762f93f2019-07-08 10:19:25 +02001971 tmp = _PyObject_CallMethodIdNoArgs(fin, &PyId_fileno);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001972 if (tmp == NULL) {
1973 PyErr_Clear();
1974 tty = 0;
1975 }
1976 else {
1977 fd = PyLong_AsLong(tmp);
1978 Py_DECREF(tmp);
1979 if (fd < 0 && PyErr_Occurred())
1980 return NULL;
1981 tty = fd == fileno(stdin) && isatty(fd);
1982 }
1983 if (tty) {
Jeroen Demeyer762f93f2019-07-08 10:19:25 +02001984 tmp = _PyObject_CallMethodIdNoArgs(fout, &PyId_fileno);
Martin Panterc9a6ab52015-10-10 01:25:38 +00001985 if (tmp == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001986 PyErr_Clear();
Martin Panterc9a6ab52015-10-10 01:25:38 +00001987 tty = 0;
1988 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001989 else {
1990 fd = PyLong_AsLong(tmp);
1991 Py_DECREF(tmp);
1992 if (fd < 0 && PyErr_Occurred())
1993 return NULL;
1994 tty = fd == fileno(stdout) && isatty(fd);
1995 }
1996 }
Guido van Rossumeba76962007-05-27 09:13:28 +00001997
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001998 /* If we're interactive, use (GNU) readline */
1999 if (tty) {
Antoine Pitrou0d776b12011-11-06 00:34:26 +01002000 PyObject *po = NULL;
Serhiy Storchakae2f92de2017-11-11 13:06:26 +02002001 const char *promptstr;
Antoine Pitrou0d776b12011-11-06 00:34:26 +01002002 char *s = NULL;
2003 PyObject *stdin_encoding = NULL, *stdin_errors = NULL;
2004 PyObject *stdout_encoding = NULL, *stdout_errors = NULL;
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +02002005 const char *stdin_encoding_str, *stdin_errors_str;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002006 PyObject *result;
Victor Stinnerc0f1a1a2011-02-23 12:07:37 +00002007 size_t len;
Martin v. Löwis4a7b5d52007-09-04 05:24:49 +00002008
Serhiy Storchakac2cf1282017-03-12 13:50:36 +02002009 /* stdin is a text stream, so it must have an encoding. */
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02002010 stdin_encoding = _PyObject_GetAttrId(fin, &PyId_encoding);
Antoine Pitrou5ee9d8a2011-11-06 00:38:45 +01002011 stdin_errors = _PyObject_GetAttrId(fin, &PyId_errors);
Serhiy Storchakac2cf1282017-03-12 13:50:36 +02002012 if (!stdin_encoding || !stdin_errors ||
2013 !PyUnicode_Check(stdin_encoding) ||
2014 !PyUnicode_Check(stdin_errors)) {
2015 tty = 0;
Antoine Pitrou0d776b12011-11-06 00:34:26 +01002016 goto _readline_errors;
Serhiy Storchakac2cf1282017-03-12 13:50:36 +02002017 }
Serhiy Storchaka06515832016-11-20 09:13:07 +02002018 stdin_encoding_str = PyUnicode_AsUTF8(stdin_encoding);
2019 stdin_errors_str = PyUnicode_AsUTF8(stdin_errors);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01002020 if (!stdin_encoding_str || !stdin_errors_str)
2021 goto _readline_errors;
Jeroen Demeyer762f93f2019-07-08 10:19:25 +02002022 tmp = _PyObject_CallMethodIdNoArgs(fout, &PyId_flush);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002023 if (tmp == NULL)
2024 PyErr_Clear();
2025 else
2026 Py_DECREF(tmp);
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002027 if (prompt != NULL) {
Antoine Pitrou0d776b12011-11-06 00:34:26 +01002028 /* We have a prompt, encode it as stdout would */
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +02002029 const char *stdout_encoding_str, *stdout_errors_str;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002030 PyObject *stringpo;
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02002031 stdout_encoding = _PyObject_GetAttrId(fout, &PyId_encoding);
Antoine Pitrou5ee9d8a2011-11-06 00:38:45 +01002032 stdout_errors = _PyObject_GetAttrId(fout, &PyId_errors);
Serhiy Storchakac2cf1282017-03-12 13:50:36 +02002033 if (!stdout_encoding || !stdout_errors ||
2034 !PyUnicode_Check(stdout_encoding) ||
2035 !PyUnicode_Check(stdout_errors)) {
2036 tty = 0;
Antoine Pitrou0d776b12011-11-06 00:34:26 +01002037 goto _readline_errors;
Serhiy Storchakac2cf1282017-03-12 13:50:36 +02002038 }
Serhiy Storchaka06515832016-11-20 09:13:07 +02002039 stdout_encoding_str = PyUnicode_AsUTF8(stdout_encoding);
2040 stdout_errors_str = PyUnicode_AsUTF8(stdout_errors);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01002041 if (!stdout_encoding_str || !stdout_errors_str)
2042 goto _readline_errors;
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002043 stringpo = PyObject_Str(prompt);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01002044 if (stringpo == NULL)
2045 goto _readline_errors;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002046 po = PyUnicode_AsEncodedString(stringpo,
Antoine Pitrou0d776b12011-11-06 00:34:26 +01002047 stdout_encoding_str, stdout_errors_str);
2048 Py_CLEAR(stdout_encoding);
2049 Py_CLEAR(stdout_errors);
2050 Py_CLEAR(stringpo);
2051 if (po == NULL)
2052 goto _readline_errors;
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03002053 assert(PyBytes_Check(po));
2054 promptstr = PyBytes_AS_STRING(po);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002055 }
2056 else {
2057 po = NULL;
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002058 promptstr = "";
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002059 }
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002060 s = PyOS_Readline(stdin, stdout, promptstr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002061 if (s == NULL) {
Richard Oudkerk614c5782013-04-03 13:44:50 +01002062 PyErr_CheckSignals();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002063 if (!PyErr_Occurred())
2064 PyErr_SetNone(PyExc_KeyboardInterrupt);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01002065 goto _readline_errors;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002066 }
Victor Stinnerc0f1a1a2011-02-23 12:07:37 +00002067
2068 len = strlen(s);
2069 if (len == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002070 PyErr_SetNone(PyExc_EOFError);
2071 result = NULL;
2072 }
Victor Stinnerc0f1a1a2011-02-23 12:07:37 +00002073 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002074 if (len > PY_SSIZE_T_MAX) {
2075 PyErr_SetString(PyExc_OverflowError,
2076 "input: input too long");
2077 result = NULL;
2078 }
2079 else {
Victor Stinnerc0f1a1a2011-02-23 12:07:37 +00002080 len--; /* strip trailing '\n' */
2081 if (len != 0 && s[len-1] == '\r')
2082 len--; /* strip trailing '\r' */
Antoine Pitrou0d776b12011-11-06 00:34:26 +01002083 result = PyUnicode_Decode(s, len, stdin_encoding_str,
2084 stdin_errors_str);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002085 }
2086 }
2087 Py_DECREF(stdin_encoding);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01002088 Py_DECREF(stdin_errors);
2089 Py_XDECREF(po);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002090 PyMem_FREE(s);
Steve Dowerb82e17e2019-05-23 08:45:22 -07002091
2092 if (result != NULL) {
2093 if (PySys_Audit("builtins.input/result", "O", result) < 0) {
2094 return NULL;
2095 }
2096 }
2097
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002098 return result;
Serhiy Storchakac2cf1282017-03-12 13:50:36 +02002099
Antoine Pitrou0d776b12011-11-06 00:34:26 +01002100 _readline_errors:
2101 Py_XDECREF(stdin_encoding);
2102 Py_XDECREF(stdout_encoding);
2103 Py_XDECREF(stdin_errors);
2104 Py_XDECREF(stdout_errors);
2105 Py_XDECREF(po);
Serhiy Storchakac2cf1282017-03-12 13:50:36 +02002106 if (tty)
2107 return NULL;
2108
2109 PyErr_Clear();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002110 }
Guido van Rossumeba76962007-05-27 09:13:28 +00002111
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002112 /* Fallback if we're not interactive */
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002113 if (prompt != NULL) {
2114 if (PyFile_WriteObject(prompt, fout, Py_PRINT_RAW) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002115 return NULL;
2116 }
Jeroen Demeyer762f93f2019-07-08 10:19:25 +02002117 tmp = _PyObject_CallMethodIdNoArgs(fout, &PyId_flush);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002118 if (tmp == NULL)
2119 PyErr_Clear();
2120 else
2121 Py_DECREF(tmp);
2122 return PyFile_GetLine(fin, -1);
Guido van Rossuma88a0332007-02-26 16:59:55 +00002123}
2124
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002125
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002126/*[clinic input]
2127repr as builtin_repr
2128
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03002129 obj: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002130 /
2131
2132Return the canonical string representation of the object.
2133
2134For many object types, including most builtins, eval(repr(obj)) == obj.
2135[clinic start generated code]*/
2136
Guido van Rossum79f25d91997-04-29 20:08:16 +00002137static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002138builtin_repr(PyObject *module, PyObject *obj)
2139/*[clinic end generated code: output=7ed3778c44fd0194 input=1c9e6d66d3e3be04]*/
Guido van Rossumc89705d1992-11-26 08:54:07 +00002140{
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002141 return PyObject_Repr(obj);
Guido van Rossumc89705d1992-11-26 08:54:07 +00002142}
2143
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002144
Serhiy Storchakaaca7f572017-11-15 17:51:14 +02002145/*[clinic input]
2146round as builtin_round
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002147
Serhiy Storchakaaca7f572017-11-15 17:51:14 +02002148 number: object
Serhiy Storchaka279f4462019-09-14 12:24:05 +03002149 ndigits: object = None
Serhiy Storchakaaca7f572017-11-15 17:51:14 +02002150
2151Round a number to a given precision in decimal digits.
2152
2153The return value is an integer if ndigits is omitted or None. Otherwise
2154the return value has the same type as the number. ndigits may be negative.
2155[clinic start generated code]*/
2156
2157static PyObject *
2158builtin_round_impl(PyObject *module, PyObject *number, PyObject *ndigits)
Serhiy Storchaka279f4462019-09-14 12:24:05 +03002159/*[clinic end generated code: output=ff0d9dd176c02ede input=275678471d7aca15]*/
Serhiy Storchakaaca7f572017-11-15 17:51:14 +02002160{
2161 PyObject *round, *result;
Alex Martelliae211f92007-08-22 23:21:33 +00002162
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002163 if (Py_TYPE(number)->tp_dict == NULL) {
2164 if (PyType_Ready(Py_TYPE(number)) < 0)
2165 return NULL;
2166 }
Guido van Rossum15d3d042007-08-24 02:02:45 +00002167
Benjamin Peterson214a7d22013-04-13 17:19:01 -04002168 round = _PyObject_LookupSpecial(number, &PyId___round__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002169 if (round == NULL) {
Benjamin Peterson214a7d22013-04-13 17:19:01 -04002170 if (!PyErr_Occurred())
2171 PyErr_Format(PyExc_TypeError,
2172 "type %.100s doesn't define __round__ method",
2173 Py_TYPE(number)->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002174 return NULL;
2175 }
Alex Martelliae211f92007-08-22 23:21:33 +00002176
Serhiy Storchaka279f4462019-09-14 12:24:05 +03002177 if (ndigits == Py_None)
Victor Stinnerf17c3de2016-12-06 18:46:19 +01002178 result = _PyObject_CallNoArg(round);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002179 else
Jeroen Demeyer196a5302019-07-04 12:31:34 +02002180 result = _PyObject_CallOneArg(round, ndigits);
Benjamin Peterson214a7d22013-04-13 17:19:01 -04002181 Py_DECREF(round);
2182 return result;
Guido van Rossum9e51f9b1993-02-12 16:29:05 +00002183}
2184
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002185
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002186/*AC: we need to keep the kwds dict intact to easily call into the
2187 * list.sort method, which isn't currently supported in AC. So we just use
2188 * the initially generated signature with a custom implementation.
2189 */
2190/* [disabled clinic input]
2191sorted as builtin_sorted
2192
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03002193 iterable as seq: object
2194 key as keyfunc: object = None
2195 reverse: object = False
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002196
2197Return a new list containing all items from the iterable in ascending order.
2198
Raymond Hettinger7ea386e2016-08-25 21:11:50 -07002199A custom key function can be supplied to customize the sort order, and the
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002200reverse flag can be set to request the result in descending order.
2201[end disabled clinic input]*/
2202
2203PyDoc_STRVAR(builtin_sorted__doc__,
Serhiy Storchaka3a104252017-01-23 12:29:47 +02002204"sorted($module, iterable, /, *, key=None, reverse=False)\n"
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002205"--\n"
2206"\n"
2207"Return a new list containing all items from the iterable in ascending order.\n"
2208"\n"
Raymond Hettinger7ea386e2016-08-25 21:11:50 -07002209"A custom key function can be supplied to customize the sort order, and the\n"
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002210"reverse flag can be set to request the result in descending order.");
2211
2212#define BUILTIN_SORTED_METHODDEF \
Serhiy Storchaka62be7422018-11-27 13:27:31 +02002213 {"sorted", (PyCFunction)(void(*)(void))builtin_sorted, METH_FASTCALL | METH_KEYWORDS, builtin_sorted__doc__},
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002214
Raymond Hettinger64958a12003-12-17 20:43:33 +00002215static PyObject *
Serhiy Storchakaa5552f02017-12-15 13:11:11 +02002216builtin_sorted(PyObject *self, PyObject *const *args, Py_ssize_t nargs, PyObject *kwnames)
Raymond Hettinger64958a12003-12-17 20:43:33 +00002217{
Serhiy Storchaka7cf8beb2017-01-21 23:05:00 +02002218 PyObject *newlist, *v, *seq, *callable;
Victor Stinner5a60eca2017-01-17 15:17:49 +01002219
Serhiy Storchaka7cf8beb2017-01-21 23:05:00 +02002220 /* Keyword arguments are passed through list.sort() which will check
2221 them. */
2222 if (!_PyArg_UnpackStack(args, nargs, "sorted", 1, 1, &seq))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002223 return NULL;
Raymond Hettinger64958a12003-12-17 20:43:33 +00002224
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002225 newlist = PySequence_List(seq);
2226 if (newlist == NULL)
2227 return NULL;
Raymond Hettinger64958a12003-12-17 20:43:33 +00002228
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02002229 callable = _PyObject_GetAttrId(newlist, &PyId_sort);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002230 if (callable == NULL) {
2231 Py_DECREF(newlist);
2232 return NULL;
2233 }
Georg Brandl99d7e4e2005-08-31 22:21:15 +00002234
Serhiy Storchaka299dc232017-01-20 08:35:18 +02002235 assert(nargs >= 1);
Jeroen Demeyeraacc77f2019-05-29 20:31:52 +02002236 v = _PyObject_Vectorcall(callable, args + 1, nargs - 1, kwnames);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002237 Py_DECREF(callable);
2238 if (v == NULL) {
2239 Py_DECREF(newlist);
2240 return NULL;
2241 }
2242 Py_DECREF(v);
2243 return newlist;
Raymond Hettinger64958a12003-12-17 20:43:33 +00002244}
2245
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002246
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002247/* AC: cannot convert yet, as needs PEP 457 group support in inspect */
Guido van Rossum79f25d91997-04-29 20:08:16 +00002248static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002249builtin_vars(PyObject *self, PyObject *args)
Guido van Rossum2d951851994-08-29 12:52:16 +00002250{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002251 PyObject *v = NULL;
2252 PyObject *d;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002253
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002254 if (!PyArg_UnpackTuple(args, "vars", 0, 1, &v))
2255 return NULL;
2256 if (v == NULL) {
2257 d = PyEval_GetLocals();
Serhiy Storchaka41c57b32019-09-01 12:03:39 +03002258 Py_XINCREF(d);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002259 }
2260 else {
Serhiy Storchaka41c57b32019-09-01 12:03:39 +03002261 if (_PyObject_LookupAttrId(v, &PyId___dict__, &d) == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002262 PyErr_SetString(PyExc_TypeError,
2263 "vars() argument must have __dict__ attribute");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002264 }
2265 }
2266 return d;
Guido van Rossum2d951851994-08-29 12:52:16 +00002267}
2268
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002269PyDoc_STRVAR(vars_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002270"vars([object]) -> dictionary\n\
2271\n\
2272Without arguments, equivalent to locals().\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002273With an argument, equivalent to object.__dict__.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002274
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002275
2276/*[clinic input]
2277sum as builtin_sum
2278
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03002279 iterable: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002280 /
Raymond Hettinger9dfa0fe2018-09-12 10:54:06 -07002281 start: object(c_default="NULL") = 0
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002282
2283Return the sum of a 'start' value (default: 0) plus an iterable of numbers
2284
2285When the iterable is empty, return the start value.
2286This function is intended specifically for use with numeric values and may
2287reject non-numeric types.
2288[clinic start generated code]*/
2289
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002290static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002291builtin_sum_impl(PyObject *module, PyObject *iterable, PyObject *start)
Raymond Hettinger9dfa0fe2018-09-12 10:54:06 -07002292/*[clinic end generated code: output=df758cec7d1d302f input=162b50765250d222]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002293{
2294 PyObject *result = start;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002295 PyObject *temp, *item, *iter;
Alex Martellia70b1912003-04-22 08:12:33 +00002296
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002297 iter = PyObject_GetIter(iterable);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002298 if (iter == NULL)
2299 return NULL;
Alex Martellia70b1912003-04-22 08:12:33 +00002300
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002301 if (result == NULL) {
2302 result = PyLong_FromLong(0);
2303 if (result == NULL) {
2304 Py_DECREF(iter);
2305 return NULL;
2306 }
2307 } else {
2308 /* reject string values for 'start' parameter */
2309 if (PyUnicode_Check(result)) {
2310 PyErr_SetString(PyExc_TypeError,
2311 "sum() can't sum strings [use ''.join(seq) instead]");
2312 Py_DECREF(iter);
2313 return NULL;
2314 }
Benjamin Petersonce071ca2011-07-29 14:23:47 -05002315 if (PyBytes_Check(result)) {
2316 PyErr_SetString(PyExc_TypeError,
2317 "sum() can't sum bytes [use b''.join(seq) instead]");
Benjamin Peterson405f32c2011-07-29 22:43:45 -05002318 Py_DECREF(iter);
Benjamin Petersonce071ca2011-07-29 14:23:47 -05002319 return NULL;
2320 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002321 if (PyByteArray_Check(result)) {
2322 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson4f921c22011-07-29 14:24:29 -05002323 "sum() can't sum bytearray [use b''.join(seq) instead]");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002324 Py_DECREF(iter);
2325 return NULL;
2326 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002327 Py_INCREF(result);
2328 }
Alex Martellia70b1912003-04-22 08:12:33 +00002329
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002330#ifndef SLOW_SUM
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002331 /* Fast addition by keeping temporary sums in C instead of new Python objects.
2332 Assumes all inputs are the same type. If the assumption fails, default
2333 to the more general routine.
2334 */
2335 if (PyLong_CheckExact(result)) {
2336 int overflow;
2337 long i_result = PyLong_AsLongAndOverflow(result, &overflow);
2338 /* If this already overflowed, don't even enter the loop. */
2339 if (overflow == 0) {
2340 Py_DECREF(result);
2341 result = NULL;
2342 }
2343 while(result == NULL) {
2344 item = PyIter_Next(iter);
2345 if (item == NULL) {
2346 Py_DECREF(iter);
2347 if (PyErr_Occurred())
2348 return NULL;
2349 return PyLong_FromLong(i_result);
2350 }
Serhiy Storchaka88bdb922019-09-10 16:31:01 +03002351 if (PyLong_CheckExact(item) || PyBool_Check(item)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002352 long b = PyLong_AsLongAndOverflow(item, &overflow);
Serhiy Storchaka29500732019-05-05 14:26:23 +03002353 if (overflow == 0 &&
2354 (i_result >= 0 ? (b <= LONG_MAX - i_result)
2355 : (b >= LONG_MIN - i_result)))
2356 {
2357 i_result += b;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002358 Py_DECREF(item);
2359 continue;
2360 }
2361 }
2362 /* Either overflowed or is not an int. Restore real objects and process normally */
2363 result = PyLong_FromLong(i_result);
Christian Heimes704e2d32013-07-26 22:49:26 +02002364 if (result == NULL) {
2365 Py_DECREF(item);
2366 Py_DECREF(iter);
2367 return NULL;
2368 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002369 temp = PyNumber_Add(result, item);
2370 Py_DECREF(result);
2371 Py_DECREF(item);
2372 result = temp;
2373 if (result == NULL) {
2374 Py_DECREF(iter);
2375 return NULL;
2376 }
2377 }
2378 }
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002379
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002380 if (PyFloat_CheckExact(result)) {
2381 double f_result = PyFloat_AS_DOUBLE(result);
2382 Py_DECREF(result);
2383 result = NULL;
2384 while(result == NULL) {
2385 item = PyIter_Next(iter);
2386 if (item == NULL) {
2387 Py_DECREF(iter);
2388 if (PyErr_Occurred())
2389 return NULL;
2390 return PyFloat_FromDouble(f_result);
2391 }
2392 if (PyFloat_CheckExact(item)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002393 f_result += PyFloat_AS_DOUBLE(item);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002394 Py_DECREF(item);
2395 continue;
2396 }
Serhiy Storchaka88bdb922019-09-10 16:31:01 +03002397 if (PyLong_Check(item)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002398 long value;
2399 int overflow;
2400 value = PyLong_AsLongAndOverflow(item, &overflow);
2401 if (!overflow) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002402 f_result += (double)value;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002403 Py_DECREF(item);
2404 continue;
2405 }
2406 }
2407 result = PyFloat_FromDouble(f_result);
Alexey Izbyshev2b824b22018-08-24 07:27:52 +03002408 if (result == NULL) {
2409 Py_DECREF(item);
2410 Py_DECREF(iter);
2411 return NULL;
2412 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002413 temp = PyNumber_Add(result, item);
2414 Py_DECREF(result);
2415 Py_DECREF(item);
2416 result = temp;
2417 if (result == NULL) {
2418 Py_DECREF(iter);
2419 return NULL;
2420 }
2421 }
2422 }
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002423#endif
2424
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002425 for(;;) {
2426 item = PyIter_Next(iter);
2427 if (item == NULL) {
2428 /* error, or end-of-sequence */
2429 if (PyErr_Occurred()) {
2430 Py_DECREF(result);
2431 result = NULL;
2432 }
2433 break;
2434 }
2435 /* It's tempting to use PyNumber_InPlaceAdd instead of
2436 PyNumber_Add here, to avoid quadratic running time
2437 when doing 'sum(list_of_lists, [])'. However, this
2438 would produce a change in behaviour: a snippet like
Mark Dickinson9acadc52009-10-26 14:19:42 +00002439
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002440 empty = []
2441 sum([[x] for x in range(10)], empty)
Mark Dickinson9acadc52009-10-26 14:19:42 +00002442
Brandt Bucherabb9a442020-02-01 03:08:34 -08002443 would change the value of empty. In fact, using
2444 in-place addition rather that binary addition for
2445 any of the steps introduces subtle behavior changes:
2446
2447 https://bugs.python.org/issue18305 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002448 temp = PyNumber_Add(result, item);
2449 Py_DECREF(result);
2450 Py_DECREF(item);
2451 result = temp;
2452 if (result == NULL)
2453 break;
2454 }
2455 Py_DECREF(iter);
2456 return result;
Alex Martellia70b1912003-04-22 08:12:33 +00002457}
2458
Alex Martellia70b1912003-04-22 08:12:33 +00002459
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002460/*[clinic input]
2461isinstance as builtin_isinstance
2462
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03002463 obj: object
2464 class_or_tuple: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002465 /
2466
2467Return whether an object is an instance of a class or of a subclass thereof.
2468
2469A tuple, as in ``isinstance(x, (A, B, ...))``, may be given as the target to
2470check against. This is equivalent to ``isinstance(x, A) or isinstance(x, B)
2471or ...`` etc.
2472[clinic start generated code]*/
2473
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002474static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002475builtin_isinstance_impl(PyObject *module, PyObject *obj,
Larry Hastings89964c42015-04-14 18:07:59 -04002476 PyObject *class_or_tuple)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002477/*[clinic end generated code: output=6faf01472c13b003 input=ffa743db1daf7549]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002478{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002479 int retval;
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002480
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002481 retval = PyObject_IsInstance(obj, class_or_tuple);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002482 if (retval < 0)
2483 return NULL;
2484 return PyBool_FromLong(retval);
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002485}
2486
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002487
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002488/*[clinic input]
2489issubclass as builtin_issubclass
2490
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03002491 cls: object
2492 class_or_tuple: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002493 /
2494
2495Return whether 'cls' is a derived from another class or is the same class.
2496
2497A tuple, as in ``issubclass(x, (A, B, ...))``, may be given as the target to
2498check against. This is equivalent to ``issubclass(x, A) or issubclass(x, B)
2499or ...`` etc.
2500[clinic start generated code]*/
2501
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002502static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002503builtin_issubclass_impl(PyObject *module, PyObject *cls,
Larry Hastings89964c42015-04-14 18:07:59 -04002504 PyObject *class_or_tuple)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002505/*[clinic end generated code: output=358412410cd7a250 input=af5f35e9ceaddaf6]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002506{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002507 int retval;
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002508
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002509 retval = PyObject_IsSubclass(cls, class_or_tuple);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002510 if (retval < 0)
2511 return NULL;
2512 return PyBool_FromLong(retval);
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002513}
2514
2515
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002516typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002517 PyObject_HEAD
2518 Py_ssize_t tuplesize;
2519 PyObject *ittuple; /* tuple of iterators */
2520 PyObject *result;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002521} zipobject;
2522
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002523static PyObject *
2524zip_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
Barry Warsawbd599b52000-08-03 15:45:29 +00002525{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002526 zipobject *lz;
2527 Py_ssize_t i;
2528 PyObject *ittuple; /* tuple of iterators */
2529 PyObject *result;
Serhiy Storchakabf623ae2017-04-19 20:03:52 +03002530 Py_ssize_t tuplesize;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002531
Serhiy Storchaka6cca5c82017-06-08 14:41:19 +03002532 if (type == &PyZip_Type && !_PyArg_NoKeywords("zip", kwds))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002533 return NULL;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002534
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002535 /* args must be a tuple */
2536 assert(PyTuple_Check(args));
Serhiy Storchakabf623ae2017-04-19 20:03:52 +03002537 tuplesize = PyTuple_GET_SIZE(args);
Barry Warsawbd599b52000-08-03 15:45:29 +00002538
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002539 /* obtain iterators */
2540 ittuple = PyTuple_New(tuplesize);
2541 if (ittuple == NULL)
2542 return NULL;
2543 for (i=0; i < tuplesize; ++i) {
2544 PyObject *item = PyTuple_GET_ITEM(args, i);
2545 PyObject *it = PyObject_GetIter(item);
2546 if (it == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002547 Py_DECREF(ittuple);
2548 return NULL;
2549 }
2550 PyTuple_SET_ITEM(ittuple, i, it);
2551 }
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002552
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002553 /* create a result holder */
2554 result = PyTuple_New(tuplesize);
2555 if (result == NULL) {
2556 Py_DECREF(ittuple);
2557 return NULL;
2558 }
2559 for (i=0 ; i < tuplesize ; i++) {
2560 Py_INCREF(Py_None);
2561 PyTuple_SET_ITEM(result, i, Py_None);
2562 }
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002563
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002564 /* create zipobject structure */
2565 lz = (zipobject *)type->tp_alloc(type, 0);
2566 if (lz == NULL) {
2567 Py_DECREF(ittuple);
2568 Py_DECREF(result);
2569 return NULL;
2570 }
2571 lz->ittuple = ittuple;
2572 lz->tuplesize = tuplesize;
2573 lz->result = result;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002574
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002575 return (PyObject *)lz;
Barry Warsawbd599b52000-08-03 15:45:29 +00002576}
2577
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002578static void
2579zip_dealloc(zipobject *lz)
2580{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002581 PyObject_GC_UnTrack(lz);
2582 Py_XDECREF(lz->ittuple);
2583 Py_XDECREF(lz->result);
2584 Py_TYPE(lz)->tp_free(lz);
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002585}
2586
2587static int
2588zip_traverse(zipobject *lz, visitproc visit, void *arg)
2589{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002590 Py_VISIT(lz->ittuple);
2591 Py_VISIT(lz->result);
2592 return 0;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002593}
2594
2595static PyObject *
2596zip_next(zipobject *lz)
2597{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002598 Py_ssize_t i;
2599 Py_ssize_t tuplesize = lz->tuplesize;
2600 PyObject *result = lz->result;
2601 PyObject *it;
2602 PyObject *item;
2603 PyObject *olditem;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002604
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002605 if (tuplesize == 0)
2606 return NULL;
2607 if (Py_REFCNT(result) == 1) {
2608 Py_INCREF(result);
2609 for (i=0 ; i < tuplesize ; i++) {
2610 it = PyTuple_GET_ITEM(lz->ittuple, i);
2611 item = (*Py_TYPE(it)->tp_iternext)(it);
Serhiy Storchaka278d03b2013-04-06 22:52:34 +03002612 if (item == NULL) {
2613 Py_DECREF(result);
2614 return NULL;
2615 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002616 olditem = PyTuple_GET_ITEM(result, i);
2617 PyTuple_SET_ITEM(result, i, item);
2618 Py_DECREF(olditem);
2619 }
2620 } else {
2621 result = PyTuple_New(tuplesize);
2622 if (result == NULL)
Serhiy Storchaka278d03b2013-04-06 22:52:34 +03002623 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002624 for (i=0 ; i < tuplesize ; i++) {
2625 it = PyTuple_GET_ITEM(lz->ittuple, i);
2626 item = (*Py_TYPE(it)->tp_iternext)(it);
Serhiy Storchaka278d03b2013-04-06 22:52:34 +03002627 if (item == NULL) {
2628 Py_DECREF(result);
2629 return NULL;
2630 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002631 PyTuple_SET_ITEM(result, i, item);
2632 }
2633 }
2634 return result;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002635}
Barry Warsawbd599b52000-08-03 15:45:29 +00002636
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002637static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05302638zip_reduce(zipobject *lz, PyObject *Py_UNUSED(ignored))
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002639{
2640 /* Just recreate the zip with the internal iterator tuple */
2641 return Py_BuildValue("OO", Py_TYPE(lz), lz->ittuple);
2642}
2643
2644static PyMethodDef zip_methods[] = {
2645 {"__reduce__", (PyCFunction)zip_reduce, METH_NOARGS, reduce_doc},
2646 {NULL, NULL} /* sentinel */
2647};
2648
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002649PyDoc_STRVAR(zip_doc,
Sergey Fedoseevaf2f5b12019-07-18 23:19:25 +05002650"zip(*iterables) --> zip object\n\
Barry Warsawbd599b52000-08-03 15:45:29 +00002651\n\
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002652Return a zip object whose .__next__() method returns a tuple where\n\
2653the i-th element comes from the i-th iterable argument. The .__next__()\n\
2654method continues until the shortest iterable in the argument sequence\n\
Georg Brandlced51db2008-12-04 18:28:38 +00002655is exhausted and then it raises StopIteration.");
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002656
2657PyTypeObject PyZip_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002658 PyVarObject_HEAD_INIT(&PyType_Type, 0)
2659 "zip", /* tp_name */
2660 sizeof(zipobject), /* tp_basicsize */
2661 0, /* tp_itemsize */
2662 /* methods */
2663 (destructor)zip_dealloc, /* tp_dealloc */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02002664 0, /* tp_vectorcall_offset */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002665 0, /* tp_getattr */
2666 0, /* tp_setattr */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02002667 0, /* tp_as_async */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002668 0, /* tp_repr */
2669 0, /* tp_as_number */
2670 0, /* tp_as_sequence */
2671 0, /* tp_as_mapping */
2672 0, /* tp_hash */
2673 0, /* tp_call */
2674 0, /* tp_str */
2675 PyObject_GenericGetAttr, /* tp_getattro */
2676 0, /* tp_setattro */
2677 0, /* tp_as_buffer */
2678 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
2679 Py_TPFLAGS_BASETYPE, /* tp_flags */
2680 zip_doc, /* tp_doc */
2681 (traverseproc)zip_traverse, /* tp_traverse */
2682 0, /* tp_clear */
2683 0, /* tp_richcompare */
2684 0, /* tp_weaklistoffset */
2685 PyObject_SelfIter, /* tp_iter */
2686 (iternextfunc)zip_next, /* tp_iternext */
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002687 zip_methods, /* tp_methods */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002688 0, /* tp_members */
2689 0, /* tp_getset */
2690 0, /* tp_base */
2691 0, /* tp_dict */
2692 0, /* tp_descr_get */
2693 0, /* tp_descr_set */
2694 0, /* tp_dictoffset */
2695 0, /* tp_init */
2696 PyType_GenericAlloc, /* tp_alloc */
2697 zip_new, /* tp_new */
2698 PyObject_GC_Del, /* tp_free */
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002699};
Barry Warsawbd599b52000-08-03 15:45:29 +00002700
2701
Guido van Rossum79f25d91997-04-29 20:08:16 +00002702static PyMethodDef builtin_methods[] = {
Serhiy Storchaka62be7422018-11-27 13:27:31 +02002703 {"__build_class__", (PyCFunction)(void(*)(void))builtin___build_class__,
Serhiy Storchaka6969eaf2017-07-03 21:20:15 +03002704 METH_FASTCALL | METH_KEYWORDS, build_class_doc},
Serhiy Storchaka62be7422018-11-27 13:27:31 +02002705 {"__import__", (PyCFunction)(void(*)(void))builtin___import__, METH_VARARGS | METH_KEYWORDS, import_doc},
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002706 BUILTIN_ABS_METHODDEF
2707 BUILTIN_ALL_METHODDEF
2708 BUILTIN_ANY_METHODDEF
2709 BUILTIN_ASCII_METHODDEF
2710 BUILTIN_BIN_METHODDEF
Serhiy Storchaka62be7422018-11-27 13:27:31 +02002711 {"breakpoint", (PyCFunction)(void(*)(void))builtin_breakpoint, METH_FASTCALL | METH_KEYWORDS, breakpoint_doc},
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002712 BUILTIN_CALLABLE_METHODDEF
2713 BUILTIN_CHR_METHODDEF
2714 BUILTIN_COMPILE_METHODDEF
2715 BUILTIN_DELATTR_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002716 {"dir", builtin_dir, METH_VARARGS, dir_doc},
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002717 BUILTIN_DIVMOD_METHODDEF
2718 BUILTIN_EVAL_METHODDEF
2719 BUILTIN_EXEC_METHODDEF
2720 BUILTIN_FORMAT_METHODDEF
Serhiy Storchaka62be7422018-11-27 13:27:31 +02002721 {"getattr", (PyCFunction)(void(*)(void))builtin_getattr, METH_FASTCALL, getattr_doc},
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002722 BUILTIN_GLOBALS_METHODDEF
2723 BUILTIN_HASATTR_METHODDEF
2724 BUILTIN_HASH_METHODDEF
2725 BUILTIN_HEX_METHODDEF
2726 BUILTIN_ID_METHODDEF
2727 BUILTIN_INPUT_METHODDEF
2728 BUILTIN_ISINSTANCE_METHODDEF
2729 BUILTIN_ISSUBCLASS_METHODDEF
Serhiy Storchaka79342662019-01-12 08:25:41 +02002730 {"iter", (PyCFunction)(void(*)(void))builtin_iter, METH_FASTCALL, iter_doc},
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002731 BUILTIN_LEN_METHODDEF
2732 BUILTIN_LOCALS_METHODDEF
Serhiy Storchaka62be7422018-11-27 13:27:31 +02002733 {"max", (PyCFunction)(void(*)(void))builtin_max, METH_VARARGS | METH_KEYWORDS, max_doc},
2734 {"min", (PyCFunction)(void(*)(void))builtin_min, METH_VARARGS | METH_KEYWORDS, min_doc},
2735 {"next", (PyCFunction)(void(*)(void))builtin_next, METH_FASTCALL, next_doc},
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002736 BUILTIN_OCT_METHODDEF
2737 BUILTIN_ORD_METHODDEF
2738 BUILTIN_POW_METHODDEF
Serhiy Storchaka62be7422018-11-27 13:27:31 +02002739 {"print", (PyCFunction)(void(*)(void))builtin_print, METH_FASTCALL | METH_KEYWORDS, print_doc},
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002740 BUILTIN_REPR_METHODDEF
Serhiy Storchakaaca7f572017-11-15 17:51:14 +02002741 BUILTIN_ROUND_METHODDEF
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002742 BUILTIN_SETATTR_METHODDEF
2743 BUILTIN_SORTED_METHODDEF
2744 BUILTIN_SUM_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002745 {"vars", builtin_vars, METH_VARARGS, vars_doc},
2746 {NULL, NULL},
Guido van Rossum3f5da241990-12-20 15:06:42 +00002747};
2748
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002749PyDoc_STRVAR(builtin_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002750"Built-in functions, exceptions, and other objects.\n\
2751\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002752Noteworthy: None is the `nil' object; Ellipsis represents `...' in slices.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002753
Martin v. Löwis1a214512008-06-11 05:26:20 +00002754static struct PyModuleDef builtinsmodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002755 PyModuleDef_HEAD_INIT,
2756 "builtins",
2757 builtin_doc,
2758 -1, /* multiple "initialization" just copies the module dict. */
2759 builtin_methods,
2760 NULL,
2761 NULL,
2762 NULL,
2763 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00002764};
2765
2766
Guido van Rossum25ce5661997-08-02 03:10:38 +00002767PyObject *
Victor Stinnerb45d2592019-06-20 00:05:23 +02002768_PyBuiltin_Init(PyThreadState *tstate)
Guido van Rossum25ce5661997-08-02 03:10:38 +00002769{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002770 PyObject *mod, *dict, *debug;
Benjamin Peterson42124a72012-10-30 23:41:54 -04002771
Victor Stinnerb45d2592019-06-20 00:05:23 +02002772 const PyConfig *config = &tstate->interp->config;
Victor Stinnerfbca9082018-08-30 00:50:45 +02002773
Benjamin Peterson42124a72012-10-30 23:41:54 -04002774 if (PyType_Ready(&PyFilter_Type) < 0 ||
2775 PyType_Ready(&PyMap_Type) < 0 ||
2776 PyType_Ready(&PyZip_Type) < 0)
2777 return NULL;
2778
Eric Snowd393c1b2017-09-14 12:18:12 -06002779 mod = _PyModule_CreateInitialized(&builtinsmodule, PYTHON_API_VERSION);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002780 if (mod == NULL)
2781 return NULL;
2782 dict = PyModule_GetDict(mod);
Tim Peters4b7625e2001-09-13 21:37:17 +00002783
Tim Peters7571a0f2003-03-23 17:52:28 +00002784#ifdef Py_TRACE_REFS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002785 /* "builtins" exposes a number of statically allocated objects
2786 * that, before this code was added in 2.3, never showed up in
2787 * the list of "all objects" maintained by Py_TRACE_REFS. As a
2788 * result, programs leaking references to None and False (etc)
2789 * couldn't be diagnosed by examining sys.getobjects(0).
2790 */
Tim Peters7571a0f2003-03-23 17:52:28 +00002791#define ADD_TO_ALL(OBJECT) _Py_AddToAllObjects((PyObject *)(OBJECT), 0)
2792#else
2793#define ADD_TO_ALL(OBJECT) (void)0
2794#endif
2795
Tim Peters4b7625e2001-09-13 21:37:17 +00002796#define SETBUILTIN(NAME, OBJECT) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002797 if (PyDict_SetItemString(dict, NAME, (PyObject *)OBJECT) < 0) \
2798 return NULL; \
2799 ADD_TO_ALL(OBJECT)
Tim Peters4b7625e2001-09-13 21:37:17 +00002800
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002801 SETBUILTIN("None", Py_None);
2802 SETBUILTIN("Ellipsis", Py_Ellipsis);
2803 SETBUILTIN("NotImplemented", Py_NotImplemented);
2804 SETBUILTIN("False", Py_False);
2805 SETBUILTIN("True", Py_True);
2806 SETBUILTIN("bool", &PyBool_Type);
2807 SETBUILTIN("memoryview", &PyMemoryView_Type);
2808 SETBUILTIN("bytearray", &PyByteArray_Type);
2809 SETBUILTIN("bytes", &PyBytes_Type);
2810 SETBUILTIN("classmethod", &PyClassMethod_Type);
2811 SETBUILTIN("complex", &PyComplex_Type);
2812 SETBUILTIN("dict", &PyDict_Type);
2813 SETBUILTIN("enumerate", &PyEnum_Type);
2814 SETBUILTIN("filter", &PyFilter_Type);
2815 SETBUILTIN("float", &PyFloat_Type);
2816 SETBUILTIN("frozenset", &PyFrozenSet_Type);
2817 SETBUILTIN("property", &PyProperty_Type);
2818 SETBUILTIN("int", &PyLong_Type);
2819 SETBUILTIN("list", &PyList_Type);
2820 SETBUILTIN("map", &PyMap_Type);
2821 SETBUILTIN("object", &PyBaseObject_Type);
2822 SETBUILTIN("range", &PyRange_Type);
2823 SETBUILTIN("reversed", &PyReversed_Type);
2824 SETBUILTIN("set", &PySet_Type);
2825 SETBUILTIN("slice", &PySlice_Type);
2826 SETBUILTIN("staticmethod", &PyStaticMethod_Type);
2827 SETBUILTIN("str", &PyUnicode_Type);
2828 SETBUILTIN("super", &PySuper_Type);
2829 SETBUILTIN("tuple", &PyTuple_Type);
2830 SETBUILTIN("type", &PyType_Type);
2831 SETBUILTIN("zip", &PyZip_Type);
Victor Stinnerfbca9082018-08-30 00:50:45 +02002832 debug = PyBool_FromLong(config->optimization_level == 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002833 if (PyDict_SetItemString(dict, "__debug__", debug) < 0) {
Serhiy Storchakacfdfbb42016-06-18 09:44:03 +03002834 Py_DECREF(debug);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002835 return NULL;
2836 }
Serhiy Storchakacfdfbb42016-06-18 09:44:03 +03002837 Py_DECREF(debug);
Barry Warsaw757af0e1997-08-29 22:13:51 +00002838
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002839 return mod;
Tim Peters7571a0f2003-03-23 17:52:28 +00002840#undef ADD_TO_ALL
Tim Peters4b7625e2001-09-13 21:37:17 +00002841#undef SETBUILTIN
Guido van Rossum3f5da241990-12-20 15:06:42 +00002842}