blob: dec2984a068df273d86210904a79a7dc2e5e6b6d [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 Stinnerc96d00e2020-06-22 18:02:49 +02007#include "pycore_object.h" // _Py_AddToAllObjects()
Victor Stinner384621c2020-06-22 17:27:35 +02008#include "pycore_pyerrors.h" // _PyErr_NoMemory()
9#include "pycore_pystate.h" // _PyThreadState_GET()
10#include "pycore_tuple.h" // _PyTuple_FromArray()
Mark Shannon0332e562021-02-01 10:42:03 +000011#include "pycore_ceval.h" // _PyEval_Vector()
Guido van Rossum6bf62da1997-04-11 20:37:35 +000012
Victor Stinnerbd303c12013-11-07 23:07:29 +010013_Py_IDENTIFIER(__builtins__);
14_Py_IDENTIFIER(__dict__);
15_Py_IDENTIFIER(__prepare__);
16_Py_IDENTIFIER(__round__);
Ivan Levkivskyi2b5fd1e2017-12-14 23:32:56 +010017_Py_IDENTIFIER(__mro_entries__);
Victor Stinnerbd303c12013-11-07 23:07:29 +010018_Py_IDENTIFIER(encoding);
19_Py_IDENTIFIER(errors);
Martin v. Löwisbd928fe2011-10-14 10:20:37 +020020_Py_IDENTIFIER(fileno);
21_Py_IDENTIFIER(flush);
Victor Stinnerbd303c12013-11-07 23:07:29 +010022_Py_IDENTIFIER(metaclass);
23_Py_IDENTIFIER(sort);
24_Py_IDENTIFIER(stdin);
25_Py_IDENTIFIER(stdout);
26_Py_IDENTIFIER(stderr);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +020027
Serhiy Storchaka1009bf12015-04-03 23:53:51 +030028#include "clinic/bltinmodule.c.h"
29
Ivan Levkivskyi2b5fd1e2017-12-14 23:32:56 +010030static PyObject*
Victor Stinner05d68a82018-01-18 11:15:25 +010031update_bases(PyObject *bases, PyObject *const *args, Py_ssize_t nargs)
Ivan Levkivskyi2b5fd1e2017-12-14 23:32:56 +010032{
Victor Stinner05d68a82018-01-18 11:15:25 +010033 Py_ssize_t i, j;
Ivan Levkivskyi2b5fd1e2017-12-14 23:32:56 +010034 PyObject *base, *meth, *new_base, *result, *new_bases = NULL;
Ivan Levkivskyi2b5fd1e2017-12-14 23:32:56 +010035 assert(PyTuple_Check(bases));
36
37 for (i = 0; i < nargs; i++) {
38 base = args[i];
39 if (PyType_Check(base)) {
40 if (new_bases) {
41 /* If we already have made a replacement, then we append every normal base,
42 otherwise just skip it. */
43 if (PyList_Append(new_bases, base) < 0) {
44 goto error;
45 }
46 }
47 continue;
48 }
Serhiy Storchakaf320be72018-01-25 10:49:40 +020049 if (_PyObject_LookupAttrId(base, &PyId___mro_entries__, &meth) < 0) {
50 goto error;
51 }
Ivan Levkivskyi2b5fd1e2017-12-14 23:32:56 +010052 if (!meth) {
Ivan Levkivskyi2b5fd1e2017-12-14 23:32:56 +010053 if (new_bases) {
54 if (PyList_Append(new_bases, base) < 0) {
55 goto error;
56 }
57 }
58 continue;
59 }
Petr Viktorinffd97532020-02-11 17:46:57 +010060 new_base = PyObject_CallOneArg(meth, bases);
Ivan Levkivskyi2b5fd1e2017-12-14 23:32:56 +010061 Py_DECREF(meth);
62 if (!new_base) {
63 goto error;
64 }
65 if (!PyTuple_Check(new_base)) {
66 PyErr_SetString(PyExc_TypeError,
67 "__mro_entries__ must return a tuple");
68 Py_DECREF(new_base);
69 goto error;
70 }
71 if (!new_bases) {
72 /* If this is a first successful replacement, create new_bases list and
73 copy previously encountered bases. */
74 if (!(new_bases = PyList_New(i))) {
75 goto error;
76 }
77 for (j = 0; j < i; j++) {
78 base = args[j];
79 PyList_SET_ITEM(new_bases, j, base);
80 Py_INCREF(base);
81 }
82 }
83 j = PyList_GET_SIZE(new_bases);
84 if (PyList_SetSlice(new_bases, j, j, new_base) < 0) {
85 goto error;
86 }
87 Py_DECREF(new_base);
88 }
89 if (!new_bases) {
90 return bases;
91 }
92 result = PyList_AsTuple(new_bases);
93 Py_DECREF(new_bases);
94 return result;
95
96error:
97 Py_XDECREF(new_bases);
98 return NULL;
99}
100
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000101/* AC: cannot convert yet, waiting for *args support */
Guido van Rossum79f25d91997-04-29 20:08:16 +0000102static PyObject *
Serhiy Storchakaa5552f02017-12-15 13:11:11 +0200103builtin___build_class__(PyObject *self, PyObject *const *args, Py_ssize_t nargs,
Victor Stinner773dc6d2017-01-16 23:46:26 +0100104 PyObject *kwnames)
Guido van Rossum52cc1d82007-03-18 15:41:51 +0000105{
Ivan Levkivskyi2b5fd1e2017-12-14 23:32:56 +0100106 PyObject *func, *name, *bases, *mkw, *meta, *winner, *prep, *ns, *orig_bases;
Nick Coghlan19d24672016-12-05 16:47:55 +1000107 PyObject *cls = NULL, *cell = NULL;
Victor Stinner0c39b1b2015-03-18 15:02:06 +0100108 int isclass = 0; /* initialize to prevent gcc warning */
Guido van Rossum52cc1d82007-03-18 15:41:51 +0000109
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000110 if (nargs < 2) {
111 PyErr_SetString(PyExc_TypeError,
112 "__build_class__: not enough arguments");
113 return NULL;
114 }
Victor Stinner773dc6d2017-01-16 23:46:26 +0100115 func = args[0]; /* Better be callable */
Benjamin Petersone8e14592013-05-16 14:37:25 -0500116 if (!PyFunction_Check(func)) {
117 PyErr_SetString(PyExc_TypeError,
Zachary Ware9b338722014-08-05 14:01:10 -0500118 "__build_class__: func must be a function");
Benjamin Petersone8e14592013-05-16 14:37:25 -0500119 return NULL;
120 }
Victor Stinner773dc6d2017-01-16 23:46:26 +0100121 name = args[1];
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000122 if (!PyUnicode_Check(name)) {
123 PyErr_SetString(PyExc_TypeError,
124 "__build_class__: name is not a string");
125 return NULL;
126 }
Sergey Fedoseevf1b9abe2019-02-26 02:37:26 +0500127 orig_bases = _PyTuple_FromArray(args + 2, nargs - 2);
Ivan Levkivskyi2b5fd1e2017-12-14 23:32:56 +0100128 if (orig_bases == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000129 return NULL;
Guido van Rossum52cc1d82007-03-18 15:41:51 +0000130
Ivan Levkivskyi2b5fd1e2017-12-14 23:32:56 +0100131 bases = update_bases(orig_bases, args + 2, nargs - 2);
132 if (bases == NULL) {
133 Py_DECREF(orig_bases);
134 return NULL;
135 }
136
Victor Stinner773dc6d2017-01-16 23:46:26 +0100137 if (kwnames == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000138 meta = NULL;
139 mkw = NULL;
140 }
141 else {
Victor Stinner773dc6d2017-01-16 23:46:26 +0100142 mkw = _PyStack_AsDict(args + nargs, kwnames);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000143 if (mkw == NULL) {
144 Py_DECREF(bases);
145 return NULL;
Guido van Rossum52cc1d82007-03-18 15:41:51 +0000146 }
Victor Stinner773dc6d2017-01-16 23:46:26 +0100147
Serhiy Storchakaa24107b2019-02-25 17:59:46 +0200148 meta = _PyDict_GetItemIdWithError(mkw, &PyId_metaclass);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000149 if (meta != NULL) {
150 Py_INCREF(meta);
Victor Stinnerae9f1612013-11-06 22:46:51 +0100151 if (_PyDict_DelItemId(mkw, &PyId_metaclass) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000152 Py_DECREF(meta);
153 Py_DECREF(mkw);
154 Py_DECREF(bases);
155 return NULL;
156 }
Nick Coghlande31b192011-10-23 22:04:16 +1000157 /* metaclass is explicitly given, check if it's indeed a class */
158 isclass = PyType_Check(meta);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000159 }
Serhiy Storchakaa24107b2019-02-25 17:59:46 +0200160 else if (PyErr_Occurred()) {
161 Py_DECREF(mkw);
162 Py_DECREF(bases);
163 return NULL;
164 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000165 }
166 if (meta == NULL) {
Nick Coghlande31b192011-10-23 22:04:16 +1000167 /* if there are no bases, use type: */
168 if (PyTuple_GET_SIZE(bases) == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000169 meta = (PyObject *) (&PyType_Type);
Nick Coghlande31b192011-10-23 22:04:16 +1000170 }
171 /* else get the type of the first base */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000172 else {
173 PyObject *base0 = PyTuple_GET_ITEM(bases, 0);
Victor Stinnera102ed72020-02-07 02:24:48 +0100174 meta = (PyObject *)Py_TYPE(base0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000175 }
176 Py_INCREF(meta);
Nick Coghlande31b192011-10-23 22:04:16 +1000177 isclass = 1; /* meta is really a class */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000178 }
Nick Coghlan9715d262011-10-23 22:36:42 +1000179
Nick Coghlande31b192011-10-23 22:04:16 +1000180 if (isclass) {
181 /* meta is really a class, so check for a more derived
182 metaclass, or possible metaclass conflicts: */
183 winner = (PyObject *)_PyType_CalculateMetaclass((PyTypeObject *)meta,
184 bases);
185 if (winner == NULL) {
186 Py_DECREF(meta);
187 Py_XDECREF(mkw);
188 Py_DECREF(bases);
189 return NULL;
190 }
191 if (winner != meta) {
192 Py_DECREF(meta);
193 meta = winner;
194 Py_INCREF(meta);
195 }
196 }
197 /* else: meta is not a class, so we cannot do the metaclass
198 calculation, so we will use the explicitly given object as it is */
Serhiy Storchakaf320be72018-01-25 10:49:40 +0200199 if (_PyObject_LookupAttrId(meta, &PyId___prepare__, &prep) < 0) {
200 ns = NULL;
201 }
202 else if (prep == NULL) {
203 ns = PyDict_New();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000204 }
205 else {
Victor Stinner463b86a2016-08-22 23:33:13 +0200206 PyObject *pargs[2] = {name, bases};
Petr Viktorinffd97532020-02-11 17:46:57 +0100207 ns = PyObject_VectorcallDict(prep, pargs, 2, mkw);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000208 Py_DECREF(prep);
209 }
210 if (ns == NULL) {
211 Py_DECREF(meta);
212 Py_XDECREF(mkw);
213 Py_DECREF(bases);
214 return NULL;
215 }
Oren Milman5837d042017-09-27 17:04:37 +0300216 if (!PyMapping_Check(ns)) {
217 PyErr_Format(PyExc_TypeError,
218 "%.200s.__prepare__() must return a mapping, not %.200s",
219 isclass ? ((PyTypeObject *)meta)->tp_name : "<metaclass>",
220 Py_TYPE(ns)->tp_name);
221 goto error;
222 }
Mark Shannon0332e562021-02-01 10:42:03 +0000223 PyFrameConstructor *f = PyFunction_AS_FRAME_CONSTRUCTOR(func);
224 PyThreadState *tstate = PyThreadState_GET();
225 cell = _PyEval_Vector(tstate, f, ns, NULL, 0, NULL);
Nick Coghlan19d24672016-12-05 16:47:55 +1000226 if (cell != NULL) {
Ivan Levkivskyi2b5fd1e2017-12-14 23:32:56 +0100227 if (bases != orig_bases) {
228 if (PyMapping_SetItemString(ns, "__orig_bases__", orig_bases) < 0) {
229 goto error;
230 }
231 }
Victor Stinnerd1c2a8e2016-08-23 01:34:35 +0200232 PyObject *margs[3] = {name, bases, ns};
Petr Viktorinffd97532020-02-11 17:46:57 +0100233 cls = PyObject_VectorcallDict(meta, margs, 3, mkw);
Nick Coghlan19d24672016-12-05 16:47:55 +1000234 if (cls != NULL && PyType_Check(cls) && PyCell_Check(cell)) {
235 PyObject *cell_cls = PyCell_GET(cell);
236 if (cell_cls != cls) {
Nick Coghlan19d24672016-12-05 16:47:55 +1000237 if (cell_cls == NULL) {
238 const char *msg =
239 "__class__ not set defining %.200R as %.200R. "
240 "Was __classcell__ propagated to type.__new__?";
Serhiy Storchakaf5e7b192018-05-20 08:48:12 +0300241 PyErr_Format(PyExc_RuntimeError, msg, name, cls);
Nick Coghlan19d24672016-12-05 16:47:55 +1000242 } else {
243 const char *msg =
244 "__class__ set to %.200R defining %.200R as %.200R";
245 PyErr_Format(PyExc_TypeError, msg, cell_cls, name, cls);
Nick Coghlan19d24672016-12-05 16:47:55 +1000246 }
Serhiy Storchakaf5e7b192018-05-20 08:48:12 +0300247 Py_DECREF(cls);
248 cls = NULL;
249 goto error;
Nick Coghlan19d24672016-12-05 16:47:55 +1000250 }
251 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000252 }
Nick Coghlan19d24672016-12-05 16:47:55 +1000253error:
254 Py_XDECREF(cell);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000255 Py_DECREF(ns);
256 Py_DECREF(meta);
257 Py_XDECREF(mkw);
258 Py_DECREF(bases);
Ivan Levkivskyi2b5fd1e2017-12-14 23:32:56 +0100259 if (bases != orig_bases) {
260 Py_DECREF(orig_bases);
261 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000262 return cls;
Guido van Rossum52cc1d82007-03-18 15:41:51 +0000263}
264
265PyDoc_STRVAR(build_class_doc,
Pablo Galindoe3babbd2019-10-13 16:35:41 +0100266"__build_class__(func, name, /, *bases, [metaclass], **kwds) -> class\n\
Guido van Rossum52cc1d82007-03-18 15:41:51 +0000267\n\
268Internal helper function used by the class statement.");
269
270static PyObject *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000271builtin___import__(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000272{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000273 static char *kwlist[] = {"name", "globals", "locals", "fromlist",
274 "level", 0};
Victor Stinnerfe93faf2011-03-14 15:54:52 -0400275 PyObject *name, *globals = NULL, *locals = NULL, *fromlist = NULL;
Brett Cannonfd074152012-04-14 14:10:13 -0400276 int level = 0;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000277
Victor Stinnerfe93faf2011-03-14 15:54:52 -0400278 if (!PyArg_ParseTupleAndKeywords(args, kwds, "U|OOOi:__import__",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000279 kwlist, &name, &globals, &locals, &fromlist, &level))
280 return NULL;
Victor Stinnerfe93faf2011-03-14 15:54:52 -0400281 return PyImport_ImportModuleLevelObject(name, globals, locals,
282 fromlist, level);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000283}
284
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000285PyDoc_STRVAR(import_doc,
Brett Cannoncb4996a2012-08-06 16:34:44 -0400286"__import__(name, globals=None, locals=None, fromlist=(), level=0) -> module\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000287\n\
Brett Cannon5305a992010-09-27 21:08:38 +0000288Import a module. Because this function is meant for use by the Python\n\
oldk461d2252018-02-02 12:20:00 +0800289interpreter and not for general use, it is better to use\n\
Brett Cannon5305a992010-09-27 21:08:38 +0000290importlib.import_module() to programmatically import a module.\n\
291\n\
292The globals argument is only used to determine the context;\n\
293they are not modified. The locals argument is unused. The fromlist\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000294should be a list of names to emulate ``from name import ...'', or an\n\
295empty list to emulate ``import name''.\n\
296When importing a module from a package, note that __import__('A.B', ...)\n\
297returns package A when fromlist is empty, but its submodule B when\n\
oldk461d2252018-02-02 12:20:00 +0800298fromlist is not empty. The level argument is used to determine whether to\n\
299perform absolute or relative imports: 0 is absolute, while a positive number\n\
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000300is the number of parent directories to search relative to the current module.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000301
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000302
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000303/*[clinic input]
304abs as builtin_abs
305
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300306 x: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000307 /
308
309Return the absolute value of the argument.
310[clinic start generated code]*/
311
Guido van Rossum79f25d91997-04-29 20:08:16 +0000312static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300313builtin_abs(PyObject *module, PyObject *x)
314/*[clinic end generated code: output=b1b433b9e51356f5 input=bed4ca14e29c20d1]*/
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000315{
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000316 return PyNumber_Absolute(x);
Guido van Rossum3f5da241990-12-20 15:06:42 +0000317}
318
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000319/*[clinic input]
320all as builtin_all
321
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300322 iterable: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000323 /
324
325Return True if bool(x) is True for all values x in the iterable.
326
327If the iterable is empty, return True.
328[clinic start generated code]*/
329
Raymond Hettinger96229b12005-03-11 06:49:40 +0000330static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300331builtin_all(PyObject *module, PyObject *iterable)
332/*[clinic end generated code: output=ca2a7127276f79b3 input=1a7c5d1bc3438a21]*/
Raymond Hettinger96229b12005-03-11 06:49:40 +0000333{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000334 PyObject *it, *item;
335 PyObject *(*iternext)(PyObject *);
336 int cmp;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000337
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000338 it = PyObject_GetIter(iterable);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000339 if (it == NULL)
340 return NULL;
341 iternext = *Py_TYPE(it)->tp_iternext;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000342
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000343 for (;;) {
344 item = iternext(it);
345 if (item == NULL)
346 break;
347 cmp = PyObject_IsTrue(item);
348 Py_DECREF(item);
349 if (cmp < 0) {
350 Py_DECREF(it);
351 return NULL;
352 }
353 if (cmp == 0) {
354 Py_DECREF(it);
355 Py_RETURN_FALSE;
356 }
357 }
358 Py_DECREF(it);
359 if (PyErr_Occurred()) {
360 if (PyErr_ExceptionMatches(PyExc_StopIteration))
361 PyErr_Clear();
362 else
363 return NULL;
364 }
365 Py_RETURN_TRUE;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000366}
367
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000368/*[clinic input]
369any as builtin_any
370
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300371 iterable: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000372 /
373
374Return True if bool(x) is True for any x in the iterable.
375
376If the iterable is empty, return False.
377[clinic start generated code]*/
378
Raymond Hettinger96229b12005-03-11 06:49:40 +0000379static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300380builtin_any(PyObject *module, PyObject *iterable)
381/*[clinic end generated code: output=fa65684748caa60e input=41d7451c23384f24]*/
Raymond Hettinger96229b12005-03-11 06:49:40 +0000382{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000383 PyObject *it, *item;
384 PyObject *(*iternext)(PyObject *);
385 int cmp;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000386
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000387 it = PyObject_GetIter(iterable);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000388 if (it == NULL)
389 return NULL;
390 iternext = *Py_TYPE(it)->tp_iternext;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000391
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000392 for (;;) {
393 item = iternext(it);
394 if (item == NULL)
395 break;
396 cmp = PyObject_IsTrue(item);
397 Py_DECREF(item);
398 if (cmp < 0) {
399 Py_DECREF(it);
400 return NULL;
401 }
Raymond Hettinger5098b582015-10-09 00:42:47 -0400402 if (cmp > 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000403 Py_DECREF(it);
404 Py_RETURN_TRUE;
405 }
406 }
407 Py_DECREF(it);
408 if (PyErr_Occurred()) {
409 if (PyErr_ExceptionMatches(PyExc_StopIteration))
410 PyErr_Clear();
411 else
412 return NULL;
413 }
414 Py_RETURN_FALSE;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000415}
416
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000417/*[clinic input]
418ascii as builtin_ascii
419
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300420 obj: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000421 /
422
423Return an ASCII-only representation of an object.
424
425As repr(), return a string containing a printable representation of an
426object, but escape the non-ASCII characters in the string returned by
427repr() using \\x, \\u or \\U escapes. This generates a string similar
428to that returned by repr() in Python 2.
429[clinic start generated code]*/
430
Georg Brandl559e5d72008-06-11 18:37:52 +0000431static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300432builtin_ascii(PyObject *module, PyObject *obj)
433/*[clinic end generated code: output=6d37b3f0984c7eb9 input=4c62732e1b3a3cc9]*/
Georg Brandl559e5d72008-06-11 18:37:52 +0000434{
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000435 return PyObject_ASCII(obj);
Georg Brandl559e5d72008-06-11 18:37:52 +0000436}
437
Georg Brandl559e5d72008-06-11 18:37:52 +0000438
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000439/*[clinic input]
440bin as builtin_bin
441
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300442 number: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000443 /
444
445Return the binary representation of an integer.
446
447 >>> bin(2796202)
448 '0b1010101010101010101010'
449[clinic start generated code]*/
450
Guido van Rossum79f25d91997-04-29 20:08:16 +0000451static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300452builtin_bin(PyObject *module, PyObject *number)
453/*[clinic end generated code: output=b6fc4ad5e649f4f7 input=53f8a0264bacaf90]*/
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000454{
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000455 return PyNumber_ToBase(number, 2);
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000456}
457
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000458
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000459/*[clinic input]
460callable as builtin_callable
461
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300462 obj: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000463 /
464
465Return whether the object is callable (i.e., some kind of function).
466
467Note that classes are callable, as are instances of classes with a
468__call__() method.
469[clinic start generated code]*/
470
Antoine Pitroue71362d2010-11-27 22:00:11 +0000471static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300472builtin_callable(PyObject *module, PyObject *obj)
473/*[clinic end generated code: output=2b095d59d934cb7e input=1423bab99cc41f58]*/
Antoine Pitroue71362d2010-11-27 22:00:11 +0000474{
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000475 return PyBool_FromLong((long)PyCallable_Check(obj));
Antoine Pitroue71362d2010-11-27 22:00:11 +0000476}
477
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400478static PyObject *
Serhiy Storchakaa5552f02017-12-15 13:11:11 +0200479builtin_breakpoint(PyObject *self, PyObject *const *args, Py_ssize_t nargs, PyObject *keywords)
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400480{
481 PyObject *hook = PySys_GetObject("breakpointhook");
482
483 if (hook == NULL) {
484 PyErr_SetString(PyExc_RuntimeError, "lost sys.breakpointhook");
485 return NULL;
486 }
Steve Dower60419a72019-06-24 08:42:54 -0700487
488 if (PySys_Audit("builtins.breakpoint", "O", hook) < 0) {
489 return NULL;
490 }
491
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400492 Py_INCREF(hook);
Petr Viktorinffd97532020-02-11 17:46:57 +0100493 PyObject *retval = PyObject_Vectorcall(hook, args, nargs, keywords);
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400494 Py_DECREF(hook);
495 return retval;
496}
497
498PyDoc_STRVAR(breakpoint_doc,
499"breakpoint(*args, **kws)\n\
500\n\
501Call sys.breakpointhook(*args, **kws). sys.breakpointhook() must accept\n\
502whatever arguments are passed.\n\
503\n\
504By default, this drops you into the pdb debugger.");
Antoine Pitroue71362d2010-11-27 22:00:11 +0000505
Raymond Hettinger17301e92008-03-13 00:19:26 +0000506typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000507 PyObject_HEAD
508 PyObject *func;
509 PyObject *it;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000510} filterobject;
511
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000512static PyObject *
Raymond Hettinger17301e92008-03-13 00:19:26 +0000513filter_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
Guido van Rossum12d12c51993-10-26 17:58:25 +0000514{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000515 PyObject *func, *seq;
516 PyObject *it;
517 filterobject *lz;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000518
Serhiy Storchaka6cca5c82017-06-08 14:41:19 +0300519 if (type == &PyFilter_Type && !_PyArg_NoKeywords("filter", kwds))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000520 return NULL;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000521
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000522 if (!PyArg_UnpackTuple(args, "filter", 2, 2, &func, &seq))
523 return NULL;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000524
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000525 /* Get iterator. */
526 it = PyObject_GetIter(seq);
527 if (it == NULL)
528 return NULL;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000529
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000530 /* create filterobject structure */
531 lz = (filterobject *)type->tp_alloc(type, 0);
532 if (lz == NULL) {
533 Py_DECREF(it);
534 return NULL;
535 }
536 Py_INCREF(func);
537 lz->func = func;
538 lz->it = it;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000539
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000540 return (PyObject *)lz;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000541}
542
543static void
544filter_dealloc(filterobject *lz)
545{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000546 PyObject_GC_UnTrack(lz);
547 Py_XDECREF(lz->func);
548 Py_XDECREF(lz->it);
549 Py_TYPE(lz)->tp_free(lz);
Raymond Hettinger17301e92008-03-13 00:19:26 +0000550}
551
552static int
553filter_traverse(filterobject *lz, visitproc visit, void *arg)
554{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000555 Py_VISIT(lz->it);
556 Py_VISIT(lz->func);
557 return 0;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000558}
559
560static PyObject *
561filter_next(filterobject *lz)
562{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000563 PyObject *item;
564 PyObject *it = lz->it;
565 long ok;
566 PyObject *(*iternext)(PyObject *);
Raymond Hettingerbd5f0e82015-10-09 01:34:08 -0400567 int checktrue = lz->func == Py_None || lz->func == (PyObject *)&PyBool_Type;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000568
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000569 iternext = *Py_TYPE(it)->tp_iternext;
570 for (;;) {
571 item = iternext(it);
572 if (item == NULL)
573 return NULL;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000574
Raymond Hettingerbd5f0e82015-10-09 01:34:08 -0400575 if (checktrue) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000576 ok = PyObject_IsTrue(item);
577 } else {
578 PyObject *good;
Petr Viktorinffd97532020-02-11 17:46:57 +0100579 good = PyObject_CallOneArg(lz->func, item);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000580 if (good == NULL) {
581 Py_DECREF(item);
582 return NULL;
583 }
584 ok = PyObject_IsTrue(good);
585 Py_DECREF(good);
586 }
Antoine Pitrou6f430e42012-08-15 23:18:25 +0200587 if (ok > 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000588 return item;
589 Py_DECREF(item);
Antoine Pitrou6f430e42012-08-15 23:18:25 +0200590 if (ok < 0)
591 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000592 }
Guido van Rossum12d12c51993-10-26 17:58:25 +0000593}
594
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +0000595static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +0530596filter_reduce(filterobject *lz, PyObject *Py_UNUSED(ignored))
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +0000597{
598 return Py_BuildValue("O(OO)", Py_TYPE(lz), lz->func, lz->it);
599}
600
601PyDoc_STRVAR(reduce_doc, "Return state information for pickling.");
602
603static PyMethodDef filter_methods[] = {
604 {"__reduce__", (PyCFunction)filter_reduce, METH_NOARGS, reduce_doc},
605 {NULL, NULL} /* sentinel */
606};
607
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000608PyDoc_STRVAR(filter_doc,
Georg Brandld11ae5d2008-05-16 13:27:32 +0000609"filter(function or None, iterable) --> filter object\n\
Guido van Rossumc1f779c2007-07-03 08:25:58 +0000610\n\
Georg Brandld11ae5d2008-05-16 13:27:32 +0000611Return an iterator yielding those items of iterable for which function(item)\n\
Raymond Hettinger17301e92008-03-13 00:19:26 +0000612is true. If function is None, return the items that are true.");
613
614PyTypeObject PyFilter_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000615 PyVarObject_HEAD_INIT(&PyType_Type, 0)
616 "filter", /* tp_name */
617 sizeof(filterobject), /* tp_basicsize */
618 0, /* tp_itemsize */
619 /* methods */
620 (destructor)filter_dealloc, /* tp_dealloc */
Jeroen Demeyer530f5062019-05-31 04:13:39 +0200621 0, /* tp_vectorcall_offset */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000622 0, /* tp_getattr */
623 0, /* tp_setattr */
Jeroen Demeyer530f5062019-05-31 04:13:39 +0200624 0, /* tp_as_async */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000625 0, /* tp_repr */
626 0, /* tp_as_number */
627 0, /* tp_as_sequence */
628 0, /* tp_as_mapping */
629 0, /* tp_hash */
630 0, /* tp_call */
631 0, /* tp_str */
632 PyObject_GenericGetAttr, /* tp_getattro */
633 0, /* tp_setattro */
634 0, /* tp_as_buffer */
635 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
636 Py_TPFLAGS_BASETYPE, /* tp_flags */
637 filter_doc, /* tp_doc */
638 (traverseproc)filter_traverse, /* tp_traverse */
639 0, /* tp_clear */
640 0, /* tp_richcompare */
641 0, /* tp_weaklistoffset */
642 PyObject_SelfIter, /* tp_iter */
643 (iternextfunc)filter_next, /* tp_iternext */
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +0000644 filter_methods, /* tp_methods */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000645 0, /* tp_members */
646 0, /* tp_getset */
647 0, /* tp_base */
648 0, /* tp_dict */
649 0, /* tp_descr_get */
650 0, /* tp_descr_set */
651 0, /* tp_dictoffset */
652 0, /* tp_init */
653 PyType_GenericAlloc, /* tp_alloc */
654 filter_new, /* tp_new */
655 PyObject_GC_Del, /* tp_free */
Raymond Hettinger17301e92008-03-13 00:19:26 +0000656};
657
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000658
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000659/*[clinic input]
660format as builtin_format
661
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300662 value: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000663 format_spec: unicode(c_default="NULL") = ''
664 /
665
666Return value.__format__(format_spec)
667
Amit Kumar2e6bb442017-05-29 06:32:26 +0530668format_spec defaults to the empty string.
669See the Format Specification Mini-Language section of help('FORMATTING') for
670details.
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000671[clinic start generated code]*/
672
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000673static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300674builtin_format_impl(PyObject *module, PyObject *value, PyObject *format_spec)
Amit Kumar2e6bb442017-05-29 06:32:26 +0530675/*[clinic end generated code: output=2f40bdfa4954b077 input=88339c93ea522b33]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000676{
Eric Smith8fd3eba2008-02-17 19:48:00 +0000677 return PyObject_Format(value, format_spec);
Eric Smith8c663262007-08-25 02:26:07 +0000678}
679
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000680/*[clinic input]
681chr as builtin_chr
682
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300683 i: int
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000684 /
685
686Return a Unicode string of one character with ordinal i; 0 <= i <= 0x10ffff.
687[clinic start generated code]*/
688
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000689static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300690builtin_chr_impl(PyObject *module, int i)
691/*[clinic end generated code: output=c733afcd200afcb7 input=3f604ef45a70750d]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000692{
693 return PyUnicode_FromOrdinal(i);
694}
Guido van Rossum09095f32000-03-10 23:00:52 +0000695
696
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000697/*[clinic input]
698compile as builtin_compile
699
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300700 source: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000701 filename: object(converter="PyUnicode_FSDecoder")
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300702 mode: str
703 flags: int = 0
Serhiy Storchaka202fda52017-03-12 10:10:47 +0200704 dont_inherit: bool(accept={int}) = False
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300705 optimize: int = -1
Victor Stinnerefdf6ca2019-06-12 02:52:16 +0200706 *
707 _feature_version as feature_version: int = -1
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000708
709Compile source into a code object that can be executed by exec() or eval().
710
711The source code may represent a Python module, statement or expression.
712The filename will be used for run-time error messages.
713The mode must be 'exec' to compile a module, 'single' to compile a
714single (interactive) statement, or 'eval' to compile an expression.
715The flags argument, if present, controls which future statements influence
716the compilation of the code.
Serhiy Storchaka8b2e8b62015-05-30 11:30:39 +0300717The dont_inherit argument, if true, stops the compilation inheriting
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000718the effects of any future statements in effect in the code calling
Serhiy Storchaka8b2e8b62015-05-30 11:30:39 +0300719compile; if absent or false these statements do influence the compilation,
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000720in addition to any features explicitly specified.
721[clinic start generated code]*/
722
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000723static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300724builtin_compile_impl(PyObject *module, PyObject *source, PyObject *filename,
725 const char *mode, int flags, int dont_inherit,
Guido van Rossum495da292019-03-07 12:38:08 -0800726 int optimize, int feature_version)
Victor Stinnerefdf6ca2019-06-12 02:52:16 +0200727/*[clinic end generated code: output=b0c09c84f116d3d7 input=40171fb92c1d580d]*/
Guido van Rossum5b722181993-03-30 17:46:03 +0000728{
Martin Panter61d6e4a2015-11-07 02:56:11 +0000729 PyObject *source_copy;
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +0200730 const char *str;
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000731 int compile_mode = -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000732 int is_ast;
Guido van Rossumdcfcd142019-01-31 03:40:27 -0800733 int start[] = {Py_file_input, Py_eval_input, Py_single_input, Py_func_type_input};
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000734 PyObject *result;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000735
Victor Stinner37d66d72019-06-13 02:16:41 +0200736 PyCompilerFlags cf = _PyCompilerFlags_INIT;
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000737 cf.cf_flags = flags | PyCF_SOURCE_IS_UTF8;
Guido van Rossum495da292019-03-07 12:38:08 -0800738 if (feature_version >= 0 && (flags & PyCF_ONLY_AST)) {
739 cf.cf_feature_version = feature_version;
740 }
Tim Peters6cd6a822001-08-17 22:11:27 +0000741
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000742 if (flags &
Batuhan Taşkaya44540572020-04-22 19:09:03 +0300743 ~(PyCF_MASK | PyCF_MASK_OBSOLETE | PyCF_COMPILE_MASK))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000744 {
745 PyErr_SetString(PyExc_ValueError,
746 "compile(): unrecognised flags");
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000747 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000748 }
749 /* XXX Warn if (supplied_flags & PyCF_MASK_OBSOLETE) != 0? */
Tim Peters6cd6a822001-08-17 22:11:27 +0000750
Georg Brandl8334fd92010-12-04 10:26:46 +0000751 if (optimize < -1 || optimize > 2) {
752 PyErr_SetString(PyExc_ValueError,
753 "compile(): invalid optimize value");
754 goto error;
755 }
756
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000757 if (!dont_inherit) {
758 PyEval_MergeCompilerFlags(&cf);
759 }
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000760
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000761 if (strcmp(mode, "exec") == 0)
762 compile_mode = 0;
763 else if (strcmp(mode, "eval") == 0)
764 compile_mode = 1;
765 else if (strcmp(mode, "single") == 0)
766 compile_mode = 2;
Guido van Rossumdcfcd142019-01-31 03:40:27 -0800767 else if (strcmp(mode, "func_type") == 0) {
768 if (!(flags & PyCF_ONLY_AST)) {
769 PyErr_SetString(PyExc_ValueError,
770 "compile() mode 'func_type' requires flag PyCF_ONLY_AST");
771 goto error;
772 }
773 compile_mode = 3;
774 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000775 else {
Guido van Rossumdcfcd142019-01-31 03:40:27 -0800776 const char *msg;
777 if (flags & PyCF_ONLY_AST)
778 msg = "compile() mode must be 'exec', 'eval', 'single' or 'func_type'";
779 else
780 msg = "compile() mode must be 'exec', 'eval' or 'single'";
781 PyErr_SetString(PyExc_ValueError, msg);
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000782 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000783 }
Neal Norwitzdb4115f2008-03-31 04:20:05 +0000784
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000785 is_ast = PyAST_Check(source);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000786 if (is_ast == -1)
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000787 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000788 if (is_ast) {
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000789 if (flags & PyCF_ONLY_AST) {
790 Py_INCREF(source);
791 result = source;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000792 }
793 else {
794 PyArena *arena;
795 mod_ty mod;
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000796
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000797 arena = PyArena_New();
Stefan Krah07795df2012-08-20 17:19:50 +0200798 if (arena == NULL)
799 goto error;
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000800 mod = PyAST_obj2mod(source, arena, compile_mode);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000801 if (mod == NULL) {
802 PyArena_Free(arena);
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000803 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000804 }
Benjamin Peterson832bfe22011-08-09 16:15:04 -0500805 if (!PyAST_Validate(mod)) {
806 PyArena_Free(arena);
807 goto error;
808 }
Victor Stinner14e461d2013-08-26 22:28:21 +0200809 result = (PyObject*)PyAST_CompileObject(mod, filename,
810 &cf, optimize, arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000811 PyArena_Free(arena);
812 }
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000813 goto finally;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000814 }
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000815
Dino Viehland41540692019-05-28 16:21:17 -0700816 str = _Py_SourceAsString(source, "compile", "string, bytes or AST", &cf, &source_copy);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000817 if (str == NULL)
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000818 goto error;
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000819
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000820 result = Py_CompileStringObject(str, filename, start[compile_mode], &cf, optimize);
Guido van Rossumc001c092020-04-30 12:12:19 -0700821
Martin Panter61d6e4a2015-11-07 02:56:11 +0000822 Py_XDECREF(source_copy);
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000823 goto finally;
824
825error:
826 result = NULL;
827finally:
Victor Stinner14e461d2013-08-26 22:28:21 +0200828 Py_DECREF(filename);
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000829 return result;
Guido van Rossum5b722181993-03-30 17:46:03 +0000830}
831
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000832/* AC: cannot convert yet, as needs PEP 457 group support in inspect */
Guido van Rossum79f25d91997-04-29 20:08:16 +0000833static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000834builtin_dir(PyObject *self, PyObject *args)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000835{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000836 PyObject *arg = NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000837
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000838 if (!PyArg_UnpackTuple(args, "dir", 0, 1, &arg))
839 return NULL;
840 return PyObject_Dir(arg);
Guido van Rossum3f5da241990-12-20 15:06:42 +0000841}
842
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000843PyDoc_STRVAR(dir_doc,
Tim Peters5d2b77c2001-09-03 05:47:38 +0000844"dir([object]) -> list of strings\n"
845"\n"
Georg Brandle32b4222007-03-10 22:13:27 +0000846"If called without an argument, return the names in the current scope.\n"
847"Else, return an alphabetized list of names comprising (some of) the attributes\n"
848"of the given object, and of attributes reachable from it.\n"
849"If the object supplies a method named __dir__, it will be used; otherwise\n"
850"the default dir() logic is used and returns:\n"
851" for a module object: the module's attributes.\n"
852" for a class object: its attributes, and recursively the attributes\n"
853" of its bases.\n"
Guido van Rossumd8faa362007-04-27 19:54:29 +0000854" for any other object: its attributes, its class's attributes, and\n"
Georg Brandle32b4222007-03-10 22:13:27 +0000855" recursively the attributes of its class's base classes.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000856
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000857/*[clinic input]
858divmod as builtin_divmod
Guido van Rossum6a00cd81995-01-07 12:39:01 +0000859
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300860 x: object
861 y: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000862 /
863
Zachary Ware7f227d92016-04-28 14:39:50 -0500864Return the tuple (x//y, x%y). Invariant: div*y + mod == x.
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000865[clinic start generated code]*/
866
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000867static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300868builtin_divmod_impl(PyObject *module, PyObject *x, PyObject *y)
869/*[clinic end generated code: output=b06d8a5f6e0c745e input=175ad9c84ff41a85]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000870{
871 return PyNumber_Divmod(x, y);
872}
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000873
874
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000875/*[clinic input]
876eval as builtin_eval
877
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300878 source: object
879 globals: object = None
880 locals: object = None
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000881 /
882
883Evaluate the given source in the context of globals and locals.
884
885The source may be a string representing a Python expression
886or a code object as returned by compile().
887The globals must be a dictionary and locals can be any mapping,
888defaulting to the current globals and locals.
889If only globals is given, locals defaults to it.
890[clinic start generated code]*/
891
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000892static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300893builtin_eval_impl(PyObject *module, PyObject *source, PyObject *globals,
Larry Hastings89964c42015-04-14 18:07:59 -0400894 PyObject *locals)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300895/*[clinic end generated code: output=0a0824aa70093116 input=11ee718a8640e527]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000896{
Martin Panter61d6e4a2015-11-07 02:56:11 +0000897 PyObject *result, *source_copy;
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +0200898 const char *str;
Guido van Rossum590baa41993-11-30 13:40:46 +0000899
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000900 if (locals != Py_None && !PyMapping_Check(locals)) {
901 PyErr_SetString(PyExc_TypeError, "locals must be a mapping");
902 return NULL;
903 }
904 if (globals != Py_None && !PyDict_Check(globals)) {
905 PyErr_SetString(PyExc_TypeError, PyMapping_Check(globals) ?
906 "globals must be a real dict; try eval(expr, {}, mapping)"
907 : "globals must be a dict");
908 return NULL;
909 }
910 if (globals == Py_None) {
911 globals = PyEval_GetGlobals();
Victor Stinner41bb43a2013-10-29 01:19:37 +0100912 if (locals == Py_None) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000913 locals = PyEval_GetLocals();
Victor Stinner41bb43a2013-10-29 01:19:37 +0100914 if (locals == NULL)
915 return NULL;
916 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000917 }
918 else if (locals == Py_None)
919 locals = globals;
Tim Peters9fa96be2001-08-17 23:04:59 +0000920
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000921 if (globals == NULL || locals == NULL) {
922 PyErr_SetString(PyExc_TypeError,
923 "eval must be given globals and locals "
924 "when called without a frame");
925 return NULL;
926 }
Georg Brandl77c85e62005-09-15 10:46:13 +0000927
Serhiy Storchakab510e102020-10-26 12:47:57 +0200928 int r = _PyDict_ContainsId(globals, &PyId___builtins__);
929 if (r == 0) {
930 r = _PyDict_SetItemId(globals, &PyId___builtins__,
931 PyEval_GetBuiltins());
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000932 }
Serhiy Storchakab510e102020-10-26 12:47:57 +0200933 if (r < 0) {
Serhiy Storchakaa24107b2019-02-25 17:59:46 +0200934 return NULL;
935 }
Tim Peters9fa96be2001-08-17 23:04:59 +0000936
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000937 if (PyCode_Check(source)) {
Steve Dowerb82e17e2019-05-23 08:45:22 -0700938 if (PySys_Audit("exec", "O", source) < 0) {
939 return NULL;
940 }
941
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000942 if (PyCode_GetNumFree((PyCodeObject *)source) > 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000943 PyErr_SetString(PyExc_TypeError,
Steve Dowerb82e17e2019-05-23 08:45:22 -0700944 "code object passed to eval() may not contain free variables");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000945 return NULL;
946 }
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000947 return PyEval_EvalCode(source, globals, locals);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000948 }
Tim Peters9fa96be2001-08-17 23:04:59 +0000949
Victor Stinner37d66d72019-06-13 02:16:41 +0200950 PyCompilerFlags cf = _PyCompilerFlags_INIT;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000951 cf.cf_flags = PyCF_SOURCE_IS_UTF8;
Dino Viehland41540692019-05-28 16:21:17 -0700952 str = _Py_SourceAsString(source, "eval", "string, bytes or code", &cf, &source_copy);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000953 if (str == NULL)
954 return NULL;
Just van Rossum3aaf42c2003-02-10 08:21:10 +0000955
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000956 while (*str == ' ' || *str == '\t')
957 str++;
Tim Peters9fa96be2001-08-17 23:04:59 +0000958
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000959 (void)PyEval_MergeCompilerFlags(&cf);
960 result = PyRun_StringFlags(str, Py_eval_input, globals, locals, &cf);
Martin Panter61d6e4a2015-11-07 02:56:11 +0000961 Py_XDECREF(source_copy);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000962 return result;
Guido van Rossum3f5da241990-12-20 15:06:42 +0000963}
964
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000965/*[clinic input]
966exec as builtin_exec
967
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300968 source: object
969 globals: object = None
970 locals: object = None
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000971 /
972
973Execute the given source in the context of globals and locals.
974
975The source may be a string representing one or more Python statements
976or a code object as returned by compile().
977The globals must be a dictionary and locals can be any mapping,
978defaulting to the current globals and locals.
979If only globals is given, locals defaults to it.
980[clinic start generated code]*/
981
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000982static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300983builtin_exec_impl(PyObject *module, PyObject *source, PyObject *globals,
Larry Hastings89964c42015-04-14 18:07:59 -0400984 PyObject *locals)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300985/*[clinic end generated code: output=3c90efc6ab68ef5d input=01ca3e1c01692829]*/
Georg Brandl7cae87c2006-09-06 06:51:57 +0000986{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000987 PyObject *v;
Georg Brandl2cabc562008-08-28 07:57:16 +0000988
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000989 if (globals == Py_None) {
990 globals = PyEval_GetGlobals();
991 if (locals == Py_None) {
992 locals = PyEval_GetLocals();
Victor Stinner41bb43a2013-10-29 01:19:37 +0100993 if (locals == NULL)
994 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000995 }
996 if (!globals || !locals) {
997 PyErr_SetString(PyExc_SystemError,
998 "globals and locals cannot be NULL");
999 return NULL;
1000 }
1001 }
1002 else if (locals == Py_None)
1003 locals = globals;
Georg Brandl7cae87c2006-09-06 06:51:57 +00001004
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001005 if (!PyDict_Check(globals)) {
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001006 PyErr_Format(PyExc_TypeError, "exec() globals must be a dict, not %.100s",
Victor Stinnera102ed72020-02-07 02:24:48 +01001007 Py_TYPE(globals)->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001008 return NULL;
1009 }
1010 if (!PyMapping_Check(locals)) {
1011 PyErr_Format(PyExc_TypeError,
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001012 "locals must be a mapping or None, not %.100s",
Victor Stinnera102ed72020-02-07 02:24:48 +01001013 Py_TYPE(locals)->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001014 return NULL;
1015 }
Serhiy Storchakab510e102020-10-26 12:47:57 +02001016 int r = _PyDict_ContainsId(globals, &PyId___builtins__);
1017 if (r == 0) {
1018 r = _PyDict_SetItemId(globals, &PyId___builtins__,
1019 PyEval_GetBuiltins());
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001020 }
Serhiy Storchakab510e102020-10-26 12:47:57 +02001021 if (r < 0) {
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02001022 return NULL;
1023 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001024
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001025 if (PyCode_Check(source)) {
Steve Dowerb82e17e2019-05-23 08:45:22 -07001026 if (PySys_Audit("exec", "O", source) < 0) {
1027 return NULL;
1028 }
1029
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001030 if (PyCode_GetNumFree((PyCodeObject *)source) > 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001031 PyErr_SetString(PyExc_TypeError,
1032 "code object passed to exec() may not "
1033 "contain free variables");
1034 return NULL;
1035 }
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001036 v = PyEval_EvalCode(source, globals, locals);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001037 }
1038 else {
Martin Panter61d6e4a2015-11-07 02:56:11 +00001039 PyObject *source_copy;
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +02001040 const char *str;
Victor Stinner37d66d72019-06-13 02:16:41 +02001041 PyCompilerFlags cf = _PyCompilerFlags_INIT;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001042 cf.cf_flags = PyCF_SOURCE_IS_UTF8;
Dino Viehland41540692019-05-28 16:21:17 -07001043 str = _Py_SourceAsString(source, "exec",
Martin Panter61d6e4a2015-11-07 02:56:11 +00001044 "string, bytes or code", &cf,
1045 &source_copy);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001046 if (str == NULL)
1047 return NULL;
1048 if (PyEval_MergeCompilerFlags(&cf))
1049 v = PyRun_StringFlags(str, Py_file_input, globals,
1050 locals, &cf);
1051 else
1052 v = PyRun_String(str, Py_file_input, globals, locals);
Martin Panter61d6e4a2015-11-07 02:56:11 +00001053 Py_XDECREF(source_copy);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001054 }
1055 if (v == NULL)
1056 return NULL;
1057 Py_DECREF(v);
1058 Py_RETURN_NONE;
Georg Brandl7cae87c2006-09-06 06:51:57 +00001059}
1060
Georg Brandl7cae87c2006-09-06 06:51:57 +00001061
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001062/* AC: cannot convert yet, as needs PEP 457 group support in inspect */
Guido van Rossum79f25d91997-04-29 20:08:16 +00001063static PyObject *
Serhiy Storchakaa5552f02017-12-15 13:11:11 +02001064builtin_getattr(PyObject *self, PyObject *const *args, Py_ssize_t nargs)
Guido van Rossum33894be1992-01-27 16:53:09 +00001065{
Serhiy Storchaka79342662019-01-12 08:25:41 +02001066 PyObject *v, *name, *result;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001067
Serhiy Storchaka79342662019-01-12 08:25:41 +02001068 if (!_PyArg_CheckPositional("getattr", nargs, 2, 3))
Sylvain96c7c062017-06-15 17:05:23 +02001069 return NULL;
1070
Serhiy Storchaka79342662019-01-12 08:25:41 +02001071 v = args[0];
1072 name = args[1];
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001073 if (!PyUnicode_Check(name)) {
1074 PyErr_SetString(PyExc_TypeError,
1075 "getattr(): attribute name must be string");
1076 return NULL;
1077 }
Serhiy Storchaka79342662019-01-12 08:25:41 +02001078 if (nargs > 2) {
Serhiy Storchakaf320be72018-01-25 10:49:40 +02001079 if (_PyObject_LookupAttr(v, name, &result) == 0) {
Serhiy Storchaka79342662019-01-12 08:25:41 +02001080 PyObject *dflt = args[2];
INADA Naoki378edee2018-01-16 20:52:41 +09001081 Py_INCREF(dflt);
1082 return dflt;
1083 }
1084 }
1085 else {
1086 result = PyObject_GetAttr(v, name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001087 }
1088 return result;
Guido van Rossum9bfef441993-03-29 10:43:31 +00001089}
1090
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001091PyDoc_STRVAR(getattr_doc,
Guido van Rossum950ff291998-06-29 13:38:57 +00001092"getattr(object, name[, default]) -> value\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001093\n\
Guido van Rossum950ff291998-06-29 13:38:57 +00001094Get a named attribute from an object; getattr(x, 'y') is equivalent to x.y.\n\
1095When a default argument is given, it is returned when the attribute doesn't\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001096exist; without it, an exception is raised in that case.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001097
1098
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001099/*[clinic input]
1100globals as builtin_globals
1101
1102Return the dictionary containing the current scope's global variables.
1103
1104NOTE: Updates to this dictionary *will* affect name lookups in the current
1105global scope and vice-versa.
1106[clinic start generated code]*/
1107
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001108static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001109builtin_globals_impl(PyObject *module)
1110/*[clinic end generated code: output=e5dd1527067b94d2 input=9327576f92bb48ba]*/
Guido van Rossum872537c1995-07-07 22:43:42 +00001111{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001112 PyObject *d;
Guido van Rossum872537c1995-07-07 22:43:42 +00001113
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001114 d = PyEval_GetGlobals();
1115 Py_XINCREF(d);
1116 return d;
Guido van Rossum872537c1995-07-07 22:43:42 +00001117}
1118
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001119
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001120/*[clinic input]
1121hasattr as builtin_hasattr
1122
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001123 obj: object
1124 name: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001125 /
1126
1127Return whether the object has an attribute with the given name.
1128
1129This is done by calling getattr(obj, name) and catching AttributeError.
1130[clinic start generated code]*/
1131
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001132static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001133builtin_hasattr_impl(PyObject *module, PyObject *obj, PyObject *name)
1134/*[clinic end generated code: output=a7aff2090a4151e5 input=0faec9787d979542]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001135{
1136 PyObject *v;
1137
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001138 if (!PyUnicode_Check(name)) {
1139 PyErr_SetString(PyExc_TypeError,
1140 "hasattr(): attribute name must be string");
1141 return NULL;
1142 }
Serhiy Storchakaf320be72018-01-25 10:49:40 +02001143 if (_PyObject_LookupAttr(obj, name, &v) < 0) {
Benjamin Peterson17689992010-08-24 03:26:23 +00001144 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001145 }
Serhiy Storchakaf320be72018-01-25 10:49:40 +02001146 if (v == NULL) {
1147 Py_RETURN_FALSE;
1148 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001149 Py_DECREF(v);
Benjamin Peterson17689992010-08-24 03:26:23 +00001150 Py_RETURN_TRUE;
Guido van Rossum33894be1992-01-27 16:53:09 +00001151}
1152
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001153
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001154/* AC: gdb's integration with CPython relies on builtin_id having
1155 * the *exact* parameter names of "self" and "v", so we ensure we
1156 * preserve those name rather than using the AC defaults.
1157 */
1158/*[clinic input]
1159id as builtin_id
1160
Serhiy Storchaka24182a32016-05-05 16:21:35 +03001161 self: self(type="PyModuleDef *")
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001162 obj as v: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001163 /
1164
1165Return the identity of an object.
1166
1167This is guaranteed to be unique among simultaneously existing objects.
1168(CPython uses the object's memory address.)
1169[clinic start generated code]*/
1170
Guido van Rossum79f25d91997-04-29 20:08:16 +00001171static PyObject *
Serhiy Storchaka24182a32016-05-05 16:21:35 +03001172builtin_id(PyModuleDef *self, PyObject *v)
1173/*[clinic end generated code: output=0aa640785f697f65 input=5a534136419631f4]*/
Guido van Rossum5b722181993-03-30 17:46:03 +00001174{
Steve Dowerb82e17e2019-05-23 08:45:22 -07001175 PyObject *id = PyLong_FromVoidPtr(v);
1176
1177 if (id && PySys_Audit("builtins.id", "O", id) < 0) {
1178 Py_DECREF(id);
1179 return NULL;
1180 }
1181
1182 return id;
Guido van Rossum5b722181993-03-30 17:46:03 +00001183}
1184
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001185
Raymond Hettingera6c60372008-03-13 01:26:19 +00001186/* map object ************************************************************/
1187
1188typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001189 PyObject_HEAD
1190 PyObject *iters;
1191 PyObject *func;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001192} mapobject;
1193
Guido van Rossum79f25d91997-04-29 20:08:16 +00001194static PyObject *
Raymond Hettingera6c60372008-03-13 01:26:19 +00001195map_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
Guido van Rossum12d12c51993-10-26 17:58:25 +00001196{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001197 PyObject *it, *iters, *func;
1198 mapobject *lz;
1199 Py_ssize_t numargs, i;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001200
Serhiy Storchaka6cca5c82017-06-08 14:41:19 +03001201 if (type == &PyMap_Type && !_PyArg_NoKeywords("map", kwds))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001202 return NULL;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001203
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001204 numargs = PyTuple_Size(args);
1205 if (numargs < 2) {
1206 PyErr_SetString(PyExc_TypeError,
1207 "map() must have at least two arguments.");
1208 return NULL;
1209 }
Raymond Hettingera6c60372008-03-13 01:26:19 +00001210
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001211 iters = PyTuple_New(numargs-1);
1212 if (iters == NULL)
1213 return NULL;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001214
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001215 for (i=1 ; i<numargs ; i++) {
1216 /* Get iterator. */
1217 it = PyObject_GetIter(PyTuple_GET_ITEM(args, i));
1218 if (it == NULL) {
1219 Py_DECREF(iters);
1220 return NULL;
1221 }
1222 PyTuple_SET_ITEM(iters, i-1, it);
1223 }
Raymond Hettingera6c60372008-03-13 01:26:19 +00001224
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001225 /* create mapobject structure */
1226 lz = (mapobject *)type->tp_alloc(type, 0);
1227 if (lz == NULL) {
1228 Py_DECREF(iters);
1229 return NULL;
1230 }
1231 lz->iters = iters;
1232 func = PyTuple_GET_ITEM(args, 0);
1233 Py_INCREF(func);
1234 lz->func = func;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001235
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001236 return (PyObject *)lz;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001237}
1238
1239static void
1240map_dealloc(mapobject *lz)
1241{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001242 PyObject_GC_UnTrack(lz);
1243 Py_XDECREF(lz->iters);
1244 Py_XDECREF(lz->func);
1245 Py_TYPE(lz)->tp_free(lz);
Raymond Hettingera6c60372008-03-13 01:26:19 +00001246}
1247
1248static int
1249map_traverse(mapobject *lz, visitproc visit, void *arg)
1250{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001251 Py_VISIT(lz->iters);
1252 Py_VISIT(lz->func);
1253 return 0;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001254}
1255
1256static PyObject *
1257map_next(mapobject *lz)
1258{
Victor Stinnerbc08ab42016-12-15 12:40:53 +01001259 PyObject *small_stack[_PY_FASTCALL_SMALL_STACK];
Victor Stinnercdb5cee2016-08-24 01:45:13 +02001260 PyObject **stack;
Victor Stinnercdb5cee2016-08-24 01:45:13 +02001261 PyObject *result = NULL;
Victor Stinner4d231bc2019-11-14 13:36:21 +01001262 PyThreadState *tstate = _PyThreadState_GET();
Raymond Hettingera6c60372008-03-13 01:26:19 +00001263
Victor Stinner4d231bc2019-11-14 13:36:21 +01001264 const Py_ssize_t niters = PyTuple_GET_SIZE(lz->iters);
Victor Stinnercdb5cee2016-08-24 01:45:13 +02001265 if (niters <= (Py_ssize_t)Py_ARRAY_LENGTH(small_stack)) {
1266 stack = small_stack;
1267 }
1268 else {
1269 stack = PyMem_Malloc(niters * sizeof(stack[0]));
1270 if (stack == NULL) {
Victor Stinner4d231bc2019-11-14 13:36:21 +01001271 _PyErr_NoMemory(tstate);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001272 return NULL;
1273 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001274 }
Victor Stinnercdb5cee2016-08-24 01:45:13 +02001275
Victor Stinner4d231bc2019-11-14 13:36:21 +01001276 Py_ssize_t nargs = 0;
1277 for (Py_ssize_t i=0; i < niters; i++) {
Victor Stinnercdb5cee2016-08-24 01:45:13 +02001278 PyObject *it = PyTuple_GET_ITEM(lz->iters, i);
1279 PyObject *val = Py_TYPE(it)->tp_iternext(it);
1280 if (val == NULL) {
1281 goto exit;
1282 }
1283 stack[i] = val;
1284 nargs++;
1285 }
1286
Victor Stinner4d231bc2019-11-14 13:36:21 +01001287 result = _PyObject_VectorcallTstate(tstate, lz->func, stack, nargs, NULL);
Victor Stinnercdb5cee2016-08-24 01:45:13 +02001288
1289exit:
Victor Stinner4d231bc2019-11-14 13:36:21 +01001290 for (Py_ssize_t i=0; i < nargs; i++) {
Victor Stinnercdb5cee2016-08-24 01:45:13 +02001291 Py_DECREF(stack[i]);
1292 }
1293 if (stack != small_stack) {
1294 PyMem_Free(stack);
1295 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001296 return result;
Guido van Rossum12d12c51993-10-26 17:58:25 +00001297}
1298
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001299static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05301300map_reduce(mapobject *lz, PyObject *Py_UNUSED(ignored))
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001301{
1302 Py_ssize_t numargs = PyTuple_GET_SIZE(lz->iters);
1303 PyObject *args = PyTuple_New(numargs+1);
1304 Py_ssize_t i;
1305 if (args == NULL)
1306 return NULL;
1307 Py_INCREF(lz->func);
1308 PyTuple_SET_ITEM(args, 0, lz->func);
1309 for (i = 0; i<numargs; i++){
1310 PyObject *it = PyTuple_GET_ITEM(lz->iters, i);
1311 Py_INCREF(it);
1312 PyTuple_SET_ITEM(args, i+1, it);
1313 }
1314
1315 return Py_BuildValue("ON", Py_TYPE(lz), args);
1316}
1317
1318static PyMethodDef map_methods[] = {
1319 {"__reduce__", (PyCFunction)map_reduce, METH_NOARGS, reduce_doc},
1320 {NULL, NULL} /* sentinel */
1321};
1322
1323
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001324PyDoc_STRVAR(map_doc,
Raymond Hettingera6c60372008-03-13 01:26:19 +00001325"map(func, *iterables) --> map object\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001326\n\
Raymond Hettingera6c60372008-03-13 01:26:19 +00001327Make an iterator that computes the function using arguments from\n\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001328each of the iterables. Stops when the shortest iterable is exhausted.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001329
Raymond Hettingera6c60372008-03-13 01:26:19 +00001330PyTypeObject PyMap_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001331 PyVarObject_HEAD_INIT(&PyType_Type, 0)
1332 "map", /* tp_name */
1333 sizeof(mapobject), /* tp_basicsize */
1334 0, /* tp_itemsize */
1335 /* methods */
1336 (destructor)map_dealloc, /* tp_dealloc */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02001337 0, /* tp_vectorcall_offset */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001338 0, /* tp_getattr */
1339 0, /* tp_setattr */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02001340 0, /* tp_as_async */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001341 0, /* tp_repr */
1342 0, /* tp_as_number */
1343 0, /* tp_as_sequence */
1344 0, /* tp_as_mapping */
1345 0, /* tp_hash */
1346 0, /* tp_call */
1347 0, /* tp_str */
1348 PyObject_GenericGetAttr, /* tp_getattro */
1349 0, /* tp_setattro */
1350 0, /* tp_as_buffer */
1351 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
1352 Py_TPFLAGS_BASETYPE, /* tp_flags */
1353 map_doc, /* tp_doc */
1354 (traverseproc)map_traverse, /* tp_traverse */
1355 0, /* tp_clear */
1356 0, /* tp_richcompare */
1357 0, /* tp_weaklistoffset */
1358 PyObject_SelfIter, /* tp_iter */
1359 (iternextfunc)map_next, /* tp_iternext */
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001360 map_methods, /* tp_methods */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001361 0, /* tp_members */
1362 0, /* tp_getset */
1363 0, /* tp_base */
1364 0, /* tp_dict */
1365 0, /* tp_descr_get */
1366 0, /* tp_descr_set */
1367 0, /* tp_dictoffset */
1368 0, /* tp_init */
1369 PyType_GenericAlloc, /* tp_alloc */
1370 map_new, /* tp_new */
1371 PyObject_GC_Del, /* tp_free */
Raymond Hettingera6c60372008-03-13 01:26:19 +00001372};
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001373
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001374
1375/* AC: cannot convert yet, as needs PEP 457 group support in inspect */
Guido van Rossum79f25d91997-04-29 20:08:16 +00001376static PyObject *
Serhiy Storchakaa5552f02017-12-15 13:11:11 +02001377builtin_next(PyObject *self, PyObject *const *args, Py_ssize_t nargs)
Georg Brandla18af4e2007-04-21 15:47:16 +00001378{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001379 PyObject *it, *res;
Georg Brandla18af4e2007-04-21 15:47:16 +00001380
Serhiy Storchaka79342662019-01-12 08:25:41 +02001381 if (!_PyArg_CheckPositional("next", nargs, 1, 2))
Sylvain96c7c062017-06-15 17:05:23 +02001382 return NULL;
1383
Serhiy Storchaka79342662019-01-12 08:25:41 +02001384 it = args[0];
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001385 if (!PyIter_Check(it)) {
1386 PyErr_Format(PyExc_TypeError,
Philip Jenvey50add042011-11-06 16:37:52 -08001387 "'%.200s' object is not an iterator",
Victor Stinnera102ed72020-02-07 02:24:48 +01001388 Py_TYPE(it)->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001389 return NULL;
1390 }
1391
Victor Stinnera102ed72020-02-07 02:24:48 +01001392 res = (*Py_TYPE(it)->tp_iternext)(it);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001393 if (res != NULL) {
1394 return res;
Serhiy Storchaka79342662019-01-12 08:25:41 +02001395 } else if (nargs > 1) {
1396 PyObject *def = args[1];
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001397 if (PyErr_Occurred()) {
1398 if(!PyErr_ExceptionMatches(PyExc_StopIteration))
1399 return NULL;
1400 PyErr_Clear();
1401 }
1402 Py_INCREF(def);
1403 return def;
1404 } else if (PyErr_Occurred()) {
1405 return NULL;
1406 } else {
1407 PyErr_SetNone(PyExc_StopIteration);
1408 return NULL;
1409 }
Georg Brandla18af4e2007-04-21 15:47:16 +00001410}
1411
1412PyDoc_STRVAR(next_doc,
1413"next(iterator[, default])\n\
1414\n\
1415Return the next item from the iterator. If default is given and the iterator\n\
1416is exhausted, it is returned instead of raising StopIteration.");
1417
1418
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001419/*[clinic input]
1420setattr as builtin_setattr
1421
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001422 obj: object
1423 name: object
1424 value: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001425 /
1426
1427Sets the named attribute on the given object to the specified value.
1428
1429setattr(x, 'y', v) is equivalent to ``x.y = v''
1430[clinic start generated code]*/
1431
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001432static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001433builtin_setattr_impl(PyObject *module, PyObject *obj, PyObject *name,
Larry Hastings89964c42015-04-14 18:07:59 -04001434 PyObject *value)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001435/*[clinic end generated code: output=dc2ce1d1add9acb4 input=bd2b7ca6875a1899]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001436{
1437 if (PyObject_SetAttr(obj, name, value) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001438 return NULL;
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02001439 Py_RETURN_NONE;
Guido van Rossum33894be1992-01-27 16:53:09 +00001440}
1441
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001442
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001443/*[clinic input]
1444delattr as builtin_delattr
1445
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001446 obj: object
1447 name: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001448 /
1449
1450Deletes the named attribute from the given object.
1451
1452delattr(x, 'y') is equivalent to ``del x.y''
1453[clinic start generated code]*/
1454
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001455static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001456builtin_delattr_impl(PyObject *module, PyObject *obj, PyObject *name)
1457/*[clinic end generated code: output=85134bc58dff79fa input=db16685d6b4b9410]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001458{
1459 if (PyObject_SetAttr(obj, name, (PyObject *)NULL) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001460 return NULL;
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02001461 Py_RETURN_NONE;
Guido van Rossum14144fc1994-08-29 12:53:40 +00001462}
1463
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001464
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001465/*[clinic input]
1466hash as builtin_hash
1467
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001468 obj: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001469 /
1470
1471Return the hash value for the given object.
1472
1473Two objects that compare equal must also have the same hash value, but the
1474reverse is not necessarily true.
1475[clinic start generated code]*/
1476
Guido van Rossum79f25d91997-04-29 20:08:16 +00001477static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001478builtin_hash(PyObject *module, PyObject *obj)
1479/*[clinic end generated code: output=237668e9d7688db7 input=58c48be822bf9c54]*/
Guido van Rossum9bfef441993-03-29 10:43:31 +00001480{
Benjamin Peterson8f67d082010-10-17 20:54:53 +00001481 Py_hash_t x;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001482
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001483 x = PyObject_Hash(obj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001484 if (x == -1)
1485 return NULL;
Benjamin Peterson8f67d082010-10-17 20:54:53 +00001486 return PyLong_FromSsize_t(x);
Guido van Rossum9bfef441993-03-29 10:43:31 +00001487}
1488
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001489
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001490/*[clinic input]
1491hex as builtin_hex
1492
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001493 number: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001494 /
1495
1496Return the hexadecimal representation of an integer.
1497
1498 >>> hex(12648430)
1499 '0xc0ffee'
1500[clinic start generated code]*/
1501
Guido van Rossum79f25d91997-04-29 20:08:16 +00001502static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001503builtin_hex(PyObject *module, PyObject *number)
1504/*[clinic end generated code: output=e46b612169099408 input=e645aff5fc7d540e]*/
Guido van Rossum006bcd41991-10-24 14:54:44 +00001505{
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001506 return PyNumber_ToBase(number, 16);
Guido van Rossum006bcd41991-10-24 14:54:44 +00001507}
1508
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001509
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001510/* AC: cannot convert yet, as needs PEP 457 group support in inspect */
Guido van Rossum79f25d91997-04-29 20:08:16 +00001511static PyObject *
Serhiy Storchaka79342662019-01-12 08:25:41 +02001512builtin_iter(PyObject *self, PyObject *const *args, Py_ssize_t nargs)
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001513{
Serhiy Storchaka79342662019-01-12 08:25:41 +02001514 PyObject *v;
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001515
Serhiy Storchaka79342662019-01-12 08:25:41 +02001516 if (!_PyArg_CheckPositional("iter", nargs, 1, 2))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001517 return NULL;
Serhiy Storchaka79342662019-01-12 08:25:41 +02001518 v = args[0];
1519 if (nargs == 1)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001520 return PyObject_GetIter(v);
1521 if (!PyCallable_Check(v)) {
1522 PyErr_SetString(PyExc_TypeError,
1523 "iter(v, w): v must be callable");
1524 return NULL;
1525 }
Serhiy Storchaka79342662019-01-12 08:25:41 +02001526 PyObject *sentinel = args[1];
1527 return PyCallIter_New(v, sentinel);
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001528}
1529
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001530PyDoc_STRVAR(iter_doc,
Georg Brandld11ae5d2008-05-16 13:27:32 +00001531"iter(iterable) -> iterator\n\
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001532iter(callable, sentinel) -> iterator\n\
1533\n\
1534Get an iterator from an object. In the first form, the argument must\n\
1535supply its own iterator, or be a sequence.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001536In the second form, the callable is called until it returns the sentinel.");
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001537
1538
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001539/*[clinic input]
1540len as builtin_len
1541
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001542 obj: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001543 /
1544
1545Return the number of items in a container.
1546[clinic start generated code]*/
1547
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001548static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001549builtin_len(PyObject *module, PyObject *obj)
1550/*[clinic end generated code: output=fa7a270d314dfb6c input=bc55598da9e9c9b5]*/
Guido van Rossum3f5da241990-12-20 15:06:42 +00001551{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001552 Py_ssize_t res;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001553
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001554 res = PyObject_Size(obj);
Serhiy Storchaka813f9432017-04-16 09:21:44 +03001555 if (res < 0) {
1556 assert(PyErr_Occurred());
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001557 return NULL;
Serhiy Storchaka813f9432017-04-16 09:21:44 +03001558 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001559 return PyLong_FromSsize_t(res);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001560}
1561
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001562
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001563/*[clinic input]
1564locals as builtin_locals
1565
1566Return a dictionary containing the current scope's local variables.
1567
1568NOTE: Whether or not updates to this dictionary will affect name lookups in
1569the local scope and vice-versa is *implementation dependent* and not
1570covered by any backwards compatibility guarantees.
1571[clinic start generated code]*/
1572
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001573static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001574builtin_locals_impl(PyObject *module)
1575/*[clinic end generated code: output=b46c94015ce11448 input=7874018d478d5c4b]*/
Guido van Rossum872537c1995-07-07 22:43:42 +00001576{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001577 PyObject *d;
Guido van Rossum872537c1995-07-07 22:43:42 +00001578
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001579 d = PyEval_GetLocals();
1580 Py_XINCREF(d);
1581 return d;
Guido van Rossum872537c1995-07-07 22:43:42 +00001582}
1583
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001584
Guido van Rossum79f25d91997-04-29 20:08:16 +00001585static PyObject *
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001586min_max(PyObject *args, PyObject *kwds, int op)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001587{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001588 PyObject *v, *it, *item, *val, *maxitem, *maxval, *keyfunc=NULL;
Raymond Hettinger4d6018f2013-06-24 22:43:02 -07001589 PyObject *emptytuple, *defaultval = NULL;
1590 static char *kwlist[] = {"key", "default", NULL};
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001591 const char *name = op == Py_LT ? "min" : "max";
Raymond Hettinger4d6018f2013-06-24 22:43:02 -07001592 const int positional = PyTuple_Size(args) > 1;
1593 int ret;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001594
Dong-hee Naabdc6342020-01-11 01:31:43 +09001595 if (positional) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001596 v = args;
Dong-hee Naabdc6342020-01-11 01:31:43 +09001597 }
1598 else if (!PyArg_UnpackTuple(args, name, 1, 1, &v)) {
1599 if (PyExceptionClass_Check(PyExc_TypeError)) {
1600 PyErr_Format(PyExc_TypeError, "%s expected at least 1 argument, got 0", name);
1601 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001602 return NULL;
Dong-hee Naabdc6342020-01-11 01:31:43 +09001603 }
Tim Peters67d687a2002-04-29 21:27:32 +00001604
Raymond Hettinger4d6018f2013-06-24 22:43:02 -07001605 emptytuple = PyTuple_New(0);
1606 if (emptytuple == NULL)
1607 return NULL;
Oren Milman58cf7482017-08-21 20:19:07 +03001608 ret = PyArg_ParseTupleAndKeywords(emptytuple, kwds,
1609 (op == Py_LT) ? "|$OO:min" : "|$OO:max",
1610 kwlist, &keyfunc, &defaultval);
Raymond Hettinger4d6018f2013-06-24 22:43:02 -07001611 Py_DECREF(emptytuple);
1612 if (!ret)
1613 return NULL;
1614
1615 if (positional && defaultval != NULL) {
1616 PyErr_Format(PyExc_TypeError,
1617 "Cannot specify a default for %s() with multiple "
1618 "positional arguments", name);
1619 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001620 }
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001621
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001622 it = PyObject_GetIter(v);
1623 if (it == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001624 return NULL;
1625 }
Tim Petersc3074532001-05-03 07:00:32 +00001626
Alexander Marshalove22072f2018-07-24 10:58:21 +07001627 if (keyfunc == Py_None) {
1628 keyfunc = NULL;
1629 }
1630
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001631 maxitem = NULL; /* the result */
1632 maxval = NULL; /* the value associated with the result */
1633 while (( item = PyIter_Next(it) )) {
1634 /* get the value from the key function */
1635 if (keyfunc != NULL) {
Petr Viktorinffd97532020-02-11 17:46:57 +01001636 val = PyObject_CallOneArg(keyfunc, item);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001637 if (val == NULL)
1638 goto Fail_it_item;
1639 }
1640 /* no key function; the value is the item */
1641 else {
1642 val = item;
1643 Py_INCREF(val);
1644 }
Tim Petersc3074532001-05-03 07:00:32 +00001645
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001646 /* maximum value and item are unset; set them */
1647 if (maxval == NULL) {
1648 maxitem = item;
1649 maxval = val;
1650 }
1651 /* maximum value and item are set; update them as necessary */
1652 else {
1653 int cmp = PyObject_RichCompareBool(val, maxval, op);
1654 if (cmp < 0)
1655 goto Fail_it_item_and_val;
1656 else if (cmp > 0) {
1657 Py_DECREF(maxval);
1658 Py_DECREF(maxitem);
1659 maxval = val;
1660 maxitem = item;
1661 }
1662 else {
1663 Py_DECREF(item);
1664 Py_DECREF(val);
1665 }
1666 }
1667 }
1668 if (PyErr_Occurred())
1669 goto Fail_it;
1670 if (maxval == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001671 assert(maxitem == NULL);
Raymond Hettinger4d6018f2013-06-24 22:43:02 -07001672 if (defaultval != NULL) {
1673 Py_INCREF(defaultval);
1674 maxitem = defaultval;
1675 } else {
1676 PyErr_Format(PyExc_ValueError,
1677 "%s() arg is an empty sequence", name);
1678 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001679 }
1680 else
1681 Py_DECREF(maxval);
1682 Py_DECREF(it);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001683 return maxitem;
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001684
1685Fail_it_item_and_val:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001686 Py_DECREF(val);
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001687Fail_it_item:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001688 Py_DECREF(item);
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001689Fail_it:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001690 Py_XDECREF(maxval);
1691 Py_XDECREF(maxitem);
1692 Py_DECREF(it);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001693 return NULL;
Guido van Rossum3f5da241990-12-20 15:06:42 +00001694}
1695
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001696/* AC: cannot convert yet, waiting for *args support */
Guido van Rossum79f25d91997-04-29 20:08:16 +00001697static PyObject *
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001698builtin_min(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001699{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001700 return min_max(args, kwds, Py_LT);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001701}
1702
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001703PyDoc_STRVAR(min_doc,
Raymond Hettinger2a545822014-05-19 22:20:52 +01001704"min(iterable, *[, default=obj, key=func]) -> value\n\
1705min(arg1, arg2, *args, *[, key=func]) -> value\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001706\n\
Raymond Hettinger2a545822014-05-19 22:20:52 +01001707With a single iterable argument, return its smallest item. The\n\
1708default keyword-only argument specifies an object to return if\n\
1709the provided iterable is empty.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001710With two or more arguments, return the smallest argument.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001711
1712
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001713/* AC: cannot convert yet, waiting for *args support */
Guido van Rossum79f25d91997-04-29 20:08:16 +00001714static PyObject *
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001715builtin_max(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001716{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001717 return min_max(args, kwds, Py_GT);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001718}
1719
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001720PyDoc_STRVAR(max_doc,
Raymond Hettinger2a545822014-05-19 22:20:52 +01001721"max(iterable, *[, default=obj, key=func]) -> value\n\
1722max(arg1, arg2, *args, *[, key=func]) -> value\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001723\n\
Raymond Hettinger2a545822014-05-19 22:20:52 +01001724With a single iterable argument, return its biggest item. The\n\
1725default keyword-only argument specifies an object to return if\n\
1726the provided iterable is empty.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001727With two or more arguments, return the largest argument.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001728
1729
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001730/*[clinic input]
1731oct as builtin_oct
1732
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001733 number: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001734 /
1735
1736Return the octal representation of an integer.
1737
1738 >>> oct(342391)
1739 '0o1234567'
1740[clinic start generated code]*/
1741
Guido van Rossum79f25d91997-04-29 20:08:16 +00001742static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001743builtin_oct(PyObject *module, PyObject *number)
1744/*[clinic end generated code: output=40a34656b6875352 input=ad6b274af4016c72]*/
Guido van Rossum006bcd41991-10-24 14:54:44 +00001745{
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001746 return PyNumber_ToBase(number, 8);
Guido van Rossum006bcd41991-10-24 14:54:44 +00001747}
1748
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001749
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001750/*[clinic input]
1751ord as builtin_ord
1752
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001753 c: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001754 /
1755
1756Return the Unicode code point for a one-character string.
1757[clinic start generated code]*/
1758
Guido van Rossum79f25d91997-04-29 20:08:16 +00001759static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001760builtin_ord(PyObject *module, PyObject *c)
1761/*[clinic end generated code: output=4fa5e87a323bae71 input=3064e5d6203ad012]*/
Guido van Rossum3f5da241990-12-20 15:06:42 +00001762{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001763 long ord;
1764 Py_ssize_t size;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001765
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001766 if (PyBytes_Check(c)) {
1767 size = PyBytes_GET_SIZE(c);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001768 if (size == 1) {
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001769 ord = (long)((unsigned char)*PyBytes_AS_STRING(c));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001770 return PyLong_FromLong(ord);
1771 }
1772 }
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001773 else if (PyUnicode_Check(c)) {
1774 if (PyUnicode_READY(c) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001775 return NULL;
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001776 size = PyUnicode_GET_LENGTH(c);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001777 if (size == 1) {
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001778 ord = (long)PyUnicode_READ_CHAR(c, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001779 return PyLong_FromLong(ord);
1780 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001781 }
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001782 else if (PyByteArray_Check(c)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001783 /* XXX Hopefully this is temporary */
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001784 size = PyByteArray_GET_SIZE(c);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001785 if (size == 1) {
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001786 ord = (long)((unsigned char)*PyByteArray_AS_STRING(c));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001787 return PyLong_FromLong(ord);
1788 }
1789 }
1790 else {
1791 PyErr_Format(PyExc_TypeError,
1792 "ord() expected string of length 1, but " \
Victor Stinnera102ed72020-02-07 02:24:48 +01001793 "%.200s found", Py_TYPE(c)->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001794 return NULL;
1795 }
Guido van Rossum09095f32000-03-10 23:00:52 +00001796
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001797 PyErr_Format(PyExc_TypeError,
1798 "ord() expected a character, "
1799 "but string of length %zd found",
1800 size);
1801 return NULL;
Guido van Rossum3f5da241990-12-20 15:06:42 +00001802}
1803
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001804
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001805/*[clinic input]
1806pow as builtin_pow
1807
Ammar Askar87d6cd32019-09-21 00:28:49 -04001808 base: object
1809 exp: object
1810 mod: object = None
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001811
Raymond Hettingerb104ecb2019-09-21 12:57:44 -07001812Equivalent to base**exp with 2 arguments or base**exp % mod with 3 arguments
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001813
1814Some types, such as ints, are able to use a more efficient algorithm when
1815invoked using the three argument form.
1816[clinic start generated code]*/
1817
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001818static PyObject *
Ammar Askar87d6cd32019-09-21 00:28:49 -04001819builtin_pow_impl(PyObject *module, PyObject *base, PyObject *exp,
1820 PyObject *mod)
Raymond Hettingerb104ecb2019-09-21 12:57:44 -07001821/*[clinic end generated code: output=3ca1538221bbf15f input=435dbd48a12efb23]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001822{
Ammar Askar87d6cd32019-09-21 00:28:49 -04001823 return PyNumber_Power(base, exp, mod);
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001824}
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001825
1826
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001827/* AC: cannot convert yet, waiting for *args support */
Guido van Rossum34343512006-11-30 22:13:52 +00001828static PyObject *
Serhiy Storchakaa5552f02017-12-15 13:11:11 +02001829builtin_print(PyObject *self, PyObject *const *args, Py_ssize_t nargs, PyObject *kwnames)
Guido van Rossum34343512006-11-30 22:13:52 +00001830{
INADA Naokibd584f12017-01-19 12:50:34 +01001831 static const char * const _keywords[] = {"sep", "end", "file", "flush", 0};
Serhiy Storchaka1f21eaa2019-09-01 12:16:51 +03001832 static struct _PyArg_Parser _parser = {"|OOOp:print", _keywords, 0};
1833 PyObject *sep = NULL, *end = NULL, *file = NULL;
1834 int flush = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001835 int i, err;
Guido van Rossum34343512006-11-30 22:13:52 +00001836
INADA Naokibd584f12017-01-19 12:50:34 +01001837 if (kwnames != NULL &&
1838 !_PyArg_ParseStackAndKeywords(args + nargs, 0, kwnames, &_parser,
1839 &sep, &end, &file, &flush)) {
Georg Brandlbc3b6822012-01-13 19:41:25 +01001840 return NULL;
INADA Naokibd584f12017-01-19 12:50:34 +01001841 }
1842
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001843 if (file == NULL || file == Py_None) {
Victor Stinnerbd303c12013-11-07 23:07:29 +01001844 file = _PySys_GetObjectId(&PyId_stdout);
Victor Stinner1e53bba2013-07-16 22:26:05 +02001845 if (file == NULL) {
1846 PyErr_SetString(PyExc_RuntimeError, "lost sys.stdout");
1847 return NULL;
1848 }
1849
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001850 /* sys.stdout may be None when FILE* stdout isn't connected */
1851 if (file == Py_None)
1852 Py_RETURN_NONE;
1853 }
Guido van Rossum34343512006-11-30 22:13:52 +00001854
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001855 if (sep == Py_None) {
1856 sep = NULL;
1857 }
1858 else if (sep && !PyUnicode_Check(sep)) {
1859 PyErr_Format(PyExc_TypeError,
1860 "sep must be None or a string, not %.200s",
Victor Stinnera102ed72020-02-07 02:24:48 +01001861 Py_TYPE(sep)->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001862 return NULL;
1863 }
1864 if (end == Py_None) {
1865 end = NULL;
1866 }
1867 else if (end && !PyUnicode_Check(end)) {
1868 PyErr_Format(PyExc_TypeError,
1869 "end must be None or a string, not %.200s",
Victor Stinnera102ed72020-02-07 02:24:48 +01001870 Py_TYPE(end)->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001871 return NULL;
1872 }
Guido van Rossum34343512006-11-30 22:13:52 +00001873
INADA Naokibd584f12017-01-19 12:50:34 +01001874 for (i = 0; i < nargs; i++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001875 if (i > 0) {
1876 if (sep == NULL)
1877 err = PyFile_WriteString(" ", file);
1878 else
1879 err = PyFile_WriteObject(sep, file,
1880 Py_PRINT_RAW);
1881 if (err)
1882 return NULL;
1883 }
INADA Naokibd584f12017-01-19 12:50:34 +01001884 err = PyFile_WriteObject(args[i], file, Py_PRINT_RAW);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001885 if (err)
1886 return NULL;
1887 }
Guido van Rossum34343512006-11-30 22:13:52 +00001888
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001889 if (end == NULL)
1890 err = PyFile_WriteString("\n", file);
1891 else
1892 err = PyFile_WriteObject(end, file, Py_PRINT_RAW);
1893 if (err)
1894 return NULL;
Guido van Rossum34343512006-11-30 22:13:52 +00001895
Serhiy Storchaka1f21eaa2019-09-01 12:16:51 +03001896 if (flush) {
1897 PyObject *tmp = _PyObject_CallMethodIdNoArgs(file, &PyId_flush);
1898 if (tmp == NULL)
Georg Brandlbc3b6822012-01-13 19:41:25 +01001899 return NULL;
Serhiy Storchaka1f21eaa2019-09-01 12:16:51 +03001900 Py_DECREF(tmp);
Georg Brandlbc3b6822012-01-13 19:41:25 +01001901 }
1902
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001903 Py_RETURN_NONE;
Guido van Rossum34343512006-11-30 22:13:52 +00001904}
1905
1906PyDoc_STRVAR(print_doc,
Senthil Kumarane9175bd2012-08-10 13:53:45 -07001907"print(value, ..., sep=' ', end='\\n', file=sys.stdout, flush=False)\n\
Guido van Rossum34343512006-11-30 22:13:52 +00001908\n\
1909Prints the values to a stream, or to sys.stdout by default.\n\
1910Optional keyword arguments:\n\
Senthil Kumarane9175bd2012-08-10 13:53:45 -07001911file: a file-like object (stream); defaults to the current sys.stdout.\n\
1912sep: string inserted between values, default a space.\n\
1913end: string appended after the last value, default a newline.\n\
1914flush: whether to forcibly flush the stream.");
Guido van Rossum34343512006-11-30 22:13:52 +00001915
1916
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001917/*[clinic input]
1918input as builtin_input
1919
1920 prompt: object(c_default="NULL") = None
1921 /
1922
1923Read a string from standard input. The trailing newline is stripped.
1924
1925The prompt string, if given, is printed to standard output without a
1926trailing newline before reading input.
1927
1928If the user hits EOF (*nix: Ctrl-D, Windows: Ctrl-Z+Return), raise EOFError.
1929On *nix systems, readline is used if available.
1930[clinic start generated code]*/
1931
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001932static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001933builtin_input_impl(PyObject *module, PyObject *prompt)
1934/*[clinic end generated code: output=83db5a191e7a0d60 input=5e8bb70c2908fe3c]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001935{
Victor Stinnerbd303c12013-11-07 23:07:29 +01001936 PyObject *fin = _PySys_GetObjectId(&PyId_stdin);
1937 PyObject *fout = _PySys_GetObjectId(&PyId_stdout);
1938 PyObject *ferr = _PySys_GetObjectId(&PyId_stderr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001939 PyObject *tmp;
1940 long fd;
1941 int tty;
Guido van Rossuma88a0332007-02-26 16:59:55 +00001942
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001943 /* Check that stdin/out/err are intact */
1944 if (fin == NULL || fin == Py_None) {
1945 PyErr_SetString(PyExc_RuntimeError,
1946 "input(): lost sys.stdin");
1947 return NULL;
1948 }
1949 if (fout == NULL || fout == Py_None) {
1950 PyErr_SetString(PyExc_RuntimeError,
1951 "input(): lost sys.stdout");
1952 return NULL;
1953 }
1954 if (ferr == NULL || ferr == Py_None) {
1955 PyErr_SetString(PyExc_RuntimeError,
1956 "input(): lost sys.stderr");
1957 return NULL;
1958 }
Guido van Rossumeba76962007-05-27 09:13:28 +00001959
Steve Dowerb82e17e2019-05-23 08:45:22 -07001960 if (PySys_Audit("builtins.input", "O", prompt ? prompt : Py_None) < 0) {
1961 return NULL;
1962 }
1963
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001964 /* First of all, flush stderr */
Jeroen Demeyer762f93f2019-07-08 10:19:25 +02001965 tmp = _PyObject_CallMethodIdNoArgs(ferr, &PyId_flush);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001966 if (tmp == NULL)
1967 PyErr_Clear();
1968 else
1969 Py_DECREF(tmp);
Guido van Rossumeba76962007-05-27 09:13:28 +00001970
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001971 /* We should only use (GNU) readline if Python's sys.stdin and
1972 sys.stdout are the same as C's stdin and stdout, because we
1973 need to pass it those. */
Jeroen Demeyer762f93f2019-07-08 10:19:25 +02001974 tmp = _PyObject_CallMethodIdNoArgs(fin, &PyId_fileno);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001975 if (tmp == NULL) {
1976 PyErr_Clear();
1977 tty = 0;
1978 }
1979 else {
1980 fd = PyLong_AsLong(tmp);
1981 Py_DECREF(tmp);
1982 if (fd < 0 && PyErr_Occurred())
1983 return NULL;
1984 tty = fd == fileno(stdin) && isatty(fd);
1985 }
1986 if (tty) {
Jeroen Demeyer762f93f2019-07-08 10:19:25 +02001987 tmp = _PyObject_CallMethodIdNoArgs(fout, &PyId_fileno);
Martin Panterc9a6ab52015-10-10 01:25:38 +00001988 if (tmp == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001989 PyErr_Clear();
Martin Panterc9a6ab52015-10-10 01:25:38 +00001990 tty = 0;
1991 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001992 else {
1993 fd = PyLong_AsLong(tmp);
1994 Py_DECREF(tmp);
1995 if (fd < 0 && PyErr_Occurred())
1996 return NULL;
1997 tty = fd == fileno(stdout) && isatty(fd);
1998 }
1999 }
Guido van Rossumeba76962007-05-27 09:13:28 +00002000
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002001 /* If we're interactive, use (GNU) readline */
2002 if (tty) {
Antoine Pitrou0d776b12011-11-06 00:34:26 +01002003 PyObject *po = NULL;
Serhiy Storchakae2f92de2017-11-11 13:06:26 +02002004 const char *promptstr;
Antoine Pitrou0d776b12011-11-06 00:34:26 +01002005 char *s = NULL;
2006 PyObject *stdin_encoding = NULL, *stdin_errors = NULL;
2007 PyObject *stdout_encoding = NULL, *stdout_errors = NULL;
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +02002008 const char *stdin_encoding_str, *stdin_errors_str;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002009 PyObject *result;
Victor Stinnerc0f1a1a2011-02-23 12:07:37 +00002010 size_t len;
Martin v. Löwis4a7b5d52007-09-04 05:24:49 +00002011
Serhiy Storchakac2cf1282017-03-12 13:50:36 +02002012 /* stdin is a text stream, so it must have an encoding. */
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02002013 stdin_encoding = _PyObject_GetAttrId(fin, &PyId_encoding);
Antoine Pitrou5ee9d8a2011-11-06 00:38:45 +01002014 stdin_errors = _PyObject_GetAttrId(fin, &PyId_errors);
Serhiy Storchakac2cf1282017-03-12 13:50:36 +02002015 if (!stdin_encoding || !stdin_errors ||
2016 !PyUnicode_Check(stdin_encoding) ||
2017 !PyUnicode_Check(stdin_errors)) {
2018 tty = 0;
Antoine Pitrou0d776b12011-11-06 00:34:26 +01002019 goto _readline_errors;
Serhiy Storchakac2cf1282017-03-12 13:50:36 +02002020 }
Serhiy Storchaka06515832016-11-20 09:13:07 +02002021 stdin_encoding_str = PyUnicode_AsUTF8(stdin_encoding);
2022 stdin_errors_str = PyUnicode_AsUTF8(stdin_errors);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01002023 if (!stdin_encoding_str || !stdin_errors_str)
2024 goto _readline_errors;
Jeroen Demeyer762f93f2019-07-08 10:19:25 +02002025 tmp = _PyObject_CallMethodIdNoArgs(fout, &PyId_flush);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002026 if (tmp == NULL)
2027 PyErr_Clear();
2028 else
2029 Py_DECREF(tmp);
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002030 if (prompt != NULL) {
Antoine Pitrou0d776b12011-11-06 00:34:26 +01002031 /* We have a prompt, encode it as stdout would */
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +02002032 const char *stdout_encoding_str, *stdout_errors_str;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002033 PyObject *stringpo;
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02002034 stdout_encoding = _PyObject_GetAttrId(fout, &PyId_encoding);
Antoine Pitrou5ee9d8a2011-11-06 00:38:45 +01002035 stdout_errors = _PyObject_GetAttrId(fout, &PyId_errors);
Serhiy Storchakac2cf1282017-03-12 13:50:36 +02002036 if (!stdout_encoding || !stdout_errors ||
2037 !PyUnicode_Check(stdout_encoding) ||
2038 !PyUnicode_Check(stdout_errors)) {
2039 tty = 0;
Antoine Pitrou0d776b12011-11-06 00:34:26 +01002040 goto _readline_errors;
Serhiy Storchakac2cf1282017-03-12 13:50:36 +02002041 }
Serhiy Storchaka06515832016-11-20 09:13:07 +02002042 stdout_encoding_str = PyUnicode_AsUTF8(stdout_encoding);
2043 stdout_errors_str = PyUnicode_AsUTF8(stdout_errors);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01002044 if (!stdout_encoding_str || !stdout_errors_str)
2045 goto _readline_errors;
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002046 stringpo = PyObject_Str(prompt);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01002047 if (stringpo == NULL)
2048 goto _readline_errors;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002049 po = PyUnicode_AsEncodedString(stringpo,
Antoine Pitrou0d776b12011-11-06 00:34:26 +01002050 stdout_encoding_str, stdout_errors_str);
2051 Py_CLEAR(stdout_encoding);
2052 Py_CLEAR(stdout_errors);
2053 Py_CLEAR(stringpo);
2054 if (po == NULL)
2055 goto _readline_errors;
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03002056 assert(PyBytes_Check(po));
2057 promptstr = PyBytes_AS_STRING(po);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002058 }
2059 else {
2060 po = NULL;
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002061 promptstr = "";
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002062 }
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002063 s = PyOS_Readline(stdin, stdout, promptstr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002064 if (s == NULL) {
Richard Oudkerk614c5782013-04-03 13:44:50 +01002065 PyErr_CheckSignals();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002066 if (!PyErr_Occurred())
2067 PyErr_SetNone(PyExc_KeyboardInterrupt);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01002068 goto _readline_errors;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002069 }
Victor Stinnerc0f1a1a2011-02-23 12:07:37 +00002070
2071 len = strlen(s);
2072 if (len == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002073 PyErr_SetNone(PyExc_EOFError);
2074 result = NULL;
2075 }
Victor Stinnerc0f1a1a2011-02-23 12:07:37 +00002076 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002077 if (len > PY_SSIZE_T_MAX) {
2078 PyErr_SetString(PyExc_OverflowError,
2079 "input: input too long");
2080 result = NULL;
2081 }
2082 else {
Victor Stinnerc0f1a1a2011-02-23 12:07:37 +00002083 len--; /* strip trailing '\n' */
2084 if (len != 0 && s[len-1] == '\r')
2085 len--; /* strip trailing '\r' */
Antoine Pitrou0d776b12011-11-06 00:34:26 +01002086 result = PyUnicode_Decode(s, len, stdin_encoding_str,
2087 stdin_errors_str);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002088 }
2089 }
2090 Py_DECREF(stdin_encoding);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01002091 Py_DECREF(stdin_errors);
2092 Py_XDECREF(po);
Victor Stinner00d7abd2020-12-01 09:56:42 +01002093 PyMem_Free(s);
Steve Dowerb82e17e2019-05-23 08:45:22 -07002094
2095 if (result != NULL) {
2096 if (PySys_Audit("builtins.input/result", "O", result) < 0) {
2097 return NULL;
2098 }
2099 }
2100
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002101 return result;
Serhiy Storchakac2cf1282017-03-12 13:50:36 +02002102
Antoine Pitrou0d776b12011-11-06 00:34:26 +01002103 _readline_errors:
2104 Py_XDECREF(stdin_encoding);
2105 Py_XDECREF(stdout_encoding);
2106 Py_XDECREF(stdin_errors);
2107 Py_XDECREF(stdout_errors);
2108 Py_XDECREF(po);
Serhiy Storchakac2cf1282017-03-12 13:50:36 +02002109 if (tty)
2110 return NULL;
2111
2112 PyErr_Clear();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002113 }
Guido van Rossumeba76962007-05-27 09:13:28 +00002114
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002115 /* Fallback if we're not interactive */
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002116 if (prompt != NULL) {
2117 if (PyFile_WriteObject(prompt, fout, Py_PRINT_RAW) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002118 return NULL;
2119 }
Jeroen Demeyer762f93f2019-07-08 10:19:25 +02002120 tmp = _PyObject_CallMethodIdNoArgs(fout, &PyId_flush);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002121 if (tmp == NULL)
2122 PyErr_Clear();
2123 else
2124 Py_DECREF(tmp);
2125 return PyFile_GetLine(fin, -1);
Guido van Rossuma88a0332007-02-26 16:59:55 +00002126}
2127
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002128
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002129/*[clinic input]
2130repr as builtin_repr
2131
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03002132 obj: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002133 /
2134
2135Return the canonical string representation of the object.
2136
2137For many object types, including most builtins, eval(repr(obj)) == obj.
2138[clinic start generated code]*/
2139
Guido van Rossum79f25d91997-04-29 20:08:16 +00002140static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002141builtin_repr(PyObject *module, PyObject *obj)
2142/*[clinic end generated code: output=7ed3778c44fd0194 input=1c9e6d66d3e3be04]*/
Guido van Rossumc89705d1992-11-26 08:54:07 +00002143{
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002144 return PyObject_Repr(obj);
Guido van Rossumc89705d1992-11-26 08:54:07 +00002145}
2146
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002147
Serhiy Storchakaaca7f572017-11-15 17:51:14 +02002148/*[clinic input]
2149round as builtin_round
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002150
Serhiy Storchakaaca7f572017-11-15 17:51:14 +02002151 number: object
Serhiy Storchaka279f4462019-09-14 12:24:05 +03002152 ndigits: object = None
Serhiy Storchakaaca7f572017-11-15 17:51:14 +02002153
2154Round a number to a given precision in decimal digits.
2155
2156The return value is an integer if ndigits is omitted or None. Otherwise
2157the return value has the same type as the number. ndigits may be negative.
2158[clinic start generated code]*/
2159
2160static PyObject *
2161builtin_round_impl(PyObject *module, PyObject *number, PyObject *ndigits)
Serhiy Storchaka279f4462019-09-14 12:24:05 +03002162/*[clinic end generated code: output=ff0d9dd176c02ede input=275678471d7aca15]*/
Serhiy Storchakaaca7f572017-11-15 17:51:14 +02002163{
2164 PyObject *round, *result;
Alex Martelliae211f92007-08-22 23:21:33 +00002165
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002166 if (Py_TYPE(number)->tp_dict == NULL) {
2167 if (PyType_Ready(Py_TYPE(number)) < 0)
2168 return NULL;
2169 }
Guido van Rossum15d3d042007-08-24 02:02:45 +00002170
Benjamin Peterson214a7d22013-04-13 17:19:01 -04002171 round = _PyObject_LookupSpecial(number, &PyId___round__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002172 if (round == NULL) {
Benjamin Peterson214a7d22013-04-13 17:19:01 -04002173 if (!PyErr_Occurred())
2174 PyErr_Format(PyExc_TypeError,
2175 "type %.100s doesn't define __round__ method",
2176 Py_TYPE(number)->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002177 return NULL;
2178 }
Alex Martelliae211f92007-08-22 23:21:33 +00002179
Serhiy Storchaka279f4462019-09-14 12:24:05 +03002180 if (ndigits == Py_None)
Victor Stinnerf17c3de2016-12-06 18:46:19 +01002181 result = _PyObject_CallNoArg(round);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002182 else
Petr Viktorinffd97532020-02-11 17:46:57 +01002183 result = PyObject_CallOneArg(round, ndigits);
Benjamin Peterson214a7d22013-04-13 17:19:01 -04002184 Py_DECREF(round);
2185 return result;
Guido van Rossum9e51f9b1993-02-12 16:29:05 +00002186}
2187
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002188
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002189/*AC: we need to keep the kwds dict intact to easily call into the
2190 * list.sort method, which isn't currently supported in AC. So we just use
2191 * the initially generated signature with a custom implementation.
2192 */
2193/* [disabled clinic input]
2194sorted as builtin_sorted
2195
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03002196 iterable as seq: object
2197 key as keyfunc: object = None
2198 reverse: object = False
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002199
2200Return a new list containing all items from the iterable in ascending order.
2201
Raymond Hettinger7ea386e2016-08-25 21:11:50 -07002202A custom key function can be supplied to customize the sort order, and the
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002203reverse flag can be set to request the result in descending order.
2204[end disabled clinic input]*/
2205
2206PyDoc_STRVAR(builtin_sorted__doc__,
Serhiy Storchaka3a104252017-01-23 12:29:47 +02002207"sorted($module, iterable, /, *, key=None, reverse=False)\n"
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002208"--\n"
2209"\n"
2210"Return a new list containing all items from the iterable in ascending order.\n"
2211"\n"
Raymond Hettinger7ea386e2016-08-25 21:11:50 -07002212"A custom key function can be supplied to customize the sort order, and the\n"
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002213"reverse flag can be set to request the result in descending order.");
2214
2215#define BUILTIN_SORTED_METHODDEF \
Serhiy Storchaka62be7422018-11-27 13:27:31 +02002216 {"sorted", (PyCFunction)(void(*)(void))builtin_sorted, METH_FASTCALL | METH_KEYWORDS, builtin_sorted__doc__},
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002217
Raymond Hettinger64958a12003-12-17 20:43:33 +00002218static PyObject *
Serhiy Storchakaa5552f02017-12-15 13:11:11 +02002219builtin_sorted(PyObject *self, PyObject *const *args, Py_ssize_t nargs, PyObject *kwnames)
Raymond Hettinger64958a12003-12-17 20:43:33 +00002220{
Serhiy Storchaka7cf8beb2017-01-21 23:05:00 +02002221 PyObject *newlist, *v, *seq, *callable;
Victor Stinner5a60eca2017-01-17 15:17:49 +01002222
Serhiy Storchaka7cf8beb2017-01-21 23:05:00 +02002223 /* Keyword arguments are passed through list.sort() which will check
2224 them. */
2225 if (!_PyArg_UnpackStack(args, nargs, "sorted", 1, 1, &seq))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002226 return NULL;
Raymond Hettinger64958a12003-12-17 20:43:33 +00002227
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002228 newlist = PySequence_List(seq);
2229 if (newlist == NULL)
2230 return NULL;
Raymond Hettinger64958a12003-12-17 20:43:33 +00002231
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02002232 callable = _PyObject_GetAttrId(newlist, &PyId_sort);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002233 if (callable == NULL) {
2234 Py_DECREF(newlist);
2235 return NULL;
2236 }
Georg Brandl99d7e4e2005-08-31 22:21:15 +00002237
Serhiy Storchaka299dc232017-01-20 08:35:18 +02002238 assert(nargs >= 1);
Petr Viktorinffd97532020-02-11 17:46:57 +01002239 v = PyObject_Vectorcall(callable, args + 1, nargs - 1, kwnames);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002240 Py_DECREF(callable);
2241 if (v == NULL) {
2242 Py_DECREF(newlist);
2243 return NULL;
2244 }
2245 Py_DECREF(v);
2246 return newlist;
Raymond Hettinger64958a12003-12-17 20:43:33 +00002247}
2248
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002249
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002250/* AC: cannot convert yet, as needs PEP 457 group support in inspect */
Guido van Rossum79f25d91997-04-29 20:08:16 +00002251static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002252builtin_vars(PyObject *self, PyObject *args)
Guido van Rossum2d951851994-08-29 12:52:16 +00002253{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002254 PyObject *v = NULL;
2255 PyObject *d;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002256
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002257 if (!PyArg_UnpackTuple(args, "vars", 0, 1, &v))
2258 return NULL;
2259 if (v == NULL) {
2260 d = PyEval_GetLocals();
Serhiy Storchaka41c57b32019-09-01 12:03:39 +03002261 Py_XINCREF(d);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002262 }
2263 else {
Serhiy Storchaka41c57b32019-09-01 12:03:39 +03002264 if (_PyObject_LookupAttrId(v, &PyId___dict__, &d) == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002265 PyErr_SetString(PyExc_TypeError,
2266 "vars() argument must have __dict__ attribute");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002267 }
2268 }
2269 return d;
Guido van Rossum2d951851994-08-29 12:52:16 +00002270}
2271
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002272PyDoc_STRVAR(vars_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002273"vars([object]) -> dictionary\n\
2274\n\
2275Without arguments, equivalent to locals().\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002276With an argument, equivalent to object.__dict__.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002277
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002278
2279/*[clinic input]
2280sum as builtin_sum
2281
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03002282 iterable: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002283 /
Raymond Hettinger9dfa0fe2018-09-12 10:54:06 -07002284 start: object(c_default="NULL") = 0
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002285
2286Return the sum of a 'start' value (default: 0) plus an iterable of numbers
2287
2288When the iterable is empty, return the start value.
2289This function is intended specifically for use with numeric values and may
2290reject non-numeric types.
2291[clinic start generated code]*/
2292
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002293static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002294builtin_sum_impl(PyObject *module, PyObject *iterable, PyObject *start)
Raymond Hettinger9dfa0fe2018-09-12 10:54:06 -07002295/*[clinic end generated code: output=df758cec7d1d302f input=162b50765250d222]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002296{
2297 PyObject *result = start;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002298 PyObject *temp, *item, *iter;
Alex Martellia70b1912003-04-22 08:12:33 +00002299
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002300 iter = PyObject_GetIter(iterable);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002301 if (iter == NULL)
2302 return NULL;
Alex Martellia70b1912003-04-22 08:12:33 +00002303
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002304 if (result == NULL) {
2305 result = PyLong_FromLong(0);
2306 if (result == NULL) {
2307 Py_DECREF(iter);
2308 return NULL;
2309 }
2310 } else {
2311 /* reject string values for 'start' parameter */
2312 if (PyUnicode_Check(result)) {
2313 PyErr_SetString(PyExc_TypeError,
2314 "sum() can't sum strings [use ''.join(seq) instead]");
2315 Py_DECREF(iter);
2316 return NULL;
2317 }
Benjamin Petersonce071ca2011-07-29 14:23:47 -05002318 if (PyBytes_Check(result)) {
2319 PyErr_SetString(PyExc_TypeError,
2320 "sum() can't sum bytes [use b''.join(seq) instead]");
Benjamin Peterson405f32c2011-07-29 22:43:45 -05002321 Py_DECREF(iter);
Benjamin Petersonce071ca2011-07-29 14:23:47 -05002322 return NULL;
2323 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002324 if (PyByteArray_Check(result)) {
2325 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson4f921c22011-07-29 14:24:29 -05002326 "sum() can't sum bytearray [use b''.join(seq) instead]");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002327 Py_DECREF(iter);
2328 return NULL;
2329 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002330 Py_INCREF(result);
2331 }
Alex Martellia70b1912003-04-22 08:12:33 +00002332
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002333#ifndef SLOW_SUM
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002334 /* Fast addition by keeping temporary sums in C instead of new Python objects.
2335 Assumes all inputs are the same type. If the assumption fails, default
2336 to the more general routine.
2337 */
2338 if (PyLong_CheckExact(result)) {
2339 int overflow;
2340 long i_result = PyLong_AsLongAndOverflow(result, &overflow);
2341 /* If this already overflowed, don't even enter the loop. */
2342 if (overflow == 0) {
2343 Py_DECREF(result);
2344 result = NULL;
2345 }
2346 while(result == NULL) {
2347 item = PyIter_Next(iter);
2348 if (item == NULL) {
2349 Py_DECREF(iter);
2350 if (PyErr_Occurred())
2351 return NULL;
2352 return PyLong_FromLong(i_result);
2353 }
Serhiy Storchaka88bdb922019-09-10 16:31:01 +03002354 if (PyLong_CheckExact(item) || PyBool_Check(item)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002355 long b = PyLong_AsLongAndOverflow(item, &overflow);
Serhiy Storchaka29500732019-05-05 14:26:23 +03002356 if (overflow == 0 &&
2357 (i_result >= 0 ? (b <= LONG_MAX - i_result)
2358 : (b >= LONG_MIN - i_result)))
2359 {
2360 i_result += b;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002361 Py_DECREF(item);
2362 continue;
2363 }
2364 }
2365 /* Either overflowed or is not an int. Restore real objects and process normally */
2366 result = PyLong_FromLong(i_result);
Christian Heimes704e2d32013-07-26 22:49:26 +02002367 if (result == NULL) {
2368 Py_DECREF(item);
2369 Py_DECREF(iter);
2370 return NULL;
2371 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002372 temp = PyNumber_Add(result, item);
2373 Py_DECREF(result);
2374 Py_DECREF(item);
2375 result = temp;
2376 if (result == NULL) {
2377 Py_DECREF(iter);
2378 return NULL;
2379 }
2380 }
2381 }
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002382
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002383 if (PyFloat_CheckExact(result)) {
2384 double f_result = PyFloat_AS_DOUBLE(result);
2385 Py_DECREF(result);
2386 result = NULL;
2387 while(result == NULL) {
2388 item = PyIter_Next(iter);
2389 if (item == NULL) {
2390 Py_DECREF(iter);
2391 if (PyErr_Occurred())
2392 return NULL;
2393 return PyFloat_FromDouble(f_result);
2394 }
2395 if (PyFloat_CheckExact(item)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002396 f_result += PyFloat_AS_DOUBLE(item);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002397 Py_DECREF(item);
2398 continue;
2399 }
Serhiy Storchaka88bdb922019-09-10 16:31:01 +03002400 if (PyLong_Check(item)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002401 long value;
2402 int overflow;
2403 value = PyLong_AsLongAndOverflow(item, &overflow);
2404 if (!overflow) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002405 f_result += (double)value;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002406 Py_DECREF(item);
2407 continue;
2408 }
2409 }
2410 result = PyFloat_FromDouble(f_result);
Alexey Izbyshev2b824b22018-08-24 07:27:52 +03002411 if (result == NULL) {
2412 Py_DECREF(item);
2413 Py_DECREF(iter);
2414 return NULL;
2415 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002416 temp = PyNumber_Add(result, item);
2417 Py_DECREF(result);
2418 Py_DECREF(item);
2419 result = temp;
2420 if (result == NULL) {
2421 Py_DECREF(iter);
2422 return NULL;
2423 }
2424 }
2425 }
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002426#endif
2427
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002428 for(;;) {
2429 item = PyIter_Next(iter);
2430 if (item == NULL) {
2431 /* error, or end-of-sequence */
2432 if (PyErr_Occurred()) {
2433 Py_DECREF(result);
2434 result = NULL;
2435 }
2436 break;
2437 }
2438 /* It's tempting to use PyNumber_InPlaceAdd instead of
2439 PyNumber_Add here, to avoid quadratic running time
2440 when doing 'sum(list_of_lists, [])'. However, this
2441 would produce a change in behaviour: a snippet like
Mark Dickinson9acadc52009-10-26 14:19:42 +00002442
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002443 empty = []
2444 sum([[x] for x in range(10)], empty)
Mark Dickinson9acadc52009-10-26 14:19:42 +00002445
Brandt Bucherabb9a442020-02-01 03:08:34 -08002446 would change the value of empty. In fact, using
2447 in-place addition rather that binary addition for
2448 any of the steps introduces subtle behavior changes:
Victor Stinner58f4e1a2020-02-05 18:24:33 +01002449
Brandt Bucherabb9a442020-02-01 03:08:34 -08002450 https://bugs.python.org/issue18305 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002451 temp = PyNumber_Add(result, item);
2452 Py_DECREF(result);
2453 Py_DECREF(item);
2454 result = temp;
2455 if (result == NULL)
2456 break;
2457 }
2458 Py_DECREF(iter);
2459 return result;
Alex Martellia70b1912003-04-22 08:12:33 +00002460}
2461
Alex Martellia70b1912003-04-22 08:12:33 +00002462
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002463/*[clinic input]
2464isinstance as builtin_isinstance
2465
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03002466 obj: object
2467 class_or_tuple: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002468 /
2469
2470Return whether an object is an instance of a class or of a subclass thereof.
2471
2472A tuple, as in ``isinstance(x, (A, B, ...))``, may be given as the target to
2473check against. This is equivalent to ``isinstance(x, A) or isinstance(x, B)
2474or ...`` etc.
2475[clinic start generated code]*/
2476
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002477static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002478builtin_isinstance_impl(PyObject *module, PyObject *obj,
Larry Hastings89964c42015-04-14 18:07:59 -04002479 PyObject *class_or_tuple)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002480/*[clinic end generated code: output=6faf01472c13b003 input=ffa743db1daf7549]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002481{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002482 int retval;
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002483
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002484 retval = PyObject_IsInstance(obj, class_or_tuple);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002485 if (retval < 0)
2486 return NULL;
2487 return PyBool_FromLong(retval);
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002488}
2489
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002490
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002491/*[clinic input]
2492issubclass as builtin_issubclass
2493
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03002494 cls: object
2495 class_or_tuple: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002496 /
2497
Alex Poveldf773f82020-06-03 15:19:45 +02002498Return whether 'cls' is derived from another class or is the same class.
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002499
2500A tuple, as in ``issubclass(x, (A, B, ...))``, may be given as the target to
2501check against. This is equivalent to ``issubclass(x, A) or issubclass(x, B)
Alex Poveldf773f82020-06-03 15:19:45 +02002502or ...``.
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002503[clinic start generated code]*/
2504
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002505static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002506builtin_issubclass_impl(PyObject *module, PyObject *cls,
Larry Hastings89964c42015-04-14 18:07:59 -04002507 PyObject *class_or_tuple)
Alex Poveldf773f82020-06-03 15:19:45 +02002508/*[clinic end generated code: output=358412410cd7a250 input=a24b9f3d58c370d6]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002509{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002510 int retval;
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002511
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002512 retval = PyObject_IsSubclass(cls, class_or_tuple);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002513 if (retval < 0)
2514 return NULL;
2515 return PyBool_FromLong(retval);
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002516}
2517
2518
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002519typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002520 PyObject_HEAD
Guido van Rossum310f6aa2020-06-19 03:16:57 -07002521 Py_ssize_t tuplesize;
2522 PyObject *ittuple; /* tuple of iterators */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002523 PyObject *result;
Guido van Rossum310f6aa2020-06-19 03:16:57 -07002524 int strict;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002525} zipobject;
2526
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002527static PyObject *
2528zip_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
Barry Warsawbd599b52000-08-03 15:45:29 +00002529{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002530 zipobject *lz;
2531 Py_ssize_t i;
2532 PyObject *ittuple; /* tuple of iterators */
2533 PyObject *result;
Serhiy Storchakabf623ae2017-04-19 20:03:52 +03002534 Py_ssize_t tuplesize;
Guido van Rossum310f6aa2020-06-19 03:16:57 -07002535 int strict = 0;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002536
Guido van Rossum310f6aa2020-06-19 03:16:57 -07002537 if (kwds) {
2538 PyObject *empty = PyTuple_New(0);
2539 if (empty == NULL) {
2540 return NULL;
2541 }
2542 static char *kwlist[] = {"strict", NULL};
2543 int parsed = PyArg_ParseTupleAndKeywords(
2544 empty, kwds, "|$p:zip", kwlist, &strict);
2545 Py_DECREF(empty);
2546 if (!parsed) {
2547 return NULL;
2548 }
2549 }
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002550
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002551 /* args must be a tuple */
2552 assert(PyTuple_Check(args));
Serhiy Storchakabf623ae2017-04-19 20:03:52 +03002553 tuplesize = PyTuple_GET_SIZE(args);
Barry Warsawbd599b52000-08-03 15:45:29 +00002554
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002555 /* obtain iterators */
2556 ittuple = PyTuple_New(tuplesize);
2557 if (ittuple == NULL)
2558 return NULL;
2559 for (i=0; i < tuplesize; ++i) {
2560 PyObject *item = PyTuple_GET_ITEM(args, i);
2561 PyObject *it = PyObject_GetIter(item);
2562 if (it == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002563 Py_DECREF(ittuple);
2564 return NULL;
2565 }
2566 PyTuple_SET_ITEM(ittuple, i, it);
2567 }
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002568
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002569 /* create a result holder */
2570 result = PyTuple_New(tuplesize);
2571 if (result == NULL) {
2572 Py_DECREF(ittuple);
2573 return NULL;
2574 }
2575 for (i=0 ; i < tuplesize ; i++) {
2576 Py_INCREF(Py_None);
2577 PyTuple_SET_ITEM(result, i, Py_None);
2578 }
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002579
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002580 /* create zipobject structure */
2581 lz = (zipobject *)type->tp_alloc(type, 0);
2582 if (lz == NULL) {
2583 Py_DECREF(ittuple);
2584 Py_DECREF(result);
2585 return NULL;
2586 }
2587 lz->ittuple = ittuple;
2588 lz->tuplesize = tuplesize;
2589 lz->result = result;
Guido van Rossum310f6aa2020-06-19 03:16:57 -07002590 lz->strict = strict;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002591
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002592 return (PyObject *)lz;
Barry Warsawbd599b52000-08-03 15:45:29 +00002593}
2594
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002595static void
2596zip_dealloc(zipobject *lz)
2597{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002598 PyObject_GC_UnTrack(lz);
2599 Py_XDECREF(lz->ittuple);
2600 Py_XDECREF(lz->result);
2601 Py_TYPE(lz)->tp_free(lz);
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002602}
2603
2604static int
2605zip_traverse(zipobject *lz, visitproc visit, void *arg)
2606{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002607 Py_VISIT(lz->ittuple);
2608 Py_VISIT(lz->result);
2609 return 0;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002610}
2611
2612static PyObject *
2613zip_next(zipobject *lz)
2614{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002615 Py_ssize_t i;
2616 Py_ssize_t tuplesize = lz->tuplesize;
2617 PyObject *result = lz->result;
2618 PyObject *it;
2619 PyObject *item;
2620 PyObject *olditem;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002621
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002622 if (tuplesize == 0)
2623 return NULL;
2624 if (Py_REFCNT(result) == 1) {
2625 Py_INCREF(result);
2626 for (i=0 ; i < tuplesize ; i++) {
2627 it = PyTuple_GET_ITEM(lz->ittuple, i);
2628 item = (*Py_TYPE(it)->tp_iternext)(it);
Serhiy Storchaka278d03b2013-04-06 22:52:34 +03002629 if (item == NULL) {
2630 Py_DECREF(result);
Guido van Rossum310f6aa2020-06-19 03:16:57 -07002631 if (lz->strict) {
2632 goto check;
2633 }
Serhiy Storchaka278d03b2013-04-06 22:52:34 +03002634 return NULL;
2635 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002636 olditem = PyTuple_GET_ITEM(result, i);
2637 PyTuple_SET_ITEM(result, i, item);
2638 Py_DECREF(olditem);
2639 }
Brandt Bucher226a0122020-12-04 19:45:57 -08002640 // bpo-42536: The GC may have untracked this result tuple. Since we're
2641 // recycling it, make sure it's tracked again:
2642 if (!_PyObject_GC_IS_TRACKED(result)) {
2643 _PyObject_GC_TRACK(result);
2644 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002645 } else {
2646 result = PyTuple_New(tuplesize);
2647 if (result == NULL)
Serhiy Storchaka278d03b2013-04-06 22:52:34 +03002648 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002649 for (i=0 ; i < tuplesize ; i++) {
2650 it = PyTuple_GET_ITEM(lz->ittuple, i);
2651 item = (*Py_TYPE(it)->tp_iternext)(it);
Serhiy Storchaka278d03b2013-04-06 22:52:34 +03002652 if (item == NULL) {
2653 Py_DECREF(result);
Guido van Rossum310f6aa2020-06-19 03:16:57 -07002654 if (lz->strict) {
2655 goto check;
2656 }
Serhiy Storchaka278d03b2013-04-06 22:52:34 +03002657 return NULL;
2658 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002659 PyTuple_SET_ITEM(result, i, item);
2660 }
2661 }
2662 return result;
Guido van Rossum310f6aa2020-06-19 03:16:57 -07002663check:
2664 if (PyErr_Occurred()) {
2665 if (!PyErr_ExceptionMatches(PyExc_StopIteration)) {
2666 // next() on argument i raised an exception (not StopIteration)
2667 return NULL;
2668 }
2669 PyErr_Clear();
2670 }
2671 if (i) {
2672 // ValueError: zip() argument 2 is shorter than argument 1
2673 // ValueError: zip() argument 3 is shorter than arguments 1-2
2674 const char* plural = i == 1 ? " " : "s 1-";
2675 return PyErr_Format(PyExc_ValueError,
2676 "zip() argument %d is shorter than argument%s%d",
2677 i + 1, plural, i);
2678 }
2679 for (i = 1; i < tuplesize; i++) {
2680 it = PyTuple_GET_ITEM(lz->ittuple, i);
2681 item = (*Py_TYPE(it)->tp_iternext)(it);
2682 if (item) {
2683 Py_DECREF(item);
2684 const char* plural = i == 1 ? " " : "s 1-";
2685 return PyErr_Format(PyExc_ValueError,
2686 "zip() argument %d is longer than argument%s%d",
2687 i + 1, plural, i);
2688 }
2689 if (PyErr_Occurred()) {
2690 if (!PyErr_ExceptionMatches(PyExc_StopIteration)) {
2691 // next() on argument i raised an exception (not StopIteration)
2692 return NULL;
2693 }
2694 PyErr_Clear();
2695 }
2696 // Argument i is exhausted. So far so good...
2697 }
2698 // All arguments are exhausted. Success!
2699 return NULL;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002700}
Barry Warsawbd599b52000-08-03 15:45:29 +00002701
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002702static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05302703zip_reduce(zipobject *lz, PyObject *Py_UNUSED(ignored))
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002704{
2705 /* Just recreate the zip with the internal iterator tuple */
Guido van Rossum310f6aa2020-06-19 03:16:57 -07002706 if (lz->strict) {
2707 return PyTuple_Pack(3, Py_TYPE(lz), lz->ittuple, Py_True);
2708 }
2709 return PyTuple_Pack(2, Py_TYPE(lz), lz->ittuple);
2710}
2711
2712PyDoc_STRVAR(setstate_doc, "Set state information for unpickling.");
2713
2714static PyObject *
2715zip_setstate(zipobject *lz, PyObject *state)
2716{
2717 int strict = PyObject_IsTrue(state);
2718 if (strict < 0) {
2719 return NULL;
2720 }
2721 lz->strict = strict;
2722 Py_RETURN_NONE;
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002723}
2724
2725static PyMethodDef zip_methods[] = {
2726 {"__reduce__", (PyCFunction)zip_reduce, METH_NOARGS, reduce_doc},
Guido van Rossum310f6aa2020-06-19 03:16:57 -07002727 {"__setstate__", (PyCFunction)zip_setstate, METH_O, setstate_doc},
2728 {NULL} /* sentinel */
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002729};
2730
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002731PyDoc_STRVAR(zip_doc,
Guido van Rossum310f6aa2020-06-19 03:16:57 -07002732"zip(*iterables, strict=False) --> Yield tuples until an input is exhausted.\n\
Barry Warsawbd599b52000-08-03 15:45:29 +00002733\n\
Gregory P. Smith6a5d3ff2020-05-15 14:26:00 -07002734 >>> list(zip('abcdefg', range(3), range(4)))\n\
2735 [('a', 0, 0), ('b', 1, 1), ('c', 2, 2)]\n\
2736\n\
2737The zip object yields n-length tuples, where n is the number of iterables\n\
2738passed as positional arguments to zip(). The i-th element in every tuple\n\
2739comes from the i-th iterable argument to zip(). This continues until the\n\
Guido van Rossum310f6aa2020-06-19 03:16:57 -07002740shortest argument is exhausted.\n\
2741\n\
2742If strict is true and one of the arguments is exhausted before the others,\n\
2743raise a ValueError.");
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002744
2745PyTypeObject PyZip_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002746 PyVarObject_HEAD_INIT(&PyType_Type, 0)
2747 "zip", /* tp_name */
2748 sizeof(zipobject), /* tp_basicsize */
2749 0, /* tp_itemsize */
2750 /* methods */
2751 (destructor)zip_dealloc, /* tp_dealloc */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02002752 0, /* tp_vectorcall_offset */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002753 0, /* tp_getattr */
2754 0, /* tp_setattr */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02002755 0, /* tp_as_async */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002756 0, /* tp_repr */
2757 0, /* tp_as_number */
2758 0, /* tp_as_sequence */
2759 0, /* tp_as_mapping */
2760 0, /* tp_hash */
2761 0, /* tp_call */
2762 0, /* tp_str */
2763 PyObject_GenericGetAttr, /* tp_getattro */
2764 0, /* tp_setattro */
2765 0, /* tp_as_buffer */
2766 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
2767 Py_TPFLAGS_BASETYPE, /* tp_flags */
2768 zip_doc, /* tp_doc */
2769 (traverseproc)zip_traverse, /* tp_traverse */
2770 0, /* tp_clear */
2771 0, /* tp_richcompare */
2772 0, /* tp_weaklistoffset */
2773 PyObject_SelfIter, /* tp_iter */
2774 (iternextfunc)zip_next, /* tp_iternext */
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002775 zip_methods, /* tp_methods */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002776 0, /* tp_members */
2777 0, /* tp_getset */
2778 0, /* tp_base */
2779 0, /* tp_dict */
2780 0, /* tp_descr_get */
2781 0, /* tp_descr_set */
2782 0, /* tp_dictoffset */
2783 0, /* tp_init */
2784 PyType_GenericAlloc, /* tp_alloc */
2785 zip_new, /* tp_new */
2786 PyObject_GC_Del, /* tp_free */
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002787};
Barry Warsawbd599b52000-08-03 15:45:29 +00002788
2789
Guido van Rossum79f25d91997-04-29 20:08:16 +00002790static PyMethodDef builtin_methods[] = {
Serhiy Storchaka62be7422018-11-27 13:27:31 +02002791 {"__build_class__", (PyCFunction)(void(*)(void))builtin___build_class__,
Serhiy Storchaka6969eaf2017-07-03 21:20:15 +03002792 METH_FASTCALL | METH_KEYWORDS, build_class_doc},
Serhiy Storchaka62be7422018-11-27 13:27:31 +02002793 {"__import__", (PyCFunction)(void(*)(void))builtin___import__, METH_VARARGS | METH_KEYWORDS, import_doc},
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002794 BUILTIN_ABS_METHODDEF
2795 BUILTIN_ALL_METHODDEF
2796 BUILTIN_ANY_METHODDEF
2797 BUILTIN_ASCII_METHODDEF
2798 BUILTIN_BIN_METHODDEF
Serhiy Storchaka62be7422018-11-27 13:27:31 +02002799 {"breakpoint", (PyCFunction)(void(*)(void))builtin_breakpoint, METH_FASTCALL | METH_KEYWORDS, breakpoint_doc},
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002800 BUILTIN_CALLABLE_METHODDEF
2801 BUILTIN_CHR_METHODDEF
2802 BUILTIN_COMPILE_METHODDEF
2803 BUILTIN_DELATTR_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002804 {"dir", builtin_dir, METH_VARARGS, dir_doc},
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002805 BUILTIN_DIVMOD_METHODDEF
2806 BUILTIN_EVAL_METHODDEF
2807 BUILTIN_EXEC_METHODDEF
2808 BUILTIN_FORMAT_METHODDEF
Serhiy Storchaka62be7422018-11-27 13:27:31 +02002809 {"getattr", (PyCFunction)(void(*)(void))builtin_getattr, METH_FASTCALL, getattr_doc},
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002810 BUILTIN_GLOBALS_METHODDEF
2811 BUILTIN_HASATTR_METHODDEF
2812 BUILTIN_HASH_METHODDEF
2813 BUILTIN_HEX_METHODDEF
2814 BUILTIN_ID_METHODDEF
2815 BUILTIN_INPUT_METHODDEF
2816 BUILTIN_ISINSTANCE_METHODDEF
2817 BUILTIN_ISSUBCLASS_METHODDEF
Serhiy Storchaka79342662019-01-12 08:25:41 +02002818 {"iter", (PyCFunction)(void(*)(void))builtin_iter, METH_FASTCALL, iter_doc},
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002819 BUILTIN_LEN_METHODDEF
2820 BUILTIN_LOCALS_METHODDEF
Serhiy Storchaka62be7422018-11-27 13:27:31 +02002821 {"max", (PyCFunction)(void(*)(void))builtin_max, METH_VARARGS | METH_KEYWORDS, max_doc},
2822 {"min", (PyCFunction)(void(*)(void))builtin_min, METH_VARARGS | METH_KEYWORDS, min_doc},
2823 {"next", (PyCFunction)(void(*)(void))builtin_next, METH_FASTCALL, next_doc},
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002824 BUILTIN_OCT_METHODDEF
2825 BUILTIN_ORD_METHODDEF
2826 BUILTIN_POW_METHODDEF
Serhiy Storchaka62be7422018-11-27 13:27:31 +02002827 {"print", (PyCFunction)(void(*)(void))builtin_print, METH_FASTCALL | METH_KEYWORDS, print_doc},
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002828 BUILTIN_REPR_METHODDEF
Serhiy Storchakaaca7f572017-11-15 17:51:14 +02002829 BUILTIN_ROUND_METHODDEF
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002830 BUILTIN_SETATTR_METHODDEF
2831 BUILTIN_SORTED_METHODDEF
2832 BUILTIN_SUM_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002833 {"vars", builtin_vars, METH_VARARGS, vars_doc},
2834 {NULL, NULL},
Guido van Rossum3f5da241990-12-20 15:06:42 +00002835};
2836
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002837PyDoc_STRVAR(builtin_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002838"Built-in functions, exceptions, and other objects.\n\
2839\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002840Noteworthy: None is the `nil' object; Ellipsis represents `...' in slices.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002841
Martin v. Löwis1a214512008-06-11 05:26:20 +00002842static struct PyModuleDef builtinsmodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002843 PyModuleDef_HEAD_INIT,
2844 "builtins",
2845 builtin_doc,
2846 -1, /* multiple "initialization" just copies the module dict. */
2847 builtin_methods,
2848 NULL,
2849 NULL,
2850 NULL,
2851 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00002852};
2853
2854
Guido van Rossum25ce5661997-08-02 03:10:38 +00002855PyObject *
Victor Stinnerbcb094b2021-02-19 15:10:45 +01002856_PyBuiltin_Init(PyInterpreterState *interp)
Guido van Rossum25ce5661997-08-02 03:10:38 +00002857{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002858 PyObject *mod, *dict, *debug;
Benjamin Peterson42124a72012-10-30 23:41:54 -04002859
Victor Stinnerbcb094b2021-02-19 15:10:45 +01002860 const PyConfig *config = _PyInterpreterState_GetConfig(interp);
Victor Stinnerfbca9082018-08-30 00:50:45 +02002861
Benjamin Peterson42124a72012-10-30 23:41:54 -04002862 if (PyType_Ready(&PyFilter_Type) < 0 ||
2863 PyType_Ready(&PyMap_Type) < 0 ||
2864 PyType_Ready(&PyZip_Type) < 0)
2865 return NULL;
2866
Eric Snowd393c1b2017-09-14 12:18:12 -06002867 mod = _PyModule_CreateInitialized(&builtinsmodule, PYTHON_API_VERSION);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002868 if (mod == NULL)
2869 return NULL;
2870 dict = PyModule_GetDict(mod);
Tim Peters4b7625e2001-09-13 21:37:17 +00002871
Tim Peters7571a0f2003-03-23 17:52:28 +00002872#ifdef Py_TRACE_REFS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002873 /* "builtins" exposes a number of statically allocated objects
2874 * that, before this code was added in 2.3, never showed up in
2875 * the list of "all objects" maintained by Py_TRACE_REFS. As a
2876 * result, programs leaking references to None and False (etc)
2877 * couldn't be diagnosed by examining sys.getobjects(0).
2878 */
Tim Peters7571a0f2003-03-23 17:52:28 +00002879#define ADD_TO_ALL(OBJECT) _Py_AddToAllObjects((PyObject *)(OBJECT), 0)
2880#else
2881#define ADD_TO_ALL(OBJECT) (void)0
2882#endif
2883
Tim Peters4b7625e2001-09-13 21:37:17 +00002884#define SETBUILTIN(NAME, OBJECT) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002885 if (PyDict_SetItemString(dict, NAME, (PyObject *)OBJECT) < 0) \
2886 return NULL; \
2887 ADD_TO_ALL(OBJECT)
Tim Peters4b7625e2001-09-13 21:37:17 +00002888
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002889 SETBUILTIN("None", Py_None);
2890 SETBUILTIN("Ellipsis", Py_Ellipsis);
2891 SETBUILTIN("NotImplemented", Py_NotImplemented);
2892 SETBUILTIN("False", Py_False);
2893 SETBUILTIN("True", Py_True);
2894 SETBUILTIN("bool", &PyBool_Type);
2895 SETBUILTIN("memoryview", &PyMemoryView_Type);
2896 SETBUILTIN("bytearray", &PyByteArray_Type);
2897 SETBUILTIN("bytes", &PyBytes_Type);
2898 SETBUILTIN("classmethod", &PyClassMethod_Type);
2899 SETBUILTIN("complex", &PyComplex_Type);
2900 SETBUILTIN("dict", &PyDict_Type);
2901 SETBUILTIN("enumerate", &PyEnum_Type);
2902 SETBUILTIN("filter", &PyFilter_Type);
2903 SETBUILTIN("float", &PyFloat_Type);
2904 SETBUILTIN("frozenset", &PyFrozenSet_Type);
2905 SETBUILTIN("property", &PyProperty_Type);
2906 SETBUILTIN("int", &PyLong_Type);
2907 SETBUILTIN("list", &PyList_Type);
2908 SETBUILTIN("map", &PyMap_Type);
2909 SETBUILTIN("object", &PyBaseObject_Type);
2910 SETBUILTIN("range", &PyRange_Type);
2911 SETBUILTIN("reversed", &PyReversed_Type);
2912 SETBUILTIN("set", &PySet_Type);
2913 SETBUILTIN("slice", &PySlice_Type);
2914 SETBUILTIN("staticmethod", &PyStaticMethod_Type);
2915 SETBUILTIN("str", &PyUnicode_Type);
2916 SETBUILTIN("super", &PySuper_Type);
2917 SETBUILTIN("tuple", &PyTuple_Type);
2918 SETBUILTIN("type", &PyType_Type);
2919 SETBUILTIN("zip", &PyZip_Type);
Victor Stinnerfbca9082018-08-30 00:50:45 +02002920 debug = PyBool_FromLong(config->optimization_level == 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002921 if (PyDict_SetItemString(dict, "__debug__", debug) < 0) {
Serhiy Storchakacfdfbb42016-06-18 09:44:03 +03002922 Py_DECREF(debug);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002923 return NULL;
2924 }
Serhiy Storchakacfdfbb42016-06-18 09:44:03 +03002925 Py_DECREF(debug);
Barry Warsaw757af0e1997-08-29 22:13:51 +00002926
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002927 return mod;
Tim Peters7571a0f2003-03-23 17:52:28 +00002928#undef ADD_TO_ALL
Tim Peters4b7625e2001-09-13 21:37:17 +00002929#undef SETBUILTIN
Guido van Rossum3f5da241990-12-20 15:06:42 +00002930}