blob: 89b7fce8f4a9cc3ce8c52eefe8ad1ee9728f33b0 [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()
Guido van Rossum6bf62da1997-04-11 20:37:35 +000011
Victor Stinnerbd303c12013-11-07 23:07:29 +010012_Py_IDENTIFIER(__builtins__);
13_Py_IDENTIFIER(__dict__);
14_Py_IDENTIFIER(__prepare__);
15_Py_IDENTIFIER(__round__);
Ivan Levkivskyi2b5fd1e2017-12-14 23:32:56 +010016_Py_IDENTIFIER(__mro_entries__);
Victor Stinnerbd303c12013-11-07 23:07:29 +010017_Py_IDENTIFIER(encoding);
18_Py_IDENTIFIER(errors);
Martin v. Löwisbd928fe2011-10-14 10:20:37 +020019_Py_IDENTIFIER(fileno);
20_Py_IDENTIFIER(flush);
Victor Stinnerbd303c12013-11-07 23:07:29 +010021_Py_IDENTIFIER(metaclass);
22_Py_IDENTIFIER(sort);
23_Py_IDENTIFIER(stdin);
24_Py_IDENTIFIER(stdout);
25_Py_IDENTIFIER(stderr);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +020026
Serhiy Storchaka1009bf12015-04-03 23:53:51 +030027#include "clinic/bltinmodule.c.h"
28
Ivan Levkivskyi2b5fd1e2017-12-14 23:32:56 +010029static PyObject*
Victor Stinner05d68a82018-01-18 11:15:25 +010030update_bases(PyObject *bases, PyObject *const *args, Py_ssize_t nargs)
Ivan Levkivskyi2b5fd1e2017-12-14 23:32:56 +010031{
Victor Stinner05d68a82018-01-18 11:15:25 +010032 Py_ssize_t i, j;
Ivan Levkivskyi2b5fd1e2017-12-14 23:32:56 +010033 PyObject *base, *meth, *new_base, *result, *new_bases = NULL;
Ivan Levkivskyi2b5fd1e2017-12-14 23:32:56 +010034 assert(PyTuple_Check(bases));
35
36 for (i = 0; i < nargs; i++) {
37 base = args[i];
38 if (PyType_Check(base)) {
39 if (new_bases) {
40 /* If we already have made a replacement, then we append every normal base,
41 otherwise just skip it. */
42 if (PyList_Append(new_bases, base) < 0) {
43 goto error;
44 }
45 }
46 continue;
47 }
Serhiy Storchakaf320be72018-01-25 10:49:40 +020048 if (_PyObject_LookupAttrId(base, &PyId___mro_entries__, &meth) < 0) {
49 goto error;
50 }
Ivan Levkivskyi2b5fd1e2017-12-14 23:32:56 +010051 if (!meth) {
Ivan Levkivskyi2b5fd1e2017-12-14 23:32:56 +010052 if (new_bases) {
53 if (PyList_Append(new_bases, base) < 0) {
54 goto error;
55 }
56 }
57 continue;
58 }
Petr Viktorinffd97532020-02-11 17:46:57 +010059 new_base = PyObject_CallOneArg(meth, bases);
Ivan Levkivskyi2b5fd1e2017-12-14 23:32:56 +010060 Py_DECREF(meth);
61 if (!new_base) {
62 goto error;
63 }
64 if (!PyTuple_Check(new_base)) {
65 PyErr_SetString(PyExc_TypeError,
66 "__mro_entries__ must return a tuple");
67 Py_DECREF(new_base);
68 goto error;
69 }
70 if (!new_bases) {
71 /* If this is a first successful replacement, create new_bases list and
72 copy previously encountered bases. */
73 if (!(new_bases = PyList_New(i))) {
74 goto error;
75 }
76 for (j = 0; j < i; j++) {
77 base = args[j];
78 PyList_SET_ITEM(new_bases, j, base);
79 Py_INCREF(base);
80 }
81 }
82 j = PyList_GET_SIZE(new_bases);
83 if (PyList_SetSlice(new_bases, j, j, new_base) < 0) {
84 goto error;
85 }
86 Py_DECREF(new_base);
87 }
88 if (!new_bases) {
89 return bases;
90 }
91 result = PyList_AsTuple(new_bases);
92 Py_DECREF(new_bases);
93 return result;
94
95error:
96 Py_XDECREF(new_bases);
97 return NULL;
98}
99
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000100/* AC: cannot convert yet, waiting for *args support */
Guido van Rossum79f25d91997-04-29 20:08:16 +0000101static PyObject *
Serhiy Storchakaa5552f02017-12-15 13:11:11 +0200102builtin___build_class__(PyObject *self, PyObject *const *args, Py_ssize_t nargs,
Victor Stinner773dc6d2017-01-16 23:46:26 +0100103 PyObject *kwnames)
Guido van Rossum52cc1d82007-03-18 15:41:51 +0000104{
Ivan Levkivskyi2b5fd1e2017-12-14 23:32:56 +0100105 PyObject *func, *name, *bases, *mkw, *meta, *winner, *prep, *ns, *orig_bases;
Nick Coghlan19d24672016-12-05 16:47:55 +1000106 PyObject *cls = NULL, *cell = NULL;
Victor Stinner0c39b1b2015-03-18 15:02:06 +0100107 int isclass = 0; /* initialize to prevent gcc warning */
Guido van Rossum52cc1d82007-03-18 15:41:51 +0000108
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000109 if (nargs < 2) {
110 PyErr_SetString(PyExc_TypeError,
111 "__build_class__: not enough arguments");
112 return NULL;
113 }
Victor Stinner773dc6d2017-01-16 23:46:26 +0100114 func = args[0]; /* Better be callable */
Benjamin Petersone8e14592013-05-16 14:37:25 -0500115 if (!PyFunction_Check(func)) {
116 PyErr_SetString(PyExc_TypeError,
Zachary Ware9b338722014-08-05 14:01:10 -0500117 "__build_class__: func must be a function");
Benjamin Petersone8e14592013-05-16 14:37:25 -0500118 return NULL;
119 }
Victor Stinner773dc6d2017-01-16 23:46:26 +0100120 name = args[1];
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000121 if (!PyUnicode_Check(name)) {
122 PyErr_SetString(PyExc_TypeError,
123 "__build_class__: name is not a string");
124 return NULL;
125 }
Sergey Fedoseevf1b9abe2019-02-26 02:37:26 +0500126 orig_bases = _PyTuple_FromArray(args + 2, nargs - 2);
Ivan Levkivskyi2b5fd1e2017-12-14 23:32:56 +0100127 if (orig_bases == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000128 return NULL;
Guido van Rossum52cc1d82007-03-18 15:41:51 +0000129
Ivan Levkivskyi2b5fd1e2017-12-14 23:32:56 +0100130 bases = update_bases(orig_bases, args + 2, nargs - 2);
131 if (bases == NULL) {
132 Py_DECREF(orig_bases);
133 return NULL;
134 }
135
Victor Stinner773dc6d2017-01-16 23:46:26 +0100136 if (kwnames == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000137 meta = NULL;
138 mkw = NULL;
139 }
140 else {
Victor Stinner773dc6d2017-01-16 23:46:26 +0100141 mkw = _PyStack_AsDict(args + nargs, kwnames);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000142 if (mkw == NULL) {
143 Py_DECREF(bases);
144 return NULL;
Guido van Rossum52cc1d82007-03-18 15:41:51 +0000145 }
Victor Stinner773dc6d2017-01-16 23:46:26 +0100146
Serhiy Storchakaa24107b2019-02-25 17:59:46 +0200147 meta = _PyDict_GetItemIdWithError(mkw, &PyId_metaclass);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000148 if (meta != NULL) {
149 Py_INCREF(meta);
Victor Stinnerae9f1612013-11-06 22:46:51 +0100150 if (_PyDict_DelItemId(mkw, &PyId_metaclass) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000151 Py_DECREF(meta);
152 Py_DECREF(mkw);
153 Py_DECREF(bases);
154 return NULL;
155 }
Nick Coghlande31b192011-10-23 22:04:16 +1000156 /* metaclass is explicitly given, check if it's indeed a class */
157 isclass = PyType_Check(meta);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000158 }
Serhiy Storchakaa24107b2019-02-25 17:59:46 +0200159 else if (PyErr_Occurred()) {
160 Py_DECREF(mkw);
161 Py_DECREF(bases);
162 return NULL;
163 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000164 }
165 if (meta == NULL) {
Nick Coghlande31b192011-10-23 22:04:16 +1000166 /* if there are no bases, use type: */
167 if (PyTuple_GET_SIZE(bases) == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000168 meta = (PyObject *) (&PyType_Type);
Nick Coghlande31b192011-10-23 22:04:16 +1000169 }
170 /* else get the type of the first base */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000171 else {
172 PyObject *base0 = PyTuple_GET_ITEM(bases, 0);
Victor Stinnera102ed72020-02-07 02:24:48 +0100173 meta = (PyObject *)Py_TYPE(base0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000174 }
175 Py_INCREF(meta);
Nick Coghlande31b192011-10-23 22:04:16 +1000176 isclass = 1; /* meta is really a class */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000177 }
Nick Coghlan9715d262011-10-23 22:36:42 +1000178
Nick Coghlande31b192011-10-23 22:04:16 +1000179 if (isclass) {
180 /* meta is really a class, so check for a more derived
181 metaclass, or possible metaclass conflicts: */
182 winner = (PyObject *)_PyType_CalculateMetaclass((PyTypeObject *)meta,
183 bases);
184 if (winner == NULL) {
185 Py_DECREF(meta);
186 Py_XDECREF(mkw);
187 Py_DECREF(bases);
188 return NULL;
189 }
190 if (winner != meta) {
191 Py_DECREF(meta);
192 meta = winner;
193 Py_INCREF(meta);
194 }
195 }
196 /* else: meta is not a class, so we cannot do the metaclass
197 calculation, so we will use the explicitly given object as it is */
Serhiy Storchakaf320be72018-01-25 10:49:40 +0200198 if (_PyObject_LookupAttrId(meta, &PyId___prepare__, &prep) < 0) {
199 ns = NULL;
200 }
201 else if (prep == NULL) {
202 ns = PyDict_New();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000203 }
204 else {
Victor Stinner463b86a2016-08-22 23:33:13 +0200205 PyObject *pargs[2] = {name, bases};
Petr Viktorinffd97532020-02-11 17:46:57 +0100206 ns = PyObject_VectorcallDict(prep, pargs, 2, mkw);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000207 Py_DECREF(prep);
208 }
209 if (ns == NULL) {
210 Py_DECREF(meta);
211 Py_XDECREF(mkw);
212 Py_DECREF(bases);
213 return NULL;
214 }
Oren Milman5837d042017-09-27 17:04:37 +0300215 if (!PyMapping_Check(ns)) {
216 PyErr_Format(PyExc_TypeError,
217 "%.200s.__prepare__() must return a mapping, not %.200s",
218 isclass ? ((PyTypeObject *)meta)->tp_name : "<metaclass>",
219 Py_TYPE(ns)->tp_name);
220 goto error;
221 }
Nick Coghlan19d24672016-12-05 16:47:55 +1000222 cell = PyEval_EvalCodeEx(PyFunction_GET_CODE(func), PyFunction_GET_GLOBALS(func), ns,
Benjamin Petersone8e14592013-05-16 14:37:25 -0500223 NULL, 0, NULL, 0, NULL, 0, NULL,
224 PyFunction_GET_CLOSURE(func));
Nick Coghlan19d24672016-12-05 16:47:55 +1000225 if (cell != NULL) {
Ivan Levkivskyi2b5fd1e2017-12-14 23:32:56 +0100226 if (bases != orig_bases) {
227 if (PyMapping_SetItemString(ns, "__orig_bases__", orig_bases) < 0) {
228 goto error;
229 }
230 }
Victor Stinnerd1c2a8e2016-08-23 01:34:35 +0200231 PyObject *margs[3] = {name, bases, ns};
Petr Viktorinffd97532020-02-11 17:46:57 +0100232 cls = PyObject_VectorcallDict(meta, margs, 3, mkw);
Nick Coghlan19d24672016-12-05 16:47:55 +1000233 if (cls != NULL && PyType_Check(cls) && PyCell_Check(cell)) {
234 PyObject *cell_cls = PyCell_GET(cell);
235 if (cell_cls != cls) {
Nick Coghlan19d24672016-12-05 16:47:55 +1000236 if (cell_cls == NULL) {
237 const char *msg =
238 "__class__ not set defining %.200R as %.200R. "
239 "Was __classcell__ propagated to type.__new__?";
Serhiy Storchakaf5e7b192018-05-20 08:48:12 +0300240 PyErr_Format(PyExc_RuntimeError, msg, name, cls);
Nick Coghlan19d24672016-12-05 16:47:55 +1000241 } else {
242 const char *msg =
243 "__class__ set to %.200R defining %.200R as %.200R";
244 PyErr_Format(PyExc_TypeError, msg, cell_cls, name, cls);
Nick Coghlan19d24672016-12-05 16:47:55 +1000245 }
Serhiy Storchakaf5e7b192018-05-20 08:48:12 +0300246 Py_DECREF(cls);
247 cls = NULL;
248 goto error;
Nick Coghlan19d24672016-12-05 16:47:55 +1000249 }
250 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000251 }
Nick Coghlan19d24672016-12-05 16:47:55 +1000252error:
253 Py_XDECREF(cell);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000254 Py_DECREF(ns);
255 Py_DECREF(meta);
256 Py_XDECREF(mkw);
257 Py_DECREF(bases);
Ivan Levkivskyi2b5fd1e2017-12-14 23:32:56 +0100258 if (bases != orig_bases) {
259 Py_DECREF(orig_bases);
260 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000261 return cls;
Guido van Rossum52cc1d82007-03-18 15:41:51 +0000262}
263
264PyDoc_STRVAR(build_class_doc,
Pablo Galindoe3babbd2019-10-13 16:35:41 +0100265"__build_class__(func, name, /, *bases, [metaclass], **kwds) -> class\n\
Guido van Rossum52cc1d82007-03-18 15:41:51 +0000266\n\
267Internal helper function used by the class statement.");
268
269static PyObject *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000270builtin___import__(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000271{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000272 static char *kwlist[] = {"name", "globals", "locals", "fromlist",
273 "level", 0};
Victor Stinnerfe93faf2011-03-14 15:54:52 -0400274 PyObject *name, *globals = NULL, *locals = NULL, *fromlist = NULL;
Brett Cannonfd074152012-04-14 14:10:13 -0400275 int level = 0;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000276
Victor Stinnerfe93faf2011-03-14 15:54:52 -0400277 if (!PyArg_ParseTupleAndKeywords(args, kwds, "U|OOOi:__import__",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000278 kwlist, &name, &globals, &locals, &fromlist, &level))
279 return NULL;
Victor Stinnerfe93faf2011-03-14 15:54:52 -0400280 return PyImport_ImportModuleLevelObject(name, globals, locals,
281 fromlist, level);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000282}
283
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000284PyDoc_STRVAR(import_doc,
Brett Cannoncb4996a2012-08-06 16:34:44 -0400285"__import__(name, globals=None, locals=None, fromlist=(), level=0) -> module\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000286\n\
Brett Cannon5305a992010-09-27 21:08:38 +0000287Import a module. Because this function is meant for use by the Python\n\
oldk461d2252018-02-02 12:20:00 +0800288interpreter and not for general use, it is better to use\n\
Brett Cannon5305a992010-09-27 21:08:38 +0000289importlib.import_module() to programmatically import a module.\n\
290\n\
291The globals argument is only used to determine the context;\n\
292they are not modified. The locals argument is unused. The fromlist\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000293should be a list of names to emulate ``from name import ...'', or an\n\
294empty list to emulate ``import name''.\n\
295When importing a module from a package, note that __import__('A.B', ...)\n\
296returns package A when fromlist is empty, but its submodule B when\n\
oldk461d2252018-02-02 12:20:00 +0800297fromlist is not empty. The level argument is used to determine whether to\n\
298perform absolute or relative imports: 0 is absolute, while a positive number\n\
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000299is the number of parent directories to search relative to the current module.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000300
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000301
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000302/*[clinic input]
303abs as builtin_abs
304
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300305 x: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000306 /
307
308Return the absolute value of the argument.
309[clinic start generated code]*/
310
Guido van Rossum79f25d91997-04-29 20:08:16 +0000311static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300312builtin_abs(PyObject *module, PyObject *x)
313/*[clinic end generated code: output=b1b433b9e51356f5 input=bed4ca14e29c20d1]*/
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000314{
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000315 return PyNumber_Absolute(x);
Guido van Rossum3f5da241990-12-20 15:06:42 +0000316}
317
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000318/*[clinic input]
319all as builtin_all
320
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300321 iterable: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000322 /
323
324Return True if bool(x) is True for all values x in the iterable.
325
326If the iterable is empty, return True.
327[clinic start generated code]*/
328
Raymond Hettinger96229b12005-03-11 06:49:40 +0000329static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300330builtin_all(PyObject *module, PyObject *iterable)
331/*[clinic end generated code: output=ca2a7127276f79b3 input=1a7c5d1bc3438a21]*/
Raymond Hettinger96229b12005-03-11 06:49:40 +0000332{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000333 PyObject *it, *item;
334 PyObject *(*iternext)(PyObject *);
335 int cmp;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000336
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000337 it = PyObject_GetIter(iterable);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000338 if (it == NULL)
339 return NULL;
340 iternext = *Py_TYPE(it)->tp_iternext;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000341
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000342 for (;;) {
343 item = iternext(it);
344 if (item == NULL)
345 break;
346 cmp = PyObject_IsTrue(item);
347 Py_DECREF(item);
348 if (cmp < 0) {
349 Py_DECREF(it);
350 return NULL;
351 }
352 if (cmp == 0) {
353 Py_DECREF(it);
354 Py_RETURN_FALSE;
355 }
356 }
357 Py_DECREF(it);
358 if (PyErr_Occurred()) {
359 if (PyErr_ExceptionMatches(PyExc_StopIteration))
360 PyErr_Clear();
361 else
362 return NULL;
363 }
364 Py_RETURN_TRUE;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000365}
366
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000367/*[clinic input]
368any as builtin_any
369
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300370 iterable: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000371 /
372
373Return True if bool(x) is True for any x in the iterable.
374
375If the iterable is empty, return False.
376[clinic start generated code]*/
377
Raymond Hettinger96229b12005-03-11 06:49:40 +0000378static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300379builtin_any(PyObject *module, PyObject *iterable)
380/*[clinic end generated code: output=fa65684748caa60e input=41d7451c23384f24]*/
Raymond Hettinger96229b12005-03-11 06:49:40 +0000381{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000382 PyObject *it, *item;
383 PyObject *(*iternext)(PyObject *);
384 int cmp;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000385
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000386 it = PyObject_GetIter(iterable);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000387 if (it == NULL)
388 return NULL;
389 iternext = *Py_TYPE(it)->tp_iternext;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000390
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000391 for (;;) {
392 item = iternext(it);
393 if (item == NULL)
394 break;
395 cmp = PyObject_IsTrue(item);
396 Py_DECREF(item);
397 if (cmp < 0) {
398 Py_DECREF(it);
399 return NULL;
400 }
Raymond Hettinger5098b582015-10-09 00:42:47 -0400401 if (cmp > 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000402 Py_DECREF(it);
403 Py_RETURN_TRUE;
404 }
405 }
406 Py_DECREF(it);
407 if (PyErr_Occurred()) {
408 if (PyErr_ExceptionMatches(PyExc_StopIteration))
409 PyErr_Clear();
410 else
411 return NULL;
412 }
413 Py_RETURN_FALSE;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000414}
415
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000416/*[clinic input]
417ascii as builtin_ascii
418
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300419 obj: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000420 /
421
422Return an ASCII-only representation of an object.
423
424As repr(), return a string containing a printable representation of an
425object, but escape the non-ASCII characters in the string returned by
426repr() using \\x, \\u or \\U escapes. This generates a string similar
427to that returned by repr() in Python 2.
428[clinic start generated code]*/
429
Georg Brandl559e5d72008-06-11 18:37:52 +0000430static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300431builtin_ascii(PyObject *module, PyObject *obj)
432/*[clinic end generated code: output=6d37b3f0984c7eb9 input=4c62732e1b3a3cc9]*/
Georg Brandl559e5d72008-06-11 18:37:52 +0000433{
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000434 return PyObject_ASCII(obj);
Georg Brandl559e5d72008-06-11 18:37:52 +0000435}
436
Georg Brandl559e5d72008-06-11 18:37:52 +0000437
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000438/*[clinic input]
439bin as builtin_bin
440
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300441 number: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000442 /
443
444Return the binary representation of an integer.
445
446 >>> bin(2796202)
447 '0b1010101010101010101010'
448[clinic start generated code]*/
449
Guido van Rossum79f25d91997-04-29 20:08:16 +0000450static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300451builtin_bin(PyObject *module, PyObject *number)
452/*[clinic end generated code: output=b6fc4ad5e649f4f7 input=53f8a0264bacaf90]*/
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000453{
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000454 return PyNumber_ToBase(number, 2);
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000455}
456
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000457
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000458/*[clinic input]
459callable as builtin_callable
460
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300461 obj: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000462 /
463
464Return whether the object is callable (i.e., some kind of function).
465
466Note that classes are callable, as are instances of classes with a
467__call__() method.
468[clinic start generated code]*/
469
Antoine Pitroue71362d2010-11-27 22:00:11 +0000470static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300471builtin_callable(PyObject *module, PyObject *obj)
472/*[clinic end generated code: output=2b095d59d934cb7e input=1423bab99cc41f58]*/
Antoine Pitroue71362d2010-11-27 22:00:11 +0000473{
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000474 return PyBool_FromLong((long)PyCallable_Check(obj));
Antoine Pitroue71362d2010-11-27 22:00:11 +0000475}
476
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400477static PyObject *
Serhiy Storchakaa5552f02017-12-15 13:11:11 +0200478builtin_breakpoint(PyObject *self, PyObject *const *args, Py_ssize_t nargs, PyObject *keywords)
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400479{
480 PyObject *hook = PySys_GetObject("breakpointhook");
481
482 if (hook == NULL) {
483 PyErr_SetString(PyExc_RuntimeError, "lost sys.breakpointhook");
484 return NULL;
485 }
Steve Dower60419a72019-06-24 08:42:54 -0700486
487 if (PySys_Audit("builtins.breakpoint", "O", hook) < 0) {
488 return NULL;
489 }
490
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400491 Py_INCREF(hook);
Petr Viktorinffd97532020-02-11 17:46:57 +0100492 PyObject *retval = PyObject_Vectorcall(hook, args, nargs, keywords);
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400493 Py_DECREF(hook);
494 return retval;
495}
496
497PyDoc_STRVAR(breakpoint_doc,
498"breakpoint(*args, **kws)\n\
499\n\
500Call sys.breakpointhook(*args, **kws). sys.breakpointhook() must accept\n\
501whatever arguments are passed.\n\
502\n\
503By default, this drops you into the pdb debugger.");
Antoine Pitroue71362d2010-11-27 22:00:11 +0000504
Raymond Hettinger17301e92008-03-13 00:19:26 +0000505typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000506 PyObject_HEAD
507 PyObject *func;
508 PyObject *it;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000509} filterobject;
510
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000511static PyObject *
Raymond Hettinger17301e92008-03-13 00:19:26 +0000512filter_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
Guido van Rossum12d12c51993-10-26 17:58:25 +0000513{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000514 PyObject *func, *seq;
515 PyObject *it;
516 filterobject *lz;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000517
Serhiy Storchaka6cca5c82017-06-08 14:41:19 +0300518 if (type == &PyFilter_Type && !_PyArg_NoKeywords("filter", kwds))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000519 return NULL;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000520
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000521 if (!PyArg_UnpackTuple(args, "filter", 2, 2, &func, &seq))
522 return NULL;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000523
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000524 /* Get iterator. */
525 it = PyObject_GetIter(seq);
526 if (it == NULL)
527 return NULL;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000528
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000529 /* create filterobject structure */
530 lz = (filterobject *)type->tp_alloc(type, 0);
531 if (lz == NULL) {
532 Py_DECREF(it);
533 return NULL;
534 }
535 Py_INCREF(func);
536 lz->func = func;
537 lz->it = it;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000538
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000539 return (PyObject *)lz;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000540}
541
542static void
543filter_dealloc(filterobject *lz)
544{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000545 PyObject_GC_UnTrack(lz);
546 Py_XDECREF(lz->func);
547 Py_XDECREF(lz->it);
548 Py_TYPE(lz)->tp_free(lz);
Raymond Hettinger17301e92008-03-13 00:19:26 +0000549}
550
551static int
552filter_traverse(filterobject *lz, visitproc visit, void *arg)
553{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000554 Py_VISIT(lz->it);
555 Py_VISIT(lz->func);
556 return 0;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000557}
558
559static PyObject *
560filter_next(filterobject *lz)
561{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000562 PyObject *item;
563 PyObject *it = lz->it;
564 long ok;
565 PyObject *(*iternext)(PyObject *);
Raymond Hettingerbd5f0e82015-10-09 01:34:08 -0400566 int checktrue = lz->func == Py_None || lz->func == (PyObject *)&PyBool_Type;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000567
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000568 iternext = *Py_TYPE(it)->tp_iternext;
569 for (;;) {
570 item = iternext(it);
571 if (item == NULL)
572 return NULL;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000573
Raymond Hettingerbd5f0e82015-10-09 01:34:08 -0400574 if (checktrue) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000575 ok = PyObject_IsTrue(item);
576 } else {
577 PyObject *good;
Petr Viktorinffd97532020-02-11 17:46:57 +0100578 good = PyObject_CallOneArg(lz->func, item);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000579 if (good == NULL) {
580 Py_DECREF(item);
581 return NULL;
582 }
583 ok = PyObject_IsTrue(good);
584 Py_DECREF(good);
585 }
Antoine Pitrou6f430e42012-08-15 23:18:25 +0200586 if (ok > 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000587 return item;
588 Py_DECREF(item);
Antoine Pitrou6f430e42012-08-15 23:18:25 +0200589 if (ok < 0)
590 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000591 }
Guido van Rossum12d12c51993-10-26 17:58:25 +0000592}
593
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +0000594static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +0530595filter_reduce(filterobject *lz, PyObject *Py_UNUSED(ignored))
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +0000596{
597 return Py_BuildValue("O(OO)", Py_TYPE(lz), lz->func, lz->it);
598}
599
600PyDoc_STRVAR(reduce_doc, "Return state information for pickling.");
601
602static PyMethodDef filter_methods[] = {
603 {"__reduce__", (PyCFunction)filter_reduce, METH_NOARGS, reduce_doc},
604 {NULL, NULL} /* sentinel */
605};
606
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000607PyDoc_STRVAR(filter_doc,
Georg Brandld11ae5d2008-05-16 13:27:32 +0000608"filter(function or None, iterable) --> filter object\n\
Guido van Rossumc1f779c2007-07-03 08:25:58 +0000609\n\
Georg Brandld11ae5d2008-05-16 13:27:32 +0000610Return an iterator yielding those items of iterable for which function(item)\n\
Raymond Hettinger17301e92008-03-13 00:19:26 +0000611is true. If function is None, return the items that are true.");
612
613PyTypeObject PyFilter_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000614 PyVarObject_HEAD_INIT(&PyType_Type, 0)
615 "filter", /* tp_name */
616 sizeof(filterobject), /* tp_basicsize */
617 0, /* tp_itemsize */
618 /* methods */
619 (destructor)filter_dealloc, /* tp_dealloc */
Jeroen Demeyer530f5062019-05-31 04:13:39 +0200620 0, /* tp_vectorcall_offset */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000621 0, /* tp_getattr */
622 0, /* tp_setattr */
Jeroen Demeyer530f5062019-05-31 04:13:39 +0200623 0, /* tp_as_async */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000624 0, /* tp_repr */
625 0, /* tp_as_number */
626 0, /* tp_as_sequence */
627 0, /* tp_as_mapping */
628 0, /* tp_hash */
629 0, /* tp_call */
630 0, /* tp_str */
631 PyObject_GenericGetAttr, /* tp_getattro */
632 0, /* tp_setattro */
633 0, /* tp_as_buffer */
634 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
635 Py_TPFLAGS_BASETYPE, /* tp_flags */
636 filter_doc, /* tp_doc */
637 (traverseproc)filter_traverse, /* tp_traverse */
638 0, /* tp_clear */
639 0, /* tp_richcompare */
640 0, /* tp_weaklistoffset */
641 PyObject_SelfIter, /* tp_iter */
642 (iternextfunc)filter_next, /* tp_iternext */
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +0000643 filter_methods, /* tp_methods */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000644 0, /* tp_members */
645 0, /* tp_getset */
646 0, /* tp_base */
647 0, /* tp_dict */
648 0, /* tp_descr_get */
649 0, /* tp_descr_set */
650 0, /* tp_dictoffset */
651 0, /* tp_init */
652 PyType_GenericAlloc, /* tp_alloc */
653 filter_new, /* tp_new */
654 PyObject_GC_Del, /* tp_free */
Raymond Hettinger17301e92008-03-13 00:19:26 +0000655};
656
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000657
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000658/*[clinic input]
659format as builtin_format
660
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300661 value: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000662 format_spec: unicode(c_default="NULL") = ''
663 /
664
665Return value.__format__(format_spec)
666
Amit Kumar2e6bb442017-05-29 06:32:26 +0530667format_spec defaults to the empty string.
668See the Format Specification Mini-Language section of help('FORMATTING') for
669details.
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000670[clinic start generated code]*/
671
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000672static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300673builtin_format_impl(PyObject *module, PyObject *value, PyObject *format_spec)
Amit Kumar2e6bb442017-05-29 06:32:26 +0530674/*[clinic end generated code: output=2f40bdfa4954b077 input=88339c93ea522b33]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000675{
Eric Smith8fd3eba2008-02-17 19:48:00 +0000676 return PyObject_Format(value, format_spec);
Eric Smith8c663262007-08-25 02:26:07 +0000677}
678
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000679/*[clinic input]
680chr as builtin_chr
681
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300682 i: int
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000683 /
684
685Return a Unicode string of one character with ordinal i; 0 <= i <= 0x10ffff.
686[clinic start generated code]*/
687
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000688static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300689builtin_chr_impl(PyObject *module, int i)
690/*[clinic end generated code: output=c733afcd200afcb7 input=3f604ef45a70750d]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000691{
692 return PyUnicode_FromOrdinal(i);
693}
Guido van Rossum09095f32000-03-10 23:00:52 +0000694
695
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000696/*[clinic input]
697compile as builtin_compile
698
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300699 source: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000700 filename: object(converter="PyUnicode_FSDecoder")
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300701 mode: str
702 flags: int = 0
Serhiy Storchaka202fda52017-03-12 10:10:47 +0200703 dont_inherit: bool(accept={int}) = False
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300704 optimize: int = -1
Victor Stinnerefdf6ca2019-06-12 02:52:16 +0200705 *
706 _feature_version as feature_version: int = -1
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000707
708Compile source into a code object that can be executed by exec() or eval().
709
710The source code may represent a Python module, statement or expression.
711The filename will be used for run-time error messages.
712The mode must be 'exec' to compile a module, 'single' to compile a
713single (interactive) statement, or 'eval' to compile an expression.
714The flags argument, if present, controls which future statements influence
715the compilation of the code.
Serhiy Storchaka8b2e8b62015-05-30 11:30:39 +0300716The dont_inherit argument, if true, stops the compilation inheriting
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000717the effects of any future statements in effect in the code calling
Serhiy Storchaka8b2e8b62015-05-30 11:30:39 +0300718compile; if absent or false these statements do influence the compilation,
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000719in addition to any features explicitly specified.
720[clinic start generated code]*/
721
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000722static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300723builtin_compile_impl(PyObject *module, PyObject *source, PyObject *filename,
724 const char *mode, int flags, int dont_inherit,
Guido van Rossum495da292019-03-07 12:38:08 -0800725 int optimize, int feature_version)
Victor Stinnerefdf6ca2019-06-12 02:52:16 +0200726/*[clinic end generated code: output=b0c09c84f116d3d7 input=40171fb92c1d580d]*/
Guido van Rossum5b722181993-03-30 17:46:03 +0000727{
Martin Panter61d6e4a2015-11-07 02:56:11 +0000728 PyObject *source_copy;
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +0200729 const char *str;
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000730 int compile_mode = -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000731 int is_ast;
Guido van Rossumdcfcd142019-01-31 03:40:27 -0800732 int start[] = {Py_file_input, Py_eval_input, Py_single_input, Py_func_type_input};
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000733 PyObject *result;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000734
Victor Stinner37d66d72019-06-13 02:16:41 +0200735 PyCompilerFlags cf = _PyCompilerFlags_INIT;
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000736 cf.cf_flags = flags | PyCF_SOURCE_IS_UTF8;
Guido van Rossum495da292019-03-07 12:38:08 -0800737 if (feature_version >= 0 && (flags & PyCF_ONLY_AST)) {
738 cf.cf_feature_version = feature_version;
739 }
Tim Peters6cd6a822001-08-17 22:11:27 +0000740
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000741 if (flags &
Batuhan Taşkaya44540572020-04-22 19:09:03 +0300742 ~(PyCF_MASK | PyCF_MASK_OBSOLETE | PyCF_COMPILE_MASK))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000743 {
744 PyErr_SetString(PyExc_ValueError,
745 "compile(): unrecognised flags");
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000746 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000747 }
748 /* XXX Warn if (supplied_flags & PyCF_MASK_OBSOLETE) != 0? */
Tim Peters6cd6a822001-08-17 22:11:27 +0000749
Georg Brandl8334fd92010-12-04 10:26:46 +0000750 if (optimize < -1 || optimize > 2) {
751 PyErr_SetString(PyExc_ValueError,
752 "compile(): invalid optimize value");
753 goto error;
754 }
755
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000756 if (!dont_inherit) {
757 PyEval_MergeCompilerFlags(&cf);
758 }
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000759
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000760 if (strcmp(mode, "exec") == 0)
761 compile_mode = 0;
762 else if (strcmp(mode, "eval") == 0)
763 compile_mode = 1;
764 else if (strcmp(mode, "single") == 0)
765 compile_mode = 2;
Guido van Rossumdcfcd142019-01-31 03:40:27 -0800766 else if (strcmp(mode, "func_type") == 0) {
767 if (!(flags & PyCF_ONLY_AST)) {
768 PyErr_SetString(PyExc_ValueError,
769 "compile() mode 'func_type' requires flag PyCF_ONLY_AST");
770 goto error;
771 }
772 compile_mode = 3;
773 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000774 else {
Guido van Rossumdcfcd142019-01-31 03:40:27 -0800775 const char *msg;
776 if (flags & PyCF_ONLY_AST)
777 msg = "compile() mode must be 'exec', 'eval', 'single' or 'func_type'";
778 else
779 msg = "compile() mode must be 'exec', 'eval' or 'single'";
780 PyErr_SetString(PyExc_ValueError, msg);
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000781 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000782 }
Neal Norwitzdb4115f2008-03-31 04:20:05 +0000783
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000784 is_ast = PyAST_Check(source);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000785 if (is_ast == -1)
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000786 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000787 if (is_ast) {
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000788 if (flags & PyCF_ONLY_AST) {
789 Py_INCREF(source);
790 result = source;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000791 }
792 else {
793 PyArena *arena;
794 mod_ty mod;
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000795
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000796 arena = PyArena_New();
Stefan Krah07795df2012-08-20 17:19:50 +0200797 if (arena == NULL)
798 goto error;
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000799 mod = PyAST_obj2mod(source, arena, compile_mode);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000800 if (mod == NULL) {
801 PyArena_Free(arena);
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000802 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000803 }
Benjamin Peterson832bfe22011-08-09 16:15:04 -0500804 if (!PyAST_Validate(mod)) {
805 PyArena_Free(arena);
806 goto error;
807 }
Victor Stinner14e461d2013-08-26 22:28:21 +0200808 result = (PyObject*)PyAST_CompileObject(mod, filename,
809 &cf, optimize, arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000810 PyArena_Free(arena);
811 }
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000812 goto finally;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000813 }
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000814
Dino Viehland41540692019-05-28 16:21:17 -0700815 str = _Py_SourceAsString(source, "compile", "string, bytes or AST", &cf, &source_copy);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000816 if (str == NULL)
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000817 goto error;
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000818
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000819 result = Py_CompileStringObject(str, filename, start[compile_mode], &cf, optimize);
Guido van Rossumc001c092020-04-30 12:12:19 -0700820
Martin Panter61d6e4a2015-11-07 02:56:11 +0000821 Py_XDECREF(source_copy);
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000822 goto finally;
823
824error:
825 result = NULL;
826finally:
Victor Stinner14e461d2013-08-26 22:28:21 +0200827 Py_DECREF(filename);
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000828 return result;
Guido van Rossum5b722181993-03-30 17:46:03 +0000829}
830
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000831/* AC: cannot convert yet, as needs PEP 457 group support in inspect */
Guido van Rossum79f25d91997-04-29 20:08:16 +0000832static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000833builtin_dir(PyObject *self, PyObject *args)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000834{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000835 PyObject *arg = NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000836
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000837 if (!PyArg_UnpackTuple(args, "dir", 0, 1, &arg))
838 return NULL;
839 return PyObject_Dir(arg);
Guido van Rossum3f5da241990-12-20 15:06:42 +0000840}
841
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000842PyDoc_STRVAR(dir_doc,
Tim Peters5d2b77c2001-09-03 05:47:38 +0000843"dir([object]) -> list of strings\n"
844"\n"
Georg Brandle32b4222007-03-10 22:13:27 +0000845"If called without an argument, return the names in the current scope.\n"
846"Else, return an alphabetized list of names comprising (some of) the attributes\n"
847"of the given object, and of attributes reachable from it.\n"
848"If the object supplies a method named __dir__, it will be used; otherwise\n"
849"the default dir() logic is used and returns:\n"
850" for a module object: the module's attributes.\n"
851" for a class object: its attributes, and recursively the attributes\n"
852" of its bases.\n"
Guido van Rossumd8faa362007-04-27 19:54:29 +0000853" for any other object: its attributes, its class's attributes, and\n"
Georg Brandle32b4222007-03-10 22:13:27 +0000854" recursively the attributes of its class's base classes.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000855
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000856/*[clinic input]
857divmod as builtin_divmod
Guido van Rossum6a00cd81995-01-07 12:39:01 +0000858
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300859 x: object
860 y: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000861 /
862
Zachary Ware7f227d92016-04-28 14:39:50 -0500863Return the tuple (x//y, x%y). Invariant: div*y + mod == x.
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000864[clinic start generated code]*/
865
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000866static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300867builtin_divmod_impl(PyObject *module, PyObject *x, PyObject *y)
868/*[clinic end generated code: output=b06d8a5f6e0c745e input=175ad9c84ff41a85]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000869{
870 return PyNumber_Divmod(x, y);
871}
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000872
873
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000874/*[clinic input]
875eval as builtin_eval
876
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300877 source: object
878 globals: object = None
879 locals: object = None
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000880 /
881
882Evaluate the given source in the context of globals and locals.
883
884The source may be a string representing a Python expression
885or a code object as returned by compile().
886The globals must be a dictionary and locals can be any mapping,
887defaulting to the current globals and locals.
888If only globals is given, locals defaults to it.
889[clinic start generated code]*/
890
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000891static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300892builtin_eval_impl(PyObject *module, PyObject *source, PyObject *globals,
Larry Hastings89964c42015-04-14 18:07:59 -0400893 PyObject *locals)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300894/*[clinic end generated code: output=0a0824aa70093116 input=11ee718a8640e527]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000895{
Martin Panter61d6e4a2015-11-07 02:56:11 +0000896 PyObject *result, *source_copy;
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +0200897 const char *str;
Guido van Rossum590baa41993-11-30 13:40:46 +0000898
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000899 if (locals != Py_None && !PyMapping_Check(locals)) {
900 PyErr_SetString(PyExc_TypeError, "locals must be a mapping");
901 return NULL;
902 }
903 if (globals != Py_None && !PyDict_Check(globals)) {
904 PyErr_SetString(PyExc_TypeError, PyMapping_Check(globals) ?
905 "globals must be a real dict; try eval(expr, {}, mapping)"
906 : "globals must be a dict");
907 return NULL;
908 }
909 if (globals == Py_None) {
910 globals = PyEval_GetGlobals();
Victor Stinner41bb43a2013-10-29 01:19:37 +0100911 if (locals == Py_None) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000912 locals = PyEval_GetLocals();
Victor Stinner41bb43a2013-10-29 01:19:37 +0100913 if (locals == NULL)
914 return NULL;
915 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000916 }
917 else if (locals == Py_None)
918 locals = globals;
Tim Peters9fa96be2001-08-17 23:04:59 +0000919
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000920 if (globals == NULL || locals == NULL) {
921 PyErr_SetString(PyExc_TypeError,
922 "eval must be given globals and locals "
923 "when called without a frame");
924 return NULL;
925 }
Georg Brandl77c85e62005-09-15 10:46:13 +0000926
Serhiy Storchakaa24107b2019-02-25 17:59:46 +0200927 if (_PyDict_GetItemIdWithError(globals, &PyId___builtins__) == NULL) {
Victor Stinnerb44562b2013-11-06 19:03:11 +0100928 if (_PyDict_SetItemId(globals, &PyId___builtins__,
929 PyEval_GetBuiltins()) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000930 return NULL;
931 }
Serhiy Storchakaa24107b2019-02-25 17:59:46 +0200932 else if (PyErr_Occurred()) {
933 return NULL;
934 }
Tim Peters9fa96be2001-08-17 23:04:59 +0000935
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000936 if (PyCode_Check(source)) {
Steve Dowerb82e17e2019-05-23 08:45:22 -0700937 if (PySys_Audit("exec", "O", source) < 0) {
938 return NULL;
939 }
940
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000941 if (PyCode_GetNumFree((PyCodeObject *)source) > 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000942 PyErr_SetString(PyExc_TypeError,
Steve Dowerb82e17e2019-05-23 08:45:22 -0700943 "code object passed to eval() may not contain free variables");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000944 return NULL;
945 }
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000946 return PyEval_EvalCode(source, globals, locals);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000947 }
Tim Peters9fa96be2001-08-17 23:04:59 +0000948
Victor Stinner37d66d72019-06-13 02:16:41 +0200949 PyCompilerFlags cf = _PyCompilerFlags_INIT;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000950 cf.cf_flags = PyCF_SOURCE_IS_UTF8;
Dino Viehland41540692019-05-28 16:21:17 -0700951 str = _Py_SourceAsString(source, "eval", "string, bytes or code", &cf, &source_copy);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000952 if (str == NULL)
953 return NULL;
Just van Rossum3aaf42c2003-02-10 08:21:10 +0000954
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000955 while (*str == ' ' || *str == '\t')
956 str++;
Tim Peters9fa96be2001-08-17 23:04:59 +0000957
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000958 (void)PyEval_MergeCompilerFlags(&cf);
959 result = PyRun_StringFlags(str, Py_eval_input, globals, locals, &cf);
Martin Panter61d6e4a2015-11-07 02:56:11 +0000960 Py_XDECREF(source_copy);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000961 return result;
Guido van Rossum3f5da241990-12-20 15:06:42 +0000962}
963
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000964/*[clinic input]
965exec as builtin_exec
966
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300967 source: object
968 globals: object = None
969 locals: object = None
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000970 /
971
972Execute the given source in the context of globals and locals.
973
974The source may be a string representing one or more Python statements
975or a code object as returned by compile().
976The globals must be a dictionary and locals can be any mapping,
977defaulting to the current globals and locals.
978If only globals is given, locals defaults to it.
979[clinic start generated code]*/
980
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000981static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300982builtin_exec_impl(PyObject *module, PyObject *source, PyObject *globals,
Larry Hastings89964c42015-04-14 18:07:59 -0400983 PyObject *locals)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300984/*[clinic end generated code: output=3c90efc6ab68ef5d input=01ca3e1c01692829]*/
Georg Brandl7cae87c2006-09-06 06:51:57 +0000985{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000986 PyObject *v;
Georg Brandl2cabc562008-08-28 07:57:16 +0000987
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000988 if (globals == Py_None) {
989 globals = PyEval_GetGlobals();
990 if (locals == Py_None) {
991 locals = PyEval_GetLocals();
Victor Stinner41bb43a2013-10-29 01:19:37 +0100992 if (locals == NULL)
993 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000994 }
995 if (!globals || !locals) {
996 PyErr_SetString(PyExc_SystemError,
997 "globals and locals cannot be NULL");
998 return NULL;
999 }
1000 }
1001 else if (locals == Py_None)
1002 locals = globals;
Georg Brandl7cae87c2006-09-06 06:51:57 +00001003
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001004 if (!PyDict_Check(globals)) {
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001005 PyErr_Format(PyExc_TypeError, "exec() globals must be a dict, not %.100s",
Victor Stinnera102ed72020-02-07 02:24:48 +01001006 Py_TYPE(globals)->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001007 return NULL;
1008 }
1009 if (!PyMapping_Check(locals)) {
1010 PyErr_Format(PyExc_TypeError,
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001011 "locals must be a mapping or None, not %.100s",
Victor Stinnera102ed72020-02-07 02:24:48 +01001012 Py_TYPE(locals)->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001013 return NULL;
1014 }
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02001015 if (_PyDict_GetItemIdWithError(globals, &PyId___builtins__) == NULL) {
Victor Stinnerb44562b2013-11-06 19:03:11 +01001016 if (_PyDict_SetItemId(globals, &PyId___builtins__,
1017 PyEval_GetBuiltins()) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001018 return NULL;
1019 }
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02001020 else if (PyErr_Occurred()) {
1021 return NULL;
1022 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001023
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001024 if (PyCode_Check(source)) {
Steve Dowerb82e17e2019-05-23 08:45:22 -07001025 if (PySys_Audit("exec", "O", source) < 0) {
1026 return NULL;
1027 }
1028
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001029 if (PyCode_GetNumFree((PyCodeObject *)source) > 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001030 PyErr_SetString(PyExc_TypeError,
1031 "code object passed to exec() may not "
1032 "contain free variables");
1033 return NULL;
1034 }
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001035 v = PyEval_EvalCode(source, globals, locals);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001036 }
1037 else {
Martin Panter61d6e4a2015-11-07 02:56:11 +00001038 PyObject *source_copy;
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +02001039 const char *str;
Victor Stinner37d66d72019-06-13 02:16:41 +02001040 PyCompilerFlags cf = _PyCompilerFlags_INIT;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001041 cf.cf_flags = PyCF_SOURCE_IS_UTF8;
Dino Viehland41540692019-05-28 16:21:17 -07001042 str = _Py_SourceAsString(source, "exec",
Martin Panter61d6e4a2015-11-07 02:56:11 +00001043 "string, bytes or code", &cf,
1044 &source_copy);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001045 if (str == NULL)
1046 return NULL;
1047 if (PyEval_MergeCompilerFlags(&cf))
1048 v = PyRun_StringFlags(str, Py_file_input, globals,
1049 locals, &cf);
1050 else
1051 v = PyRun_String(str, Py_file_input, globals, locals);
Martin Panter61d6e4a2015-11-07 02:56:11 +00001052 Py_XDECREF(source_copy);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001053 }
1054 if (v == NULL)
1055 return NULL;
1056 Py_DECREF(v);
1057 Py_RETURN_NONE;
Georg Brandl7cae87c2006-09-06 06:51:57 +00001058}
1059
Georg Brandl7cae87c2006-09-06 06:51:57 +00001060
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001061/* AC: cannot convert yet, as needs PEP 457 group support in inspect */
Guido van Rossum79f25d91997-04-29 20:08:16 +00001062static PyObject *
Serhiy Storchakaa5552f02017-12-15 13:11:11 +02001063builtin_getattr(PyObject *self, PyObject *const *args, Py_ssize_t nargs)
Guido van Rossum33894be1992-01-27 16:53:09 +00001064{
Serhiy Storchaka79342662019-01-12 08:25:41 +02001065 PyObject *v, *name, *result;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001066
Serhiy Storchaka79342662019-01-12 08:25:41 +02001067 if (!_PyArg_CheckPositional("getattr", nargs, 2, 3))
Sylvain96c7c062017-06-15 17:05:23 +02001068 return NULL;
1069
Serhiy Storchaka79342662019-01-12 08:25:41 +02001070 v = args[0];
1071 name = args[1];
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001072 if (!PyUnicode_Check(name)) {
1073 PyErr_SetString(PyExc_TypeError,
1074 "getattr(): attribute name must be string");
1075 return NULL;
1076 }
Serhiy Storchaka79342662019-01-12 08:25:41 +02001077 if (nargs > 2) {
Serhiy Storchakaf320be72018-01-25 10:49:40 +02001078 if (_PyObject_LookupAttr(v, name, &result) == 0) {
Serhiy Storchaka79342662019-01-12 08:25:41 +02001079 PyObject *dflt = args[2];
INADA Naoki378edee2018-01-16 20:52:41 +09001080 Py_INCREF(dflt);
1081 return dflt;
1082 }
1083 }
1084 else {
1085 result = PyObject_GetAttr(v, name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001086 }
1087 return result;
Guido van Rossum9bfef441993-03-29 10:43:31 +00001088}
1089
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001090PyDoc_STRVAR(getattr_doc,
Guido van Rossum950ff291998-06-29 13:38:57 +00001091"getattr(object, name[, default]) -> value\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001092\n\
Guido van Rossum950ff291998-06-29 13:38:57 +00001093Get a named attribute from an object; getattr(x, 'y') is equivalent to x.y.\n\
1094When a default argument is given, it is returned when the attribute doesn't\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001095exist; without it, an exception is raised in that case.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001096
1097
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001098/*[clinic input]
1099globals as builtin_globals
1100
1101Return the dictionary containing the current scope's global variables.
1102
1103NOTE: Updates to this dictionary *will* affect name lookups in the current
1104global scope and vice-versa.
1105[clinic start generated code]*/
1106
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001107static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001108builtin_globals_impl(PyObject *module)
1109/*[clinic end generated code: output=e5dd1527067b94d2 input=9327576f92bb48ba]*/
Guido van Rossum872537c1995-07-07 22:43:42 +00001110{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001111 PyObject *d;
Guido van Rossum872537c1995-07-07 22:43:42 +00001112
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001113 d = PyEval_GetGlobals();
1114 Py_XINCREF(d);
1115 return d;
Guido van Rossum872537c1995-07-07 22:43:42 +00001116}
1117
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001118
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001119/*[clinic input]
1120hasattr as builtin_hasattr
1121
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001122 obj: object
1123 name: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001124 /
1125
1126Return whether the object has an attribute with the given name.
1127
1128This is done by calling getattr(obj, name) and catching AttributeError.
1129[clinic start generated code]*/
1130
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001131static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001132builtin_hasattr_impl(PyObject *module, PyObject *obj, PyObject *name)
1133/*[clinic end generated code: output=a7aff2090a4151e5 input=0faec9787d979542]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001134{
1135 PyObject *v;
1136
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001137 if (!PyUnicode_Check(name)) {
1138 PyErr_SetString(PyExc_TypeError,
1139 "hasattr(): attribute name must be string");
1140 return NULL;
1141 }
Serhiy Storchakaf320be72018-01-25 10:49:40 +02001142 if (_PyObject_LookupAttr(obj, name, &v) < 0) {
Benjamin Peterson17689992010-08-24 03:26:23 +00001143 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001144 }
Serhiy Storchakaf320be72018-01-25 10:49:40 +02001145 if (v == NULL) {
1146 Py_RETURN_FALSE;
1147 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001148 Py_DECREF(v);
Benjamin Peterson17689992010-08-24 03:26:23 +00001149 Py_RETURN_TRUE;
Guido van Rossum33894be1992-01-27 16:53:09 +00001150}
1151
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001152
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001153/* AC: gdb's integration with CPython relies on builtin_id having
1154 * the *exact* parameter names of "self" and "v", so we ensure we
1155 * preserve those name rather than using the AC defaults.
1156 */
1157/*[clinic input]
1158id as builtin_id
1159
Serhiy Storchaka24182a32016-05-05 16:21:35 +03001160 self: self(type="PyModuleDef *")
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001161 obj as v: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001162 /
1163
1164Return the identity of an object.
1165
1166This is guaranteed to be unique among simultaneously existing objects.
1167(CPython uses the object's memory address.)
1168[clinic start generated code]*/
1169
Guido van Rossum79f25d91997-04-29 20:08:16 +00001170static PyObject *
Serhiy Storchaka24182a32016-05-05 16:21:35 +03001171builtin_id(PyModuleDef *self, PyObject *v)
1172/*[clinic end generated code: output=0aa640785f697f65 input=5a534136419631f4]*/
Guido van Rossum5b722181993-03-30 17:46:03 +00001173{
Steve Dowerb82e17e2019-05-23 08:45:22 -07001174 PyObject *id = PyLong_FromVoidPtr(v);
1175
1176 if (id && PySys_Audit("builtins.id", "O", id) < 0) {
1177 Py_DECREF(id);
1178 return NULL;
1179 }
1180
1181 return id;
Guido van Rossum5b722181993-03-30 17:46:03 +00001182}
1183
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001184
Raymond Hettingera6c60372008-03-13 01:26:19 +00001185/* map object ************************************************************/
1186
1187typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001188 PyObject_HEAD
1189 PyObject *iters;
1190 PyObject *func;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001191} mapobject;
1192
Guido van Rossum79f25d91997-04-29 20:08:16 +00001193static PyObject *
Raymond Hettingera6c60372008-03-13 01:26:19 +00001194map_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
Guido van Rossum12d12c51993-10-26 17:58:25 +00001195{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001196 PyObject *it, *iters, *func;
1197 mapobject *lz;
1198 Py_ssize_t numargs, i;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001199
Serhiy Storchaka6cca5c82017-06-08 14:41:19 +03001200 if (type == &PyMap_Type && !_PyArg_NoKeywords("map", kwds))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001201 return NULL;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001202
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001203 numargs = PyTuple_Size(args);
1204 if (numargs < 2) {
1205 PyErr_SetString(PyExc_TypeError,
1206 "map() must have at least two arguments.");
1207 return NULL;
1208 }
Raymond Hettingera6c60372008-03-13 01:26:19 +00001209
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001210 iters = PyTuple_New(numargs-1);
1211 if (iters == NULL)
1212 return NULL;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001213
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001214 for (i=1 ; i<numargs ; i++) {
1215 /* Get iterator. */
1216 it = PyObject_GetIter(PyTuple_GET_ITEM(args, i));
1217 if (it == NULL) {
1218 Py_DECREF(iters);
1219 return NULL;
1220 }
1221 PyTuple_SET_ITEM(iters, i-1, it);
1222 }
Raymond Hettingera6c60372008-03-13 01:26:19 +00001223
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001224 /* create mapobject structure */
1225 lz = (mapobject *)type->tp_alloc(type, 0);
1226 if (lz == NULL) {
1227 Py_DECREF(iters);
1228 return NULL;
1229 }
1230 lz->iters = iters;
1231 func = PyTuple_GET_ITEM(args, 0);
1232 Py_INCREF(func);
1233 lz->func = func;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001234
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001235 return (PyObject *)lz;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001236}
1237
1238static void
1239map_dealloc(mapobject *lz)
1240{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001241 PyObject_GC_UnTrack(lz);
1242 Py_XDECREF(lz->iters);
1243 Py_XDECREF(lz->func);
1244 Py_TYPE(lz)->tp_free(lz);
Raymond Hettingera6c60372008-03-13 01:26:19 +00001245}
1246
1247static int
1248map_traverse(mapobject *lz, visitproc visit, void *arg)
1249{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001250 Py_VISIT(lz->iters);
1251 Py_VISIT(lz->func);
1252 return 0;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001253}
1254
1255static PyObject *
1256map_next(mapobject *lz)
1257{
Victor Stinnerbc08ab42016-12-15 12:40:53 +01001258 PyObject *small_stack[_PY_FASTCALL_SMALL_STACK];
Victor Stinnercdb5cee2016-08-24 01:45:13 +02001259 PyObject **stack;
Victor Stinnercdb5cee2016-08-24 01:45:13 +02001260 PyObject *result = NULL;
Victor Stinner4d231bc2019-11-14 13:36:21 +01001261 PyThreadState *tstate = _PyThreadState_GET();
Raymond Hettingera6c60372008-03-13 01:26:19 +00001262
Victor Stinner4d231bc2019-11-14 13:36:21 +01001263 const Py_ssize_t niters = PyTuple_GET_SIZE(lz->iters);
Victor Stinnercdb5cee2016-08-24 01:45:13 +02001264 if (niters <= (Py_ssize_t)Py_ARRAY_LENGTH(small_stack)) {
1265 stack = small_stack;
1266 }
1267 else {
1268 stack = PyMem_Malloc(niters * sizeof(stack[0]));
1269 if (stack == NULL) {
Victor Stinner4d231bc2019-11-14 13:36:21 +01001270 _PyErr_NoMemory(tstate);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001271 return NULL;
1272 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001273 }
Victor Stinnercdb5cee2016-08-24 01:45:13 +02001274
Victor Stinner4d231bc2019-11-14 13:36:21 +01001275 Py_ssize_t nargs = 0;
1276 for (Py_ssize_t i=0; i < niters; i++) {
Victor Stinnercdb5cee2016-08-24 01:45:13 +02001277 PyObject *it = PyTuple_GET_ITEM(lz->iters, i);
1278 PyObject *val = Py_TYPE(it)->tp_iternext(it);
1279 if (val == NULL) {
1280 goto exit;
1281 }
1282 stack[i] = val;
1283 nargs++;
1284 }
1285
Victor Stinner4d231bc2019-11-14 13:36:21 +01001286 result = _PyObject_VectorcallTstate(tstate, lz->func, stack, nargs, NULL);
Victor Stinnercdb5cee2016-08-24 01:45:13 +02001287
1288exit:
Victor Stinner4d231bc2019-11-14 13:36:21 +01001289 for (Py_ssize_t i=0; i < nargs; i++) {
Victor Stinnercdb5cee2016-08-24 01:45:13 +02001290 Py_DECREF(stack[i]);
1291 }
1292 if (stack != small_stack) {
1293 PyMem_Free(stack);
1294 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001295 return result;
Guido van Rossum12d12c51993-10-26 17:58:25 +00001296}
1297
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001298static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05301299map_reduce(mapobject *lz, PyObject *Py_UNUSED(ignored))
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001300{
1301 Py_ssize_t numargs = PyTuple_GET_SIZE(lz->iters);
1302 PyObject *args = PyTuple_New(numargs+1);
1303 Py_ssize_t i;
1304 if (args == NULL)
1305 return NULL;
1306 Py_INCREF(lz->func);
1307 PyTuple_SET_ITEM(args, 0, lz->func);
1308 for (i = 0; i<numargs; i++){
1309 PyObject *it = PyTuple_GET_ITEM(lz->iters, i);
1310 Py_INCREF(it);
1311 PyTuple_SET_ITEM(args, i+1, it);
1312 }
1313
1314 return Py_BuildValue("ON", Py_TYPE(lz), args);
1315}
1316
1317static PyMethodDef map_methods[] = {
1318 {"__reduce__", (PyCFunction)map_reduce, METH_NOARGS, reduce_doc},
1319 {NULL, NULL} /* sentinel */
1320};
1321
1322
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001323PyDoc_STRVAR(map_doc,
Raymond Hettingera6c60372008-03-13 01:26:19 +00001324"map(func, *iterables) --> map object\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001325\n\
Raymond Hettingera6c60372008-03-13 01:26:19 +00001326Make an iterator that computes the function using arguments from\n\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001327each of the iterables. Stops when the shortest iterable is exhausted.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001328
Raymond Hettingera6c60372008-03-13 01:26:19 +00001329PyTypeObject PyMap_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001330 PyVarObject_HEAD_INIT(&PyType_Type, 0)
1331 "map", /* tp_name */
1332 sizeof(mapobject), /* tp_basicsize */
1333 0, /* tp_itemsize */
1334 /* methods */
1335 (destructor)map_dealloc, /* tp_dealloc */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02001336 0, /* tp_vectorcall_offset */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001337 0, /* tp_getattr */
1338 0, /* tp_setattr */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02001339 0, /* tp_as_async */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001340 0, /* tp_repr */
1341 0, /* tp_as_number */
1342 0, /* tp_as_sequence */
1343 0, /* tp_as_mapping */
1344 0, /* tp_hash */
1345 0, /* tp_call */
1346 0, /* tp_str */
1347 PyObject_GenericGetAttr, /* tp_getattro */
1348 0, /* tp_setattro */
1349 0, /* tp_as_buffer */
1350 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
1351 Py_TPFLAGS_BASETYPE, /* tp_flags */
1352 map_doc, /* tp_doc */
1353 (traverseproc)map_traverse, /* tp_traverse */
1354 0, /* tp_clear */
1355 0, /* tp_richcompare */
1356 0, /* tp_weaklistoffset */
1357 PyObject_SelfIter, /* tp_iter */
1358 (iternextfunc)map_next, /* tp_iternext */
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001359 map_methods, /* tp_methods */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001360 0, /* tp_members */
1361 0, /* tp_getset */
1362 0, /* tp_base */
1363 0, /* tp_dict */
1364 0, /* tp_descr_get */
1365 0, /* tp_descr_set */
1366 0, /* tp_dictoffset */
1367 0, /* tp_init */
1368 PyType_GenericAlloc, /* tp_alloc */
1369 map_new, /* tp_new */
1370 PyObject_GC_Del, /* tp_free */
Raymond Hettingera6c60372008-03-13 01:26:19 +00001371};
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001372
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001373
1374/* AC: cannot convert yet, as needs PEP 457 group support in inspect */
Guido van Rossum79f25d91997-04-29 20:08:16 +00001375static PyObject *
Serhiy Storchakaa5552f02017-12-15 13:11:11 +02001376builtin_next(PyObject *self, PyObject *const *args, Py_ssize_t nargs)
Georg Brandla18af4e2007-04-21 15:47:16 +00001377{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001378 PyObject *it, *res;
Georg Brandla18af4e2007-04-21 15:47:16 +00001379
Serhiy Storchaka79342662019-01-12 08:25:41 +02001380 if (!_PyArg_CheckPositional("next", nargs, 1, 2))
Sylvain96c7c062017-06-15 17:05:23 +02001381 return NULL;
1382
Serhiy Storchaka79342662019-01-12 08:25:41 +02001383 it = args[0];
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001384 if (!PyIter_Check(it)) {
1385 PyErr_Format(PyExc_TypeError,
Philip Jenvey50add042011-11-06 16:37:52 -08001386 "'%.200s' object is not an iterator",
Victor Stinnera102ed72020-02-07 02:24:48 +01001387 Py_TYPE(it)->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001388 return NULL;
1389 }
1390
Victor Stinnera102ed72020-02-07 02:24:48 +01001391 res = (*Py_TYPE(it)->tp_iternext)(it);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001392 if (res != NULL) {
1393 return res;
Serhiy Storchaka79342662019-01-12 08:25:41 +02001394 } else if (nargs > 1) {
1395 PyObject *def = args[1];
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001396 if (PyErr_Occurred()) {
1397 if(!PyErr_ExceptionMatches(PyExc_StopIteration))
1398 return NULL;
1399 PyErr_Clear();
1400 }
1401 Py_INCREF(def);
1402 return def;
1403 } else if (PyErr_Occurred()) {
1404 return NULL;
1405 } else {
1406 PyErr_SetNone(PyExc_StopIteration);
1407 return NULL;
1408 }
Georg Brandla18af4e2007-04-21 15:47:16 +00001409}
1410
1411PyDoc_STRVAR(next_doc,
1412"next(iterator[, default])\n\
1413\n\
1414Return the next item from the iterator. If default is given and the iterator\n\
1415is exhausted, it is returned instead of raising StopIteration.");
1416
1417
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001418/*[clinic input]
1419setattr as builtin_setattr
1420
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001421 obj: object
1422 name: object
1423 value: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001424 /
1425
1426Sets the named attribute on the given object to the specified value.
1427
1428setattr(x, 'y', v) is equivalent to ``x.y = v''
1429[clinic start generated code]*/
1430
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001431static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001432builtin_setattr_impl(PyObject *module, PyObject *obj, PyObject *name,
Larry Hastings89964c42015-04-14 18:07:59 -04001433 PyObject *value)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001434/*[clinic end generated code: output=dc2ce1d1add9acb4 input=bd2b7ca6875a1899]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001435{
1436 if (PyObject_SetAttr(obj, name, value) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001437 return NULL;
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02001438 Py_RETURN_NONE;
Guido van Rossum33894be1992-01-27 16:53:09 +00001439}
1440
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001441
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001442/*[clinic input]
1443delattr as builtin_delattr
1444
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001445 obj: object
1446 name: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001447 /
1448
1449Deletes the named attribute from the given object.
1450
1451delattr(x, 'y') is equivalent to ``del x.y''
1452[clinic start generated code]*/
1453
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001454static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001455builtin_delattr_impl(PyObject *module, PyObject *obj, PyObject *name)
1456/*[clinic end generated code: output=85134bc58dff79fa input=db16685d6b4b9410]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001457{
1458 if (PyObject_SetAttr(obj, name, (PyObject *)NULL) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001459 return NULL;
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02001460 Py_RETURN_NONE;
Guido van Rossum14144fc1994-08-29 12:53:40 +00001461}
1462
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001463
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001464/*[clinic input]
1465hash as builtin_hash
1466
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001467 obj: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001468 /
1469
1470Return the hash value for the given object.
1471
1472Two objects that compare equal must also have the same hash value, but the
1473reverse is not necessarily true.
1474[clinic start generated code]*/
1475
Guido van Rossum79f25d91997-04-29 20:08:16 +00001476static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001477builtin_hash(PyObject *module, PyObject *obj)
1478/*[clinic end generated code: output=237668e9d7688db7 input=58c48be822bf9c54]*/
Guido van Rossum9bfef441993-03-29 10:43:31 +00001479{
Benjamin Peterson8f67d082010-10-17 20:54:53 +00001480 Py_hash_t x;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001481
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001482 x = PyObject_Hash(obj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001483 if (x == -1)
1484 return NULL;
Benjamin Peterson8f67d082010-10-17 20:54:53 +00001485 return PyLong_FromSsize_t(x);
Guido van Rossum9bfef441993-03-29 10:43:31 +00001486}
1487
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001488
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001489/*[clinic input]
1490hex as builtin_hex
1491
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001492 number: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001493 /
1494
1495Return the hexadecimal representation of an integer.
1496
1497 >>> hex(12648430)
1498 '0xc0ffee'
1499[clinic start generated code]*/
1500
Guido van Rossum79f25d91997-04-29 20:08:16 +00001501static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001502builtin_hex(PyObject *module, PyObject *number)
1503/*[clinic end generated code: output=e46b612169099408 input=e645aff5fc7d540e]*/
Guido van Rossum006bcd41991-10-24 14:54:44 +00001504{
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001505 return PyNumber_ToBase(number, 16);
Guido van Rossum006bcd41991-10-24 14:54:44 +00001506}
1507
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001508
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001509/* AC: cannot convert yet, as needs PEP 457 group support in inspect */
Guido van Rossum79f25d91997-04-29 20:08:16 +00001510static PyObject *
Serhiy Storchaka79342662019-01-12 08:25:41 +02001511builtin_iter(PyObject *self, PyObject *const *args, Py_ssize_t nargs)
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001512{
Serhiy Storchaka79342662019-01-12 08:25:41 +02001513 PyObject *v;
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001514
Serhiy Storchaka79342662019-01-12 08:25:41 +02001515 if (!_PyArg_CheckPositional("iter", nargs, 1, 2))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001516 return NULL;
Serhiy Storchaka79342662019-01-12 08:25:41 +02001517 v = args[0];
1518 if (nargs == 1)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001519 return PyObject_GetIter(v);
1520 if (!PyCallable_Check(v)) {
1521 PyErr_SetString(PyExc_TypeError,
1522 "iter(v, w): v must be callable");
1523 return NULL;
1524 }
Serhiy Storchaka79342662019-01-12 08:25:41 +02001525 PyObject *sentinel = args[1];
1526 return PyCallIter_New(v, sentinel);
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001527}
1528
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001529PyDoc_STRVAR(iter_doc,
Georg Brandld11ae5d2008-05-16 13:27:32 +00001530"iter(iterable) -> iterator\n\
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001531iter(callable, sentinel) -> iterator\n\
1532\n\
1533Get an iterator from an object. In the first form, the argument must\n\
1534supply its own iterator, or be a sequence.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001535In the second form, the callable is called until it returns the sentinel.");
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001536
1537
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001538/*[clinic input]
1539len as builtin_len
1540
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001541 obj: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001542 /
1543
1544Return the number of items in a container.
1545[clinic start generated code]*/
1546
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001547static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001548builtin_len(PyObject *module, PyObject *obj)
1549/*[clinic end generated code: output=fa7a270d314dfb6c input=bc55598da9e9c9b5]*/
Guido van Rossum3f5da241990-12-20 15:06:42 +00001550{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001551 Py_ssize_t res;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001552
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001553 res = PyObject_Size(obj);
Serhiy Storchaka813f9432017-04-16 09:21:44 +03001554 if (res < 0) {
1555 assert(PyErr_Occurred());
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001556 return NULL;
Serhiy Storchaka813f9432017-04-16 09:21:44 +03001557 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001558 return PyLong_FromSsize_t(res);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001559}
1560
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001561
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001562/*[clinic input]
1563locals as builtin_locals
1564
1565Return a dictionary containing the current scope's local variables.
1566
1567NOTE: Whether or not updates to this dictionary will affect name lookups in
1568the local scope and vice-versa is *implementation dependent* and not
1569covered by any backwards compatibility guarantees.
1570[clinic start generated code]*/
1571
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001572static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001573builtin_locals_impl(PyObject *module)
1574/*[clinic end generated code: output=b46c94015ce11448 input=7874018d478d5c4b]*/
Guido van Rossum872537c1995-07-07 22:43:42 +00001575{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001576 PyObject *d;
Guido van Rossum872537c1995-07-07 22:43:42 +00001577
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001578 d = PyEval_GetLocals();
1579 Py_XINCREF(d);
1580 return d;
Guido van Rossum872537c1995-07-07 22:43:42 +00001581}
1582
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001583
Guido van Rossum79f25d91997-04-29 20:08:16 +00001584static PyObject *
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001585min_max(PyObject *args, PyObject *kwds, int op)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001586{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001587 PyObject *v, *it, *item, *val, *maxitem, *maxval, *keyfunc=NULL;
Raymond Hettinger4d6018f2013-06-24 22:43:02 -07001588 PyObject *emptytuple, *defaultval = NULL;
1589 static char *kwlist[] = {"key", "default", NULL};
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001590 const char *name = op == Py_LT ? "min" : "max";
Raymond Hettinger4d6018f2013-06-24 22:43:02 -07001591 const int positional = PyTuple_Size(args) > 1;
1592 int ret;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001593
Dong-hee Naabdc6342020-01-11 01:31:43 +09001594 if (positional) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001595 v = args;
Dong-hee Naabdc6342020-01-11 01:31:43 +09001596 }
1597 else if (!PyArg_UnpackTuple(args, name, 1, 1, &v)) {
1598 if (PyExceptionClass_Check(PyExc_TypeError)) {
1599 PyErr_Format(PyExc_TypeError, "%s expected at least 1 argument, got 0", name);
1600 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001601 return NULL;
Dong-hee Naabdc6342020-01-11 01:31:43 +09001602 }
Tim Peters67d687a2002-04-29 21:27:32 +00001603
Raymond Hettinger4d6018f2013-06-24 22:43:02 -07001604 emptytuple = PyTuple_New(0);
1605 if (emptytuple == NULL)
1606 return NULL;
Oren Milman58cf7482017-08-21 20:19:07 +03001607 ret = PyArg_ParseTupleAndKeywords(emptytuple, kwds,
1608 (op == Py_LT) ? "|$OO:min" : "|$OO:max",
1609 kwlist, &keyfunc, &defaultval);
Raymond Hettinger4d6018f2013-06-24 22:43:02 -07001610 Py_DECREF(emptytuple);
1611 if (!ret)
1612 return NULL;
1613
1614 if (positional && defaultval != NULL) {
1615 PyErr_Format(PyExc_TypeError,
1616 "Cannot specify a default for %s() with multiple "
1617 "positional arguments", name);
1618 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001619 }
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001620
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001621 it = PyObject_GetIter(v);
1622 if (it == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001623 return NULL;
1624 }
Tim Petersc3074532001-05-03 07:00:32 +00001625
Alexander Marshalove22072f2018-07-24 10:58:21 +07001626 if (keyfunc == Py_None) {
1627 keyfunc = NULL;
1628 }
1629
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001630 maxitem = NULL; /* the result */
1631 maxval = NULL; /* the value associated with the result */
1632 while (( item = PyIter_Next(it) )) {
1633 /* get the value from the key function */
1634 if (keyfunc != NULL) {
Petr Viktorinffd97532020-02-11 17:46:57 +01001635 val = PyObject_CallOneArg(keyfunc, item);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001636 if (val == NULL)
1637 goto Fail_it_item;
1638 }
1639 /* no key function; the value is the item */
1640 else {
1641 val = item;
1642 Py_INCREF(val);
1643 }
Tim Petersc3074532001-05-03 07:00:32 +00001644
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001645 /* maximum value and item are unset; set them */
1646 if (maxval == NULL) {
1647 maxitem = item;
1648 maxval = val;
1649 }
1650 /* maximum value and item are set; update them as necessary */
1651 else {
1652 int cmp = PyObject_RichCompareBool(val, maxval, op);
1653 if (cmp < 0)
1654 goto Fail_it_item_and_val;
1655 else if (cmp > 0) {
1656 Py_DECREF(maxval);
1657 Py_DECREF(maxitem);
1658 maxval = val;
1659 maxitem = item;
1660 }
1661 else {
1662 Py_DECREF(item);
1663 Py_DECREF(val);
1664 }
1665 }
1666 }
1667 if (PyErr_Occurred())
1668 goto Fail_it;
1669 if (maxval == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001670 assert(maxitem == NULL);
Raymond Hettinger4d6018f2013-06-24 22:43:02 -07001671 if (defaultval != NULL) {
1672 Py_INCREF(defaultval);
1673 maxitem = defaultval;
1674 } else {
1675 PyErr_Format(PyExc_ValueError,
1676 "%s() arg is an empty sequence", name);
1677 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001678 }
1679 else
1680 Py_DECREF(maxval);
1681 Py_DECREF(it);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001682 return maxitem;
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001683
1684Fail_it_item_and_val:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001685 Py_DECREF(val);
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001686Fail_it_item:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001687 Py_DECREF(item);
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001688Fail_it:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001689 Py_XDECREF(maxval);
1690 Py_XDECREF(maxitem);
1691 Py_DECREF(it);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001692 return NULL;
Guido van Rossum3f5da241990-12-20 15:06:42 +00001693}
1694
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001695/* AC: cannot convert yet, waiting for *args support */
Guido van Rossum79f25d91997-04-29 20:08:16 +00001696static PyObject *
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001697builtin_min(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001698{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001699 return min_max(args, kwds, Py_LT);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001700}
1701
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001702PyDoc_STRVAR(min_doc,
Raymond Hettinger2a545822014-05-19 22:20:52 +01001703"min(iterable, *[, default=obj, key=func]) -> value\n\
1704min(arg1, arg2, *args, *[, key=func]) -> value\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001705\n\
Raymond Hettinger2a545822014-05-19 22:20:52 +01001706With a single iterable argument, return its smallest item. The\n\
1707default keyword-only argument specifies an object to return if\n\
1708the provided iterable is empty.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001709With two or more arguments, return the smallest argument.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001710
1711
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001712/* AC: cannot convert yet, waiting for *args support */
Guido van Rossum79f25d91997-04-29 20:08:16 +00001713static PyObject *
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001714builtin_max(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001715{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001716 return min_max(args, kwds, Py_GT);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001717}
1718
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001719PyDoc_STRVAR(max_doc,
Raymond Hettinger2a545822014-05-19 22:20:52 +01001720"max(iterable, *[, default=obj, key=func]) -> value\n\
1721max(arg1, arg2, *args, *[, key=func]) -> value\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001722\n\
Raymond Hettinger2a545822014-05-19 22:20:52 +01001723With a single iterable argument, return its biggest item. The\n\
1724default keyword-only argument specifies an object to return if\n\
1725the provided iterable is empty.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001726With two or more arguments, return the largest argument.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001727
1728
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001729/*[clinic input]
1730oct as builtin_oct
1731
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001732 number: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001733 /
1734
1735Return the octal representation of an integer.
1736
1737 >>> oct(342391)
1738 '0o1234567'
1739[clinic start generated code]*/
1740
Guido van Rossum79f25d91997-04-29 20:08:16 +00001741static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001742builtin_oct(PyObject *module, PyObject *number)
1743/*[clinic end generated code: output=40a34656b6875352 input=ad6b274af4016c72]*/
Guido van Rossum006bcd41991-10-24 14:54:44 +00001744{
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001745 return PyNumber_ToBase(number, 8);
Guido van Rossum006bcd41991-10-24 14:54:44 +00001746}
1747
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001748
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001749/*[clinic input]
1750ord as builtin_ord
1751
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001752 c: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001753 /
1754
1755Return the Unicode code point for a one-character string.
1756[clinic start generated code]*/
1757
Guido van Rossum79f25d91997-04-29 20:08:16 +00001758static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001759builtin_ord(PyObject *module, PyObject *c)
1760/*[clinic end generated code: output=4fa5e87a323bae71 input=3064e5d6203ad012]*/
Guido van Rossum3f5da241990-12-20 15:06:42 +00001761{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001762 long ord;
1763 Py_ssize_t size;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001764
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001765 if (PyBytes_Check(c)) {
1766 size = PyBytes_GET_SIZE(c);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001767 if (size == 1) {
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001768 ord = (long)((unsigned char)*PyBytes_AS_STRING(c));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001769 return PyLong_FromLong(ord);
1770 }
1771 }
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001772 else if (PyUnicode_Check(c)) {
1773 if (PyUnicode_READY(c) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001774 return NULL;
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001775 size = PyUnicode_GET_LENGTH(c);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001776 if (size == 1) {
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001777 ord = (long)PyUnicode_READ_CHAR(c, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001778 return PyLong_FromLong(ord);
1779 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001780 }
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001781 else if (PyByteArray_Check(c)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001782 /* XXX Hopefully this is temporary */
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001783 size = PyByteArray_GET_SIZE(c);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001784 if (size == 1) {
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001785 ord = (long)((unsigned char)*PyByteArray_AS_STRING(c));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001786 return PyLong_FromLong(ord);
1787 }
1788 }
1789 else {
1790 PyErr_Format(PyExc_TypeError,
1791 "ord() expected string of length 1, but " \
Victor Stinnera102ed72020-02-07 02:24:48 +01001792 "%.200s found", Py_TYPE(c)->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001793 return NULL;
1794 }
Guido van Rossum09095f32000-03-10 23:00:52 +00001795
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001796 PyErr_Format(PyExc_TypeError,
1797 "ord() expected a character, "
1798 "but string of length %zd found",
1799 size);
1800 return NULL;
Guido van Rossum3f5da241990-12-20 15:06:42 +00001801}
1802
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001803
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001804/*[clinic input]
1805pow as builtin_pow
1806
Ammar Askar87d6cd32019-09-21 00:28:49 -04001807 base: object
1808 exp: object
1809 mod: object = None
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001810
Raymond Hettingerb104ecb2019-09-21 12:57:44 -07001811Equivalent to base**exp with 2 arguments or base**exp % mod with 3 arguments
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001812
1813Some types, such as ints, are able to use a more efficient algorithm when
1814invoked using the three argument form.
1815[clinic start generated code]*/
1816
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001817static PyObject *
Ammar Askar87d6cd32019-09-21 00:28:49 -04001818builtin_pow_impl(PyObject *module, PyObject *base, PyObject *exp,
1819 PyObject *mod)
Raymond Hettingerb104ecb2019-09-21 12:57:44 -07001820/*[clinic end generated code: output=3ca1538221bbf15f input=435dbd48a12efb23]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001821{
Ammar Askar87d6cd32019-09-21 00:28:49 -04001822 return PyNumber_Power(base, exp, mod);
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001823}
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001824
1825
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001826/* AC: cannot convert yet, waiting for *args support */
Guido van Rossum34343512006-11-30 22:13:52 +00001827static PyObject *
Serhiy Storchakaa5552f02017-12-15 13:11:11 +02001828builtin_print(PyObject *self, PyObject *const *args, Py_ssize_t nargs, PyObject *kwnames)
Guido van Rossum34343512006-11-30 22:13:52 +00001829{
INADA Naokibd584f12017-01-19 12:50:34 +01001830 static const char * const _keywords[] = {"sep", "end", "file", "flush", 0};
Serhiy Storchaka1f21eaa2019-09-01 12:16:51 +03001831 static struct _PyArg_Parser _parser = {"|OOOp:print", _keywords, 0};
1832 PyObject *sep = NULL, *end = NULL, *file = NULL;
1833 int flush = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001834 int i, err;
Guido van Rossum34343512006-11-30 22:13:52 +00001835
INADA Naokibd584f12017-01-19 12:50:34 +01001836 if (kwnames != NULL &&
1837 !_PyArg_ParseStackAndKeywords(args + nargs, 0, kwnames, &_parser,
1838 &sep, &end, &file, &flush)) {
Georg Brandlbc3b6822012-01-13 19:41:25 +01001839 return NULL;
INADA Naokibd584f12017-01-19 12:50:34 +01001840 }
1841
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001842 if (file == NULL || file == Py_None) {
Victor Stinnerbd303c12013-11-07 23:07:29 +01001843 file = _PySys_GetObjectId(&PyId_stdout);
Victor Stinner1e53bba2013-07-16 22:26:05 +02001844 if (file == NULL) {
1845 PyErr_SetString(PyExc_RuntimeError, "lost sys.stdout");
1846 return NULL;
1847 }
1848
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001849 /* sys.stdout may be None when FILE* stdout isn't connected */
1850 if (file == Py_None)
1851 Py_RETURN_NONE;
1852 }
Guido van Rossum34343512006-11-30 22:13:52 +00001853
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001854 if (sep == Py_None) {
1855 sep = NULL;
1856 }
1857 else if (sep && !PyUnicode_Check(sep)) {
1858 PyErr_Format(PyExc_TypeError,
1859 "sep must be None or a string, not %.200s",
Victor Stinnera102ed72020-02-07 02:24:48 +01001860 Py_TYPE(sep)->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001861 return NULL;
1862 }
1863 if (end == Py_None) {
1864 end = NULL;
1865 }
1866 else if (end && !PyUnicode_Check(end)) {
1867 PyErr_Format(PyExc_TypeError,
1868 "end must be None or a string, not %.200s",
Victor Stinnera102ed72020-02-07 02:24:48 +01001869 Py_TYPE(end)->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001870 return NULL;
1871 }
Guido van Rossum34343512006-11-30 22:13:52 +00001872
INADA Naokibd584f12017-01-19 12:50:34 +01001873 for (i = 0; i < nargs; i++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001874 if (i > 0) {
1875 if (sep == NULL)
1876 err = PyFile_WriteString(" ", file);
1877 else
1878 err = PyFile_WriteObject(sep, file,
1879 Py_PRINT_RAW);
1880 if (err)
1881 return NULL;
1882 }
INADA Naokibd584f12017-01-19 12:50:34 +01001883 err = PyFile_WriteObject(args[i], file, Py_PRINT_RAW);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001884 if (err)
1885 return NULL;
1886 }
Guido van Rossum34343512006-11-30 22:13:52 +00001887
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001888 if (end == NULL)
1889 err = PyFile_WriteString("\n", file);
1890 else
1891 err = PyFile_WriteObject(end, file, Py_PRINT_RAW);
1892 if (err)
1893 return NULL;
Guido van Rossum34343512006-11-30 22:13:52 +00001894
Serhiy Storchaka1f21eaa2019-09-01 12:16:51 +03001895 if (flush) {
1896 PyObject *tmp = _PyObject_CallMethodIdNoArgs(file, &PyId_flush);
1897 if (tmp == NULL)
Georg Brandlbc3b6822012-01-13 19:41:25 +01001898 return NULL;
Serhiy Storchaka1f21eaa2019-09-01 12:16:51 +03001899 Py_DECREF(tmp);
Georg Brandlbc3b6822012-01-13 19:41:25 +01001900 }
1901
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001902 Py_RETURN_NONE;
Guido van Rossum34343512006-11-30 22:13:52 +00001903}
1904
1905PyDoc_STRVAR(print_doc,
Senthil Kumarane9175bd2012-08-10 13:53:45 -07001906"print(value, ..., sep=' ', end='\\n', file=sys.stdout, flush=False)\n\
Guido van Rossum34343512006-11-30 22:13:52 +00001907\n\
1908Prints the values to a stream, or to sys.stdout by default.\n\
1909Optional keyword arguments:\n\
Senthil Kumarane9175bd2012-08-10 13:53:45 -07001910file: a file-like object (stream); defaults to the current sys.stdout.\n\
1911sep: string inserted between values, default a space.\n\
1912end: string appended after the last value, default a newline.\n\
1913flush: whether to forcibly flush the stream.");
Guido van Rossum34343512006-11-30 22:13:52 +00001914
1915
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001916/*[clinic input]
1917input as builtin_input
1918
1919 prompt: object(c_default="NULL") = None
1920 /
1921
1922Read a string from standard input. The trailing newline is stripped.
1923
1924The prompt string, if given, is printed to standard output without a
1925trailing newline before reading input.
1926
1927If the user hits EOF (*nix: Ctrl-D, Windows: Ctrl-Z+Return), raise EOFError.
1928On *nix systems, readline is used if available.
1929[clinic start generated code]*/
1930
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001931static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001932builtin_input_impl(PyObject *module, PyObject *prompt)
1933/*[clinic end generated code: output=83db5a191e7a0d60 input=5e8bb70c2908fe3c]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001934{
Victor Stinnerbd303c12013-11-07 23:07:29 +01001935 PyObject *fin = _PySys_GetObjectId(&PyId_stdin);
1936 PyObject *fout = _PySys_GetObjectId(&PyId_stdout);
1937 PyObject *ferr = _PySys_GetObjectId(&PyId_stderr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001938 PyObject *tmp;
1939 long fd;
1940 int tty;
Guido van Rossuma88a0332007-02-26 16:59:55 +00001941
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001942 /* Check that stdin/out/err are intact */
1943 if (fin == NULL || fin == Py_None) {
1944 PyErr_SetString(PyExc_RuntimeError,
1945 "input(): lost sys.stdin");
1946 return NULL;
1947 }
1948 if (fout == NULL || fout == Py_None) {
1949 PyErr_SetString(PyExc_RuntimeError,
1950 "input(): lost sys.stdout");
1951 return NULL;
1952 }
1953 if (ferr == NULL || ferr == Py_None) {
1954 PyErr_SetString(PyExc_RuntimeError,
1955 "input(): lost sys.stderr");
1956 return NULL;
1957 }
Guido van Rossumeba76962007-05-27 09:13:28 +00001958
Steve Dowerb82e17e2019-05-23 08:45:22 -07001959 if (PySys_Audit("builtins.input", "O", prompt ? prompt : Py_None) < 0) {
1960 return NULL;
1961 }
1962
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001963 /* First of all, flush stderr */
Jeroen Demeyer762f93f2019-07-08 10:19:25 +02001964 tmp = _PyObject_CallMethodIdNoArgs(ferr, &PyId_flush);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001965 if (tmp == NULL)
1966 PyErr_Clear();
1967 else
1968 Py_DECREF(tmp);
Guido van Rossumeba76962007-05-27 09:13:28 +00001969
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001970 /* We should only use (GNU) readline if Python's sys.stdin and
1971 sys.stdout are the same as C's stdin and stdout, because we
1972 need to pass it those. */
Jeroen Demeyer762f93f2019-07-08 10:19:25 +02001973 tmp = _PyObject_CallMethodIdNoArgs(fin, &PyId_fileno);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001974 if (tmp == NULL) {
1975 PyErr_Clear();
1976 tty = 0;
1977 }
1978 else {
1979 fd = PyLong_AsLong(tmp);
1980 Py_DECREF(tmp);
1981 if (fd < 0 && PyErr_Occurred())
1982 return NULL;
1983 tty = fd == fileno(stdin) && isatty(fd);
1984 }
1985 if (tty) {
Jeroen Demeyer762f93f2019-07-08 10:19:25 +02001986 tmp = _PyObject_CallMethodIdNoArgs(fout, &PyId_fileno);
Martin Panterc9a6ab52015-10-10 01:25:38 +00001987 if (tmp == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001988 PyErr_Clear();
Martin Panterc9a6ab52015-10-10 01:25:38 +00001989 tty = 0;
1990 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001991 else {
1992 fd = PyLong_AsLong(tmp);
1993 Py_DECREF(tmp);
1994 if (fd < 0 && PyErr_Occurred())
1995 return NULL;
1996 tty = fd == fileno(stdout) && isatty(fd);
1997 }
1998 }
Guido van Rossumeba76962007-05-27 09:13:28 +00001999
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002000 /* If we're interactive, use (GNU) readline */
2001 if (tty) {
Antoine Pitrou0d776b12011-11-06 00:34:26 +01002002 PyObject *po = NULL;
Serhiy Storchakae2f92de2017-11-11 13:06:26 +02002003 const char *promptstr;
Antoine Pitrou0d776b12011-11-06 00:34:26 +01002004 char *s = NULL;
2005 PyObject *stdin_encoding = NULL, *stdin_errors = NULL;
2006 PyObject *stdout_encoding = NULL, *stdout_errors = NULL;
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +02002007 const char *stdin_encoding_str, *stdin_errors_str;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002008 PyObject *result;
Victor Stinnerc0f1a1a2011-02-23 12:07:37 +00002009 size_t len;
Martin v. Löwis4a7b5d52007-09-04 05:24:49 +00002010
Serhiy Storchakac2cf1282017-03-12 13:50:36 +02002011 /* stdin is a text stream, so it must have an encoding. */
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02002012 stdin_encoding = _PyObject_GetAttrId(fin, &PyId_encoding);
Antoine Pitrou5ee9d8a2011-11-06 00:38:45 +01002013 stdin_errors = _PyObject_GetAttrId(fin, &PyId_errors);
Serhiy Storchakac2cf1282017-03-12 13:50:36 +02002014 if (!stdin_encoding || !stdin_errors ||
2015 !PyUnicode_Check(stdin_encoding) ||
2016 !PyUnicode_Check(stdin_errors)) {
2017 tty = 0;
Antoine Pitrou0d776b12011-11-06 00:34:26 +01002018 goto _readline_errors;
Serhiy Storchakac2cf1282017-03-12 13:50:36 +02002019 }
Serhiy Storchaka06515832016-11-20 09:13:07 +02002020 stdin_encoding_str = PyUnicode_AsUTF8(stdin_encoding);
2021 stdin_errors_str = PyUnicode_AsUTF8(stdin_errors);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01002022 if (!stdin_encoding_str || !stdin_errors_str)
2023 goto _readline_errors;
Jeroen Demeyer762f93f2019-07-08 10:19:25 +02002024 tmp = _PyObject_CallMethodIdNoArgs(fout, &PyId_flush);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002025 if (tmp == NULL)
2026 PyErr_Clear();
2027 else
2028 Py_DECREF(tmp);
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002029 if (prompt != NULL) {
Antoine Pitrou0d776b12011-11-06 00:34:26 +01002030 /* We have a prompt, encode it as stdout would */
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +02002031 const char *stdout_encoding_str, *stdout_errors_str;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002032 PyObject *stringpo;
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02002033 stdout_encoding = _PyObject_GetAttrId(fout, &PyId_encoding);
Antoine Pitrou5ee9d8a2011-11-06 00:38:45 +01002034 stdout_errors = _PyObject_GetAttrId(fout, &PyId_errors);
Serhiy Storchakac2cf1282017-03-12 13:50:36 +02002035 if (!stdout_encoding || !stdout_errors ||
2036 !PyUnicode_Check(stdout_encoding) ||
2037 !PyUnicode_Check(stdout_errors)) {
2038 tty = 0;
Antoine Pitrou0d776b12011-11-06 00:34:26 +01002039 goto _readline_errors;
Serhiy Storchakac2cf1282017-03-12 13:50:36 +02002040 }
Serhiy Storchaka06515832016-11-20 09:13:07 +02002041 stdout_encoding_str = PyUnicode_AsUTF8(stdout_encoding);
2042 stdout_errors_str = PyUnicode_AsUTF8(stdout_errors);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01002043 if (!stdout_encoding_str || !stdout_errors_str)
2044 goto _readline_errors;
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002045 stringpo = PyObject_Str(prompt);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01002046 if (stringpo == NULL)
2047 goto _readline_errors;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002048 po = PyUnicode_AsEncodedString(stringpo,
Antoine Pitrou0d776b12011-11-06 00:34:26 +01002049 stdout_encoding_str, stdout_errors_str);
2050 Py_CLEAR(stdout_encoding);
2051 Py_CLEAR(stdout_errors);
2052 Py_CLEAR(stringpo);
2053 if (po == NULL)
2054 goto _readline_errors;
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03002055 assert(PyBytes_Check(po));
2056 promptstr = PyBytes_AS_STRING(po);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002057 }
2058 else {
2059 po = NULL;
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002060 promptstr = "";
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002061 }
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002062 s = PyOS_Readline(stdin, stdout, promptstr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002063 if (s == NULL) {
Richard Oudkerk614c5782013-04-03 13:44:50 +01002064 PyErr_CheckSignals();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002065 if (!PyErr_Occurred())
2066 PyErr_SetNone(PyExc_KeyboardInterrupt);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01002067 goto _readline_errors;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002068 }
Victor Stinnerc0f1a1a2011-02-23 12:07:37 +00002069
2070 len = strlen(s);
2071 if (len == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002072 PyErr_SetNone(PyExc_EOFError);
2073 result = NULL;
2074 }
Victor Stinnerc0f1a1a2011-02-23 12:07:37 +00002075 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002076 if (len > PY_SSIZE_T_MAX) {
2077 PyErr_SetString(PyExc_OverflowError,
2078 "input: input too long");
2079 result = NULL;
2080 }
2081 else {
Victor Stinnerc0f1a1a2011-02-23 12:07:37 +00002082 len--; /* strip trailing '\n' */
2083 if (len != 0 && s[len-1] == '\r')
2084 len--; /* strip trailing '\r' */
Antoine Pitrou0d776b12011-11-06 00:34:26 +01002085 result = PyUnicode_Decode(s, len, stdin_encoding_str,
2086 stdin_errors_str);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002087 }
2088 }
2089 Py_DECREF(stdin_encoding);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01002090 Py_DECREF(stdin_errors);
2091 Py_XDECREF(po);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002092 PyMem_FREE(s);
Steve Dowerb82e17e2019-05-23 08:45:22 -07002093
2094 if (result != NULL) {
2095 if (PySys_Audit("builtins.input/result", "O", result) < 0) {
2096 return NULL;
2097 }
2098 }
2099
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002100 return result;
Serhiy Storchakac2cf1282017-03-12 13:50:36 +02002101
Antoine Pitrou0d776b12011-11-06 00:34:26 +01002102 _readline_errors:
2103 Py_XDECREF(stdin_encoding);
2104 Py_XDECREF(stdout_encoding);
2105 Py_XDECREF(stdin_errors);
2106 Py_XDECREF(stdout_errors);
2107 Py_XDECREF(po);
Serhiy Storchakac2cf1282017-03-12 13:50:36 +02002108 if (tty)
2109 return NULL;
2110
2111 PyErr_Clear();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002112 }
Guido van Rossumeba76962007-05-27 09:13:28 +00002113
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002114 /* Fallback if we're not interactive */
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002115 if (prompt != NULL) {
2116 if (PyFile_WriteObject(prompt, fout, Py_PRINT_RAW) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002117 return NULL;
2118 }
Jeroen Demeyer762f93f2019-07-08 10:19:25 +02002119 tmp = _PyObject_CallMethodIdNoArgs(fout, &PyId_flush);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002120 if (tmp == NULL)
2121 PyErr_Clear();
2122 else
2123 Py_DECREF(tmp);
2124 return PyFile_GetLine(fin, -1);
Guido van Rossuma88a0332007-02-26 16:59:55 +00002125}
2126
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002127
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002128/*[clinic input]
2129repr as builtin_repr
2130
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03002131 obj: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002132 /
2133
2134Return the canonical string representation of the object.
2135
2136For many object types, including most builtins, eval(repr(obj)) == obj.
2137[clinic start generated code]*/
2138
Guido van Rossum79f25d91997-04-29 20:08:16 +00002139static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002140builtin_repr(PyObject *module, PyObject *obj)
2141/*[clinic end generated code: output=7ed3778c44fd0194 input=1c9e6d66d3e3be04]*/
Guido van Rossumc89705d1992-11-26 08:54:07 +00002142{
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002143 return PyObject_Repr(obj);
Guido van Rossumc89705d1992-11-26 08:54:07 +00002144}
2145
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002146
Serhiy Storchakaaca7f572017-11-15 17:51:14 +02002147/*[clinic input]
2148round as builtin_round
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002149
Serhiy Storchakaaca7f572017-11-15 17:51:14 +02002150 number: object
Serhiy Storchaka279f4462019-09-14 12:24:05 +03002151 ndigits: object = None
Serhiy Storchakaaca7f572017-11-15 17:51:14 +02002152
2153Round a number to a given precision in decimal digits.
2154
2155The return value is an integer if ndigits is omitted or None. Otherwise
2156the return value has the same type as the number. ndigits may be negative.
2157[clinic start generated code]*/
2158
2159static PyObject *
2160builtin_round_impl(PyObject *module, PyObject *number, PyObject *ndigits)
Serhiy Storchaka279f4462019-09-14 12:24:05 +03002161/*[clinic end generated code: output=ff0d9dd176c02ede input=275678471d7aca15]*/
Serhiy Storchakaaca7f572017-11-15 17:51:14 +02002162{
2163 PyObject *round, *result;
Alex Martelliae211f92007-08-22 23:21:33 +00002164
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002165 if (Py_TYPE(number)->tp_dict == NULL) {
2166 if (PyType_Ready(Py_TYPE(number)) < 0)
2167 return NULL;
2168 }
Guido van Rossum15d3d042007-08-24 02:02:45 +00002169
Benjamin Peterson214a7d22013-04-13 17:19:01 -04002170 round = _PyObject_LookupSpecial(number, &PyId___round__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002171 if (round == NULL) {
Benjamin Peterson214a7d22013-04-13 17:19:01 -04002172 if (!PyErr_Occurred())
2173 PyErr_Format(PyExc_TypeError,
2174 "type %.100s doesn't define __round__ method",
2175 Py_TYPE(number)->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002176 return NULL;
2177 }
Alex Martelliae211f92007-08-22 23:21:33 +00002178
Serhiy Storchaka279f4462019-09-14 12:24:05 +03002179 if (ndigits == Py_None)
Victor Stinnerf17c3de2016-12-06 18:46:19 +01002180 result = _PyObject_CallNoArg(round);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002181 else
Petr Viktorinffd97532020-02-11 17:46:57 +01002182 result = PyObject_CallOneArg(round, ndigits);
Benjamin Peterson214a7d22013-04-13 17:19:01 -04002183 Py_DECREF(round);
2184 return result;
Guido van Rossum9e51f9b1993-02-12 16:29:05 +00002185}
2186
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002187
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002188/*AC: we need to keep the kwds dict intact to easily call into the
2189 * list.sort method, which isn't currently supported in AC. So we just use
2190 * the initially generated signature with a custom implementation.
2191 */
2192/* [disabled clinic input]
2193sorted as builtin_sorted
2194
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03002195 iterable as seq: object
2196 key as keyfunc: object = None
2197 reverse: object = False
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002198
2199Return a new list containing all items from the iterable in ascending order.
2200
Raymond Hettinger7ea386e2016-08-25 21:11:50 -07002201A custom key function can be supplied to customize the sort order, and the
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002202reverse flag can be set to request the result in descending order.
2203[end disabled clinic input]*/
2204
2205PyDoc_STRVAR(builtin_sorted__doc__,
Serhiy Storchaka3a104252017-01-23 12:29:47 +02002206"sorted($module, iterable, /, *, key=None, reverse=False)\n"
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002207"--\n"
2208"\n"
2209"Return a new list containing all items from the iterable in ascending order.\n"
2210"\n"
Raymond Hettinger7ea386e2016-08-25 21:11:50 -07002211"A custom key function can be supplied to customize the sort order, and the\n"
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002212"reverse flag can be set to request the result in descending order.");
2213
2214#define BUILTIN_SORTED_METHODDEF \
Serhiy Storchaka62be7422018-11-27 13:27:31 +02002215 {"sorted", (PyCFunction)(void(*)(void))builtin_sorted, METH_FASTCALL | METH_KEYWORDS, builtin_sorted__doc__},
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002216
Raymond Hettinger64958a12003-12-17 20:43:33 +00002217static PyObject *
Serhiy Storchakaa5552f02017-12-15 13:11:11 +02002218builtin_sorted(PyObject *self, PyObject *const *args, Py_ssize_t nargs, PyObject *kwnames)
Raymond Hettinger64958a12003-12-17 20:43:33 +00002219{
Serhiy Storchaka7cf8beb2017-01-21 23:05:00 +02002220 PyObject *newlist, *v, *seq, *callable;
Victor Stinner5a60eca2017-01-17 15:17:49 +01002221
Serhiy Storchaka7cf8beb2017-01-21 23:05:00 +02002222 /* Keyword arguments are passed through list.sort() which will check
2223 them. */
2224 if (!_PyArg_UnpackStack(args, nargs, "sorted", 1, 1, &seq))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002225 return NULL;
Raymond Hettinger64958a12003-12-17 20:43:33 +00002226
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002227 newlist = PySequence_List(seq);
2228 if (newlist == NULL)
2229 return NULL;
Raymond Hettinger64958a12003-12-17 20:43:33 +00002230
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02002231 callable = _PyObject_GetAttrId(newlist, &PyId_sort);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002232 if (callable == NULL) {
2233 Py_DECREF(newlist);
2234 return NULL;
2235 }
Georg Brandl99d7e4e2005-08-31 22:21:15 +00002236
Serhiy Storchaka299dc232017-01-20 08:35:18 +02002237 assert(nargs >= 1);
Petr Viktorinffd97532020-02-11 17:46:57 +01002238 v = PyObject_Vectorcall(callable, args + 1, nargs - 1, kwnames);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002239 Py_DECREF(callable);
2240 if (v == NULL) {
2241 Py_DECREF(newlist);
2242 return NULL;
2243 }
2244 Py_DECREF(v);
2245 return newlist;
Raymond Hettinger64958a12003-12-17 20:43:33 +00002246}
2247
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002248
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002249/* AC: cannot convert yet, as needs PEP 457 group support in inspect */
Guido van Rossum79f25d91997-04-29 20:08:16 +00002250static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002251builtin_vars(PyObject *self, PyObject *args)
Guido van Rossum2d951851994-08-29 12:52:16 +00002252{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002253 PyObject *v = NULL;
2254 PyObject *d;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002255
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002256 if (!PyArg_UnpackTuple(args, "vars", 0, 1, &v))
2257 return NULL;
2258 if (v == NULL) {
2259 d = PyEval_GetLocals();
Serhiy Storchaka41c57b32019-09-01 12:03:39 +03002260 Py_XINCREF(d);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002261 }
2262 else {
Serhiy Storchaka41c57b32019-09-01 12:03:39 +03002263 if (_PyObject_LookupAttrId(v, &PyId___dict__, &d) == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002264 PyErr_SetString(PyExc_TypeError,
2265 "vars() argument must have __dict__ attribute");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002266 }
2267 }
2268 return d;
Guido van Rossum2d951851994-08-29 12:52:16 +00002269}
2270
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002271PyDoc_STRVAR(vars_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002272"vars([object]) -> dictionary\n\
2273\n\
2274Without arguments, equivalent to locals().\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002275With an argument, equivalent to object.__dict__.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002276
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002277
2278/*[clinic input]
2279sum as builtin_sum
2280
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03002281 iterable: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002282 /
Raymond Hettinger9dfa0fe2018-09-12 10:54:06 -07002283 start: object(c_default="NULL") = 0
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002284
2285Return the sum of a 'start' value (default: 0) plus an iterable of numbers
2286
2287When the iterable is empty, return the start value.
2288This function is intended specifically for use with numeric values and may
2289reject non-numeric types.
2290[clinic start generated code]*/
2291
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002292static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002293builtin_sum_impl(PyObject *module, PyObject *iterable, PyObject *start)
Raymond Hettinger9dfa0fe2018-09-12 10:54:06 -07002294/*[clinic end generated code: output=df758cec7d1d302f input=162b50765250d222]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002295{
2296 PyObject *result = start;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002297 PyObject *temp, *item, *iter;
Alex Martellia70b1912003-04-22 08:12:33 +00002298
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002299 iter = PyObject_GetIter(iterable);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002300 if (iter == NULL)
2301 return NULL;
Alex Martellia70b1912003-04-22 08:12:33 +00002302
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002303 if (result == NULL) {
2304 result = PyLong_FromLong(0);
2305 if (result == NULL) {
2306 Py_DECREF(iter);
2307 return NULL;
2308 }
2309 } else {
2310 /* reject string values for 'start' parameter */
2311 if (PyUnicode_Check(result)) {
2312 PyErr_SetString(PyExc_TypeError,
2313 "sum() can't sum strings [use ''.join(seq) instead]");
2314 Py_DECREF(iter);
2315 return NULL;
2316 }
Benjamin Petersonce071ca2011-07-29 14:23:47 -05002317 if (PyBytes_Check(result)) {
2318 PyErr_SetString(PyExc_TypeError,
2319 "sum() can't sum bytes [use b''.join(seq) instead]");
Benjamin Peterson405f32c2011-07-29 22:43:45 -05002320 Py_DECREF(iter);
Benjamin Petersonce071ca2011-07-29 14:23:47 -05002321 return NULL;
2322 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002323 if (PyByteArray_Check(result)) {
2324 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson4f921c22011-07-29 14:24:29 -05002325 "sum() can't sum bytearray [use b''.join(seq) instead]");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002326 Py_DECREF(iter);
2327 return NULL;
2328 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002329 Py_INCREF(result);
2330 }
Alex Martellia70b1912003-04-22 08:12:33 +00002331
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002332#ifndef SLOW_SUM
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002333 /* Fast addition by keeping temporary sums in C instead of new Python objects.
2334 Assumes all inputs are the same type. If the assumption fails, default
2335 to the more general routine.
2336 */
2337 if (PyLong_CheckExact(result)) {
2338 int overflow;
2339 long i_result = PyLong_AsLongAndOverflow(result, &overflow);
2340 /* If this already overflowed, don't even enter the loop. */
2341 if (overflow == 0) {
2342 Py_DECREF(result);
2343 result = NULL;
2344 }
2345 while(result == NULL) {
2346 item = PyIter_Next(iter);
2347 if (item == NULL) {
2348 Py_DECREF(iter);
2349 if (PyErr_Occurred())
2350 return NULL;
2351 return PyLong_FromLong(i_result);
2352 }
Serhiy Storchaka88bdb922019-09-10 16:31:01 +03002353 if (PyLong_CheckExact(item) || PyBool_Check(item)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002354 long b = PyLong_AsLongAndOverflow(item, &overflow);
Serhiy Storchaka29500732019-05-05 14:26:23 +03002355 if (overflow == 0 &&
2356 (i_result >= 0 ? (b <= LONG_MAX - i_result)
2357 : (b >= LONG_MIN - i_result)))
2358 {
2359 i_result += b;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002360 Py_DECREF(item);
2361 continue;
2362 }
2363 }
2364 /* Either overflowed or is not an int. Restore real objects and process normally */
2365 result = PyLong_FromLong(i_result);
Christian Heimes704e2d32013-07-26 22:49:26 +02002366 if (result == NULL) {
2367 Py_DECREF(item);
2368 Py_DECREF(iter);
2369 return NULL;
2370 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002371 temp = PyNumber_Add(result, item);
2372 Py_DECREF(result);
2373 Py_DECREF(item);
2374 result = temp;
2375 if (result == NULL) {
2376 Py_DECREF(iter);
2377 return NULL;
2378 }
2379 }
2380 }
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002381
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002382 if (PyFloat_CheckExact(result)) {
2383 double f_result = PyFloat_AS_DOUBLE(result);
2384 Py_DECREF(result);
2385 result = NULL;
2386 while(result == NULL) {
2387 item = PyIter_Next(iter);
2388 if (item == NULL) {
2389 Py_DECREF(iter);
2390 if (PyErr_Occurred())
2391 return NULL;
2392 return PyFloat_FromDouble(f_result);
2393 }
2394 if (PyFloat_CheckExact(item)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002395 f_result += PyFloat_AS_DOUBLE(item);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002396 Py_DECREF(item);
2397 continue;
2398 }
Serhiy Storchaka88bdb922019-09-10 16:31:01 +03002399 if (PyLong_Check(item)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002400 long value;
2401 int overflow;
2402 value = PyLong_AsLongAndOverflow(item, &overflow);
2403 if (!overflow) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002404 f_result += (double)value;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002405 Py_DECREF(item);
2406 continue;
2407 }
2408 }
2409 result = PyFloat_FromDouble(f_result);
Alexey Izbyshev2b824b22018-08-24 07:27:52 +03002410 if (result == NULL) {
2411 Py_DECREF(item);
2412 Py_DECREF(iter);
2413 return NULL;
2414 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002415 temp = PyNumber_Add(result, item);
2416 Py_DECREF(result);
2417 Py_DECREF(item);
2418 result = temp;
2419 if (result == NULL) {
2420 Py_DECREF(iter);
2421 return NULL;
2422 }
2423 }
2424 }
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002425#endif
2426
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002427 for(;;) {
2428 item = PyIter_Next(iter);
2429 if (item == NULL) {
2430 /* error, or end-of-sequence */
2431 if (PyErr_Occurred()) {
2432 Py_DECREF(result);
2433 result = NULL;
2434 }
2435 break;
2436 }
2437 /* It's tempting to use PyNumber_InPlaceAdd instead of
2438 PyNumber_Add here, to avoid quadratic running time
2439 when doing 'sum(list_of_lists, [])'. However, this
2440 would produce a change in behaviour: a snippet like
Mark Dickinson9acadc52009-10-26 14:19:42 +00002441
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002442 empty = []
2443 sum([[x] for x in range(10)], empty)
Mark Dickinson9acadc52009-10-26 14:19:42 +00002444
Brandt Bucherabb9a442020-02-01 03:08:34 -08002445 would change the value of empty. In fact, using
2446 in-place addition rather that binary addition for
2447 any of the steps introduces subtle behavior changes:
Victor Stinner58f4e1a2020-02-05 18:24:33 +01002448
Brandt Bucherabb9a442020-02-01 03:08:34 -08002449 https://bugs.python.org/issue18305 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002450 temp = PyNumber_Add(result, item);
2451 Py_DECREF(result);
2452 Py_DECREF(item);
2453 result = temp;
2454 if (result == NULL)
2455 break;
2456 }
2457 Py_DECREF(iter);
2458 return result;
Alex Martellia70b1912003-04-22 08:12:33 +00002459}
2460
Alex Martellia70b1912003-04-22 08:12:33 +00002461
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002462/*[clinic input]
2463isinstance as builtin_isinstance
2464
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03002465 obj: object
2466 class_or_tuple: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002467 /
2468
2469Return whether an object is an instance of a class or of a subclass thereof.
2470
2471A tuple, as in ``isinstance(x, (A, B, ...))``, may be given as the target to
2472check against. This is equivalent to ``isinstance(x, A) or isinstance(x, B)
2473or ...`` etc.
2474[clinic start generated code]*/
2475
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002476static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002477builtin_isinstance_impl(PyObject *module, PyObject *obj,
Larry Hastings89964c42015-04-14 18:07:59 -04002478 PyObject *class_or_tuple)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002479/*[clinic end generated code: output=6faf01472c13b003 input=ffa743db1daf7549]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002480{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002481 int retval;
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002482
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002483 retval = PyObject_IsInstance(obj, class_or_tuple);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002484 if (retval < 0)
2485 return NULL;
2486 return PyBool_FromLong(retval);
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002487}
2488
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002489
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002490/*[clinic input]
2491issubclass as builtin_issubclass
2492
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03002493 cls: object
2494 class_or_tuple: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002495 /
2496
Alex Poveldf773f82020-06-03 15:19:45 +02002497Return whether 'cls' is derived from another class or is the same class.
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002498
2499A tuple, as in ``issubclass(x, (A, B, ...))``, may be given as the target to
2500check against. This is equivalent to ``issubclass(x, A) or issubclass(x, B)
Alex Poveldf773f82020-06-03 15:19:45 +02002501or ...``.
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002502[clinic start generated code]*/
2503
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002504static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002505builtin_issubclass_impl(PyObject *module, PyObject *cls,
Larry Hastings89964c42015-04-14 18:07:59 -04002506 PyObject *class_or_tuple)
Alex Poveldf773f82020-06-03 15:19:45 +02002507/*[clinic end generated code: output=358412410cd7a250 input=a24b9f3d58c370d6]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002508{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002509 int retval;
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002510
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002511 retval = PyObject_IsSubclass(cls, class_or_tuple);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002512 if (retval < 0)
2513 return NULL;
2514 return PyBool_FromLong(retval);
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002515}
2516
2517
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002518typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002519 PyObject_HEAD
Guido van Rossum310f6aa2020-06-19 03:16:57 -07002520 Py_ssize_t tuplesize;
2521 PyObject *ittuple; /* tuple of iterators */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002522 PyObject *result;
Guido van Rossum310f6aa2020-06-19 03:16:57 -07002523 int strict;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002524} zipobject;
2525
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002526static PyObject *
2527zip_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
Barry Warsawbd599b52000-08-03 15:45:29 +00002528{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002529 zipobject *lz;
2530 Py_ssize_t i;
2531 PyObject *ittuple; /* tuple of iterators */
2532 PyObject *result;
Serhiy Storchakabf623ae2017-04-19 20:03:52 +03002533 Py_ssize_t tuplesize;
Guido van Rossum310f6aa2020-06-19 03:16:57 -07002534 int strict = 0;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002535
Guido van Rossum310f6aa2020-06-19 03:16:57 -07002536 if (kwds) {
2537 PyObject *empty = PyTuple_New(0);
2538 if (empty == NULL) {
2539 return NULL;
2540 }
2541 static char *kwlist[] = {"strict", NULL};
2542 int parsed = PyArg_ParseTupleAndKeywords(
2543 empty, kwds, "|$p:zip", kwlist, &strict);
2544 Py_DECREF(empty);
2545 if (!parsed) {
2546 return NULL;
2547 }
2548 }
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002549
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002550 /* args must be a tuple */
2551 assert(PyTuple_Check(args));
Serhiy Storchakabf623ae2017-04-19 20:03:52 +03002552 tuplesize = PyTuple_GET_SIZE(args);
Barry Warsawbd599b52000-08-03 15:45:29 +00002553
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002554 /* obtain iterators */
2555 ittuple = PyTuple_New(tuplesize);
2556 if (ittuple == NULL)
2557 return NULL;
2558 for (i=0; i < tuplesize; ++i) {
2559 PyObject *item = PyTuple_GET_ITEM(args, i);
2560 PyObject *it = PyObject_GetIter(item);
2561 if (it == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002562 Py_DECREF(ittuple);
2563 return NULL;
2564 }
2565 PyTuple_SET_ITEM(ittuple, i, it);
2566 }
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002567
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002568 /* create a result holder */
2569 result = PyTuple_New(tuplesize);
2570 if (result == NULL) {
2571 Py_DECREF(ittuple);
2572 return NULL;
2573 }
2574 for (i=0 ; i < tuplesize ; i++) {
2575 Py_INCREF(Py_None);
2576 PyTuple_SET_ITEM(result, i, Py_None);
2577 }
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002578
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002579 /* create zipobject structure */
2580 lz = (zipobject *)type->tp_alloc(type, 0);
2581 if (lz == NULL) {
2582 Py_DECREF(ittuple);
2583 Py_DECREF(result);
2584 return NULL;
2585 }
2586 lz->ittuple = ittuple;
2587 lz->tuplesize = tuplesize;
2588 lz->result = result;
Guido van Rossum310f6aa2020-06-19 03:16:57 -07002589 lz->strict = strict;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002590
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002591 return (PyObject *)lz;
Barry Warsawbd599b52000-08-03 15:45:29 +00002592}
2593
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002594static void
2595zip_dealloc(zipobject *lz)
2596{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002597 PyObject_GC_UnTrack(lz);
2598 Py_XDECREF(lz->ittuple);
2599 Py_XDECREF(lz->result);
2600 Py_TYPE(lz)->tp_free(lz);
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002601}
2602
2603static int
2604zip_traverse(zipobject *lz, visitproc visit, void *arg)
2605{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002606 Py_VISIT(lz->ittuple);
2607 Py_VISIT(lz->result);
2608 return 0;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002609}
2610
2611static PyObject *
2612zip_next(zipobject *lz)
2613{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002614 Py_ssize_t i;
2615 Py_ssize_t tuplesize = lz->tuplesize;
2616 PyObject *result = lz->result;
2617 PyObject *it;
2618 PyObject *item;
2619 PyObject *olditem;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002620
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002621 if (tuplesize == 0)
2622 return NULL;
2623 if (Py_REFCNT(result) == 1) {
2624 Py_INCREF(result);
2625 for (i=0 ; i < tuplesize ; i++) {
2626 it = PyTuple_GET_ITEM(lz->ittuple, i);
2627 item = (*Py_TYPE(it)->tp_iternext)(it);
Serhiy Storchaka278d03b2013-04-06 22:52:34 +03002628 if (item == NULL) {
2629 Py_DECREF(result);
Guido van Rossum310f6aa2020-06-19 03:16:57 -07002630 if (lz->strict) {
2631 goto check;
2632 }
Serhiy Storchaka278d03b2013-04-06 22:52:34 +03002633 return NULL;
2634 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002635 olditem = PyTuple_GET_ITEM(result, i);
2636 PyTuple_SET_ITEM(result, i, item);
2637 Py_DECREF(olditem);
2638 }
2639 } else {
2640 result = PyTuple_New(tuplesize);
2641 if (result == NULL)
Serhiy Storchaka278d03b2013-04-06 22:52:34 +03002642 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002643 for (i=0 ; i < tuplesize ; i++) {
2644 it = PyTuple_GET_ITEM(lz->ittuple, i);
2645 item = (*Py_TYPE(it)->tp_iternext)(it);
Serhiy Storchaka278d03b2013-04-06 22:52:34 +03002646 if (item == NULL) {
2647 Py_DECREF(result);
Guido van Rossum310f6aa2020-06-19 03:16:57 -07002648 if (lz->strict) {
2649 goto check;
2650 }
Serhiy Storchaka278d03b2013-04-06 22:52:34 +03002651 return NULL;
2652 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002653 PyTuple_SET_ITEM(result, i, item);
2654 }
2655 }
2656 return result;
Guido van Rossum310f6aa2020-06-19 03:16:57 -07002657check:
2658 if (PyErr_Occurred()) {
2659 if (!PyErr_ExceptionMatches(PyExc_StopIteration)) {
2660 // next() on argument i raised an exception (not StopIteration)
2661 return NULL;
2662 }
2663 PyErr_Clear();
2664 }
2665 if (i) {
2666 // ValueError: zip() argument 2 is shorter than argument 1
2667 // ValueError: zip() argument 3 is shorter than arguments 1-2
2668 const char* plural = i == 1 ? " " : "s 1-";
2669 return PyErr_Format(PyExc_ValueError,
2670 "zip() argument %d is shorter than argument%s%d",
2671 i + 1, plural, i);
2672 }
2673 for (i = 1; i < tuplesize; i++) {
2674 it = PyTuple_GET_ITEM(lz->ittuple, i);
2675 item = (*Py_TYPE(it)->tp_iternext)(it);
2676 if (item) {
2677 Py_DECREF(item);
2678 const char* plural = i == 1 ? " " : "s 1-";
2679 return PyErr_Format(PyExc_ValueError,
2680 "zip() argument %d is longer than argument%s%d",
2681 i + 1, plural, i);
2682 }
2683 if (PyErr_Occurred()) {
2684 if (!PyErr_ExceptionMatches(PyExc_StopIteration)) {
2685 // next() on argument i raised an exception (not StopIteration)
2686 return NULL;
2687 }
2688 PyErr_Clear();
2689 }
2690 // Argument i is exhausted. So far so good...
2691 }
2692 // All arguments are exhausted. Success!
2693 return NULL;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002694}
Barry Warsawbd599b52000-08-03 15:45:29 +00002695
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002696static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05302697zip_reduce(zipobject *lz, PyObject *Py_UNUSED(ignored))
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002698{
2699 /* Just recreate the zip with the internal iterator tuple */
Guido van Rossum310f6aa2020-06-19 03:16:57 -07002700 if (lz->strict) {
2701 return PyTuple_Pack(3, Py_TYPE(lz), lz->ittuple, Py_True);
2702 }
2703 return PyTuple_Pack(2, Py_TYPE(lz), lz->ittuple);
2704}
2705
2706PyDoc_STRVAR(setstate_doc, "Set state information for unpickling.");
2707
2708static PyObject *
2709zip_setstate(zipobject *lz, PyObject *state)
2710{
2711 int strict = PyObject_IsTrue(state);
2712 if (strict < 0) {
2713 return NULL;
2714 }
2715 lz->strict = strict;
2716 Py_RETURN_NONE;
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002717}
2718
2719static PyMethodDef zip_methods[] = {
2720 {"__reduce__", (PyCFunction)zip_reduce, METH_NOARGS, reduce_doc},
Guido van Rossum310f6aa2020-06-19 03:16:57 -07002721 {"__setstate__", (PyCFunction)zip_setstate, METH_O, setstate_doc},
2722 {NULL} /* sentinel */
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002723};
2724
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002725PyDoc_STRVAR(zip_doc,
Guido van Rossum310f6aa2020-06-19 03:16:57 -07002726"zip(*iterables, strict=False) --> Yield tuples until an input is exhausted.\n\
Barry Warsawbd599b52000-08-03 15:45:29 +00002727\n\
Gregory P. Smith6a5d3ff2020-05-15 14:26:00 -07002728 >>> list(zip('abcdefg', range(3), range(4)))\n\
2729 [('a', 0, 0), ('b', 1, 1), ('c', 2, 2)]\n\
2730\n\
2731The zip object yields n-length tuples, where n is the number of iterables\n\
2732passed as positional arguments to zip(). The i-th element in every tuple\n\
2733comes from the i-th iterable argument to zip(). This continues until the\n\
Guido van Rossum310f6aa2020-06-19 03:16:57 -07002734shortest argument is exhausted.\n\
2735\n\
2736If strict is true and one of the arguments is exhausted before the others,\n\
2737raise a ValueError.");
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002738
2739PyTypeObject PyZip_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002740 PyVarObject_HEAD_INIT(&PyType_Type, 0)
2741 "zip", /* tp_name */
2742 sizeof(zipobject), /* tp_basicsize */
2743 0, /* tp_itemsize */
2744 /* methods */
2745 (destructor)zip_dealloc, /* tp_dealloc */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02002746 0, /* tp_vectorcall_offset */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002747 0, /* tp_getattr */
2748 0, /* tp_setattr */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02002749 0, /* tp_as_async */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002750 0, /* tp_repr */
2751 0, /* tp_as_number */
2752 0, /* tp_as_sequence */
2753 0, /* tp_as_mapping */
2754 0, /* tp_hash */
2755 0, /* tp_call */
2756 0, /* tp_str */
2757 PyObject_GenericGetAttr, /* tp_getattro */
2758 0, /* tp_setattro */
2759 0, /* tp_as_buffer */
2760 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
2761 Py_TPFLAGS_BASETYPE, /* tp_flags */
2762 zip_doc, /* tp_doc */
2763 (traverseproc)zip_traverse, /* tp_traverse */
2764 0, /* tp_clear */
2765 0, /* tp_richcompare */
2766 0, /* tp_weaklistoffset */
2767 PyObject_SelfIter, /* tp_iter */
2768 (iternextfunc)zip_next, /* tp_iternext */
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002769 zip_methods, /* tp_methods */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002770 0, /* tp_members */
2771 0, /* tp_getset */
2772 0, /* tp_base */
2773 0, /* tp_dict */
2774 0, /* tp_descr_get */
2775 0, /* tp_descr_set */
2776 0, /* tp_dictoffset */
2777 0, /* tp_init */
2778 PyType_GenericAlloc, /* tp_alloc */
2779 zip_new, /* tp_new */
2780 PyObject_GC_Del, /* tp_free */
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002781};
Barry Warsawbd599b52000-08-03 15:45:29 +00002782
2783
Guido van Rossum79f25d91997-04-29 20:08:16 +00002784static PyMethodDef builtin_methods[] = {
Serhiy Storchaka62be7422018-11-27 13:27:31 +02002785 {"__build_class__", (PyCFunction)(void(*)(void))builtin___build_class__,
Serhiy Storchaka6969eaf2017-07-03 21:20:15 +03002786 METH_FASTCALL | METH_KEYWORDS, build_class_doc},
Serhiy Storchaka62be7422018-11-27 13:27:31 +02002787 {"__import__", (PyCFunction)(void(*)(void))builtin___import__, METH_VARARGS | METH_KEYWORDS, import_doc},
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002788 BUILTIN_ABS_METHODDEF
2789 BUILTIN_ALL_METHODDEF
2790 BUILTIN_ANY_METHODDEF
2791 BUILTIN_ASCII_METHODDEF
2792 BUILTIN_BIN_METHODDEF
Serhiy Storchaka62be7422018-11-27 13:27:31 +02002793 {"breakpoint", (PyCFunction)(void(*)(void))builtin_breakpoint, METH_FASTCALL | METH_KEYWORDS, breakpoint_doc},
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002794 BUILTIN_CALLABLE_METHODDEF
2795 BUILTIN_CHR_METHODDEF
2796 BUILTIN_COMPILE_METHODDEF
2797 BUILTIN_DELATTR_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002798 {"dir", builtin_dir, METH_VARARGS, dir_doc},
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002799 BUILTIN_DIVMOD_METHODDEF
2800 BUILTIN_EVAL_METHODDEF
2801 BUILTIN_EXEC_METHODDEF
2802 BUILTIN_FORMAT_METHODDEF
Serhiy Storchaka62be7422018-11-27 13:27:31 +02002803 {"getattr", (PyCFunction)(void(*)(void))builtin_getattr, METH_FASTCALL, getattr_doc},
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002804 BUILTIN_GLOBALS_METHODDEF
2805 BUILTIN_HASATTR_METHODDEF
2806 BUILTIN_HASH_METHODDEF
2807 BUILTIN_HEX_METHODDEF
2808 BUILTIN_ID_METHODDEF
2809 BUILTIN_INPUT_METHODDEF
2810 BUILTIN_ISINSTANCE_METHODDEF
2811 BUILTIN_ISSUBCLASS_METHODDEF
Serhiy Storchaka79342662019-01-12 08:25:41 +02002812 {"iter", (PyCFunction)(void(*)(void))builtin_iter, METH_FASTCALL, iter_doc},
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002813 BUILTIN_LEN_METHODDEF
2814 BUILTIN_LOCALS_METHODDEF
Serhiy Storchaka62be7422018-11-27 13:27:31 +02002815 {"max", (PyCFunction)(void(*)(void))builtin_max, METH_VARARGS | METH_KEYWORDS, max_doc},
2816 {"min", (PyCFunction)(void(*)(void))builtin_min, METH_VARARGS | METH_KEYWORDS, min_doc},
2817 {"next", (PyCFunction)(void(*)(void))builtin_next, METH_FASTCALL, next_doc},
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002818 BUILTIN_OCT_METHODDEF
2819 BUILTIN_ORD_METHODDEF
2820 BUILTIN_POW_METHODDEF
Serhiy Storchaka62be7422018-11-27 13:27:31 +02002821 {"print", (PyCFunction)(void(*)(void))builtin_print, METH_FASTCALL | METH_KEYWORDS, print_doc},
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002822 BUILTIN_REPR_METHODDEF
Serhiy Storchakaaca7f572017-11-15 17:51:14 +02002823 BUILTIN_ROUND_METHODDEF
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002824 BUILTIN_SETATTR_METHODDEF
2825 BUILTIN_SORTED_METHODDEF
2826 BUILTIN_SUM_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002827 {"vars", builtin_vars, METH_VARARGS, vars_doc},
2828 {NULL, NULL},
Guido van Rossum3f5da241990-12-20 15:06:42 +00002829};
2830
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002831PyDoc_STRVAR(builtin_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002832"Built-in functions, exceptions, and other objects.\n\
2833\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002834Noteworthy: None is the `nil' object; Ellipsis represents `...' in slices.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002835
Martin v. Löwis1a214512008-06-11 05:26:20 +00002836static struct PyModuleDef builtinsmodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002837 PyModuleDef_HEAD_INIT,
2838 "builtins",
2839 builtin_doc,
2840 -1, /* multiple "initialization" just copies the module dict. */
2841 builtin_methods,
2842 NULL,
2843 NULL,
2844 NULL,
2845 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00002846};
2847
2848
Guido van Rossum25ce5661997-08-02 03:10:38 +00002849PyObject *
Victor Stinnerb45d2592019-06-20 00:05:23 +02002850_PyBuiltin_Init(PyThreadState *tstate)
Guido van Rossum25ce5661997-08-02 03:10:38 +00002851{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002852 PyObject *mod, *dict, *debug;
Benjamin Peterson42124a72012-10-30 23:41:54 -04002853
Victor Stinnerda7933e2020-04-13 03:04:28 +02002854 const PyConfig *config = _PyInterpreterState_GetConfig(tstate->interp);
Victor Stinnerfbca9082018-08-30 00:50:45 +02002855
Benjamin Peterson42124a72012-10-30 23:41:54 -04002856 if (PyType_Ready(&PyFilter_Type) < 0 ||
2857 PyType_Ready(&PyMap_Type) < 0 ||
2858 PyType_Ready(&PyZip_Type) < 0)
2859 return NULL;
2860
Eric Snowd393c1b2017-09-14 12:18:12 -06002861 mod = _PyModule_CreateInitialized(&builtinsmodule, PYTHON_API_VERSION);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002862 if (mod == NULL)
2863 return NULL;
2864 dict = PyModule_GetDict(mod);
Tim Peters4b7625e2001-09-13 21:37:17 +00002865
Tim Peters7571a0f2003-03-23 17:52:28 +00002866#ifdef Py_TRACE_REFS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002867 /* "builtins" exposes a number of statically allocated objects
2868 * that, before this code was added in 2.3, never showed up in
2869 * the list of "all objects" maintained by Py_TRACE_REFS. As a
2870 * result, programs leaking references to None and False (etc)
2871 * couldn't be diagnosed by examining sys.getobjects(0).
2872 */
Tim Peters7571a0f2003-03-23 17:52:28 +00002873#define ADD_TO_ALL(OBJECT) _Py_AddToAllObjects((PyObject *)(OBJECT), 0)
2874#else
2875#define ADD_TO_ALL(OBJECT) (void)0
2876#endif
2877
Tim Peters4b7625e2001-09-13 21:37:17 +00002878#define SETBUILTIN(NAME, OBJECT) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002879 if (PyDict_SetItemString(dict, NAME, (PyObject *)OBJECT) < 0) \
2880 return NULL; \
2881 ADD_TO_ALL(OBJECT)
Tim Peters4b7625e2001-09-13 21:37:17 +00002882
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002883 SETBUILTIN("None", Py_None);
2884 SETBUILTIN("Ellipsis", Py_Ellipsis);
2885 SETBUILTIN("NotImplemented", Py_NotImplemented);
2886 SETBUILTIN("False", Py_False);
2887 SETBUILTIN("True", Py_True);
2888 SETBUILTIN("bool", &PyBool_Type);
2889 SETBUILTIN("memoryview", &PyMemoryView_Type);
2890 SETBUILTIN("bytearray", &PyByteArray_Type);
2891 SETBUILTIN("bytes", &PyBytes_Type);
2892 SETBUILTIN("classmethod", &PyClassMethod_Type);
2893 SETBUILTIN("complex", &PyComplex_Type);
2894 SETBUILTIN("dict", &PyDict_Type);
2895 SETBUILTIN("enumerate", &PyEnum_Type);
2896 SETBUILTIN("filter", &PyFilter_Type);
2897 SETBUILTIN("float", &PyFloat_Type);
2898 SETBUILTIN("frozenset", &PyFrozenSet_Type);
2899 SETBUILTIN("property", &PyProperty_Type);
2900 SETBUILTIN("int", &PyLong_Type);
2901 SETBUILTIN("list", &PyList_Type);
2902 SETBUILTIN("map", &PyMap_Type);
2903 SETBUILTIN("object", &PyBaseObject_Type);
2904 SETBUILTIN("range", &PyRange_Type);
2905 SETBUILTIN("reversed", &PyReversed_Type);
2906 SETBUILTIN("set", &PySet_Type);
2907 SETBUILTIN("slice", &PySlice_Type);
2908 SETBUILTIN("staticmethod", &PyStaticMethod_Type);
2909 SETBUILTIN("str", &PyUnicode_Type);
2910 SETBUILTIN("super", &PySuper_Type);
2911 SETBUILTIN("tuple", &PyTuple_Type);
2912 SETBUILTIN("type", &PyType_Type);
2913 SETBUILTIN("zip", &PyZip_Type);
Victor Stinnerfbca9082018-08-30 00:50:45 +02002914 debug = PyBool_FromLong(config->optimization_level == 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002915 if (PyDict_SetItemString(dict, "__debug__", debug) < 0) {
Serhiy Storchakacfdfbb42016-06-18 09:44:03 +03002916 Py_DECREF(debug);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002917 return NULL;
2918 }
Serhiy Storchakacfdfbb42016-06-18 09:44:03 +03002919 Py_DECREF(debug);
Barry Warsaw757af0e1997-08-29 22:13:51 +00002920
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002921 return mod;
Tim Peters7571a0f2003-03-23 17:52:28 +00002922#undef ADD_TO_ALL
Tim Peters4b7625e2001-09-13 21:37:17 +00002923#undef SETBUILTIN
Guido van Rossum3f5da241990-12-20 15:06:42 +00002924}