blob: ff5a51216939e7c66e466c868f23232746dd9f45 [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 Stinner621cebe2018-11-12 16:53:38 +01007#include "pycore_pystate.h"
Sergey Fedoseevf1b9abe2019-02-26 02:37:26 +05008#include "pycore_tupleobject.h"
Guido van Rossum6bf62da1997-04-11 20:37:35 +00009
Victor Stinnerbd303c12013-11-07 23:07:29 +010010_Py_IDENTIFIER(__builtins__);
11_Py_IDENTIFIER(__dict__);
12_Py_IDENTIFIER(__prepare__);
13_Py_IDENTIFIER(__round__);
Ivan Levkivskyi2b5fd1e2017-12-14 23:32:56 +010014_Py_IDENTIFIER(__mro_entries__);
Victor Stinnerbd303c12013-11-07 23:07:29 +010015_Py_IDENTIFIER(encoding);
16_Py_IDENTIFIER(errors);
Martin v. Löwisbd928fe2011-10-14 10:20:37 +020017_Py_IDENTIFIER(fileno);
18_Py_IDENTIFIER(flush);
Victor Stinnerbd303c12013-11-07 23:07:29 +010019_Py_IDENTIFIER(metaclass);
20_Py_IDENTIFIER(sort);
21_Py_IDENTIFIER(stdin);
22_Py_IDENTIFIER(stdout);
23_Py_IDENTIFIER(stderr);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +020024
Serhiy Storchaka1009bf12015-04-03 23:53:51 +030025#include "clinic/bltinmodule.c.h"
26
Ivan Levkivskyi2b5fd1e2017-12-14 23:32:56 +010027static PyObject*
Victor Stinner05d68a82018-01-18 11:15:25 +010028update_bases(PyObject *bases, PyObject *const *args, Py_ssize_t nargs)
Ivan Levkivskyi2b5fd1e2017-12-14 23:32:56 +010029{
Victor Stinner05d68a82018-01-18 11:15:25 +010030 Py_ssize_t i, j;
Ivan Levkivskyi2b5fd1e2017-12-14 23:32:56 +010031 PyObject *base, *meth, *new_base, *result, *new_bases = NULL;
32 PyObject *stack[1] = {bases};
33 assert(PyTuple_Check(bases));
34
35 for (i = 0; i < nargs; i++) {
36 base = args[i];
37 if (PyType_Check(base)) {
38 if (new_bases) {
39 /* If we already have made a replacement, then we append every normal base,
40 otherwise just skip it. */
41 if (PyList_Append(new_bases, base) < 0) {
42 goto error;
43 }
44 }
45 continue;
46 }
Serhiy Storchakaf320be72018-01-25 10:49:40 +020047 if (_PyObject_LookupAttrId(base, &PyId___mro_entries__, &meth) < 0) {
48 goto error;
49 }
Ivan Levkivskyi2b5fd1e2017-12-14 23:32:56 +010050 if (!meth) {
Ivan Levkivskyi2b5fd1e2017-12-14 23:32:56 +010051 if (new_bases) {
52 if (PyList_Append(new_bases, base) < 0) {
53 goto error;
54 }
55 }
56 continue;
57 }
58 new_base = _PyObject_FastCall(meth, stack, 1);
59 Py_DECREF(meth);
60 if (!new_base) {
61 goto error;
62 }
63 if (!PyTuple_Check(new_base)) {
64 PyErr_SetString(PyExc_TypeError,
65 "__mro_entries__ must return a tuple");
66 Py_DECREF(new_base);
67 goto error;
68 }
69 if (!new_bases) {
70 /* If this is a first successful replacement, create new_bases list and
71 copy previously encountered bases. */
72 if (!(new_bases = PyList_New(i))) {
73 goto error;
74 }
75 for (j = 0; j < i; j++) {
76 base = args[j];
77 PyList_SET_ITEM(new_bases, j, base);
78 Py_INCREF(base);
79 }
80 }
81 j = PyList_GET_SIZE(new_bases);
82 if (PyList_SetSlice(new_bases, j, j, new_base) < 0) {
83 goto error;
84 }
85 Py_DECREF(new_base);
86 }
87 if (!new_bases) {
88 return bases;
89 }
90 result = PyList_AsTuple(new_bases);
91 Py_DECREF(new_bases);
92 return result;
93
94error:
95 Py_XDECREF(new_bases);
96 return NULL;
97}
98
Nick Coghlanf9e227e2014-08-17 14:01:19 +100099/* AC: cannot convert yet, waiting for *args support */
Guido van Rossum79f25d91997-04-29 20:08:16 +0000100static PyObject *
Serhiy Storchakaa5552f02017-12-15 13:11:11 +0200101builtin___build_class__(PyObject *self, PyObject *const *args, Py_ssize_t nargs,
Victor Stinner773dc6d2017-01-16 23:46:26 +0100102 PyObject *kwnames)
Guido van Rossum52cc1d82007-03-18 15:41:51 +0000103{
Ivan Levkivskyi2b5fd1e2017-12-14 23:32:56 +0100104 PyObject *func, *name, *bases, *mkw, *meta, *winner, *prep, *ns, *orig_bases;
Nick Coghlan19d24672016-12-05 16:47:55 +1000105 PyObject *cls = NULL, *cell = NULL;
Victor Stinner0c39b1b2015-03-18 15:02:06 +0100106 int isclass = 0; /* initialize to prevent gcc warning */
Guido van Rossum52cc1d82007-03-18 15:41:51 +0000107
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000108 if (nargs < 2) {
109 PyErr_SetString(PyExc_TypeError,
110 "__build_class__: not enough arguments");
111 return NULL;
112 }
Victor Stinner773dc6d2017-01-16 23:46:26 +0100113 func = args[0]; /* Better be callable */
Benjamin Petersone8e14592013-05-16 14:37:25 -0500114 if (!PyFunction_Check(func)) {
115 PyErr_SetString(PyExc_TypeError,
Zachary Ware9b338722014-08-05 14:01:10 -0500116 "__build_class__: func must be a function");
Benjamin Petersone8e14592013-05-16 14:37:25 -0500117 return NULL;
118 }
Victor Stinner773dc6d2017-01-16 23:46:26 +0100119 name = args[1];
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000120 if (!PyUnicode_Check(name)) {
121 PyErr_SetString(PyExc_TypeError,
122 "__build_class__: name is not a string");
123 return NULL;
124 }
Sergey Fedoseevf1b9abe2019-02-26 02:37:26 +0500125 orig_bases = _PyTuple_FromArray(args + 2, nargs - 2);
Ivan Levkivskyi2b5fd1e2017-12-14 23:32:56 +0100126 if (orig_bases == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000127 return NULL;
Guido van Rossum52cc1d82007-03-18 15:41:51 +0000128
Ivan Levkivskyi2b5fd1e2017-12-14 23:32:56 +0100129 bases = update_bases(orig_bases, args + 2, nargs - 2);
130 if (bases == NULL) {
131 Py_DECREF(orig_bases);
132 return NULL;
133 }
134
Victor Stinner773dc6d2017-01-16 23:46:26 +0100135 if (kwnames == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000136 meta = NULL;
137 mkw = NULL;
138 }
139 else {
Victor Stinner773dc6d2017-01-16 23:46:26 +0100140 mkw = _PyStack_AsDict(args + nargs, kwnames);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000141 if (mkw == NULL) {
142 Py_DECREF(bases);
143 return NULL;
Guido van Rossum52cc1d82007-03-18 15:41:51 +0000144 }
Victor Stinner773dc6d2017-01-16 23:46:26 +0100145
Serhiy Storchakaa24107b2019-02-25 17:59:46 +0200146 meta = _PyDict_GetItemIdWithError(mkw, &PyId_metaclass);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000147 if (meta != NULL) {
148 Py_INCREF(meta);
Victor Stinnerae9f1612013-11-06 22:46:51 +0100149 if (_PyDict_DelItemId(mkw, &PyId_metaclass) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000150 Py_DECREF(meta);
151 Py_DECREF(mkw);
152 Py_DECREF(bases);
153 return NULL;
154 }
Nick Coghlande31b192011-10-23 22:04:16 +1000155 /* metaclass is explicitly given, check if it's indeed a class */
156 isclass = PyType_Check(meta);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000157 }
Serhiy Storchakaa24107b2019-02-25 17:59:46 +0200158 else if (PyErr_Occurred()) {
159 Py_DECREF(mkw);
160 Py_DECREF(bases);
161 return NULL;
162 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000163 }
164 if (meta == NULL) {
Nick Coghlande31b192011-10-23 22:04:16 +1000165 /* if there are no bases, use type: */
166 if (PyTuple_GET_SIZE(bases) == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000167 meta = (PyObject *) (&PyType_Type);
Nick Coghlande31b192011-10-23 22:04:16 +1000168 }
169 /* else get the type of the first base */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000170 else {
171 PyObject *base0 = PyTuple_GET_ITEM(bases, 0);
172 meta = (PyObject *) (base0->ob_type);
173 }
174 Py_INCREF(meta);
Nick Coghlande31b192011-10-23 22:04:16 +1000175 isclass = 1; /* meta is really a class */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000176 }
Nick Coghlan9715d262011-10-23 22:36:42 +1000177
Nick Coghlande31b192011-10-23 22:04:16 +1000178 if (isclass) {
179 /* meta is really a class, so check for a more derived
180 metaclass, or possible metaclass conflicts: */
181 winner = (PyObject *)_PyType_CalculateMetaclass((PyTypeObject *)meta,
182 bases);
183 if (winner == NULL) {
184 Py_DECREF(meta);
185 Py_XDECREF(mkw);
186 Py_DECREF(bases);
187 return NULL;
188 }
189 if (winner != meta) {
190 Py_DECREF(meta);
191 meta = winner;
192 Py_INCREF(meta);
193 }
194 }
195 /* else: meta is not a class, so we cannot do the metaclass
196 calculation, so we will use the explicitly given object as it is */
Serhiy Storchakaf320be72018-01-25 10:49:40 +0200197 if (_PyObject_LookupAttrId(meta, &PyId___prepare__, &prep) < 0) {
198 ns = NULL;
199 }
200 else if (prep == NULL) {
201 ns = PyDict_New();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000202 }
203 else {
Victor Stinner463b86a2016-08-22 23:33:13 +0200204 PyObject *pargs[2] = {name, bases};
205 ns = _PyObject_FastCallDict(prep, pargs, 2, mkw);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000206 Py_DECREF(prep);
207 }
208 if (ns == NULL) {
209 Py_DECREF(meta);
210 Py_XDECREF(mkw);
211 Py_DECREF(bases);
212 return NULL;
213 }
Oren Milman5837d042017-09-27 17:04:37 +0300214 if (!PyMapping_Check(ns)) {
215 PyErr_Format(PyExc_TypeError,
216 "%.200s.__prepare__() must return a mapping, not %.200s",
217 isclass ? ((PyTypeObject *)meta)->tp_name : "<metaclass>",
218 Py_TYPE(ns)->tp_name);
219 goto error;
220 }
Nick Coghlan19d24672016-12-05 16:47:55 +1000221 cell = PyEval_EvalCodeEx(PyFunction_GET_CODE(func), PyFunction_GET_GLOBALS(func), ns,
Benjamin Petersone8e14592013-05-16 14:37:25 -0500222 NULL, 0, NULL, 0, NULL, 0, NULL,
223 PyFunction_GET_CLOSURE(func));
Nick Coghlan19d24672016-12-05 16:47:55 +1000224 if (cell != NULL) {
Ivan Levkivskyi2b5fd1e2017-12-14 23:32:56 +0100225 if (bases != orig_bases) {
226 if (PyMapping_SetItemString(ns, "__orig_bases__", orig_bases) < 0) {
227 goto error;
228 }
229 }
Victor Stinnerd1c2a8e2016-08-23 01:34:35 +0200230 PyObject *margs[3] = {name, bases, ns};
231 cls = _PyObject_FastCallDict(meta, margs, 3, mkw);
Nick Coghlan19d24672016-12-05 16:47:55 +1000232 if (cls != NULL && PyType_Check(cls) && PyCell_Check(cell)) {
233 PyObject *cell_cls = PyCell_GET(cell);
234 if (cell_cls != cls) {
Nick Coghlan19d24672016-12-05 16:47:55 +1000235 if (cell_cls == NULL) {
236 const char *msg =
237 "__class__ not set defining %.200R as %.200R. "
238 "Was __classcell__ propagated to type.__new__?";
Serhiy Storchakaf5e7b192018-05-20 08:48:12 +0300239 PyErr_Format(PyExc_RuntimeError, msg, name, cls);
Nick Coghlan19d24672016-12-05 16:47:55 +1000240 } else {
241 const char *msg =
242 "__class__ set to %.200R defining %.200R as %.200R";
243 PyErr_Format(PyExc_TypeError, msg, cell_cls, name, cls);
Nick Coghlan19d24672016-12-05 16:47:55 +1000244 }
Serhiy Storchakaf5e7b192018-05-20 08:48:12 +0300245 Py_DECREF(cls);
246 cls = NULL;
247 goto error;
Nick Coghlan19d24672016-12-05 16:47:55 +1000248 }
249 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000250 }
Nick Coghlan19d24672016-12-05 16:47:55 +1000251error:
252 Py_XDECREF(cell);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000253 Py_DECREF(ns);
254 Py_DECREF(meta);
255 Py_XDECREF(mkw);
256 Py_DECREF(bases);
Ivan Levkivskyi2b5fd1e2017-12-14 23:32:56 +0100257 if (bases != orig_bases) {
258 Py_DECREF(orig_bases);
259 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000260 return cls;
Guido van Rossum52cc1d82007-03-18 15:41:51 +0000261}
262
263PyDoc_STRVAR(build_class_doc,
264"__build_class__(func, name, *bases, metaclass=None, **kwds) -> class\n\
265\n\
266Internal helper function used by the class statement.");
267
268static PyObject *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000269builtin___import__(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000270{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000271 static char *kwlist[] = {"name", "globals", "locals", "fromlist",
272 "level", 0};
Victor Stinnerfe93faf2011-03-14 15:54:52 -0400273 PyObject *name, *globals = NULL, *locals = NULL, *fromlist = NULL;
Brett Cannonfd074152012-04-14 14:10:13 -0400274 int level = 0;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000275
Victor Stinnerfe93faf2011-03-14 15:54:52 -0400276 if (!PyArg_ParseTupleAndKeywords(args, kwds, "U|OOOi:__import__",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000277 kwlist, &name, &globals, &locals, &fromlist, &level))
278 return NULL;
Victor Stinnerfe93faf2011-03-14 15:54:52 -0400279 return PyImport_ImportModuleLevelObject(name, globals, locals,
280 fromlist, level);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000281}
282
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000283PyDoc_STRVAR(import_doc,
Brett Cannoncb4996a2012-08-06 16:34:44 -0400284"__import__(name, globals=None, locals=None, fromlist=(), level=0) -> module\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000285\n\
Brett Cannon5305a992010-09-27 21:08:38 +0000286Import a module. Because this function is meant for use by the Python\n\
oldk461d2252018-02-02 12:20:00 +0800287interpreter and not for general use, it is better to use\n\
Brett Cannon5305a992010-09-27 21:08:38 +0000288importlib.import_module() to programmatically import a module.\n\
289\n\
290The globals argument is only used to determine the context;\n\
291they are not modified. The locals argument is unused. The fromlist\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000292should be a list of names to emulate ``from name import ...'', or an\n\
293empty list to emulate ``import name''.\n\
294When importing a module from a package, note that __import__('A.B', ...)\n\
295returns package A when fromlist is empty, but its submodule B when\n\
oldk461d2252018-02-02 12:20:00 +0800296fromlist is not empty. The level argument is used to determine whether to\n\
297perform absolute or relative imports: 0 is absolute, while a positive number\n\
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000298is the number of parent directories to search relative to the current module.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000299
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000300
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000301/*[clinic input]
302abs as builtin_abs
303
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300304 x: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000305 /
306
307Return the absolute value of the argument.
308[clinic start generated code]*/
309
Guido van Rossum79f25d91997-04-29 20:08:16 +0000310static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300311builtin_abs(PyObject *module, PyObject *x)
312/*[clinic end generated code: output=b1b433b9e51356f5 input=bed4ca14e29c20d1]*/
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000313{
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000314 return PyNumber_Absolute(x);
Guido van Rossum3f5da241990-12-20 15:06:42 +0000315}
316
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000317/*[clinic input]
318all as builtin_all
319
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300320 iterable: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000321 /
322
323Return True if bool(x) is True for all values x in the iterable.
324
325If the iterable is empty, return True.
326[clinic start generated code]*/
327
Raymond Hettinger96229b12005-03-11 06:49:40 +0000328static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300329builtin_all(PyObject *module, PyObject *iterable)
330/*[clinic end generated code: output=ca2a7127276f79b3 input=1a7c5d1bc3438a21]*/
Raymond Hettinger96229b12005-03-11 06:49:40 +0000331{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000332 PyObject *it, *item;
333 PyObject *(*iternext)(PyObject *);
334 int cmp;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000335
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000336 it = PyObject_GetIter(iterable);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000337 if (it == NULL)
338 return NULL;
339 iternext = *Py_TYPE(it)->tp_iternext;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000340
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000341 for (;;) {
342 item = iternext(it);
343 if (item == NULL)
344 break;
345 cmp = PyObject_IsTrue(item);
346 Py_DECREF(item);
347 if (cmp < 0) {
348 Py_DECREF(it);
349 return NULL;
350 }
351 if (cmp == 0) {
352 Py_DECREF(it);
353 Py_RETURN_FALSE;
354 }
355 }
356 Py_DECREF(it);
357 if (PyErr_Occurred()) {
358 if (PyErr_ExceptionMatches(PyExc_StopIteration))
359 PyErr_Clear();
360 else
361 return NULL;
362 }
363 Py_RETURN_TRUE;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000364}
365
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000366/*[clinic input]
367any as builtin_any
368
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300369 iterable: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000370 /
371
372Return True if bool(x) is True for any x in the iterable.
373
374If the iterable is empty, return False.
375[clinic start generated code]*/
376
Raymond Hettinger96229b12005-03-11 06:49:40 +0000377static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300378builtin_any(PyObject *module, PyObject *iterable)
379/*[clinic end generated code: output=fa65684748caa60e input=41d7451c23384f24]*/
Raymond Hettinger96229b12005-03-11 06:49:40 +0000380{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000381 PyObject *it, *item;
382 PyObject *(*iternext)(PyObject *);
383 int cmp;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000384
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000385 it = PyObject_GetIter(iterable);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000386 if (it == NULL)
387 return NULL;
388 iternext = *Py_TYPE(it)->tp_iternext;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000389
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000390 for (;;) {
391 item = iternext(it);
392 if (item == NULL)
393 break;
394 cmp = PyObject_IsTrue(item);
395 Py_DECREF(item);
396 if (cmp < 0) {
397 Py_DECREF(it);
398 return NULL;
399 }
Raymond Hettinger5098b582015-10-09 00:42:47 -0400400 if (cmp > 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000401 Py_DECREF(it);
402 Py_RETURN_TRUE;
403 }
404 }
405 Py_DECREF(it);
406 if (PyErr_Occurred()) {
407 if (PyErr_ExceptionMatches(PyExc_StopIteration))
408 PyErr_Clear();
409 else
410 return NULL;
411 }
412 Py_RETURN_FALSE;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000413}
414
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000415/*[clinic input]
416ascii as builtin_ascii
417
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300418 obj: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000419 /
420
421Return an ASCII-only representation of an object.
422
423As repr(), return a string containing a printable representation of an
424object, but escape the non-ASCII characters in the string returned by
425repr() using \\x, \\u or \\U escapes. This generates a string similar
426to that returned by repr() in Python 2.
427[clinic start generated code]*/
428
Georg Brandl559e5d72008-06-11 18:37:52 +0000429static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300430builtin_ascii(PyObject *module, PyObject *obj)
431/*[clinic end generated code: output=6d37b3f0984c7eb9 input=4c62732e1b3a3cc9]*/
Georg Brandl559e5d72008-06-11 18:37:52 +0000432{
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000433 return PyObject_ASCII(obj);
Georg Brandl559e5d72008-06-11 18:37:52 +0000434}
435
Georg Brandl559e5d72008-06-11 18:37:52 +0000436
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000437/*[clinic input]
438bin as builtin_bin
439
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300440 number: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000441 /
442
443Return the binary representation of an integer.
444
445 >>> bin(2796202)
446 '0b1010101010101010101010'
447[clinic start generated code]*/
448
Guido van Rossum79f25d91997-04-29 20:08:16 +0000449static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300450builtin_bin(PyObject *module, PyObject *number)
451/*[clinic end generated code: output=b6fc4ad5e649f4f7 input=53f8a0264bacaf90]*/
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000452{
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000453 return PyNumber_ToBase(number, 2);
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000454}
455
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000456
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000457/*[clinic input]
458callable as builtin_callable
459
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300460 obj: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000461 /
462
463Return whether the object is callable (i.e., some kind of function).
464
465Note that classes are callable, as are instances of classes with a
466__call__() method.
467[clinic start generated code]*/
468
Antoine Pitroue71362d2010-11-27 22:00:11 +0000469static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300470builtin_callable(PyObject *module, PyObject *obj)
471/*[clinic end generated code: output=2b095d59d934cb7e input=1423bab99cc41f58]*/
Antoine Pitroue71362d2010-11-27 22:00:11 +0000472{
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000473 return PyBool_FromLong((long)PyCallable_Check(obj));
Antoine Pitroue71362d2010-11-27 22:00:11 +0000474}
475
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400476static PyObject *
Serhiy Storchakaa5552f02017-12-15 13:11:11 +0200477builtin_breakpoint(PyObject *self, PyObject *const *args, Py_ssize_t nargs, PyObject *keywords)
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400478{
479 PyObject *hook = PySys_GetObject("breakpointhook");
480
481 if (hook == NULL) {
482 PyErr_SetString(PyExc_RuntimeError, "lost sys.breakpointhook");
483 return NULL;
484 }
485 Py_INCREF(hook);
486 PyObject *retval = _PyObject_FastCallKeywords(hook, args, nargs, keywords);
487 Py_DECREF(hook);
488 return retval;
489}
490
491PyDoc_STRVAR(breakpoint_doc,
492"breakpoint(*args, **kws)\n\
493\n\
494Call sys.breakpointhook(*args, **kws). sys.breakpointhook() must accept\n\
495whatever arguments are passed.\n\
496\n\
497By default, this drops you into the pdb debugger.");
Antoine Pitroue71362d2010-11-27 22:00:11 +0000498
Raymond Hettinger17301e92008-03-13 00:19:26 +0000499typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000500 PyObject_HEAD
501 PyObject *func;
502 PyObject *it;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000503} filterobject;
504
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000505static PyObject *
Raymond Hettinger17301e92008-03-13 00:19:26 +0000506filter_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
Guido van Rossum12d12c51993-10-26 17:58:25 +0000507{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000508 PyObject *func, *seq;
509 PyObject *it;
510 filterobject *lz;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000511
Serhiy Storchaka6cca5c82017-06-08 14:41:19 +0300512 if (type == &PyFilter_Type && !_PyArg_NoKeywords("filter", kwds))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000513 return NULL;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000514
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000515 if (!PyArg_UnpackTuple(args, "filter", 2, 2, &func, &seq))
516 return NULL;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000517
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000518 /* Get iterator. */
519 it = PyObject_GetIter(seq);
520 if (it == NULL)
521 return NULL;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000522
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000523 /* create filterobject structure */
524 lz = (filterobject *)type->tp_alloc(type, 0);
525 if (lz == NULL) {
526 Py_DECREF(it);
527 return NULL;
528 }
529 Py_INCREF(func);
530 lz->func = func;
531 lz->it = it;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000532
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000533 return (PyObject *)lz;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000534}
535
536static void
537filter_dealloc(filterobject *lz)
538{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000539 PyObject_GC_UnTrack(lz);
540 Py_XDECREF(lz->func);
541 Py_XDECREF(lz->it);
542 Py_TYPE(lz)->tp_free(lz);
Raymond Hettinger17301e92008-03-13 00:19:26 +0000543}
544
545static int
546filter_traverse(filterobject *lz, visitproc visit, void *arg)
547{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000548 Py_VISIT(lz->it);
549 Py_VISIT(lz->func);
550 return 0;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000551}
552
553static PyObject *
554filter_next(filterobject *lz)
555{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000556 PyObject *item;
557 PyObject *it = lz->it;
558 long ok;
559 PyObject *(*iternext)(PyObject *);
Raymond Hettingerbd5f0e82015-10-09 01:34:08 -0400560 int checktrue = lz->func == Py_None || lz->func == (PyObject *)&PyBool_Type;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000561
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000562 iternext = *Py_TYPE(it)->tp_iternext;
563 for (;;) {
564 item = iternext(it);
565 if (item == NULL)
566 return NULL;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000567
Raymond Hettingerbd5f0e82015-10-09 01:34:08 -0400568 if (checktrue) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000569 ok = PyObject_IsTrue(item);
570 } else {
571 PyObject *good;
Victor Stinnerde4ae3d2016-12-04 22:59:09 +0100572 good = PyObject_CallFunctionObjArgs(lz->func, item, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000573 if (good == NULL) {
574 Py_DECREF(item);
575 return NULL;
576 }
577 ok = PyObject_IsTrue(good);
578 Py_DECREF(good);
579 }
Antoine Pitrou6f430e42012-08-15 23:18:25 +0200580 if (ok > 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000581 return item;
582 Py_DECREF(item);
Antoine Pitrou6f430e42012-08-15 23:18:25 +0200583 if (ok < 0)
584 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000585 }
Guido van Rossum12d12c51993-10-26 17:58:25 +0000586}
587
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +0000588static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +0530589filter_reduce(filterobject *lz, PyObject *Py_UNUSED(ignored))
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +0000590{
591 return Py_BuildValue("O(OO)", Py_TYPE(lz), lz->func, lz->it);
592}
593
594PyDoc_STRVAR(reduce_doc, "Return state information for pickling.");
595
596static PyMethodDef filter_methods[] = {
597 {"__reduce__", (PyCFunction)filter_reduce, METH_NOARGS, reduce_doc},
598 {NULL, NULL} /* sentinel */
599};
600
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000601PyDoc_STRVAR(filter_doc,
Georg Brandld11ae5d2008-05-16 13:27:32 +0000602"filter(function or None, iterable) --> filter object\n\
Guido van Rossumc1f779c2007-07-03 08:25:58 +0000603\n\
Georg Brandld11ae5d2008-05-16 13:27:32 +0000604Return an iterator yielding those items of iterable for which function(item)\n\
Raymond Hettinger17301e92008-03-13 00:19:26 +0000605is true. If function is None, return the items that are true.");
606
607PyTypeObject PyFilter_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000608 PyVarObject_HEAD_INIT(&PyType_Type, 0)
609 "filter", /* tp_name */
610 sizeof(filterobject), /* tp_basicsize */
611 0, /* tp_itemsize */
612 /* methods */
613 (destructor)filter_dealloc, /* tp_dealloc */
614 0, /* tp_print */
615 0, /* tp_getattr */
616 0, /* tp_setattr */
617 0, /* tp_reserved */
618 0, /* tp_repr */
619 0, /* tp_as_number */
620 0, /* tp_as_sequence */
621 0, /* tp_as_mapping */
622 0, /* tp_hash */
623 0, /* tp_call */
624 0, /* tp_str */
625 PyObject_GenericGetAttr, /* tp_getattro */
626 0, /* tp_setattro */
627 0, /* tp_as_buffer */
628 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
629 Py_TPFLAGS_BASETYPE, /* tp_flags */
630 filter_doc, /* tp_doc */
631 (traverseproc)filter_traverse, /* tp_traverse */
632 0, /* tp_clear */
633 0, /* tp_richcompare */
634 0, /* tp_weaklistoffset */
635 PyObject_SelfIter, /* tp_iter */
636 (iternextfunc)filter_next, /* tp_iternext */
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +0000637 filter_methods, /* tp_methods */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000638 0, /* tp_members */
639 0, /* tp_getset */
640 0, /* tp_base */
641 0, /* tp_dict */
642 0, /* tp_descr_get */
643 0, /* tp_descr_set */
644 0, /* tp_dictoffset */
645 0, /* tp_init */
646 PyType_GenericAlloc, /* tp_alloc */
647 filter_new, /* tp_new */
648 PyObject_GC_Del, /* tp_free */
Raymond Hettinger17301e92008-03-13 00:19:26 +0000649};
650
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000651
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000652/*[clinic input]
653format as builtin_format
654
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300655 value: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000656 format_spec: unicode(c_default="NULL") = ''
657 /
658
659Return value.__format__(format_spec)
660
Amit Kumar2e6bb442017-05-29 06:32:26 +0530661format_spec defaults to the empty string.
662See the Format Specification Mini-Language section of help('FORMATTING') for
663details.
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000664[clinic start generated code]*/
665
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000666static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300667builtin_format_impl(PyObject *module, PyObject *value, PyObject *format_spec)
Amit Kumar2e6bb442017-05-29 06:32:26 +0530668/*[clinic end generated code: output=2f40bdfa4954b077 input=88339c93ea522b33]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000669{
Eric Smith8fd3eba2008-02-17 19:48:00 +0000670 return PyObject_Format(value, format_spec);
Eric Smith8c663262007-08-25 02:26:07 +0000671}
672
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000673/*[clinic input]
674chr as builtin_chr
675
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300676 i: int
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000677 /
678
679Return a Unicode string of one character with ordinal i; 0 <= i <= 0x10ffff.
680[clinic start generated code]*/
681
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000682static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300683builtin_chr_impl(PyObject *module, int i)
684/*[clinic end generated code: output=c733afcd200afcb7 input=3f604ef45a70750d]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000685{
686 return PyUnicode_FromOrdinal(i);
687}
Guido van Rossum09095f32000-03-10 23:00:52 +0000688
689
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +0200690static const char *
Martin Pantereeb896c2015-11-07 02:32:21 +0000691source_as_string(PyObject *cmd, const char *funcname, const char *what, PyCompilerFlags *cf, PyObject **cmd_copy)
Guido van Rossumf15a29f2007-05-04 00:41:39 +0000692{
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +0200693 const char *str;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000694 Py_ssize_t size;
Martin Pantereeb896c2015-11-07 02:32:21 +0000695 Py_buffer view;
Guido van Rossumf15a29f2007-05-04 00:41:39 +0000696
Martin Pantereeb896c2015-11-07 02:32:21 +0000697 *cmd_copy = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000698 if (PyUnicode_Check(cmd)) {
699 cf->cf_flags |= PyCF_IGNORE_COOKIE;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200700 str = PyUnicode_AsUTF8AndSize(cmd, &size);
701 if (str == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000702 return NULL;
703 }
Martin Pantereeb896c2015-11-07 02:32:21 +0000704 else if (PyBytes_Check(cmd)) {
705 str = PyBytes_AS_STRING(cmd);
706 size = PyBytes_GET_SIZE(cmd);
707 }
708 else if (PyByteArray_Check(cmd)) {
709 str = PyByteArray_AS_STRING(cmd);
710 size = PyByteArray_GET_SIZE(cmd);
711 }
712 else if (PyObject_GetBuffer(cmd, &view, PyBUF_SIMPLE) == 0) {
713 /* Copy to NUL-terminated buffer. */
714 *cmd_copy = PyBytes_FromStringAndSize(
715 (const char *)view.buf, view.len);
716 PyBuffer_Release(&view);
717 if (*cmd_copy == NULL) {
718 return NULL;
719 }
720 str = PyBytes_AS_STRING(*cmd_copy);
721 size = PyBytes_GET_SIZE(*cmd_copy);
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +0200722 }
723 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000724 PyErr_Format(PyExc_TypeError,
725 "%s() arg 1 must be a %s object",
726 funcname, what);
727 return NULL;
728 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200729
Serhiy Storchaka3dd3e262015-02-03 01:25:42 +0200730 if (strlen(str) != (size_t)size) {
Serhiy Storchakad8a14472014-09-06 20:07:17 +0300731 PyErr_SetString(PyExc_ValueError,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000732 "source code string cannot contain null bytes");
Martin Pantereeb896c2015-11-07 02:32:21 +0000733 Py_CLEAR(*cmd_copy);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000734 return NULL;
735 }
736 return str;
Guido van Rossumf15a29f2007-05-04 00:41:39 +0000737}
738
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000739/*[clinic input]
740compile as builtin_compile
741
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300742 source: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000743 filename: object(converter="PyUnicode_FSDecoder")
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300744 mode: str
745 flags: int = 0
Serhiy Storchaka202fda52017-03-12 10:10:47 +0200746 dont_inherit: bool(accept={int}) = False
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300747 optimize: int = -1
Guido van Rossum495da292019-03-07 12:38:08 -0800748 feature_version: int = -1
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000749
750Compile source into a code object that can be executed by exec() or eval().
751
752The source code may represent a Python module, statement or expression.
753The filename will be used for run-time error messages.
754The mode must be 'exec' to compile a module, 'single' to compile a
755single (interactive) statement, or 'eval' to compile an expression.
756The flags argument, if present, controls which future statements influence
757the compilation of the code.
Serhiy Storchaka8b2e8b62015-05-30 11:30:39 +0300758The dont_inherit argument, if true, stops the compilation inheriting
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000759the effects of any future statements in effect in the code calling
Serhiy Storchaka8b2e8b62015-05-30 11:30:39 +0300760compile; if absent or false these statements do influence the compilation,
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000761in addition to any features explicitly specified.
762[clinic start generated code]*/
763
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000764static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300765builtin_compile_impl(PyObject *module, PyObject *source, PyObject *filename,
766 const char *mode, int flags, int dont_inherit,
Guido van Rossum495da292019-03-07 12:38:08 -0800767 int optimize, int feature_version)
768/*[clinic end generated code: output=b0c09c84f116d3d7 input=5fcc30651a6acaa9]*/
Guido van Rossum5b722181993-03-30 17:46:03 +0000769{
Martin Panter61d6e4a2015-11-07 02:56:11 +0000770 PyObject *source_copy;
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +0200771 const char *str;
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000772 int compile_mode = -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000773 int is_ast;
774 PyCompilerFlags cf;
Guido van Rossumdcfcd142019-01-31 03:40:27 -0800775 int start[] = {Py_file_input, Py_eval_input, Py_single_input, Py_func_type_input};
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000776 PyObject *result;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000777
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000778 cf.cf_flags = flags | PyCF_SOURCE_IS_UTF8;
Guido van Rossum495da292019-03-07 12:38:08 -0800779 cf.cf_feature_version = PY_MINOR_VERSION;
780 if (feature_version >= 0 && (flags & PyCF_ONLY_AST)) {
781 cf.cf_feature_version = feature_version;
782 }
Tim Peters6cd6a822001-08-17 22:11:27 +0000783
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000784 if (flags &
Guido van Rossumdcfcd142019-01-31 03:40:27 -0800785 ~(PyCF_MASK | PyCF_MASK_OBSOLETE | PyCF_DONT_IMPLY_DEDENT | PyCF_ONLY_AST | PyCF_TYPE_COMMENTS))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000786 {
787 PyErr_SetString(PyExc_ValueError,
788 "compile(): unrecognised flags");
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000789 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000790 }
791 /* XXX Warn if (supplied_flags & PyCF_MASK_OBSOLETE) != 0? */
Tim Peters6cd6a822001-08-17 22:11:27 +0000792
Georg Brandl8334fd92010-12-04 10:26:46 +0000793 if (optimize < -1 || optimize > 2) {
794 PyErr_SetString(PyExc_ValueError,
795 "compile(): invalid optimize value");
796 goto error;
797 }
798
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000799 if (!dont_inherit) {
800 PyEval_MergeCompilerFlags(&cf);
801 }
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000802
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000803 if (strcmp(mode, "exec") == 0)
804 compile_mode = 0;
805 else if (strcmp(mode, "eval") == 0)
806 compile_mode = 1;
807 else if (strcmp(mode, "single") == 0)
808 compile_mode = 2;
Guido van Rossumdcfcd142019-01-31 03:40:27 -0800809 else if (strcmp(mode, "func_type") == 0) {
810 if (!(flags & PyCF_ONLY_AST)) {
811 PyErr_SetString(PyExc_ValueError,
812 "compile() mode 'func_type' requires flag PyCF_ONLY_AST");
813 goto error;
814 }
815 compile_mode = 3;
816 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000817 else {
Guido van Rossumdcfcd142019-01-31 03:40:27 -0800818 const char *msg;
819 if (flags & PyCF_ONLY_AST)
820 msg = "compile() mode must be 'exec', 'eval', 'single' or 'func_type'";
821 else
822 msg = "compile() mode must be 'exec', 'eval' or 'single'";
823 PyErr_SetString(PyExc_ValueError, msg);
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000824 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000825 }
Neal Norwitzdb4115f2008-03-31 04:20:05 +0000826
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000827 is_ast = PyAST_Check(source);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000828 if (is_ast == -1)
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000829 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000830 if (is_ast) {
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000831 if (flags & PyCF_ONLY_AST) {
832 Py_INCREF(source);
833 result = source;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000834 }
835 else {
836 PyArena *arena;
837 mod_ty mod;
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000838
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000839 arena = PyArena_New();
Stefan Krah07795df2012-08-20 17:19:50 +0200840 if (arena == NULL)
841 goto error;
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000842 mod = PyAST_obj2mod(source, arena, compile_mode);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000843 if (mod == NULL) {
844 PyArena_Free(arena);
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000845 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000846 }
Benjamin Peterson832bfe22011-08-09 16:15:04 -0500847 if (!PyAST_Validate(mod)) {
848 PyArena_Free(arena);
849 goto error;
850 }
Victor Stinner14e461d2013-08-26 22:28:21 +0200851 result = (PyObject*)PyAST_CompileObject(mod, filename,
852 &cf, optimize, arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000853 PyArena_Free(arena);
854 }
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000855 goto finally;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000856 }
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000857
Martin Panter61d6e4a2015-11-07 02:56:11 +0000858 str = source_as_string(source, "compile", "string, bytes or AST", &cf, &source_copy);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000859 if (str == NULL)
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000860 goto error;
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000861
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000862 result = Py_CompileStringObject(str, filename, start[compile_mode], &cf, optimize);
Martin Panter61d6e4a2015-11-07 02:56:11 +0000863 Py_XDECREF(source_copy);
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000864 goto finally;
865
866error:
867 result = NULL;
868finally:
Victor Stinner14e461d2013-08-26 22:28:21 +0200869 Py_DECREF(filename);
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000870 return result;
Guido van Rossum5b722181993-03-30 17:46:03 +0000871}
872
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000873/* AC: cannot convert yet, as needs PEP 457 group support in inspect */
Guido van Rossum79f25d91997-04-29 20:08:16 +0000874static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000875builtin_dir(PyObject *self, PyObject *args)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000876{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000877 PyObject *arg = NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000878
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000879 if (!PyArg_UnpackTuple(args, "dir", 0, 1, &arg))
880 return NULL;
881 return PyObject_Dir(arg);
Guido van Rossum3f5da241990-12-20 15:06:42 +0000882}
883
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000884PyDoc_STRVAR(dir_doc,
Tim Peters5d2b77c2001-09-03 05:47:38 +0000885"dir([object]) -> list of strings\n"
886"\n"
Georg Brandle32b4222007-03-10 22:13:27 +0000887"If called without an argument, return the names in the current scope.\n"
888"Else, return an alphabetized list of names comprising (some of) the attributes\n"
889"of the given object, and of attributes reachable from it.\n"
890"If the object supplies a method named __dir__, it will be used; otherwise\n"
891"the default dir() logic is used and returns:\n"
892" for a module object: the module's attributes.\n"
893" for a class object: its attributes, and recursively the attributes\n"
894" of its bases.\n"
Guido van Rossumd8faa362007-04-27 19:54:29 +0000895" for any other object: its attributes, its class's attributes, and\n"
Georg Brandle32b4222007-03-10 22:13:27 +0000896" recursively the attributes of its class's base classes.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000897
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000898/*[clinic input]
899divmod as builtin_divmod
Guido van Rossum6a00cd81995-01-07 12:39:01 +0000900
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300901 x: object
902 y: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000903 /
904
Zachary Ware7f227d92016-04-28 14:39:50 -0500905Return the tuple (x//y, x%y). Invariant: div*y + mod == x.
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000906[clinic start generated code]*/
907
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000908static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300909builtin_divmod_impl(PyObject *module, PyObject *x, PyObject *y)
910/*[clinic end generated code: output=b06d8a5f6e0c745e input=175ad9c84ff41a85]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000911{
912 return PyNumber_Divmod(x, y);
913}
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000914
915
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000916/*[clinic input]
917eval as builtin_eval
918
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300919 source: object
920 globals: object = None
921 locals: object = None
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000922 /
923
924Evaluate the given source in the context of globals and locals.
925
926The source may be a string representing a Python expression
927or a code object as returned by compile().
928The globals must be a dictionary and locals can be any mapping,
929defaulting to the current globals and locals.
930If only globals is given, locals defaults to it.
931[clinic start generated code]*/
932
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000933static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300934builtin_eval_impl(PyObject *module, PyObject *source, PyObject *globals,
Larry Hastings89964c42015-04-14 18:07:59 -0400935 PyObject *locals)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300936/*[clinic end generated code: output=0a0824aa70093116 input=11ee718a8640e527]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000937{
Martin Panter61d6e4a2015-11-07 02:56:11 +0000938 PyObject *result, *source_copy;
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +0200939 const char *str;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000940 PyCompilerFlags cf;
Guido van Rossum590baa41993-11-30 13:40:46 +0000941
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000942 if (locals != Py_None && !PyMapping_Check(locals)) {
943 PyErr_SetString(PyExc_TypeError, "locals must be a mapping");
944 return NULL;
945 }
946 if (globals != Py_None && !PyDict_Check(globals)) {
947 PyErr_SetString(PyExc_TypeError, PyMapping_Check(globals) ?
948 "globals must be a real dict; try eval(expr, {}, mapping)"
949 : "globals must be a dict");
950 return NULL;
951 }
952 if (globals == Py_None) {
953 globals = PyEval_GetGlobals();
Victor Stinner41bb43a2013-10-29 01:19:37 +0100954 if (locals == Py_None) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000955 locals = PyEval_GetLocals();
Victor Stinner41bb43a2013-10-29 01:19:37 +0100956 if (locals == NULL)
957 return NULL;
958 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000959 }
960 else if (locals == Py_None)
961 locals = globals;
Tim Peters9fa96be2001-08-17 23:04:59 +0000962
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000963 if (globals == NULL || locals == NULL) {
964 PyErr_SetString(PyExc_TypeError,
965 "eval must be given globals and locals "
966 "when called without a frame");
967 return NULL;
968 }
Georg Brandl77c85e62005-09-15 10:46:13 +0000969
Serhiy Storchakaa24107b2019-02-25 17:59:46 +0200970 if (_PyDict_GetItemIdWithError(globals, &PyId___builtins__) == NULL) {
Victor Stinnerb44562b2013-11-06 19:03:11 +0100971 if (_PyDict_SetItemId(globals, &PyId___builtins__,
972 PyEval_GetBuiltins()) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000973 return NULL;
974 }
Serhiy Storchakaa24107b2019-02-25 17:59:46 +0200975 else if (PyErr_Occurred()) {
976 return NULL;
977 }
Tim Peters9fa96be2001-08-17 23:04:59 +0000978
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000979 if (PyCode_Check(source)) {
Steve Dowerb82e17e2019-05-23 08:45:22 -0700980 if (PySys_Audit("exec", "O", source) < 0) {
981 return NULL;
982 }
983
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000984 if (PyCode_GetNumFree((PyCodeObject *)source) > 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000985 PyErr_SetString(PyExc_TypeError,
Steve Dowerb82e17e2019-05-23 08:45:22 -0700986 "code object passed to eval() may not contain free variables");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000987 return NULL;
988 }
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000989 return PyEval_EvalCode(source, globals, locals);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000990 }
Tim Peters9fa96be2001-08-17 23:04:59 +0000991
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000992 cf.cf_flags = PyCF_SOURCE_IS_UTF8;
Guido van Rossum495da292019-03-07 12:38:08 -0800993 cf.cf_feature_version = PY_MINOR_VERSION;
Martin Panter61d6e4a2015-11-07 02:56:11 +0000994 str = source_as_string(source, "eval", "string, bytes or code", &cf, &source_copy);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000995 if (str == NULL)
996 return NULL;
Just van Rossum3aaf42c2003-02-10 08:21:10 +0000997
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000998 while (*str == ' ' || *str == '\t')
999 str++;
Tim Peters9fa96be2001-08-17 23:04:59 +00001000
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001001 (void)PyEval_MergeCompilerFlags(&cf);
1002 result = PyRun_StringFlags(str, Py_eval_input, globals, locals, &cf);
Martin Panter61d6e4a2015-11-07 02:56:11 +00001003 Py_XDECREF(source_copy);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001004 return result;
Guido van Rossum3f5da241990-12-20 15:06:42 +00001005}
1006
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001007/*[clinic input]
1008exec as builtin_exec
1009
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001010 source: object
1011 globals: object = None
1012 locals: object = None
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001013 /
1014
1015Execute the given source in the context of globals and locals.
1016
1017The source may be a string representing one or more Python statements
1018or a code object as returned by compile().
1019The globals must be a dictionary and locals can be any mapping,
1020defaulting to the current globals and locals.
1021If only globals is given, locals defaults to it.
1022[clinic start generated code]*/
1023
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001024static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001025builtin_exec_impl(PyObject *module, PyObject *source, PyObject *globals,
Larry Hastings89964c42015-04-14 18:07:59 -04001026 PyObject *locals)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001027/*[clinic end generated code: output=3c90efc6ab68ef5d input=01ca3e1c01692829]*/
Georg Brandl7cae87c2006-09-06 06:51:57 +00001028{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001029 PyObject *v;
Georg Brandl2cabc562008-08-28 07:57:16 +00001030
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001031 if (globals == Py_None) {
1032 globals = PyEval_GetGlobals();
1033 if (locals == Py_None) {
1034 locals = PyEval_GetLocals();
Victor Stinner41bb43a2013-10-29 01:19:37 +01001035 if (locals == NULL)
1036 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001037 }
1038 if (!globals || !locals) {
1039 PyErr_SetString(PyExc_SystemError,
1040 "globals and locals cannot be NULL");
1041 return NULL;
1042 }
1043 }
1044 else if (locals == Py_None)
1045 locals = globals;
Georg Brandl7cae87c2006-09-06 06:51:57 +00001046
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001047 if (!PyDict_Check(globals)) {
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001048 PyErr_Format(PyExc_TypeError, "exec() globals must be a dict, not %.100s",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001049 globals->ob_type->tp_name);
1050 return NULL;
1051 }
1052 if (!PyMapping_Check(locals)) {
1053 PyErr_Format(PyExc_TypeError,
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001054 "locals must be a mapping or None, not %.100s",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001055 locals->ob_type->tp_name);
1056 return NULL;
1057 }
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02001058 if (_PyDict_GetItemIdWithError(globals, &PyId___builtins__) == NULL) {
Victor Stinnerb44562b2013-11-06 19:03:11 +01001059 if (_PyDict_SetItemId(globals, &PyId___builtins__,
1060 PyEval_GetBuiltins()) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001061 return NULL;
1062 }
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02001063 else if (PyErr_Occurred()) {
1064 return NULL;
1065 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001066
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001067 if (PyCode_Check(source)) {
Steve Dowerb82e17e2019-05-23 08:45:22 -07001068 if (PySys_Audit("exec", "O", source) < 0) {
1069 return NULL;
1070 }
1071
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001072 if (PyCode_GetNumFree((PyCodeObject *)source) > 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001073 PyErr_SetString(PyExc_TypeError,
1074 "code object passed to exec() may not "
1075 "contain free variables");
1076 return NULL;
1077 }
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001078 v = PyEval_EvalCode(source, globals, locals);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001079 }
1080 else {
Martin Panter61d6e4a2015-11-07 02:56:11 +00001081 PyObject *source_copy;
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +02001082 const char *str;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001083 PyCompilerFlags cf;
1084 cf.cf_flags = PyCF_SOURCE_IS_UTF8;
Guido van Rossum495da292019-03-07 12:38:08 -08001085 cf.cf_feature_version = PY_MINOR_VERSION;
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001086 str = source_as_string(source, "exec",
Martin Panter61d6e4a2015-11-07 02:56:11 +00001087 "string, bytes or code", &cf,
1088 &source_copy);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001089 if (str == NULL)
1090 return NULL;
1091 if (PyEval_MergeCompilerFlags(&cf))
1092 v = PyRun_StringFlags(str, Py_file_input, globals,
1093 locals, &cf);
1094 else
1095 v = PyRun_String(str, Py_file_input, globals, locals);
Martin Panter61d6e4a2015-11-07 02:56:11 +00001096 Py_XDECREF(source_copy);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001097 }
1098 if (v == NULL)
1099 return NULL;
1100 Py_DECREF(v);
1101 Py_RETURN_NONE;
Georg Brandl7cae87c2006-09-06 06:51:57 +00001102}
1103
Georg Brandl7cae87c2006-09-06 06:51:57 +00001104
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001105/* AC: cannot convert yet, as needs PEP 457 group support in inspect */
Guido van Rossum79f25d91997-04-29 20:08:16 +00001106static PyObject *
Serhiy Storchakaa5552f02017-12-15 13:11:11 +02001107builtin_getattr(PyObject *self, PyObject *const *args, Py_ssize_t nargs)
Guido van Rossum33894be1992-01-27 16:53:09 +00001108{
Serhiy Storchaka79342662019-01-12 08:25:41 +02001109 PyObject *v, *name, *result;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001110
Serhiy Storchaka79342662019-01-12 08:25:41 +02001111 if (!_PyArg_CheckPositional("getattr", nargs, 2, 3))
Sylvain96c7c062017-06-15 17:05:23 +02001112 return NULL;
1113
Serhiy Storchaka79342662019-01-12 08:25:41 +02001114 v = args[0];
1115 name = args[1];
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001116 if (!PyUnicode_Check(name)) {
1117 PyErr_SetString(PyExc_TypeError,
1118 "getattr(): attribute name must be string");
1119 return NULL;
1120 }
Serhiy Storchaka79342662019-01-12 08:25:41 +02001121 if (nargs > 2) {
Serhiy Storchakaf320be72018-01-25 10:49:40 +02001122 if (_PyObject_LookupAttr(v, name, &result) == 0) {
Serhiy Storchaka79342662019-01-12 08:25:41 +02001123 PyObject *dflt = args[2];
INADA Naoki378edee2018-01-16 20:52:41 +09001124 Py_INCREF(dflt);
1125 return dflt;
1126 }
1127 }
1128 else {
1129 result = PyObject_GetAttr(v, name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001130 }
1131 return result;
Guido van Rossum9bfef441993-03-29 10:43:31 +00001132}
1133
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001134PyDoc_STRVAR(getattr_doc,
Guido van Rossum950ff291998-06-29 13:38:57 +00001135"getattr(object, name[, default]) -> value\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001136\n\
Guido van Rossum950ff291998-06-29 13:38:57 +00001137Get a named attribute from an object; getattr(x, 'y') is equivalent to x.y.\n\
1138When a default argument is given, it is returned when the attribute doesn't\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001139exist; without it, an exception is raised in that case.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001140
1141
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001142/*[clinic input]
1143globals as builtin_globals
1144
1145Return the dictionary containing the current scope's global variables.
1146
1147NOTE: Updates to this dictionary *will* affect name lookups in the current
1148global scope and vice-versa.
1149[clinic start generated code]*/
1150
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001151static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001152builtin_globals_impl(PyObject *module)
1153/*[clinic end generated code: output=e5dd1527067b94d2 input=9327576f92bb48ba]*/
Guido van Rossum872537c1995-07-07 22:43:42 +00001154{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001155 PyObject *d;
Guido van Rossum872537c1995-07-07 22:43:42 +00001156
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001157 d = PyEval_GetGlobals();
1158 Py_XINCREF(d);
1159 return d;
Guido van Rossum872537c1995-07-07 22:43:42 +00001160}
1161
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001162
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001163/*[clinic input]
1164hasattr as builtin_hasattr
1165
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001166 obj: object
1167 name: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001168 /
1169
1170Return whether the object has an attribute with the given name.
1171
1172This is done by calling getattr(obj, name) and catching AttributeError.
1173[clinic start generated code]*/
1174
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001175static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001176builtin_hasattr_impl(PyObject *module, PyObject *obj, PyObject *name)
1177/*[clinic end generated code: output=a7aff2090a4151e5 input=0faec9787d979542]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001178{
1179 PyObject *v;
1180
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001181 if (!PyUnicode_Check(name)) {
1182 PyErr_SetString(PyExc_TypeError,
1183 "hasattr(): attribute name must be string");
1184 return NULL;
1185 }
Serhiy Storchakaf320be72018-01-25 10:49:40 +02001186 if (_PyObject_LookupAttr(obj, name, &v) < 0) {
Benjamin Peterson17689992010-08-24 03:26:23 +00001187 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001188 }
Serhiy Storchakaf320be72018-01-25 10:49:40 +02001189 if (v == NULL) {
1190 Py_RETURN_FALSE;
1191 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001192 Py_DECREF(v);
Benjamin Peterson17689992010-08-24 03:26:23 +00001193 Py_RETURN_TRUE;
Guido van Rossum33894be1992-01-27 16:53:09 +00001194}
1195
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001196
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001197/* AC: gdb's integration with CPython relies on builtin_id having
1198 * the *exact* parameter names of "self" and "v", so we ensure we
1199 * preserve those name rather than using the AC defaults.
1200 */
1201/*[clinic input]
1202id as builtin_id
1203
Serhiy Storchaka24182a32016-05-05 16:21:35 +03001204 self: self(type="PyModuleDef *")
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001205 obj as v: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001206 /
1207
1208Return the identity of an object.
1209
1210This is guaranteed to be unique among simultaneously existing objects.
1211(CPython uses the object's memory address.)
1212[clinic start generated code]*/
1213
Guido van Rossum79f25d91997-04-29 20:08:16 +00001214static PyObject *
Serhiy Storchaka24182a32016-05-05 16:21:35 +03001215builtin_id(PyModuleDef *self, PyObject *v)
1216/*[clinic end generated code: output=0aa640785f697f65 input=5a534136419631f4]*/
Guido van Rossum5b722181993-03-30 17:46:03 +00001217{
Steve Dowerb82e17e2019-05-23 08:45:22 -07001218 PyObject *id = PyLong_FromVoidPtr(v);
1219
1220 if (id && PySys_Audit("builtins.id", "O", id) < 0) {
1221 Py_DECREF(id);
1222 return NULL;
1223 }
1224
1225 return id;
Guido van Rossum5b722181993-03-30 17:46:03 +00001226}
1227
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001228
Raymond Hettingera6c60372008-03-13 01:26:19 +00001229/* map object ************************************************************/
1230
1231typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001232 PyObject_HEAD
1233 PyObject *iters;
1234 PyObject *func;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001235} mapobject;
1236
Guido van Rossum79f25d91997-04-29 20:08:16 +00001237static PyObject *
Raymond Hettingera6c60372008-03-13 01:26:19 +00001238map_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
Guido van Rossum12d12c51993-10-26 17:58:25 +00001239{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001240 PyObject *it, *iters, *func;
1241 mapobject *lz;
1242 Py_ssize_t numargs, i;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001243
Serhiy Storchaka6cca5c82017-06-08 14:41:19 +03001244 if (type == &PyMap_Type && !_PyArg_NoKeywords("map", kwds))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001245 return NULL;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001246
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001247 numargs = PyTuple_Size(args);
1248 if (numargs < 2) {
1249 PyErr_SetString(PyExc_TypeError,
1250 "map() must have at least two arguments.");
1251 return NULL;
1252 }
Raymond Hettingera6c60372008-03-13 01:26:19 +00001253
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001254 iters = PyTuple_New(numargs-1);
1255 if (iters == NULL)
1256 return NULL;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001257
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001258 for (i=1 ; i<numargs ; i++) {
1259 /* Get iterator. */
1260 it = PyObject_GetIter(PyTuple_GET_ITEM(args, i));
1261 if (it == NULL) {
1262 Py_DECREF(iters);
1263 return NULL;
1264 }
1265 PyTuple_SET_ITEM(iters, i-1, it);
1266 }
Raymond Hettingera6c60372008-03-13 01:26:19 +00001267
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001268 /* create mapobject structure */
1269 lz = (mapobject *)type->tp_alloc(type, 0);
1270 if (lz == NULL) {
1271 Py_DECREF(iters);
1272 return NULL;
1273 }
1274 lz->iters = iters;
1275 func = PyTuple_GET_ITEM(args, 0);
1276 Py_INCREF(func);
1277 lz->func = func;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001278
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001279 return (PyObject *)lz;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001280}
1281
1282static void
1283map_dealloc(mapobject *lz)
1284{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001285 PyObject_GC_UnTrack(lz);
1286 Py_XDECREF(lz->iters);
1287 Py_XDECREF(lz->func);
1288 Py_TYPE(lz)->tp_free(lz);
Raymond Hettingera6c60372008-03-13 01:26:19 +00001289}
1290
1291static int
1292map_traverse(mapobject *lz, visitproc visit, void *arg)
1293{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001294 Py_VISIT(lz->iters);
1295 Py_VISIT(lz->func);
1296 return 0;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001297}
1298
1299static PyObject *
1300map_next(mapobject *lz)
1301{
Victor Stinnerbc08ab42016-12-15 12:40:53 +01001302 PyObject *small_stack[_PY_FASTCALL_SMALL_STACK];
Victor Stinnercdb5cee2016-08-24 01:45:13 +02001303 PyObject **stack;
1304 Py_ssize_t niters, nargs, i;
1305 PyObject *result = NULL;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001306
Victor Stinnercdb5cee2016-08-24 01:45:13 +02001307 niters = PyTuple_GET_SIZE(lz->iters);
1308 if (niters <= (Py_ssize_t)Py_ARRAY_LENGTH(small_stack)) {
1309 stack = small_stack;
1310 }
1311 else {
1312 stack = PyMem_Malloc(niters * sizeof(stack[0]));
1313 if (stack == NULL) {
1314 PyErr_NoMemory();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001315 return NULL;
1316 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001317 }
Victor Stinnercdb5cee2016-08-24 01:45:13 +02001318
1319 nargs = 0;
1320 for (i=0; i < niters; i++) {
1321 PyObject *it = PyTuple_GET_ITEM(lz->iters, i);
1322 PyObject *val = Py_TYPE(it)->tp_iternext(it);
1323 if (val == NULL) {
1324 goto exit;
1325 }
1326 stack[i] = val;
1327 nargs++;
1328 }
1329
1330 result = _PyObject_FastCall(lz->func, stack, nargs);
1331
1332exit:
1333 for (i=0; i < nargs; i++) {
1334 Py_DECREF(stack[i]);
1335 }
1336 if (stack != small_stack) {
1337 PyMem_Free(stack);
1338 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001339 return result;
Guido van Rossum12d12c51993-10-26 17:58:25 +00001340}
1341
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001342static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05301343map_reduce(mapobject *lz, PyObject *Py_UNUSED(ignored))
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001344{
1345 Py_ssize_t numargs = PyTuple_GET_SIZE(lz->iters);
1346 PyObject *args = PyTuple_New(numargs+1);
1347 Py_ssize_t i;
1348 if (args == NULL)
1349 return NULL;
1350 Py_INCREF(lz->func);
1351 PyTuple_SET_ITEM(args, 0, lz->func);
1352 for (i = 0; i<numargs; i++){
1353 PyObject *it = PyTuple_GET_ITEM(lz->iters, i);
1354 Py_INCREF(it);
1355 PyTuple_SET_ITEM(args, i+1, it);
1356 }
1357
1358 return Py_BuildValue("ON", Py_TYPE(lz), args);
1359}
1360
1361static PyMethodDef map_methods[] = {
1362 {"__reduce__", (PyCFunction)map_reduce, METH_NOARGS, reduce_doc},
1363 {NULL, NULL} /* sentinel */
1364};
1365
1366
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001367PyDoc_STRVAR(map_doc,
Raymond Hettingera6c60372008-03-13 01:26:19 +00001368"map(func, *iterables) --> map object\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001369\n\
Raymond Hettingera6c60372008-03-13 01:26:19 +00001370Make an iterator that computes the function using arguments from\n\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001371each of the iterables. Stops when the shortest iterable is exhausted.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001372
Raymond Hettingera6c60372008-03-13 01:26:19 +00001373PyTypeObject PyMap_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001374 PyVarObject_HEAD_INIT(&PyType_Type, 0)
1375 "map", /* tp_name */
1376 sizeof(mapobject), /* tp_basicsize */
1377 0, /* tp_itemsize */
1378 /* methods */
1379 (destructor)map_dealloc, /* tp_dealloc */
1380 0, /* tp_print */
1381 0, /* tp_getattr */
1382 0, /* tp_setattr */
1383 0, /* tp_reserved */
1384 0, /* tp_repr */
1385 0, /* tp_as_number */
1386 0, /* tp_as_sequence */
1387 0, /* tp_as_mapping */
1388 0, /* tp_hash */
1389 0, /* tp_call */
1390 0, /* tp_str */
1391 PyObject_GenericGetAttr, /* tp_getattro */
1392 0, /* tp_setattro */
1393 0, /* tp_as_buffer */
1394 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
1395 Py_TPFLAGS_BASETYPE, /* tp_flags */
1396 map_doc, /* tp_doc */
1397 (traverseproc)map_traverse, /* tp_traverse */
1398 0, /* tp_clear */
1399 0, /* tp_richcompare */
1400 0, /* tp_weaklistoffset */
1401 PyObject_SelfIter, /* tp_iter */
1402 (iternextfunc)map_next, /* tp_iternext */
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001403 map_methods, /* tp_methods */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001404 0, /* tp_members */
1405 0, /* tp_getset */
1406 0, /* tp_base */
1407 0, /* tp_dict */
1408 0, /* tp_descr_get */
1409 0, /* tp_descr_set */
1410 0, /* tp_dictoffset */
1411 0, /* tp_init */
1412 PyType_GenericAlloc, /* tp_alloc */
1413 map_new, /* tp_new */
1414 PyObject_GC_Del, /* tp_free */
Raymond Hettingera6c60372008-03-13 01:26:19 +00001415};
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001416
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001417
1418/* AC: cannot convert yet, as needs PEP 457 group support in inspect */
Guido van Rossum79f25d91997-04-29 20:08:16 +00001419static PyObject *
Serhiy Storchakaa5552f02017-12-15 13:11:11 +02001420builtin_next(PyObject *self, PyObject *const *args, Py_ssize_t nargs)
Georg Brandla18af4e2007-04-21 15:47:16 +00001421{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001422 PyObject *it, *res;
Georg Brandla18af4e2007-04-21 15:47:16 +00001423
Serhiy Storchaka79342662019-01-12 08:25:41 +02001424 if (!_PyArg_CheckPositional("next", nargs, 1, 2))
Sylvain96c7c062017-06-15 17:05:23 +02001425 return NULL;
1426
Serhiy Storchaka79342662019-01-12 08:25:41 +02001427 it = args[0];
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001428 if (!PyIter_Check(it)) {
1429 PyErr_Format(PyExc_TypeError,
Philip Jenvey50add042011-11-06 16:37:52 -08001430 "'%.200s' object is not an iterator",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001431 it->ob_type->tp_name);
1432 return NULL;
1433 }
1434
1435 res = (*it->ob_type->tp_iternext)(it);
1436 if (res != NULL) {
1437 return res;
Serhiy Storchaka79342662019-01-12 08:25:41 +02001438 } else if (nargs > 1) {
1439 PyObject *def = args[1];
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001440 if (PyErr_Occurred()) {
1441 if(!PyErr_ExceptionMatches(PyExc_StopIteration))
1442 return NULL;
1443 PyErr_Clear();
1444 }
1445 Py_INCREF(def);
1446 return def;
1447 } else if (PyErr_Occurred()) {
1448 return NULL;
1449 } else {
1450 PyErr_SetNone(PyExc_StopIteration);
1451 return NULL;
1452 }
Georg Brandla18af4e2007-04-21 15:47:16 +00001453}
1454
1455PyDoc_STRVAR(next_doc,
1456"next(iterator[, default])\n\
1457\n\
1458Return the next item from the iterator. If default is given and the iterator\n\
1459is exhausted, it is returned instead of raising StopIteration.");
1460
1461
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001462/*[clinic input]
1463setattr as builtin_setattr
1464
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001465 obj: object
1466 name: object
1467 value: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001468 /
1469
1470Sets the named attribute on the given object to the specified value.
1471
1472setattr(x, 'y', v) is equivalent to ``x.y = v''
1473[clinic start generated code]*/
1474
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001475static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001476builtin_setattr_impl(PyObject *module, PyObject *obj, PyObject *name,
Larry Hastings89964c42015-04-14 18:07:59 -04001477 PyObject *value)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001478/*[clinic end generated code: output=dc2ce1d1add9acb4 input=bd2b7ca6875a1899]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001479{
1480 if (PyObject_SetAttr(obj, name, value) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001481 return NULL;
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02001482 Py_RETURN_NONE;
Guido van Rossum33894be1992-01-27 16:53:09 +00001483}
1484
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001485
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001486/*[clinic input]
1487delattr as builtin_delattr
1488
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001489 obj: object
1490 name: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001491 /
1492
1493Deletes the named attribute from the given object.
1494
1495delattr(x, 'y') is equivalent to ``del x.y''
1496[clinic start generated code]*/
1497
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001498static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001499builtin_delattr_impl(PyObject *module, PyObject *obj, PyObject *name)
1500/*[clinic end generated code: output=85134bc58dff79fa input=db16685d6b4b9410]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001501{
1502 if (PyObject_SetAttr(obj, name, (PyObject *)NULL) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001503 return NULL;
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02001504 Py_RETURN_NONE;
Guido van Rossum14144fc1994-08-29 12:53:40 +00001505}
1506
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001507
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001508/*[clinic input]
1509hash as builtin_hash
1510
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001511 obj: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001512 /
1513
1514Return the hash value for the given object.
1515
1516Two objects that compare equal must also have the same hash value, but the
1517reverse is not necessarily true.
1518[clinic start generated code]*/
1519
Guido van Rossum79f25d91997-04-29 20:08:16 +00001520static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001521builtin_hash(PyObject *module, PyObject *obj)
1522/*[clinic end generated code: output=237668e9d7688db7 input=58c48be822bf9c54]*/
Guido van Rossum9bfef441993-03-29 10:43:31 +00001523{
Benjamin Peterson8f67d082010-10-17 20:54:53 +00001524 Py_hash_t x;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001525
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001526 x = PyObject_Hash(obj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001527 if (x == -1)
1528 return NULL;
Benjamin Peterson8f67d082010-10-17 20:54:53 +00001529 return PyLong_FromSsize_t(x);
Guido van Rossum9bfef441993-03-29 10:43:31 +00001530}
1531
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001532
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001533/*[clinic input]
1534hex as builtin_hex
1535
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001536 number: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001537 /
1538
1539Return the hexadecimal representation of an integer.
1540
1541 >>> hex(12648430)
1542 '0xc0ffee'
1543[clinic start generated code]*/
1544
Guido van Rossum79f25d91997-04-29 20:08:16 +00001545static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001546builtin_hex(PyObject *module, PyObject *number)
1547/*[clinic end generated code: output=e46b612169099408 input=e645aff5fc7d540e]*/
Guido van Rossum006bcd41991-10-24 14:54:44 +00001548{
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001549 return PyNumber_ToBase(number, 16);
Guido van Rossum006bcd41991-10-24 14:54:44 +00001550}
1551
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001552
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001553/* AC: cannot convert yet, as needs PEP 457 group support in inspect */
Guido van Rossum79f25d91997-04-29 20:08:16 +00001554static PyObject *
Serhiy Storchaka79342662019-01-12 08:25:41 +02001555builtin_iter(PyObject *self, PyObject *const *args, Py_ssize_t nargs)
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001556{
Serhiy Storchaka79342662019-01-12 08:25:41 +02001557 PyObject *v;
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001558
Serhiy Storchaka79342662019-01-12 08:25:41 +02001559 if (!_PyArg_CheckPositional("iter", nargs, 1, 2))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001560 return NULL;
Serhiy Storchaka79342662019-01-12 08:25:41 +02001561 v = args[0];
1562 if (nargs == 1)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001563 return PyObject_GetIter(v);
1564 if (!PyCallable_Check(v)) {
1565 PyErr_SetString(PyExc_TypeError,
1566 "iter(v, w): v must be callable");
1567 return NULL;
1568 }
Serhiy Storchaka79342662019-01-12 08:25:41 +02001569 PyObject *sentinel = args[1];
1570 return PyCallIter_New(v, sentinel);
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001571}
1572
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001573PyDoc_STRVAR(iter_doc,
Georg Brandld11ae5d2008-05-16 13:27:32 +00001574"iter(iterable) -> iterator\n\
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001575iter(callable, sentinel) -> iterator\n\
1576\n\
1577Get an iterator from an object. In the first form, the argument must\n\
1578supply its own iterator, or be a sequence.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001579In the second form, the callable is called until it returns the sentinel.");
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001580
1581
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001582/*[clinic input]
1583len as builtin_len
1584
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001585 obj: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001586 /
1587
1588Return the number of items in a container.
1589[clinic start generated code]*/
1590
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001591static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001592builtin_len(PyObject *module, PyObject *obj)
1593/*[clinic end generated code: output=fa7a270d314dfb6c input=bc55598da9e9c9b5]*/
Guido van Rossum3f5da241990-12-20 15:06:42 +00001594{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001595 Py_ssize_t res;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001596
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001597 res = PyObject_Size(obj);
Serhiy Storchaka813f9432017-04-16 09:21:44 +03001598 if (res < 0) {
1599 assert(PyErr_Occurred());
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001600 return NULL;
Serhiy Storchaka813f9432017-04-16 09:21:44 +03001601 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001602 return PyLong_FromSsize_t(res);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001603}
1604
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001605
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001606/*[clinic input]
1607locals as builtin_locals
1608
1609Return a dictionary containing the current scope's local variables.
1610
1611NOTE: Whether or not updates to this dictionary will affect name lookups in
1612the local scope and vice-versa is *implementation dependent* and not
1613covered by any backwards compatibility guarantees.
1614[clinic start generated code]*/
1615
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001616static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001617builtin_locals_impl(PyObject *module)
1618/*[clinic end generated code: output=b46c94015ce11448 input=7874018d478d5c4b]*/
Guido van Rossum872537c1995-07-07 22:43:42 +00001619{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001620 PyObject *d;
Guido van Rossum872537c1995-07-07 22:43:42 +00001621
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001622 d = PyEval_GetLocals();
1623 Py_XINCREF(d);
1624 return d;
Guido van Rossum872537c1995-07-07 22:43:42 +00001625}
1626
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001627
Guido van Rossum79f25d91997-04-29 20:08:16 +00001628static PyObject *
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001629min_max(PyObject *args, PyObject *kwds, int op)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001630{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001631 PyObject *v, *it, *item, *val, *maxitem, *maxval, *keyfunc=NULL;
Raymond Hettinger4d6018f2013-06-24 22:43:02 -07001632 PyObject *emptytuple, *defaultval = NULL;
1633 static char *kwlist[] = {"key", "default", NULL};
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001634 const char *name = op == Py_LT ? "min" : "max";
Raymond Hettinger4d6018f2013-06-24 22:43:02 -07001635 const int positional = PyTuple_Size(args) > 1;
1636 int ret;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001637
Raymond Hettinger4d6018f2013-06-24 22:43:02 -07001638 if (positional)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001639 v = args;
Serhiy Storchakac6792272013-10-19 21:03:34 +03001640 else if (!PyArg_UnpackTuple(args, name, 1, 1, &v))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001641 return NULL;
Tim Peters67d687a2002-04-29 21:27:32 +00001642
Raymond Hettinger4d6018f2013-06-24 22:43:02 -07001643 emptytuple = PyTuple_New(0);
1644 if (emptytuple == NULL)
1645 return NULL;
Oren Milman58cf7482017-08-21 20:19:07 +03001646 ret = PyArg_ParseTupleAndKeywords(emptytuple, kwds,
1647 (op == Py_LT) ? "|$OO:min" : "|$OO:max",
1648 kwlist, &keyfunc, &defaultval);
Raymond Hettinger4d6018f2013-06-24 22:43:02 -07001649 Py_DECREF(emptytuple);
1650 if (!ret)
1651 return NULL;
1652
1653 if (positional && defaultval != NULL) {
1654 PyErr_Format(PyExc_TypeError,
1655 "Cannot specify a default for %s() with multiple "
1656 "positional arguments", name);
1657 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001658 }
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001659
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001660 it = PyObject_GetIter(v);
1661 if (it == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001662 return NULL;
1663 }
Tim Petersc3074532001-05-03 07:00:32 +00001664
Alexander Marshalove22072f2018-07-24 10:58:21 +07001665 if (keyfunc == Py_None) {
1666 keyfunc = NULL;
1667 }
1668
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001669 maxitem = NULL; /* the result */
1670 maxval = NULL; /* the value associated with the result */
1671 while (( item = PyIter_Next(it) )) {
1672 /* get the value from the key function */
1673 if (keyfunc != NULL) {
Victor Stinnerde4ae3d2016-12-04 22:59:09 +01001674 val = PyObject_CallFunctionObjArgs(keyfunc, item, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001675 if (val == NULL)
1676 goto Fail_it_item;
1677 }
1678 /* no key function; the value is the item */
1679 else {
1680 val = item;
1681 Py_INCREF(val);
1682 }
Tim Petersc3074532001-05-03 07:00:32 +00001683
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001684 /* maximum value and item are unset; set them */
1685 if (maxval == NULL) {
1686 maxitem = item;
1687 maxval = val;
1688 }
1689 /* maximum value and item are set; update them as necessary */
1690 else {
1691 int cmp = PyObject_RichCompareBool(val, maxval, op);
1692 if (cmp < 0)
1693 goto Fail_it_item_and_val;
1694 else if (cmp > 0) {
1695 Py_DECREF(maxval);
1696 Py_DECREF(maxitem);
1697 maxval = val;
1698 maxitem = item;
1699 }
1700 else {
1701 Py_DECREF(item);
1702 Py_DECREF(val);
1703 }
1704 }
1705 }
1706 if (PyErr_Occurred())
1707 goto Fail_it;
1708 if (maxval == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001709 assert(maxitem == NULL);
Raymond Hettinger4d6018f2013-06-24 22:43:02 -07001710 if (defaultval != NULL) {
1711 Py_INCREF(defaultval);
1712 maxitem = defaultval;
1713 } else {
1714 PyErr_Format(PyExc_ValueError,
1715 "%s() arg is an empty sequence", name);
1716 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001717 }
1718 else
1719 Py_DECREF(maxval);
1720 Py_DECREF(it);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001721 return maxitem;
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001722
1723Fail_it_item_and_val:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001724 Py_DECREF(val);
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001725Fail_it_item:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001726 Py_DECREF(item);
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001727Fail_it:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001728 Py_XDECREF(maxval);
1729 Py_XDECREF(maxitem);
1730 Py_DECREF(it);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001731 return NULL;
Guido van Rossum3f5da241990-12-20 15:06:42 +00001732}
1733
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001734/* AC: cannot convert yet, waiting for *args support */
Guido van Rossum79f25d91997-04-29 20:08:16 +00001735static PyObject *
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001736builtin_min(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001737{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001738 return min_max(args, kwds, Py_LT);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001739}
1740
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001741PyDoc_STRVAR(min_doc,
Raymond Hettinger2a545822014-05-19 22:20:52 +01001742"min(iterable, *[, default=obj, key=func]) -> value\n\
1743min(arg1, arg2, *args, *[, key=func]) -> value\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001744\n\
Raymond Hettinger2a545822014-05-19 22:20:52 +01001745With a single iterable argument, return its smallest item. The\n\
1746default keyword-only argument specifies an object to return if\n\
1747the provided iterable is empty.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001748With two or more arguments, return the smallest argument.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001749
1750
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001751/* AC: cannot convert yet, waiting for *args support */
Guido van Rossum79f25d91997-04-29 20:08:16 +00001752static PyObject *
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001753builtin_max(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001754{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001755 return min_max(args, kwds, Py_GT);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001756}
1757
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001758PyDoc_STRVAR(max_doc,
Raymond Hettinger2a545822014-05-19 22:20:52 +01001759"max(iterable, *[, default=obj, key=func]) -> value\n\
1760max(arg1, arg2, *args, *[, key=func]) -> value\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001761\n\
Raymond Hettinger2a545822014-05-19 22:20:52 +01001762With a single iterable argument, return its biggest item. The\n\
1763default keyword-only argument specifies an object to return if\n\
1764the provided iterable is empty.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001765With two or more arguments, return the largest argument.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001766
1767
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001768/*[clinic input]
1769oct as builtin_oct
1770
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001771 number: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001772 /
1773
1774Return the octal representation of an integer.
1775
1776 >>> oct(342391)
1777 '0o1234567'
1778[clinic start generated code]*/
1779
Guido van Rossum79f25d91997-04-29 20:08:16 +00001780static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001781builtin_oct(PyObject *module, PyObject *number)
1782/*[clinic end generated code: output=40a34656b6875352 input=ad6b274af4016c72]*/
Guido van Rossum006bcd41991-10-24 14:54:44 +00001783{
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001784 return PyNumber_ToBase(number, 8);
Guido van Rossum006bcd41991-10-24 14:54:44 +00001785}
1786
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001787
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001788/*[clinic input]
1789ord as builtin_ord
1790
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001791 c: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001792 /
1793
1794Return the Unicode code point for a one-character string.
1795[clinic start generated code]*/
1796
Guido van Rossum79f25d91997-04-29 20:08:16 +00001797static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001798builtin_ord(PyObject *module, PyObject *c)
1799/*[clinic end generated code: output=4fa5e87a323bae71 input=3064e5d6203ad012]*/
Guido van Rossum3f5da241990-12-20 15:06:42 +00001800{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001801 long ord;
1802 Py_ssize_t size;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001803
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001804 if (PyBytes_Check(c)) {
1805 size = PyBytes_GET_SIZE(c);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001806 if (size == 1) {
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001807 ord = (long)((unsigned char)*PyBytes_AS_STRING(c));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001808 return PyLong_FromLong(ord);
1809 }
1810 }
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001811 else if (PyUnicode_Check(c)) {
1812 if (PyUnicode_READY(c) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001813 return NULL;
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001814 size = PyUnicode_GET_LENGTH(c);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001815 if (size == 1) {
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001816 ord = (long)PyUnicode_READ_CHAR(c, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001817 return PyLong_FromLong(ord);
1818 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001819 }
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001820 else if (PyByteArray_Check(c)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001821 /* XXX Hopefully this is temporary */
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001822 size = PyByteArray_GET_SIZE(c);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001823 if (size == 1) {
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001824 ord = (long)((unsigned char)*PyByteArray_AS_STRING(c));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001825 return PyLong_FromLong(ord);
1826 }
1827 }
1828 else {
1829 PyErr_Format(PyExc_TypeError,
1830 "ord() expected string of length 1, but " \
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001831 "%.200s found", c->ob_type->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001832 return NULL;
1833 }
Guido van Rossum09095f32000-03-10 23:00:52 +00001834
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001835 PyErr_Format(PyExc_TypeError,
1836 "ord() expected a character, "
1837 "but string of length %zd found",
1838 size);
1839 return NULL;
Guido van Rossum3f5da241990-12-20 15:06:42 +00001840}
1841
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001842
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001843/*[clinic input]
1844pow as builtin_pow
1845
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001846 x: object
1847 y: object
1848 z: object = None
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001849 /
1850
1851Equivalent to x**y (with two arguments) or x**y % z (with three arguments)
1852
1853Some types, such as ints, are able to use a more efficient algorithm when
1854invoked using the three argument form.
1855[clinic start generated code]*/
1856
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001857static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001858builtin_pow_impl(PyObject *module, PyObject *x, PyObject *y, PyObject *z)
1859/*[clinic end generated code: output=50a14d5d130d404b input=653d57d38d41fc07]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001860{
1861 return PyNumber_Power(x, y, z);
1862}
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001863
1864
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001865/* AC: cannot convert yet, waiting for *args support */
Guido van Rossum34343512006-11-30 22:13:52 +00001866static PyObject *
Serhiy Storchakaa5552f02017-12-15 13:11:11 +02001867builtin_print(PyObject *self, PyObject *const *args, Py_ssize_t nargs, PyObject *kwnames)
Guido van Rossum34343512006-11-30 22:13:52 +00001868{
INADA Naokibd584f12017-01-19 12:50:34 +01001869 static const char * const _keywords[] = {"sep", "end", "file", "flush", 0};
1870 static struct _PyArg_Parser _parser = {"|OOOO:print", _keywords, 0};
Georg Brandlbc3b6822012-01-13 19:41:25 +01001871 PyObject *sep = NULL, *end = NULL, *file = NULL, *flush = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001872 int i, err;
Guido van Rossum34343512006-11-30 22:13:52 +00001873
INADA Naokibd584f12017-01-19 12:50:34 +01001874 if (kwnames != NULL &&
1875 !_PyArg_ParseStackAndKeywords(args + nargs, 0, kwnames, &_parser,
1876 &sep, &end, &file, &flush)) {
Georg Brandlbc3b6822012-01-13 19:41:25 +01001877 return NULL;
INADA Naokibd584f12017-01-19 12:50:34 +01001878 }
1879
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001880 if (file == NULL || file == Py_None) {
Victor Stinnerbd303c12013-11-07 23:07:29 +01001881 file = _PySys_GetObjectId(&PyId_stdout);
Victor Stinner1e53bba2013-07-16 22:26:05 +02001882 if (file == NULL) {
1883 PyErr_SetString(PyExc_RuntimeError, "lost sys.stdout");
1884 return NULL;
1885 }
1886
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001887 /* sys.stdout may be None when FILE* stdout isn't connected */
1888 if (file == Py_None)
1889 Py_RETURN_NONE;
1890 }
Guido van Rossum34343512006-11-30 22:13:52 +00001891
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001892 if (sep == Py_None) {
1893 sep = NULL;
1894 }
1895 else if (sep && !PyUnicode_Check(sep)) {
1896 PyErr_Format(PyExc_TypeError,
1897 "sep must be None or a string, not %.200s",
1898 sep->ob_type->tp_name);
1899 return NULL;
1900 }
1901 if (end == Py_None) {
1902 end = NULL;
1903 }
1904 else if (end && !PyUnicode_Check(end)) {
1905 PyErr_Format(PyExc_TypeError,
1906 "end must be None or a string, not %.200s",
1907 end->ob_type->tp_name);
1908 return NULL;
1909 }
Guido van Rossum34343512006-11-30 22:13:52 +00001910
INADA Naokibd584f12017-01-19 12:50:34 +01001911 for (i = 0; i < nargs; i++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001912 if (i > 0) {
1913 if (sep == NULL)
1914 err = PyFile_WriteString(" ", file);
1915 else
1916 err = PyFile_WriteObject(sep, file,
1917 Py_PRINT_RAW);
1918 if (err)
1919 return NULL;
1920 }
INADA Naokibd584f12017-01-19 12:50:34 +01001921 err = PyFile_WriteObject(args[i], file, Py_PRINT_RAW);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001922 if (err)
1923 return NULL;
1924 }
Guido van Rossum34343512006-11-30 22:13:52 +00001925
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001926 if (end == NULL)
1927 err = PyFile_WriteString("\n", file);
1928 else
1929 err = PyFile_WriteObject(end, file, Py_PRINT_RAW);
1930 if (err)
1931 return NULL;
Guido van Rossum34343512006-11-30 22:13:52 +00001932
Georg Brandlbc3b6822012-01-13 19:41:25 +01001933 if (flush != NULL) {
1934 PyObject *tmp;
1935 int do_flush = PyObject_IsTrue(flush);
1936 if (do_flush == -1)
1937 return NULL;
1938 else if (do_flush) {
Victor Stinner3466bde2016-09-05 18:16:01 -07001939 tmp = _PyObject_CallMethodId(file, &PyId_flush, NULL);
Georg Brandlbc3b6822012-01-13 19:41:25 +01001940 if (tmp == NULL)
1941 return NULL;
1942 else
1943 Py_DECREF(tmp);
1944 }
1945 }
1946
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001947 Py_RETURN_NONE;
Guido van Rossum34343512006-11-30 22:13:52 +00001948}
1949
1950PyDoc_STRVAR(print_doc,
Senthil Kumarane9175bd2012-08-10 13:53:45 -07001951"print(value, ..., sep=' ', end='\\n', file=sys.stdout, flush=False)\n\
Guido van Rossum34343512006-11-30 22:13:52 +00001952\n\
1953Prints the values to a stream, or to sys.stdout by default.\n\
1954Optional keyword arguments:\n\
Senthil Kumarane9175bd2012-08-10 13:53:45 -07001955file: a file-like object (stream); defaults to the current sys.stdout.\n\
1956sep: string inserted between values, default a space.\n\
1957end: string appended after the last value, default a newline.\n\
1958flush: whether to forcibly flush the stream.");
Guido van Rossum34343512006-11-30 22:13:52 +00001959
1960
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001961/*[clinic input]
1962input as builtin_input
1963
1964 prompt: object(c_default="NULL") = None
1965 /
1966
1967Read a string from standard input. The trailing newline is stripped.
1968
1969The prompt string, if given, is printed to standard output without a
1970trailing newline before reading input.
1971
1972If the user hits EOF (*nix: Ctrl-D, Windows: Ctrl-Z+Return), raise EOFError.
1973On *nix systems, readline is used if available.
1974[clinic start generated code]*/
1975
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001976static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001977builtin_input_impl(PyObject *module, PyObject *prompt)
1978/*[clinic end generated code: output=83db5a191e7a0d60 input=5e8bb70c2908fe3c]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001979{
Victor Stinnerbd303c12013-11-07 23:07:29 +01001980 PyObject *fin = _PySys_GetObjectId(&PyId_stdin);
1981 PyObject *fout = _PySys_GetObjectId(&PyId_stdout);
1982 PyObject *ferr = _PySys_GetObjectId(&PyId_stderr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001983 PyObject *tmp;
1984 long fd;
1985 int tty;
Guido van Rossuma88a0332007-02-26 16:59:55 +00001986
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001987 /* Check that stdin/out/err are intact */
1988 if (fin == NULL || fin == Py_None) {
1989 PyErr_SetString(PyExc_RuntimeError,
1990 "input(): lost sys.stdin");
1991 return NULL;
1992 }
1993 if (fout == NULL || fout == Py_None) {
1994 PyErr_SetString(PyExc_RuntimeError,
1995 "input(): lost sys.stdout");
1996 return NULL;
1997 }
1998 if (ferr == NULL || ferr == Py_None) {
1999 PyErr_SetString(PyExc_RuntimeError,
2000 "input(): lost sys.stderr");
2001 return NULL;
2002 }
Guido van Rossumeba76962007-05-27 09:13:28 +00002003
Steve Dowerb82e17e2019-05-23 08:45:22 -07002004 if (PySys_Audit("builtins.input", "O", prompt ? prompt : Py_None) < 0) {
2005 return NULL;
2006 }
2007
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002008 /* First of all, flush stderr */
Victor Stinner3466bde2016-09-05 18:16:01 -07002009 tmp = _PyObject_CallMethodId(ferr, &PyId_flush, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002010 if (tmp == NULL)
2011 PyErr_Clear();
2012 else
2013 Py_DECREF(tmp);
Guido van Rossumeba76962007-05-27 09:13:28 +00002014
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002015 /* We should only use (GNU) readline if Python's sys.stdin and
2016 sys.stdout are the same as C's stdin and stdout, because we
2017 need to pass it those. */
Victor Stinner3466bde2016-09-05 18:16:01 -07002018 tmp = _PyObject_CallMethodId(fin, &PyId_fileno, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002019 if (tmp == NULL) {
2020 PyErr_Clear();
2021 tty = 0;
2022 }
2023 else {
2024 fd = PyLong_AsLong(tmp);
2025 Py_DECREF(tmp);
2026 if (fd < 0 && PyErr_Occurred())
2027 return NULL;
2028 tty = fd == fileno(stdin) && isatty(fd);
2029 }
2030 if (tty) {
Victor Stinner3466bde2016-09-05 18:16:01 -07002031 tmp = _PyObject_CallMethodId(fout, &PyId_fileno, NULL);
Martin Panterc9a6ab52015-10-10 01:25:38 +00002032 if (tmp == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002033 PyErr_Clear();
Martin Panterc9a6ab52015-10-10 01:25:38 +00002034 tty = 0;
2035 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002036 else {
2037 fd = PyLong_AsLong(tmp);
2038 Py_DECREF(tmp);
2039 if (fd < 0 && PyErr_Occurred())
2040 return NULL;
2041 tty = fd == fileno(stdout) && isatty(fd);
2042 }
2043 }
Guido van Rossumeba76962007-05-27 09:13:28 +00002044
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002045 /* If we're interactive, use (GNU) readline */
2046 if (tty) {
Antoine Pitrou0d776b12011-11-06 00:34:26 +01002047 PyObject *po = NULL;
Serhiy Storchakae2f92de2017-11-11 13:06:26 +02002048 const char *promptstr;
Antoine Pitrou0d776b12011-11-06 00:34:26 +01002049 char *s = NULL;
2050 PyObject *stdin_encoding = NULL, *stdin_errors = NULL;
2051 PyObject *stdout_encoding = NULL, *stdout_errors = NULL;
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +02002052 const char *stdin_encoding_str, *stdin_errors_str;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002053 PyObject *result;
Victor Stinnerc0f1a1a2011-02-23 12:07:37 +00002054 size_t len;
Martin v. Löwis4a7b5d52007-09-04 05:24:49 +00002055
Serhiy Storchakac2cf1282017-03-12 13:50:36 +02002056 /* stdin is a text stream, so it must have an encoding. */
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02002057 stdin_encoding = _PyObject_GetAttrId(fin, &PyId_encoding);
Antoine Pitrou5ee9d8a2011-11-06 00:38:45 +01002058 stdin_errors = _PyObject_GetAttrId(fin, &PyId_errors);
Serhiy Storchakac2cf1282017-03-12 13:50:36 +02002059 if (!stdin_encoding || !stdin_errors ||
2060 !PyUnicode_Check(stdin_encoding) ||
2061 !PyUnicode_Check(stdin_errors)) {
2062 tty = 0;
Antoine Pitrou0d776b12011-11-06 00:34:26 +01002063 goto _readline_errors;
Serhiy Storchakac2cf1282017-03-12 13:50:36 +02002064 }
Serhiy Storchaka06515832016-11-20 09:13:07 +02002065 stdin_encoding_str = PyUnicode_AsUTF8(stdin_encoding);
2066 stdin_errors_str = PyUnicode_AsUTF8(stdin_errors);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01002067 if (!stdin_encoding_str || !stdin_errors_str)
2068 goto _readline_errors;
Victor Stinner3466bde2016-09-05 18:16:01 -07002069 tmp = _PyObject_CallMethodId(fout, &PyId_flush, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002070 if (tmp == NULL)
2071 PyErr_Clear();
2072 else
2073 Py_DECREF(tmp);
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002074 if (prompt != NULL) {
Antoine Pitrou0d776b12011-11-06 00:34:26 +01002075 /* We have a prompt, encode it as stdout would */
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +02002076 const char *stdout_encoding_str, *stdout_errors_str;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002077 PyObject *stringpo;
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02002078 stdout_encoding = _PyObject_GetAttrId(fout, &PyId_encoding);
Antoine Pitrou5ee9d8a2011-11-06 00:38:45 +01002079 stdout_errors = _PyObject_GetAttrId(fout, &PyId_errors);
Serhiy Storchakac2cf1282017-03-12 13:50:36 +02002080 if (!stdout_encoding || !stdout_errors ||
2081 !PyUnicode_Check(stdout_encoding) ||
2082 !PyUnicode_Check(stdout_errors)) {
2083 tty = 0;
Antoine Pitrou0d776b12011-11-06 00:34:26 +01002084 goto _readline_errors;
Serhiy Storchakac2cf1282017-03-12 13:50:36 +02002085 }
Serhiy Storchaka06515832016-11-20 09:13:07 +02002086 stdout_encoding_str = PyUnicode_AsUTF8(stdout_encoding);
2087 stdout_errors_str = PyUnicode_AsUTF8(stdout_errors);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01002088 if (!stdout_encoding_str || !stdout_errors_str)
2089 goto _readline_errors;
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002090 stringpo = PyObject_Str(prompt);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01002091 if (stringpo == NULL)
2092 goto _readline_errors;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002093 po = PyUnicode_AsEncodedString(stringpo,
Antoine Pitrou0d776b12011-11-06 00:34:26 +01002094 stdout_encoding_str, stdout_errors_str);
2095 Py_CLEAR(stdout_encoding);
2096 Py_CLEAR(stdout_errors);
2097 Py_CLEAR(stringpo);
2098 if (po == NULL)
2099 goto _readline_errors;
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03002100 assert(PyBytes_Check(po));
2101 promptstr = PyBytes_AS_STRING(po);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002102 }
2103 else {
2104 po = NULL;
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002105 promptstr = "";
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002106 }
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002107 s = PyOS_Readline(stdin, stdout, promptstr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002108 if (s == NULL) {
Richard Oudkerk614c5782013-04-03 13:44:50 +01002109 PyErr_CheckSignals();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002110 if (!PyErr_Occurred())
2111 PyErr_SetNone(PyExc_KeyboardInterrupt);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01002112 goto _readline_errors;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002113 }
Victor Stinnerc0f1a1a2011-02-23 12:07:37 +00002114
2115 len = strlen(s);
2116 if (len == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002117 PyErr_SetNone(PyExc_EOFError);
2118 result = NULL;
2119 }
Victor Stinnerc0f1a1a2011-02-23 12:07:37 +00002120 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002121 if (len > PY_SSIZE_T_MAX) {
2122 PyErr_SetString(PyExc_OverflowError,
2123 "input: input too long");
2124 result = NULL;
2125 }
2126 else {
Victor Stinnerc0f1a1a2011-02-23 12:07:37 +00002127 len--; /* strip trailing '\n' */
2128 if (len != 0 && s[len-1] == '\r')
2129 len--; /* strip trailing '\r' */
Antoine Pitrou0d776b12011-11-06 00:34:26 +01002130 result = PyUnicode_Decode(s, len, stdin_encoding_str,
2131 stdin_errors_str);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002132 }
2133 }
2134 Py_DECREF(stdin_encoding);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01002135 Py_DECREF(stdin_errors);
2136 Py_XDECREF(po);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002137 PyMem_FREE(s);
Steve Dowerb82e17e2019-05-23 08:45:22 -07002138
2139 if (result != NULL) {
2140 if (PySys_Audit("builtins.input/result", "O", result) < 0) {
2141 return NULL;
2142 }
2143 }
2144
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002145 return result;
Serhiy Storchakac2cf1282017-03-12 13:50:36 +02002146
Antoine Pitrou0d776b12011-11-06 00:34:26 +01002147 _readline_errors:
2148 Py_XDECREF(stdin_encoding);
2149 Py_XDECREF(stdout_encoding);
2150 Py_XDECREF(stdin_errors);
2151 Py_XDECREF(stdout_errors);
2152 Py_XDECREF(po);
Serhiy Storchakac2cf1282017-03-12 13:50:36 +02002153 if (tty)
2154 return NULL;
2155
2156 PyErr_Clear();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002157 }
Guido van Rossumeba76962007-05-27 09:13:28 +00002158
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002159 /* Fallback if we're not interactive */
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002160 if (prompt != NULL) {
2161 if (PyFile_WriteObject(prompt, fout, Py_PRINT_RAW) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002162 return NULL;
2163 }
Victor Stinner3466bde2016-09-05 18:16:01 -07002164 tmp = _PyObject_CallMethodId(fout, &PyId_flush, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002165 if (tmp == NULL)
2166 PyErr_Clear();
2167 else
2168 Py_DECREF(tmp);
2169 return PyFile_GetLine(fin, -1);
Guido van Rossuma88a0332007-02-26 16:59:55 +00002170}
2171
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002172
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002173/*[clinic input]
2174repr as builtin_repr
2175
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03002176 obj: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002177 /
2178
2179Return the canonical string representation of the object.
2180
2181For many object types, including most builtins, eval(repr(obj)) == obj.
2182[clinic start generated code]*/
2183
Guido van Rossum79f25d91997-04-29 20:08:16 +00002184static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002185builtin_repr(PyObject *module, PyObject *obj)
2186/*[clinic end generated code: output=7ed3778c44fd0194 input=1c9e6d66d3e3be04]*/
Guido van Rossumc89705d1992-11-26 08:54:07 +00002187{
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002188 return PyObject_Repr(obj);
Guido van Rossumc89705d1992-11-26 08:54:07 +00002189}
2190
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002191
Serhiy Storchakaaca7f572017-11-15 17:51:14 +02002192/*[clinic input]
2193round as builtin_round
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002194
Serhiy Storchakaaca7f572017-11-15 17:51:14 +02002195 number: object
2196 ndigits: object = NULL
2197
2198Round a number to a given precision in decimal digits.
2199
2200The return value is an integer if ndigits is omitted or None. Otherwise
2201the return value has the same type as the number. ndigits may be negative.
2202[clinic start generated code]*/
2203
2204static PyObject *
2205builtin_round_impl(PyObject *module, PyObject *number, PyObject *ndigits)
2206/*[clinic end generated code: output=ff0d9dd176c02ede input=854bc3a217530c3d]*/
2207{
2208 PyObject *round, *result;
Alex Martelliae211f92007-08-22 23:21:33 +00002209
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002210 if (Py_TYPE(number)->tp_dict == NULL) {
2211 if (PyType_Ready(Py_TYPE(number)) < 0)
2212 return NULL;
2213 }
Guido van Rossum15d3d042007-08-24 02:02:45 +00002214
Benjamin Peterson214a7d22013-04-13 17:19:01 -04002215 round = _PyObject_LookupSpecial(number, &PyId___round__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002216 if (round == NULL) {
Benjamin Peterson214a7d22013-04-13 17:19:01 -04002217 if (!PyErr_Occurred())
2218 PyErr_Format(PyExc_TypeError,
2219 "type %.100s doesn't define __round__ method",
2220 Py_TYPE(number)->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002221 return NULL;
2222 }
Alex Martelliae211f92007-08-22 23:21:33 +00002223
Raymond Hettingerf0f1c232016-09-03 01:55:11 -07002224 if (ndigits == NULL || ndigits == Py_None)
Victor Stinnerf17c3de2016-12-06 18:46:19 +01002225 result = _PyObject_CallNoArg(round);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002226 else
Victor Stinnerde4ae3d2016-12-04 22:59:09 +01002227 result = PyObject_CallFunctionObjArgs(round, ndigits, NULL);
Benjamin Peterson214a7d22013-04-13 17:19:01 -04002228 Py_DECREF(round);
2229 return result;
Guido van Rossum9e51f9b1993-02-12 16:29:05 +00002230}
2231
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002232
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002233/*AC: we need to keep the kwds dict intact to easily call into the
2234 * list.sort method, which isn't currently supported in AC. So we just use
2235 * the initially generated signature with a custom implementation.
2236 */
2237/* [disabled clinic input]
2238sorted as builtin_sorted
2239
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03002240 iterable as seq: object
2241 key as keyfunc: object = None
2242 reverse: object = False
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002243
2244Return a new list containing all items from the iterable in ascending order.
2245
Raymond Hettinger7ea386e2016-08-25 21:11:50 -07002246A custom key function can be supplied to customize the sort order, and the
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002247reverse flag can be set to request the result in descending order.
2248[end disabled clinic input]*/
2249
2250PyDoc_STRVAR(builtin_sorted__doc__,
Serhiy Storchaka3a104252017-01-23 12:29:47 +02002251"sorted($module, iterable, /, *, key=None, reverse=False)\n"
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002252"--\n"
2253"\n"
2254"Return a new list containing all items from the iterable in ascending order.\n"
2255"\n"
Raymond Hettinger7ea386e2016-08-25 21:11:50 -07002256"A custom key function can be supplied to customize the sort order, and the\n"
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002257"reverse flag can be set to request the result in descending order.");
2258
2259#define BUILTIN_SORTED_METHODDEF \
Serhiy Storchaka62be7422018-11-27 13:27:31 +02002260 {"sorted", (PyCFunction)(void(*)(void))builtin_sorted, METH_FASTCALL | METH_KEYWORDS, builtin_sorted__doc__},
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002261
Raymond Hettinger64958a12003-12-17 20:43:33 +00002262static PyObject *
Serhiy Storchakaa5552f02017-12-15 13:11:11 +02002263builtin_sorted(PyObject *self, PyObject *const *args, Py_ssize_t nargs, PyObject *kwnames)
Raymond Hettinger64958a12003-12-17 20:43:33 +00002264{
Serhiy Storchaka7cf8beb2017-01-21 23:05:00 +02002265 PyObject *newlist, *v, *seq, *callable;
Victor Stinner5a60eca2017-01-17 15:17:49 +01002266
Serhiy Storchaka7cf8beb2017-01-21 23:05:00 +02002267 /* Keyword arguments are passed through list.sort() which will check
2268 them. */
2269 if (!_PyArg_UnpackStack(args, nargs, "sorted", 1, 1, &seq))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002270 return NULL;
Raymond Hettinger64958a12003-12-17 20:43:33 +00002271
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002272 newlist = PySequence_List(seq);
2273 if (newlist == NULL)
2274 return NULL;
Raymond Hettinger64958a12003-12-17 20:43:33 +00002275
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02002276 callable = _PyObject_GetAttrId(newlist, &PyId_sort);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002277 if (callable == NULL) {
2278 Py_DECREF(newlist);
2279 return NULL;
2280 }
Georg Brandl99d7e4e2005-08-31 22:21:15 +00002281
Serhiy Storchaka299dc232017-01-20 08:35:18 +02002282 assert(nargs >= 1);
Victor Stinner5a60eca2017-01-17 15:17:49 +01002283 v = _PyObject_FastCallKeywords(callable, args + 1, nargs - 1, kwnames);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002284 Py_DECREF(callable);
2285 if (v == NULL) {
2286 Py_DECREF(newlist);
2287 return NULL;
2288 }
2289 Py_DECREF(v);
2290 return newlist;
Raymond Hettinger64958a12003-12-17 20:43:33 +00002291}
2292
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002293
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002294/* AC: cannot convert yet, as needs PEP 457 group support in inspect */
Guido van Rossum79f25d91997-04-29 20:08:16 +00002295static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002296builtin_vars(PyObject *self, PyObject *args)
Guido van Rossum2d951851994-08-29 12:52:16 +00002297{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002298 PyObject *v = NULL;
2299 PyObject *d;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002300
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002301 if (!PyArg_UnpackTuple(args, "vars", 0, 1, &v))
2302 return NULL;
2303 if (v == NULL) {
2304 d = PyEval_GetLocals();
Victor Stinner41bb43a2013-10-29 01:19:37 +01002305 if (d == NULL)
2306 return NULL;
2307 Py_INCREF(d);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002308 }
2309 else {
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02002310 d = _PyObject_GetAttrId(v, &PyId___dict__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002311 if (d == NULL) {
2312 PyErr_SetString(PyExc_TypeError,
2313 "vars() argument must have __dict__ attribute");
2314 return NULL;
2315 }
2316 }
2317 return d;
Guido van Rossum2d951851994-08-29 12:52:16 +00002318}
2319
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002320PyDoc_STRVAR(vars_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002321"vars([object]) -> dictionary\n\
2322\n\
2323Without arguments, equivalent to locals().\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002324With an argument, equivalent to object.__dict__.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002325
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002326
2327/*[clinic input]
2328sum as builtin_sum
2329
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03002330 iterable: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002331 /
Raymond Hettinger9dfa0fe2018-09-12 10:54:06 -07002332 start: object(c_default="NULL") = 0
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002333
2334Return the sum of a 'start' value (default: 0) plus an iterable of numbers
2335
2336When the iterable is empty, return the start value.
2337This function is intended specifically for use with numeric values and may
2338reject non-numeric types.
2339[clinic start generated code]*/
2340
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002341static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002342builtin_sum_impl(PyObject *module, PyObject *iterable, PyObject *start)
Raymond Hettinger9dfa0fe2018-09-12 10:54:06 -07002343/*[clinic end generated code: output=df758cec7d1d302f input=162b50765250d222]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002344{
2345 PyObject *result = start;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002346 PyObject *temp, *item, *iter;
Alex Martellia70b1912003-04-22 08:12:33 +00002347
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002348 iter = PyObject_GetIter(iterable);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002349 if (iter == NULL)
2350 return NULL;
Alex Martellia70b1912003-04-22 08:12:33 +00002351
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002352 if (result == NULL) {
2353 result = PyLong_FromLong(0);
2354 if (result == NULL) {
2355 Py_DECREF(iter);
2356 return NULL;
2357 }
2358 } else {
2359 /* reject string values for 'start' parameter */
2360 if (PyUnicode_Check(result)) {
2361 PyErr_SetString(PyExc_TypeError,
2362 "sum() can't sum strings [use ''.join(seq) instead]");
2363 Py_DECREF(iter);
2364 return NULL;
2365 }
Benjamin Petersonce071ca2011-07-29 14:23:47 -05002366 if (PyBytes_Check(result)) {
2367 PyErr_SetString(PyExc_TypeError,
2368 "sum() can't sum bytes [use b''.join(seq) instead]");
Benjamin Peterson405f32c2011-07-29 22:43:45 -05002369 Py_DECREF(iter);
Benjamin Petersonce071ca2011-07-29 14:23:47 -05002370 return NULL;
2371 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002372 if (PyByteArray_Check(result)) {
2373 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson4f921c22011-07-29 14:24:29 -05002374 "sum() can't sum bytearray [use b''.join(seq) instead]");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002375 Py_DECREF(iter);
2376 return NULL;
2377 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002378 Py_INCREF(result);
2379 }
Alex Martellia70b1912003-04-22 08:12:33 +00002380
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002381#ifndef SLOW_SUM
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002382 /* Fast addition by keeping temporary sums in C instead of new Python objects.
2383 Assumes all inputs are the same type. If the assumption fails, default
2384 to the more general routine.
2385 */
2386 if (PyLong_CheckExact(result)) {
2387 int overflow;
2388 long i_result = PyLong_AsLongAndOverflow(result, &overflow);
2389 /* If this already overflowed, don't even enter the loop. */
2390 if (overflow == 0) {
2391 Py_DECREF(result);
2392 result = NULL;
2393 }
2394 while(result == NULL) {
2395 item = PyIter_Next(iter);
2396 if (item == NULL) {
2397 Py_DECREF(iter);
2398 if (PyErr_Occurred())
2399 return NULL;
2400 return PyLong_FromLong(i_result);
2401 }
2402 if (PyLong_CheckExact(item)) {
2403 long b = PyLong_AsLongAndOverflow(item, &overflow);
Serhiy Storchaka29500732019-05-05 14:26:23 +03002404 if (overflow == 0 &&
2405 (i_result >= 0 ? (b <= LONG_MAX - i_result)
2406 : (b >= LONG_MIN - i_result)))
2407 {
2408 i_result += b;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002409 Py_DECREF(item);
2410 continue;
2411 }
2412 }
2413 /* Either overflowed or is not an int. Restore real objects and process normally */
2414 result = PyLong_FromLong(i_result);
Christian Heimes704e2d32013-07-26 22:49:26 +02002415 if (result == NULL) {
2416 Py_DECREF(item);
2417 Py_DECREF(iter);
2418 return NULL;
2419 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002420 temp = PyNumber_Add(result, item);
2421 Py_DECREF(result);
2422 Py_DECREF(item);
2423 result = temp;
2424 if (result == NULL) {
2425 Py_DECREF(iter);
2426 return NULL;
2427 }
2428 }
2429 }
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002430
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002431 if (PyFloat_CheckExact(result)) {
2432 double f_result = PyFloat_AS_DOUBLE(result);
2433 Py_DECREF(result);
2434 result = NULL;
2435 while(result == NULL) {
2436 item = PyIter_Next(iter);
2437 if (item == NULL) {
2438 Py_DECREF(iter);
2439 if (PyErr_Occurred())
2440 return NULL;
2441 return PyFloat_FromDouble(f_result);
2442 }
2443 if (PyFloat_CheckExact(item)) {
2444 PyFPE_START_PROTECT("add", Py_DECREF(item); Py_DECREF(iter); return 0)
2445 f_result += PyFloat_AS_DOUBLE(item);
2446 PyFPE_END_PROTECT(f_result)
2447 Py_DECREF(item);
2448 continue;
2449 }
2450 if (PyLong_CheckExact(item)) {
2451 long value;
2452 int overflow;
2453 value = PyLong_AsLongAndOverflow(item, &overflow);
2454 if (!overflow) {
2455 PyFPE_START_PROTECT("add", Py_DECREF(item); Py_DECREF(iter); return 0)
2456 f_result += (double)value;
2457 PyFPE_END_PROTECT(f_result)
2458 Py_DECREF(item);
2459 continue;
2460 }
2461 }
2462 result = PyFloat_FromDouble(f_result);
Alexey Izbyshev2b824b22018-08-24 07:27:52 +03002463 if (result == NULL) {
2464 Py_DECREF(item);
2465 Py_DECREF(iter);
2466 return NULL;
2467 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002468 temp = PyNumber_Add(result, item);
2469 Py_DECREF(result);
2470 Py_DECREF(item);
2471 result = temp;
2472 if (result == NULL) {
2473 Py_DECREF(iter);
2474 return NULL;
2475 }
2476 }
2477 }
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002478#endif
2479
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002480 for(;;) {
2481 item = PyIter_Next(iter);
2482 if (item == NULL) {
2483 /* error, or end-of-sequence */
2484 if (PyErr_Occurred()) {
2485 Py_DECREF(result);
2486 result = NULL;
2487 }
2488 break;
2489 }
2490 /* It's tempting to use PyNumber_InPlaceAdd instead of
2491 PyNumber_Add here, to avoid quadratic running time
2492 when doing 'sum(list_of_lists, [])'. However, this
2493 would produce a change in behaviour: a snippet like
Mark Dickinson9acadc52009-10-26 14:19:42 +00002494
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002495 empty = []
2496 sum([[x] for x in range(10)], empty)
Mark Dickinson9acadc52009-10-26 14:19:42 +00002497
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002498 would change the value of empty. */
2499 temp = PyNumber_Add(result, item);
2500 Py_DECREF(result);
2501 Py_DECREF(item);
2502 result = temp;
2503 if (result == NULL)
2504 break;
2505 }
2506 Py_DECREF(iter);
2507 return result;
Alex Martellia70b1912003-04-22 08:12:33 +00002508}
2509
Alex Martellia70b1912003-04-22 08:12:33 +00002510
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002511/*[clinic input]
2512isinstance as builtin_isinstance
2513
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03002514 obj: object
2515 class_or_tuple: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002516 /
2517
2518Return whether an object is an instance of a class or of a subclass thereof.
2519
2520A tuple, as in ``isinstance(x, (A, B, ...))``, may be given as the target to
2521check against. This is equivalent to ``isinstance(x, A) or isinstance(x, B)
2522or ...`` etc.
2523[clinic start generated code]*/
2524
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002525static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002526builtin_isinstance_impl(PyObject *module, PyObject *obj,
Larry Hastings89964c42015-04-14 18:07:59 -04002527 PyObject *class_or_tuple)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002528/*[clinic end generated code: output=6faf01472c13b003 input=ffa743db1daf7549]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002529{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002530 int retval;
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002531
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002532 retval = PyObject_IsInstance(obj, class_or_tuple);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002533 if (retval < 0)
2534 return NULL;
2535 return PyBool_FromLong(retval);
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002536}
2537
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002538
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002539/*[clinic input]
2540issubclass as builtin_issubclass
2541
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03002542 cls: object
2543 class_or_tuple: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002544 /
2545
2546Return whether 'cls' is a derived from another class or is the same class.
2547
2548A tuple, as in ``issubclass(x, (A, B, ...))``, may be given as the target to
2549check against. This is equivalent to ``issubclass(x, A) or issubclass(x, B)
2550or ...`` etc.
2551[clinic start generated code]*/
2552
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002553static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002554builtin_issubclass_impl(PyObject *module, PyObject *cls,
Larry Hastings89964c42015-04-14 18:07:59 -04002555 PyObject *class_or_tuple)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002556/*[clinic end generated code: output=358412410cd7a250 input=af5f35e9ceaddaf6]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002557{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002558 int retval;
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002559
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002560 retval = PyObject_IsSubclass(cls, class_or_tuple);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002561 if (retval < 0)
2562 return NULL;
2563 return PyBool_FromLong(retval);
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002564}
2565
2566
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002567typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002568 PyObject_HEAD
2569 Py_ssize_t tuplesize;
2570 PyObject *ittuple; /* tuple of iterators */
2571 PyObject *result;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002572} zipobject;
2573
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002574static PyObject *
2575zip_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
Barry Warsawbd599b52000-08-03 15:45:29 +00002576{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002577 zipobject *lz;
2578 Py_ssize_t i;
2579 PyObject *ittuple; /* tuple of iterators */
2580 PyObject *result;
Serhiy Storchakabf623ae2017-04-19 20:03:52 +03002581 Py_ssize_t tuplesize;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002582
Serhiy Storchaka6cca5c82017-06-08 14:41:19 +03002583 if (type == &PyZip_Type && !_PyArg_NoKeywords("zip", kwds))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002584 return NULL;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002585
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002586 /* args must be a tuple */
2587 assert(PyTuple_Check(args));
Serhiy Storchakabf623ae2017-04-19 20:03:52 +03002588 tuplesize = PyTuple_GET_SIZE(args);
Barry Warsawbd599b52000-08-03 15:45:29 +00002589
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002590 /* obtain iterators */
2591 ittuple = PyTuple_New(tuplesize);
2592 if (ittuple == NULL)
2593 return NULL;
2594 for (i=0; i < tuplesize; ++i) {
2595 PyObject *item = PyTuple_GET_ITEM(args, i);
2596 PyObject *it = PyObject_GetIter(item);
2597 if (it == NULL) {
2598 if (PyErr_ExceptionMatches(PyExc_TypeError))
2599 PyErr_Format(PyExc_TypeError,
2600 "zip argument #%zd must support iteration",
2601 i+1);
2602 Py_DECREF(ittuple);
2603 return NULL;
2604 }
2605 PyTuple_SET_ITEM(ittuple, i, it);
2606 }
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002607
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002608 /* create a result holder */
2609 result = PyTuple_New(tuplesize);
2610 if (result == NULL) {
2611 Py_DECREF(ittuple);
2612 return NULL;
2613 }
2614 for (i=0 ; i < tuplesize ; i++) {
2615 Py_INCREF(Py_None);
2616 PyTuple_SET_ITEM(result, i, Py_None);
2617 }
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002618
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002619 /* create zipobject structure */
2620 lz = (zipobject *)type->tp_alloc(type, 0);
2621 if (lz == NULL) {
2622 Py_DECREF(ittuple);
2623 Py_DECREF(result);
2624 return NULL;
2625 }
2626 lz->ittuple = ittuple;
2627 lz->tuplesize = tuplesize;
2628 lz->result = result;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002629
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002630 return (PyObject *)lz;
Barry Warsawbd599b52000-08-03 15:45:29 +00002631}
2632
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002633static void
2634zip_dealloc(zipobject *lz)
2635{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002636 PyObject_GC_UnTrack(lz);
2637 Py_XDECREF(lz->ittuple);
2638 Py_XDECREF(lz->result);
2639 Py_TYPE(lz)->tp_free(lz);
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002640}
2641
2642static int
2643zip_traverse(zipobject *lz, visitproc visit, void *arg)
2644{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002645 Py_VISIT(lz->ittuple);
2646 Py_VISIT(lz->result);
2647 return 0;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002648}
2649
2650static PyObject *
2651zip_next(zipobject *lz)
2652{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002653 Py_ssize_t i;
2654 Py_ssize_t tuplesize = lz->tuplesize;
2655 PyObject *result = lz->result;
2656 PyObject *it;
2657 PyObject *item;
2658 PyObject *olditem;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002659
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002660 if (tuplesize == 0)
2661 return NULL;
2662 if (Py_REFCNT(result) == 1) {
2663 Py_INCREF(result);
2664 for (i=0 ; i < tuplesize ; i++) {
2665 it = PyTuple_GET_ITEM(lz->ittuple, i);
2666 item = (*Py_TYPE(it)->tp_iternext)(it);
Serhiy Storchaka278d03b2013-04-06 22:52:34 +03002667 if (item == NULL) {
2668 Py_DECREF(result);
2669 return NULL;
2670 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002671 olditem = PyTuple_GET_ITEM(result, i);
2672 PyTuple_SET_ITEM(result, i, item);
2673 Py_DECREF(olditem);
2674 }
2675 } else {
2676 result = PyTuple_New(tuplesize);
2677 if (result == NULL)
Serhiy Storchaka278d03b2013-04-06 22:52:34 +03002678 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002679 for (i=0 ; i < tuplesize ; i++) {
2680 it = PyTuple_GET_ITEM(lz->ittuple, i);
2681 item = (*Py_TYPE(it)->tp_iternext)(it);
Serhiy Storchaka278d03b2013-04-06 22:52:34 +03002682 if (item == NULL) {
2683 Py_DECREF(result);
2684 return NULL;
2685 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002686 PyTuple_SET_ITEM(result, i, item);
2687 }
2688 }
2689 return result;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002690}
Barry Warsawbd599b52000-08-03 15:45:29 +00002691
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002692static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05302693zip_reduce(zipobject *lz, PyObject *Py_UNUSED(ignored))
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002694{
2695 /* Just recreate the zip with the internal iterator tuple */
2696 return Py_BuildValue("OO", Py_TYPE(lz), lz->ittuple);
2697}
2698
2699static PyMethodDef zip_methods[] = {
2700 {"__reduce__", (PyCFunction)zip_reduce, METH_NOARGS, reduce_doc},
2701 {NULL, NULL} /* sentinel */
2702};
2703
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002704PyDoc_STRVAR(zip_doc,
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002705"zip(iter1 [,iter2 [...]]) --> zip object\n\
Barry Warsawbd599b52000-08-03 15:45:29 +00002706\n\
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002707Return a zip object whose .__next__() method returns a tuple where\n\
2708the i-th element comes from the i-th iterable argument. The .__next__()\n\
2709method continues until the shortest iterable in the argument sequence\n\
Georg Brandlced51db2008-12-04 18:28:38 +00002710is exhausted and then it raises StopIteration.");
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002711
2712PyTypeObject PyZip_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002713 PyVarObject_HEAD_INIT(&PyType_Type, 0)
2714 "zip", /* tp_name */
2715 sizeof(zipobject), /* tp_basicsize */
2716 0, /* tp_itemsize */
2717 /* methods */
2718 (destructor)zip_dealloc, /* tp_dealloc */
2719 0, /* tp_print */
2720 0, /* tp_getattr */
2721 0, /* tp_setattr */
2722 0, /* tp_reserved */
2723 0, /* tp_repr */
2724 0, /* tp_as_number */
2725 0, /* tp_as_sequence */
2726 0, /* tp_as_mapping */
2727 0, /* tp_hash */
2728 0, /* tp_call */
2729 0, /* tp_str */
2730 PyObject_GenericGetAttr, /* tp_getattro */
2731 0, /* tp_setattro */
2732 0, /* tp_as_buffer */
2733 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
2734 Py_TPFLAGS_BASETYPE, /* tp_flags */
2735 zip_doc, /* tp_doc */
2736 (traverseproc)zip_traverse, /* tp_traverse */
2737 0, /* tp_clear */
2738 0, /* tp_richcompare */
2739 0, /* tp_weaklistoffset */
2740 PyObject_SelfIter, /* tp_iter */
2741 (iternextfunc)zip_next, /* tp_iternext */
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002742 zip_methods, /* tp_methods */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002743 0, /* tp_members */
2744 0, /* tp_getset */
2745 0, /* tp_base */
2746 0, /* tp_dict */
2747 0, /* tp_descr_get */
2748 0, /* tp_descr_set */
2749 0, /* tp_dictoffset */
2750 0, /* tp_init */
2751 PyType_GenericAlloc, /* tp_alloc */
2752 zip_new, /* tp_new */
2753 PyObject_GC_Del, /* tp_free */
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002754};
Barry Warsawbd599b52000-08-03 15:45:29 +00002755
2756
Guido van Rossum79f25d91997-04-29 20:08:16 +00002757static PyMethodDef builtin_methods[] = {
Serhiy Storchaka62be7422018-11-27 13:27:31 +02002758 {"__build_class__", (PyCFunction)(void(*)(void))builtin___build_class__,
Serhiy Storchaka6969eaf2017-07-03 21:20:15 +03002759 METH_FASTCALL | METH_KEYWORDS, build_class_doc},
Serhiy Storchaka62be7422018-11-27 13:27:31 +02002760 {"__import__", (PyCFunction)(void(*)(void))builtin___import__, METH_VARARGS | METH_KEYWORDS, import_doc},
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002761 BUILTIN_ABS_METHODDEF
2762 BUILTIN_ALL_METHODDEF
2763 BUILTIN_ANY_METHODDEF
2764 BUILTIN_ASCII_METHODDEF
2765 BUILTIN_BIN_METHODDEF
Serhiy Storchaka62be7422018-11-27 13:27:31 +02002766 {"breakpoint", (PyCFunction)(void(*)(void))builtin_breakpoint, METH_FASTCALL | METH_KEYWORDS, breakpoint_doc},
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002767 BUILTIN_CALLABLE_METHODDEF
2768 BUILTIN_CHR_METHODDEF
2769 BUILTIN_COMPILE_METHODDEF
2770 BUILTIN_DELATTR_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002771 {"dir", builtin_dir, METH_VARARGS, dir_doc},
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002772 BUILTIN_DIVMOD_METHODDEF
2773 BUILTIN_EVAL_METHODDEF
2774 BUILTIN_EXEC_METHODDEF
2775 BUILTIN_FORMAT_METHODDEF
Serhiy Storchaka62be7422018-11-27 13:27:31 +02002776 {"getattr", (PyCFunction)(void(*)(void))builtin_getattr, METH_FASTCALL, getattr_doc},
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002777 BUILTIN_GLOBALS_METHODDEF
2778 BUILTIN_HASATTR_METHODDEF
2779 BUILTIN_HASH_METHODDEF
2780 BUILTIN_HEX_METHODDEF
2781 BUILTIN_ID_METHODDEF
2782 BUILTIN_INPUT_METHODDEF
2783 BUILTIN_ISINSTANCE_METHODDEF
2784 BUILTIN_ISSUBCLASS_METHODDEF
Serhiy Storchaka79342662019-01-12 08:25:41 +02002785 {"iter", (PyCFunction)(void(*)(void))builtin_iter, METH_FASTCALL, iter_doc},
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002786 BUILTIN_LEN_METHODDEF
2787 BUILTIN_LOCALS_METHODDEF
Serhiy Storchaka62be7422018-11-27 13:27:31 +02002788 {"max", (PyCFunction)(void(*)(void))builtin_max, METH_VARARGS | METH_KEYWORDS, max_doc},
2789 {"min", (PyCFunction)(void(*)(void))builtin_min, METH_VARARGS | METH_KEYWORDS, min_doc},
2790 {"next", (PyCFunction)(void(*)(void))builtin_next, METH_FASTCALL, next_doc},
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002791 BUILTIN_OCT_METHODDEF
2792 BUILTIN_ORD_METHODDEF
2793 BUILTIN_POW_METHODDEF
Serhiy Storchaka62be7422018-11-27 13:27:31 +02002794 {"print", (PyCFunction)(void(*)(void))builtin_print, METH_FASTCALL | METH_KEYWORDS, print_doc},
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002795 BUILTIN_REPR_METHODDEF
Serhiy Storchakaaca7f572017-11-15 17:51:14 +02002796 BUILTIN_ROUND_METHODDEF
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002797 BUILTIN_SETATTR_METHODDEF
2798 BUILTIN_SORTED_METHODDEF
2799 BUILTIN_SUM_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002800 {"vars", builtin_vars, METH_VARARGS, vars_doc},
2801 {NULL, NULL},
Guido van Rossum3f5da241990-12-20 15:06:42 +00002802};
2803
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002804PyDoc_STRVAR(builtin_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002805"Built-in functions, exceptions, and other objects.\n\
2806\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002807Noteworthy: None is the `nil' object; Ellipsis represents `...' in slices.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002808
Martin v. Löwis1a214512008-06-11 05:26:20 +00002809static struct PyModuleDef builtinsmodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002810 PyModuleDef_HEAD_INIT,
2811 "builtins",
2812 builtin_doc,
2813 -1, /* multiple "initialization" just copies the module dict. */
2814 builtin_methods,
2815 NULL,
2816 NULL,
2817 NULL,
2818 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00002819};
2820
2821
Guido van Rossum25ce5661997-08-02 03:10:38 +00002822PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002823_PyBuiltin_Init(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +00002824{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002825 PyObject *mod, *dict, *debug;
Benjamin Peterson42124a72012-10-30 23:41:54 -04002826
Victor Stinnerfbca9082018-08-30 00:50:45 +02002827 const _PyCoreConfig *config = &_PyInterpreterState_GET_UNSAFE()->core_config;
2828
Benjamin Peterson42124a72012-10-30 23:41:54 -04002829 if (PyType_Ready(&PyFilter_Type) < 0 ||
2830 PyType_Ready(&PyMap_Type) < 0 ||
2831 PyType_Ready(&PyZip_Type) < 0)
2832 return NULL;
2833
Eric Snowd393c1b2017-09-14 12:18:12 -06002834 mod = _PyModule_CreateInitialized(&builtinsmodule, PYTHON_API_VERSION);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002835 if (mod == NULL)
2836 return NULL;
2837 dict = PyModule_GetDict(mod);
Tim Peters4b7625e2001-09-13 21:37:17 +00002838
Tim Peters7571a0f2003-03-23 17:52:28 +00002839#ifdef Py_TRACE_REFS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002840 /* "builtins" exposes a number of statically allocated objects
2841 * that, before this code was added in 2.3, never showed up in
2842 * the list of "all objects" maintained by Py_TRACE_REFS. As a
2843 * result, programs leaking references to None and False (etc)
2844 * couldn't be diagnosed by examining sys.getobjects(0).
2845 */
Tim Peters7571a0f2003-03-23 17:52:28 +00002846#define ADD_TO_ALL(OBJECT) _Py_AddToAllObjects((PyObject *)(OBJECT), 0)
2847#else
2848#define ADD_TO_ALL(OBJECT) (void)0
2849#endif
2850
Tim Peters4b7625e2001-09-13 21:37:17 +00002851#define SETBUILTIN(NAME, OBJECT) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002852 if (PyDict_SetItemString(dict, NAME, (PyObject *)OBJECT) < 0) \
2853 return NULL; \
2854 ADD_TO_ALL(OBJECT)
Tim Peters4b7625e2001-09-13 21:37:17 +00002855
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002856 SETBUILTIN("None", Py_None);
2857 SETBUILTIN("Ellipsis", Py_Ellipsis);
2858 SETBUILTIN("NotImplemented", Py_NotImplemented);
2859 SETBUILTIN("False", Py_False);
2860 SETBUILTIN("True", Py_True);
2861 SETBUILTIN("bool", &PyBool_Type);
2862 SETBUILTIN("memoryview", &PyMemoryView_Type);
2863 SETBUILTIN("bytearray", &PyByteArray_Type);
2864 SETBUILTIN("bytes", &PyBytes_Type);
2865 SETBUILTIN("classmethod", &PyClassMethod_Type);
2866 SETBUILTIN("complex", &PyComplex_Type);
2867 SETBUILTIN("dict", &PyDict_Type);
2868 SETBUILTIN("enumerate", &PyEnum_Type);
2869 SETBUILTIN("filter", &PyFilter_Type);
2870 SETBUILTIN("float", &PyFloat_Type);
2871 SETBUILTIN("frozenset", &PyFrozenSet_Type);
2872 SETBUILTIN("property", &PyProperty_Type);
2873 SETBUILTIN("int", &PyLong_Type);
2874 SETBUILTIN("list", &PyList_Type);
2875 SETBUILTIN("map", &PyMap_Type);
2876 SETBUILTIN("object", &PyBaseObject_Type);
2877 SETBUILTIN("range", &PyRange_Type);
2878 SETBUILTIN("reversed", &PyReversed_Type);
2879 SETBUILTIN("set", &PySet_Type);
2880 SETBUILTIN("slice", &PySlice_Type);
2881 SETBUILTIN("staticmethod", &PyStaticMethod_Type);
2882 SETBUILTIN("str", &PyUnicode_Type);
2883 SETBUILTIN("super", &PySuper_Type);
2884 SETBUILTIN("tuple", &PyTuple_Type);
2885 SETBUILTIN("type", &PyType_Type);
2886 SETBUILTIN("zip", &PyZip_Type);
Victor Stinnerfbca9082018-08-30 00:50:45 +02002887 debug = PyBool_FromLong(config->optimization_level == 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002888 if (PyDict_SetItemString(dict, "__debug__", debug) < 0) {
Serhiy Storchakacfdfbb42016-06-18 09:44:03 +03002889 Py_DECREF(debug);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002890 return NULL;
2891 }
Serhiy Storchakacfdfbb42016-06-18 09:44:03 +03002892 Py_DECREF(debug);
Barry Warsaw757af0e1997-08-29 22:13:51 +00002893
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002894 return mod;
Tim Peters7571a0f2003-03-23 17:52:28 +00002895#undef ADD_TO_ALL
Tim Peters4b7625e2001-09-13 21:37:17 +00002896#undef SETBUILTIN
Guido van Rossum3f5da241990-12-20 15:06:42 +00002897}