blob: 7bb5687d9ae0ac8e498c4c13bbbc203c490389a3 [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"
Martin v. Löwis618dc5e2008-03-30 20:03:44 +00004#include "Python-ast.h"
Guido van Rossum3f5da241990-12-20 15:06:42 +00005
6#include "node.h"
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00007#include "code.h"
Guido van Rossum3f5da241990-12-20 15:06:42 +00008
Benjamin Petersonea281a52011-08-12 23:10:50 -05009#include "asdl.h"
10#include "ast.h"
11
Guido van Rossum6bf62da1997-04-11 20:37:35 +000012#include <ctype.h>
13
Mark Hammond26cffde42001-05-14 12:17:34 +000014/* The default encoding used by the platform file system APIs
15 Can remain NULL for all platforms that don't have such a concept
Guido van Rossum00bc0e02007-10-15 02:52:41 +000016
17 Don't forget to modify PyUnicode_DecodeFSDefault() if you touch any of the
18 values for Py_FileSystemDefaultEncoding!
Mark Hammond26cffde42001-05-14 12:17:34 +000019*/
Steve Dowercc16be82016-09-08 10:35:16 -070020#if defined(__APPLE__)
21const char *Py_FileSystemDefaultEncoding = "utf-8";
Martin v. Löwis04dc25c2008-10-03 16:09:28 +000022int Py_HasFileSystemDefaultEncoding = 1;
Steve Dowercc16be82016-09-08 10:35:16 -070023#elif defined(MS_WINDOWS)
24/* may be changed by initfsencoding(), but should never be free()d */
Just van Rossumb9b8e9c2003-02-10 09:22:01 +000025const char *Py_FileSystemDefaultEncoding = "utf-8";
Martin v. Löwis04dc25c2008-10-03 16:09:28 +000026int Py_HasFileSystemDefaultEncoding = 1;
Victor Stinnerd64e8a72011-07-04 13:48:30 +020027#else
Victor Stinnerb744ba12010-05-15 12:27:16 +000028const char *Py_FileSystemDefaultEncoding = NULL; /* set by initfsencoding() */
Martin v. Löwis04dc25c2008-10-03 16:09:28 +000029int Py_HasFileSystemDefaultEncoding = 0;
Mark Hammond26cffde42001-05-14 12:17:34 +000030#endif
Steve Dowercc16be82016-09-08 10:35:16 -070031const char *Py_FileSystemDefaultEncodeErrors = "surrogateescape";
Victor Stinner94540602017-12-16 04:54:22 +010032/* UTF-8 mode (PEP 540): if equals to 1, use the UTF-8 encoding, and change
33 stdin and stdout error handler to "surrogateescape". It is equal to
34 -1 by default: unknown, will be set by Py_Main() */
35int Py_UTF8Mode = -1;
Mark Hammondef8b6542001-05-13 08:04:26 +000036
Victor Stinnerbd303c12013-11-07 23:07:29 +010037_Py_IDENTIFIER(__builtins__);
38_Py_IDENTIFIER(__dict__);
39_Py_IDENTIFIER(__prepare__);
40_Py_IDENTIFIER(__round__);
Ivan Levkivskyi2b5fd1e2017-12-14 23:32:56 +010041_Py_IDENTIFIER(__mro_entries__);
Victor Stinnerbd303c12013-11-07 23:07:29 +010042_Py_IDENTIFIER(encoding);
43_Py_IDENTIFIER(errors);
Martin v. Löwisbd928fe2011-10-14 10:20:37 +020044_Py_IDENTIFIER(fileno);
45_Py_IDENTIFIER(flush);
Victor Stinnerbd303c12013-11-07 23:07:29 +010046_Py_IDENTIFIER(metaclass);
47_Py_IDENTIFIER(sort);
48_Py_IDENTIFIER(stdin);
49_Py_IDENTIFIER(stdout);
50_Py_IDENTIFIER(stderr);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +020051
Serhiy Storchaka1009bf12015-04-03 23:53:51 +030052#include "clinic/bltinmodule.c.h"
53
Ivan Levkivskyi2b5fd1e2017-12-14 23:32:56 +010054static PyObject*
Victor Stinner05d68a82018-01-18 11:15:25 +010055update_bases(PyObject *bases, PyObject *const *args, Py_ssize_t nargs)
Ivan Levkivskyi2b5fd1e2017-12-14 23:32:56 +010056{
Victor Stinner05d68a82018-01-18 11:15:25 +010057 Py_ssize_t i, j;
Ivan Levkivskyi2b5fd1e2017-12-14 23:32:56 +010058 PyObject *base, *meth, *new_base, *result, *new_bases = NULL;
59 PyObject *stack[1] = {bases};
60 assert(PyTuple_Check(bases));
61
62 for (i = 0; i < nargs; i++) {
63 base = args[i];
64 if (PyType_Check(base)) {
65 if (new_bases) {
66 /* If we already have made a replacement, then we append every normal base,
67 otherwise just skip it. */
68 if (PyList_Append(new_bases, base) < 0) {
69 goto error;
70 }
71 }
72 continue;
73 }
Serhiy Storchakaf320be72018-01-25 10:49:40 +020074 if (_PyObject_LookupAttrId(base, &PyId___mro_entries__, &meth) < 0) {
75 goto error;
76 }
Ivan Levkivskyi2b5fd1e2017-12-14 23:32:56 +010077 if (!meth) {
Ivan Levkivskyi2b5fd1e2017-12-14 23:32:56 +010078 if (new_bases) {
79 if (PyList_Append(new_bases, base) < 0) {
80 goto error;
81 }
82 }
83 continue;
84 }
85 new_base = _PyObject_FastCall(meth, stack, 1);
86 Py_DECREF(meth);
87 if (!new_base) {
88 goto error;
89 }
90 if (!PyTuple_Check(new_base)) {
91 PyErr_SetString(PyExc_TypeError,
92 "__mro_entries__ must return a tuple");
93 Py_DECREF(new_base);
94 goto error;
95 }
96 if (!new_bases) {
97 /* If this is a first successful replacement, create new_bases list and
98 copy previously encountered bases. */
99 if (!(new_bases = PyList_New(i))) {
100 goto error;
101 }
102 for (j = 0; j < i; j++) {
103 base = args[j];
104 PyList_SET_ITEM(new_bases, j, base);
105 Py_INCREF(base);
106 }
107 }
108 j = PyList_GET_SIZE(new_bases);
109 if (PyList_SetSlice(new_bases, j, j, new_base) < 0) {
110 goto error;
111 }
112 Py_DECREF(new_base);
113 }
114 if (!new_bases) {
115 return bases;
116 }
117 result = PyList_AsTuple(new_bases);
118 Py_DECREF(new_bases);
119 return result;
120
121error:
122 Py_XDECREF(new_bases);
123 return NULL;
124}
125
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000126/* AC: cannot convert yet, waiting for *args support */
Guido van Rossum79f25d91997-04-29 20:08:16 +0000127static PyObject *
Serhiy Storchakaa5552f02017-12-15 13:11:11 +0200128builtin___build_class__(PyObject *self, PyObject *const *args, Py_ssize_t nargs,
Victor Stinner773dc6d2017-01-16 23:46:26 +0100129 PyObject *kwnames)
Guido van Rossum52cc1d82007-03-18 15:41:51 +0000130{
Ivan Levkivskyi2b5fd1e2017-12-14 23:32:56 +0100131 PyObject *func, *name, *bases, *mkw, *meta, *winner, *prep, *ns, *orig_bases;
Nick Coghlan19d24672016-12-05 16:47:55 +1000132 PyObject *cls = NULL, *cell = NULL;
Victor Stinner0c39b1b2015-03-18 15:02:06 +0100133 int isclass = 0; /* initialize to prevent gcc warning */
Guido van Rossum52cc1d82007-03-18 15:41:51 +0000134
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000135 if (nargs < 2) {
136 PyErr_SetString(PyExc_TypeError,
137 "__build_class__: not enough arguments");
138 return NULL;
139 }
Victor Stinner773dc6d2017-01-16 23:46:26 +0100140 func = args[0]; /* Better be callable */
Benjamin Petersone8e14592013-05-16 14:37:25 -0500141 if (!PyFunction_Check(func)) {
142 PyErr_SetString(PyExc_TypeError,
Zachary Ware9b338722014-08-05 14:01:10 -0500143 "__build_class__: func must be a function");
Benjamin Petersone8e14592013-05-16 14:37:25 -0500144 return NULL;
145 }
Victor Stinner773dc6d2017-01-16 23:46:26 +0100146 name = args[1];
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000147 if (!PyUnicode_Check(name)) {
148 PyErr_SetString(PyExc_TypeError,
149 "__build_class__: name is not a string");
150 return NULL;
151 }
Ivan Levkivskyi2b5fd1e2017-12-14 23:32:56 +0100152 orig_bases = _PyStack_AsTupleSlice(args, nargs, 2, nargs);
153 if (orig_bases == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000154 return NULL;
Guido van Rossum52cc1d82007-03-18 15:41:51 +0000155
Ivan Levkivskyi2b5fd1e2017-12-14 23:32:56 +0100156 bases = update_bases(orig_bases, args + 2, nargs - 2);
157 if (bases == NULL) {
158 Py_DECREF(orig_bases);
159 return NULL;
160 }
161
Victor Stinner773dc6d2017-01-16 23:46:26 +0100162 if (kwnames == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000163 meta = NULL;
164 mkw = NULL;
165 }
166 else {
Victor Stinner773dc6d2017-01-16 23:46:26 +0100167 mkw = _PyStack_AsDict(args + nargs, kwnames);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000168 if (mkw == NULL) {
169 Py_DECREF(bases);
170 return NULL;
Guido van Rossum52cc1d82007-03-18 15:41:51 +0000171 }
Victor Stinner773dc6d2017-01-16 23:46:26 +0100172
Victor Stinnerae9f1612013-11-06 22:46:51 +0100173 meta = _PyDict_GetItemId(mkw, &PyId_metaclass);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000174 if (meta != NULL) {
175 Py_INCREF(meta);
Victor Stinnerae9f1612013-11-06 22:46:51 +0100176 if (_PyDict_DelItemId(mkw, &PyId_metaclass) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000177 Py_DECREF(meta);
178 Py_DECREF(mkw);
179 Py_DECREF(bases);
180 return NULL;
181 }
Nick Coghlande31b192011-10-23 22:04:16 +1000182 /* metaclass is explicitly given, check if it's indeed a class */
183 isclass = PyType_Check(meta);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000184 }
185 }
186 if (meta == NULL) {
Nick Coghlande31b192011-10-23 22:04:16 +1000187 /* if there are no bases, use type: */
188 if (PyTuple_GET_SIZE(bases) == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000189 meta = (PyObject *) (&PyType_Type);
Nick Coghlande31b192011-10-23 22:04:16 +1000190 }
191 /* else get the type of the first base */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000192 else {
193 PyObject *base0 = PyTuple_GET_ITEM(bases, 0);
194 meta = (PyObject *) (base0->ob_type);
195 }
196 Py_INCREF(meta);
Nick Coghlande31b192011-10-23 22:04:16 +1000197 isclass = 1; /* meta is really a class */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000198 }
Nick Coghlan9715d262011-10-23 22:36:42 +1000199
Nick Coghlande31b192011-10-23 22:04:16 +1000200 if (isclass) {
201 /* meta is really a class, so check for a more derived
202 metaclass, or possible metaclass conflicts: */
203 winner = (PyObject *)_PyType_CalculateMetaclass((PyTypeObject *)meta,
204 bases);
205 if (winner == NULL) {
206 Py_DECREF(meta);
207 Py_XDECREF(mkw);
208 Py_DECREF(bases);
209 return NULL;
210 }
211 if (winner != meta) {
212 Py_DECREF(meta);
213 meta = winner;
214 Py_INCREF(meta);
215 }
216 }
217 /* else: meta is not a class, so we cannot do the metaclass
218 calculation, so we will use the explicitly given object as it is */
Serhiy Storchakaf320be72018-01-25 10:49:40 +0200219 if (_PyObject_LookupAttrId(meta, &PyId___prepare__, &prep) < 0) {
220 ns = NULL;
221 }
222 else if (prep == NULL) {
223 ns = PyDict_New();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000224 }
225 else {
Victor Stinner463b86a2016-08-22 23:33:13 +0200226 PyObject *pargs[2] = {name, bases};
227 ns = _PyObject_FastCallDict(prep, pargs, 2, mkw);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000228 Py_DECREF(prep);
229 }
230 if (ns == NULL) {
231 Py_DECREF(meta);
232 Py_XDECREF(mkw);
233 Py_DECREF(bases);
234 return NULL;
235 }
Oren Milman5837d042017-09-27 17:04:37 +0300236 if (!PyMapping_Check(ns)) {
237 PyErr_Format(PyExc_TypeError,
238 "%.200s.__prepare__() must return a mapping, not %.200s",
239 isclass ? ((PyTypeObject *)meta)->tp_name : "<metaclass>",
240 Py_TYPE(ns)->tp_name);
241 goto error;
242 }
Nick Coghlan19d24672016-12-05 16:47:55 +1000243 cell = PyEval_EvalCodeEx(PyFunction_GET_CODE(func), PyFunction_GET_GLOBALS(func), ns,
Benjamin Petersone8e14592013-05-16 14:37:25 -0500244 NULL, 0, NULL, 0, NULL, 0, NULL,
245 PyFunction_GET_CLOSURE(func));
Nick Coghlan19d24672016-12-05 16:47:55 +1000246 if (cell != NULL) {
Ivan Levkivskyi2b5fd1e2017-12-14 23:32:56 +0100247 if (bases != orig_bases) {
248 if (PyMapping_SetItemString(ns, "__orig_bases__", orig_bases) < 0) {
249 goto error;
250 }
251 }
Victor Stinnerd1c2a8e2016-08-23 01:34:35 +0200252 PyObject *margs[3] = {name, bases, ns};
253 cls = _PyObject_FastCallDict(meta, margs, 3, mkw);
Nick Coghlan19d24672016-12-05 16:47:55 +1000254 if (cls != NULL && PyType_Check(cls) && PyCell_Check(cell)) {
255 PyObject *cell_cls = PyCell_GET(cell);
256 if (cell_cls != cls) {
Nick Coghlan19d24672016-12-05 16:47:55 +1000257 if (cell_cls == NULL) {
258 const char *msg =
259 "__class__ not set defining %.200R as %.200R. "
260 "Was __classcell__ propagated to type.__new__?";
Serhiy Storchakaf5e7b192018-05-20 08:48:12 +0300261 PyErr_Format(PyExc_RuntimeError, msg, name, cls);
Nick Coghlan19d24672016-12-05 16:47:55 +1000262 } else {
263 const char *msg =
264 "__class__ set to %.200R defining %.200R as %.200R";
265 PyErr_Format(PyExc_TypeError, msg, cell_cls, name, cls);
Nick Coghlan19d24672016-12-05 16:47:55 +1000266 }
Serhiy Storchakaf5e7b192018-05-20 08:48:12 +0300267 Py_DECREF(cls);
268 cls = NULL;
269 goto error;
Nick Coghlan19d24672016-12-05 16:47:55 +1000270 }
271 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000272 }
Nick Coghlan19d24672016-12-05 16:47:55 +1000273error:
274 Py_XDECREF(cell);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000275 Py_DECREF(ns);
276 Py_DECREF(meta);
277 Py_XDECREF(mkw);
278 Py_DECREF(bases);
Ivan Levkivskyi2b5fd1e2017-12-14 23:32:56 +0100279 if (bases != orig_bases) {
280 Py_DECREF(orig_bases);
281 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000282 return cls;
Guido van Rossum52cc1d82007-03-18 15:41:51 +0000283}
284
285PyDoc_STRVAR(build_class_doc,
286"__build_class__(func, name, *bases, metaclass=None, **kwds) -> class\n\
287\n\
288Internal helper function used by the class statement.");
289
290static PyObject *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000291builtin___import__(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000292{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000293 static char *kwlist[] = {"name", "globals", "locals", "fromlist",
294 "level", 0};
Victor Stinnerfe93faf2011-03-14 15:54:52 -0400295 PyObject *name, *globals = NULL, *locals = NULL, *fromlist = NULL;
Brett Cannonfd074152012-04-14 14:10:13 -0400296 int level = 0;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000297
Victor Stinnerfe93faf2011-03-14 15:54:52 -0400298 if (!PyArg_ParseTupleAndKeywords(args, kwds, "U|OOOi:__import__",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000299 kwlist, &name, &globals, &locals, &fromlist, &level))
300 return NULL;
Victor Stinnerfe93faf2011-03-14 15:54:52 -0400301 return PyImport_ImportModuleLevelObject(name, globals, locals,
302 fromlist, level);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000303}
304
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000305PyDoc_STRVAR(import_doc,
Brett Cannoncb4996a2012-08-06 16:34:44 -0400306"__import__(name, globals=None, locals=None, fromlist=(), level=0) -> module\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000307\n\
Brett Cannon5305a992010-09-27 21:08:38 +0000308Import a module. Because this function is meant for use by the Python\n\
oldk461d2252018-02-02 12:20:00 +0800309interpreter and not for general use, it is better to use\n\
Brett Cannon5305a992010-09-27 21:08:38 +0000310importlib.import_module() to programmatically import a module.\n\
311\n\
312The globals argument is only used to determine the context;\n\
313they are not modified. The locals argument is unused. The fromlist\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000314should be a list of names to emulate ``from name import ...'', or an\n\
315empty list to emulate ``import name''.\n\
316When importing a module from a package, note that __import__('A.B', ...)\n\
317returns package A when fromlist is empty, but its submodule B when\n\
oldk461d2252018-02-02 12:20:00 +0800318fromlist is not empty. The level argument is used to determine whether to\n\
319perform absolute or relative imports: 0 is absolute, while a positive number\n\
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000320is the number of parent directories to search relative to the current module.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000321
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000322
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000323/*[clinic input]
324abs as builtin_abs
325
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300326 x: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000327 /
328
329Return the absolute value of the argument.
330[clinic start generated code]*/
331
Guido van Rossum79f25d91997-04-29 20:08:16 +0000332static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300333builtin_abs(PyObject *module, PyObject *x)
334/*[clinic end generated code: output=b1b433b9e51356f5 input=bed4ca14e29c20d1]*/
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000335{
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000336 return PyNumber_Absolute(x);
Guido van Rossum3f5da241990-12-20 15:06:42 +0000337}
338
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000339/*[clinic input]
340all as builtin_all
341
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300342 iterable: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000343 /
344
345Return True if bool(x) is True for all values x in the iterable.
346
347If the iterable is empty, return True.
348[clinic start generated code]*/
349
Raymond Hettinger96229b12005-03-11 06:49:40 +0000350static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300351builtin_all(PyObject *module, PyObject *iterable)
352/*[clinic end generated code: output=ca2a7127276f79b3 input=1a7c5d1bc3438a21]*/
Raymond Hettinger96229b12005-03-11 06:49:40 +0000353{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000354 PyObject *it, *item;
355 PyObject *(*iternext)(PyObject *);
356 int cmp;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000357
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000358 it = PyObject_GetIter(iterable);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000359 if (it == NULL)
360 return NULL;
361 iternext = *Py_TYPE(it)->tp_iternext;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000362
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000363 for (;;) {
364 item = iternext(it);
365 if (item == NULL)
366 break;
367 cmp = PyObject_IsTrue(item);
368 Py_DECREF(item);
369 if (cmp < 0) {
370 Py_DECREF(it);
371 return NULL;
372 }
373 if (cmp == 0) {
374 Py_DECREF(it);
375 Py_RETURN_FALSE;
376 }
377 }
378 Py_DECREF(it);
379 if (PyErr_Occurred()) {
380 if (PyErr_ExceptionMatches(PyExc_StopIteration))
381 PyErr_Clear();
382 else
383 return NULL;
384 }
385 Py_RETURN_TRUE;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000386}
387
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000388/*[clinic input]
389any as builtin_any
390
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300391 iterable: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000392 /
393
394Return True if bool(x) is True for any x in the iterable.
395
396If the iterable is empty, return False.
397[clinic start generated code]*/
398
Raymond Hettinger96229b12005-03-11 06:49:40 +0000399static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300400builtin_any(PyObject *module, PyObject *iterable)
401/*[clinic end generated code: output=fa65684748caa60e input=41d7451c23384f24]*/
Raymond Hettinger96229b12005-03-11 06:49:40 +0000402{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000403 PyObject *it, *item;
404 PyObject *(*iternext)(PyObject *);
405 int cmp;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000406
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000407 it = PyObject_GetIter(iterable);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000408 if (it == NULL)
409 return NULL;
410 iternext = *Py_TYPE(it)->tp_iternext;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000411
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000412 for (;;) {
413 item = iternext(it);
414 if (item == NULL)
415 break;
416 cmp = PyObject_IsTrue(item);
417 Py_DECREF(item);
418 if (cmp < 0) {
419 Py_DECREF(it);
420 return NULL;
421 }
Raymond Hettinger5098b582015-10-09 00:42:47 -0400422 if (cmp > 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000423 Py_DECREF(it);
424 Py_RETURN_TRUE;
425 }
426 }
427 Py_DECREF(it);
428 if (PyErr_Occurred()) {
429 if (PyErr_ExceptionMatches(PyExc_StopIteration))
430 PyErr_Clear();
431 else
432 return NULL;
433 }
434 Py_RETURN_FALSE;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000435}
436
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000437/*[clinic input]
438ascii as builtin_ascii
439
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300440 obj: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000441 /
442
443Return an ASCII-only representation of an object.
444
445As repr(), return a string containing a printable representation of an
446object, but escape the non-ASCII characters in the string returned by
447repr() using \\x, \\u or \\U escapes. This generates a string similar
448to that returned by repr() in Python 2.
449[clinic start generated code]*/
450
Georg Brandl559e5d72008-06-11 18:37:52 +0000451static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300452builtin_ascii(PyObject *module, PyObject *obj)
453/*[clinic end generated code: output=6d37b3f0984c7eb9 input=4c62732e1b3a3cc9]*/
Georg Brandl559e5d72008-06-11 18:37:52 +0000454{
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000455 return PyObject_ASCII(obj);
Georg Brandl559e5d72008-06-11 18:37:52 +0000456}
457
Georg Brandl559e5d72008-06-11 18:37:52 +0000458
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000459/*[clinic input]
460bin as builtin_bin
461
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300462 number: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000463 /
464
465Return the binary representation of an integer.
466
467 >>> bin(2796202)
468 '0b1010101010101010101010'
469[clinic start generated code]*/
470
Guido van Rossum79f25d91997-04-29 20:08:16 +0000471static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300472builtin_bin(PyObject *module, PyObject *number)
473/*[clinic end generated code: output=b6fc4ad5e649f4f7 input=53f8a0264bacaf90]*/
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000474{
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000475 return PyNumber_ToBase(number, 2);
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000476}
477
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000478
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000479/*[clinic input]
480callable as builtin_callable
481
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300482 obj: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000483 /
484
485Return whether the object is callable (i.e., some kind of function).
486
487Note that classes are callable, as are instances of classes with a
488__call__() method.
489[clinic start generated code]*/
490
Antoine Pitroue71362d2010-11-27 22:00:11 +0000491static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300492builtin_callable(PyObject *module, PyObject *obj)
493/*[clinic end generated code: output=2b095d59d934cb7e input=1423bab99cc41f58]*/
Antoine Pitroue71362d2010-11-27 22:00:11 +0000494{
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000495 return PyBool_FromLong((long)PyCallable_Check(obj));
Antoine Pitroue71362d2010-11-27 22:00:11 +0000496}
497
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400498static PyObject *
Serhiy Storchakaa5552f02017-12-15 13:11:11 +0200499builtin_breakpoint(PyObject *self, PyObject *const *args, Py_ssize_t nargs, PyObject *keywords)
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400500{
501 PyObject *hook = PySys_GetObject("breakpointhook");
502
503 if (hook == NULL) {
504 PyErr_SetString(PyExc_RuntimeError, "lost sys.breakpointhook");
505 return NULL;
506 }
507 Py_INCREF(hook);
508 PyObject *retval = _PyObject_FastCallKeywords(hook, args, nargs, keywords);
509 Py_DECREF(hook);
510 return retval;
511}
512
513PyDoc_STRVAR(breakpoint_doc,
514"breakpoint(*args, **kws)\n\
515\n\
516Call sys.breakpointhook(*args, **kws). sys.breakpointhook() must accept\n\
517whatever arguments are passed.\n\
518\n\
519By default, this drops you into the pdb debugger.");
Antoine Pitroue71362d2010-11-27 22:00:11 +0000520
Raymond Hettinger17301e92008-03-13 00:19:26 +0000521typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000522 PyObject_HEAD
523 PyObject *func;
524 PyObject *it;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000525} filterobject;
526
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000527static PyObject *
Raymond Hettinger17301e92008-03-13 00:19:26 +0000528filter_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
Guido van Rossum12d12c51993-10-26 17:58:25 +0000529{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000530 PyObject *func, *seq;
531 PyObject *it;
532 filterobject *lz;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000533
Serhiy Storchaka6cca5c82017-06-08 14:41:19 +0300534 if (type == &PyFilter_Type && !_PyArg_NoKeywords("filter", kwds))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000535 return NULL;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000536
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000537 if (!PyArg_UnpackTuple(args, "filter", 2, 2, &func, &seq))
538 return NULL;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000539
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000540 /* Get iterator. */
541 it = PyObject_GetIter(seq);
542 if (it == NULL)
543 return NULL;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000544
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000545 /* create filterobject structure */
546 lz = (filterobject *)type->tp_alloc(type, 0);
547 if (lz == NULL) {
548 Py_DECREF(it);
549 return NULL;
550 }
551 Py_INCREF(func);
552 lz->func = func;
553 lz->it = it;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000554
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000555 return (PyObject *)lz;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000556}
557
558static void
559filter_dealloc(filterobject *lz)
560{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000561 PyObject_GC_UnTrack(lz);
562 Py_XDECREF(lz->func);
563 Py_XDECREF(lz->it);
564 Py_TYPE(lz)->tp_free(lz);
Raymond Hettinger17301e92008-03-13 00:19:26 +0000565}
566
567static int
568filter_traverse(filterobject *lz, visitproc visit, void *arg)
569{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000570 Py_VISIT(lz->it);
571 Py_VISIT(lz->func);
572 return 0;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000573}
574
575static PyObject *
576filter_next(filterobject *lz)
577{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000578 PyObject *item;
579 PyObject *it = lz->it;
580 long ok;
581 PyObject *(*iternext)(PyObject *);
Raymond Hettingerbd5f0e82015-10-09 01:34:08 -0400582 int checktrue = lz->func == Py_None || lz->func == (PyObject *)&PyBool_Type;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000583
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000584 iternext = *Py_TYPE(it)->tp_iternext;
585 for (;;) {
586 item = iternext(it);
587 if (item == NULL)
588 return NULL;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000589
Raymond Hettingerbd5f0e82015-10-09 01:34:08 -0400590 if (checktrue) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000591 ok = PyObject_IsTrue(item);
592 } else {
593 PyObject *good;
Victor Stinnerde4ae3d2016-12-04 22:59:09 +0100594 good = PyObject_CallFunctionObjArgs(lz->func, item, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000595 if (good == NULL) {
596 Py_DECREF(item);
597 return NULL;
598 }
599 ok = PyObject_IsTrue(good);
600 Py_DECREF(good);
601 }
Antoine Pitrou6f430e42012-08-15 23:18:25 +0200602 if (ok > 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000603 return item;
604 Py_DECREF(item);
Antoine Pitrou6f430e42012-08-15 23:18:25 +0200605 if (ok < 0)
606 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000607 }
Guido van Rossum12d12c51993-10-26 17:58:25 +0000608}
609
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +0000610static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +0530611filter_reduce(filterobject *lz, PyObject *Py_UNUSED(ignored))
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +0000612{
613 return Py_BuildValue("O(OO)", Py_TYPE(lz), lz->func, lz->it);
614}
615
616PyDoc_STRVAR(reduce_doc, "Return state information for pickling.");
617
618static PyMethodDef filter_methods[] = {
619 {"__reduce__", (PyCFunction)filter_reduce, METH_NOARGS, reduce_doc},
620 {NULL, NULL} /* sentinel */
621};
622
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000623PyDoc_STRVAR(filter_doc,
Georg Brandld11ae5d2008-05-16 13:27:32 +0000624"filter(function or None, iterable) --> filter object\n\
Guido van Rossumc1f779c2007-07-03 08:25:58 +0000625\n\
Georg Brandld11ae5d2008-05-16 13:27:32 +0000626Return an iterator yielding those items of iterable for which function(item)\n\
Raymond Hettinger17301e92008-03-13 00:19:26 +0000627is true. If function is None, return the items that are true.");
628
629PyTypeObject PyFilter_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000630 PyVarObject_HEAD_INIT(&PyType_Type, 0)
631 "filter", /* tp_name */
632 sizeof(filterobject), /* tp_basicsize */
633 0, /* tp_itemsize */
634 /* methods */
635 (destructor)filter_dealloc, /* tp_dealloc */
636 0, /* tp_print */
637 0, /* tp_getattr */
638 0, /* tp_setattr */
639 0, /* tp_reserved */
640 0, /* tp_repr */
641 0, /* tp_as_number */
642 0, /* tp_as_sequence */
643 0, /* tp_as_mapping */
644 0, /* tp_hash */
645 0, /* tp_call */
646 0, /* tp_str */
647 PyObject_GenericGetAttr, /* tp_getattro */
648 0, /* tp_setattro */
649 0, /* tp_as_buffer */
650 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
651 Py_TPFLAGS_BASETYPE, /* tp_flags */
652 filter_doc, /* tp_doc */
653 (traverseproc)filter_traverse, /* tp_traverse */
654 0, /* tp_clear */
655 0, /* tp_richcompare */
656 0, /* tp_weaklistoffset */
657 PyObject_SelfIter, /* tp_iter */
658 (iternextfunc)filter_next, /* tp_iternext */
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +0000659 filter_methods, /* tp_methods */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000660 0, /* tp_members */
661 0, /* tp_getset */
662 0, /* tp_base */
663 0, /* tp_dict */
664 0, /* tp_descr_get */
665 0, /* tp_descr_set */
666 0, /* tp_dictoffset */
667 0, /* tp_init */
668 PyType_GenericAlloc, /* tp_alloc */
669 filter_new, /* tp_new */
670 PyObject_GC_Del, /* tp_free */
Raymond Hettinger17301e92008-03-13 00:19:26 +0000671};
672
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000673
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000674/*[clinic input]
675format as builtin_format
676
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300677 value: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000678 format_spec: unicode(c_default="NULL") = ''
679 /
680
681Return value.__format__(format_spec)
682
Amit Kumar2e6bb442017-05-29 06:32:26 +0530683format_spec defaults to the empty string.
684See the Format Specification Mini-Language section of help('FORMATTING') for
685details.
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000686[clinic start generated code]*/
687
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000688static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300689builtin_format_impl(PyObject *module, PyObject *value, PyObject *format_spec)
Amit Kumar2e6bb442017-05-29 06:32:26 +0530690/*[clinic end generated code: output=2f40bdfa4954b077 input=88339c93ea522b33]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000691{
Eric Smith8fd3eba2008-02-17 19:48:00 +0000692 return PyObject_Format(value, format_spec);
Eric Smith8c663262007-08-25 02:26:07 +0000693}
694
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000695/*[clinic input]
696chr as builtin_chr
697
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300698 i: int
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000699 /
700
701Return a Unicode string of one character with ordinal i; 0 <= i <= 0x10ffff.
702[clinic start generated code]*/
703
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000704static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300705builtin_chr_impl(PyObject *module, int i)
706/*[clinic end generated code: output=c733afcd200afcb7 input=3f604ef45a70750d]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000707{
708 return PyUnicode_FromOrdinal(i);
709}
Guido van Rossum09095f32000-03-10 23:00:52 +0000710
711
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +0200712static const char *
Martin Pantereeb896c2015-11-07 02:32:21 +0000713source_as_string(PyObject *cmd, const char *funcname, const char *what, PyCompilerFlags *cf, PyObject **cmd_copy)
Guido van Rossumf15a29f2007-05-04 00:41:39 +0000714{
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +0200715 const char *str;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000716 Py_ssize_t size;
Martin Pantereeb896c2015-11-07 02:32:21 +0000717 Py_buffer view;
Guido van Rossumf15a29f2007-05-04 00:41:39 +0000718
Martin Pantereeb896c2015-11-07 02:32:21 +0000719 *cmd_copy = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000720 if (PyUnicode_Check(cmd)) {
721 cf->cf_flags |= PyCF_IGNORE_COOKIE;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200722 str = PyUnicode_AsUTF8AndSize(cmd, &size);
723 if (str == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000724 return NULL;
725 }
Martin Pantereeb896c2015-11-07 02:32:21 +0000726 else if (PyBytes_Check(cmd)) {
727 str = PyBytes_AS_STRING(cmd);
728 size = PyBytes_GET_SIZE(cmd);
729 }
730 else if (PyByteArray_Check(cmd)) {
731 str = PyByteArray_AS_STRING(cmd);
732 size = PyByteArray_GET_SIZE(cmd);
733 }
734 else if (PyObject_GetBuffer(cmd, &view, PyBUF_SIMPLE) == 0) {
735 /* Copy to NUL-terminated buffer. */
736 *cmd_copy = PyBytes_FromStringAndSize(
737 (const char *)view.buf, view.len);
738 PyBuffer_Release(&view);
739 if (*cmd_copy == NULL) {
740 return NULL;
741 }
742 str = PyBytes_AS_STRING(*cmd_copy);
743 size = PyBytes_GET_SIZE(*cmd_copy);
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +0200744 }
745 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000746 PyErr_Format(PyExc_TypeError,
747 "%s() arg 1 must be a %s object",
748 funcname, what);
749 return NULL;
750 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200751
Serhiy Storchaka3dd3e262015-02-03 01:25:42 +0200752 if (strlen(str) != (size_t)size) {
Serhiy Storchakad8a14472014-09-06 20:07:17 +0300753 PyErr_SetString(PyExc_ValueError,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000754 "source code string cannot contain null bytes");
Martin Pantereeb896c2015-11-07 02:32:21 +0000755 Py_CLEAR(*cmd_copy);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000756 return NULL;
757 }
758 return str;
Guido van Rossumf15a29f2007-05-04 00:41:39 +0000759}
760
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000761/*[clinic input]
762compile as builtin_compile
763
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300764 source: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000765 filename: object(converter="PyUnicode_FSDecoder")
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300766 mode: str
767 flags: int = 0
Serhiy Storchaka202fda52017-03-12 10:10:47 +0200768 dont_inherit: bool(accept={int}) = False
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300769 optimize: int = -1
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000770
771Compile source into a code object that can be executed by exec() or eval().
772
773The source code may represent a Python module, statement or expression.
774The filename will be used for run-time error messages.
775The mode must be 'exec' to compile a module, 'single' to compile a
776single (interactive) statement, or 'eval' to compile an expression.
777The flags argument, if present, controls which future statements influence
778the compilation of the code.
Serhiy Storchaka8b2e8b62015-05-30 11:30:39 +0300779The dont_inherit argument, if true, stops the compilation inheriting
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000780the effects of any future statements in effect in the code calling
Serhiy Storchaka8b2e8b62015-05-30 11:30:39 +0300781compile; if absent or false these statements do influence the compilation,
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000782in addition to any features explicitly specified.
783[clinic start generated code]*/
784
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000785static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300786builtin_compile_impl(PyObject *module, PyObject *source, PyObject *filename,
787 const char *mode, int flags, int dont_inherit,
788 int optimize)
Serhiy Storchaka202fda52017-03-12 10:10:47 +0200789/*[clinic end generated code: output=1fa176e33452bb63 input=0ff726f595eb9fcd]*/
Guido van Rossum5b722181993-03-30 17:46:03 +0000790{
Martin Panter61d6e4a2015-11-07 02:56:11 +0000791 PyObject *source_copy;
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +0200792 const char *str;
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000793 int compile_mode = -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000794 int is_ast;
795 PyCompilerFlags cf;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000796 int start[] = {Py_file_input, Py_eval_input, Py_single_input};
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000797 PyObject *result;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000798
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000799 cf.cf_flags = flags | PyCF_SOURCE_IS_UTF8;
Tim Peters6cd6a822001-08-17 22:11:27 +0000800
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000801 if (flags &
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000802 ~(PyCF_MASK | PyCF_MASK_OBSOLETE | PyCF_DONT_IMPLY_DEDENT | PyCF_ONLY_AST))
803 {
804 PyErr_SetString(PyExc_ValueError,
805 "compile(): unrecognised flags");
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000806 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000807 }
808 /* XXX Warn if (supplied_flags & PyCF_MASK_OBSOLETE) != 0? */
Tim Peters6cd6a822001-08-17 22:11:27 +0000809
Georg Brandl8334fd92010-12-04 10:26:46 +0000810 if (optimize < -1 || optimize > 2) {
811 PyErr_SetString(PyExc_ValueError,
812 "compile(): invalid optimize value");
813 goto error;
814 }
815
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000816 if (!dont_inherit) {
817 PyEval_MergeCompilerFlags(&cf);
818 }
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000819
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000820 if (strcmp(mode, "exec") == 0)
821 compile_mode = 0;
822 else if (strcmp(mode, "eval") == 0)
823 compile_mode = 1;
824 else if (strcmp(mode, "single") == 0)
825 compile_mode = 2;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000826 else {
827 PyErr_SetString(PyExc_ValueError,
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000828 "compile() mode must be 'exec', 'eval' or 'single'");
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000829 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000830 }
Neal Norwitzdb4115f2008-03-31 04:20:05 +0000831
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000832 is_ast = PyAST_Check(source);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000833 if (is_ast == -1)
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000834 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000835 if (is_ast) {
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000836 if (flags & PyCF_ONLY_AST) {
837 Py_INCREF(source);
838 result = source;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000839 }
840 else {
841 PyArena *arena;
842 mod_ty mod;
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000843
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000844 arena = PyArena_New();
Stefan Krah07795df2012-08-20 17:19:50 +0200845 if (arena == NULL)
846 goto error;
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000847 mod = PyAST_obj2mod(source, arena, compile_mode);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000848 if (mod == NULL) {
849 PyArena_Free(arena);
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000850 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000851 }
Benjamin Peterson832bfe22011-08-09 16:15:04 -0500852 if (!PyAST_Validate(mod)) {
853 PyArena_Free(arena);
854 goto error;
855 }
Victor Stinner14e461d2013-08-26 22:28:21 +0200856 result = (PyObject*)PyAST_CompileObject(mod, filename,
857 &cf, optimize, arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000858 PyArena_Free(arena);
859 }
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000860 goto finally;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000861 }
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000862
Martin Panter61d6e4a2015-11-07 02:56:11 +0000863 str = source_as_string(source, "compile", "string, bytes or AST", &cf, &source_copy);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000864 if (str == NULL)
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000865 goto error;
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000866
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000867 result = Py_CompileStringObject(str, filename, start[compile_mode], &cf, optimize);
Martin Panter61d6e4a2015-11-07 02:56:11 +0000868 Py_XDECREF(source_copy);
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000869 goto finally;
870
871error:
872 result = NULL;
873finally:
Victor Stinner14e461d2013-08-26 22:28:21 +0200874 Py_DECREF(filename);
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000875 return result;
Guido van Rossum5b722181993-03-30 17:46:03 +0000876}
877
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000878/* AC: cannot convert yet, as needs PEP 457 group support in inspect */
Guido van Rossum79f25d91997-04-29 20:08:16 +0000879static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000880builtin_dir(PyObject *self, PyObject *args)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000881{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000882 PyObject *arg = NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000883
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000884 if (!PyArg_UnpackTuple(args, "dir", 0, 1, &arg))
885 return NULL;
886 return PyObject_Dir(arg);
Guido van Rossum3f5da241990-12-20 15:06:42 +0000887}
888
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000889PyDoc_STRVAR(dir_doc,
Tim Peters5d2b77c2001-09-03 05:47:38 +0000890"dir([object]) -> list of strings\n"
891"\n"
Georg Brandle32b4222007-03-10 22:13:27 +0000892"If called without an argument, return the names in the current scope.\n"
893"Else, return an alphabetized list of names comprising (some of) the attributes\n"
894"of the given object, and of attributes reachable from it.\n"
895"If the object supplies a method named __dir__, it will be used; otherwise\n"
896"the default dir() logic is used and returns:\n"
897" for a module object: the module's attributes.\n"
898" for a class object: its attributes, and recursively the attributes\n"
899" of its bases.\n"
Guido van Rossumd8faa362007-04-27 19:54:29 +0000900" for any other object: its attributes, its class's attributes, and\n"
Georg Brandle32b4222007-03-10 22:13:27 +0000901" recursively the attributes of its class's base classes.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000902
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000903/*[clinic input]
904divmod as builtin_divmod
Guido van Rossum6a00cd81995-01-07 12:39:01 +0000905
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300906 x: object
907 y: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000908 /
909
Zachary Ware7f227d92016-04-28 14:39:50 -0500910Return the tuple (x//y, x%y). Invariant: div*y + mod == x.
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000911[clinic start generated code]*/
912
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000913static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300914builtin_divmod_impl(PyObject *module, PyObject *x, PyObject *y)
915/*[clinic end generated code: output=b06d8a5f6e0c745e input=175ad9c84ff41a85]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000916{
917 return PyNumber_Divmod(x, y);
918}
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000919
920
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000921/*[clinic input]
922eval as builtin_eval
923
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300924 source: object
925 globals: object = None
926 locals: object = None
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000927 /
928
929Evaluate the given source in the context of globals and locals.
930
931The source may be a string representing a Python expression
932or a code object as returned by compile().
933The globals must be a dictionary and locals can be any mapping,
934defaulting to the current globals and locals.
935If only globals is given, locals defaults to it.
936[clinic start generated code]*/
937
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000938static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300939builtin_eval_impl(PyObject *module, PyObject *source, PyObject *globals,
Larry Hastings89964c42015-04-14 18:07:59 -0400940 PyObject *locals)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300941/*[clinic end generated code: output=0a0824aa70093116 input=11ee718a8640e527]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000942{
Martin Panter61d6e4a2015-11-07 02:56:11 +0000943 PyObject *result, *source_copy;
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +0200944 const char *str;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000945 PyCompilerFlags cf;
Guido van Rossum590baa41993-11-30 13:40:46 +0000946
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000947 if (locals != Py_None && !PyMapping_Check(locals)) {
948 PyErr_SetString(PyExc_TypeError, "locals must be a mapping");
949 return NULL;
950 }
951 if (globals != Py_None && !PyDict_Check(globals)) {
952 PyErr_SetString(PyExc_TypeError, PyMapping_Check(globals) ?
953 "globals must be a real dict; try eval(expr, {}, mapping)"
954 : "globals must be a dict");
955 return NULL;
956 }
957 if (globals == Py_None) {
958 globals = PyEval_GetGlobals();
Victor Stinner41bb43a2013-10-29 01:19:37 +0100959 if (locals == Py_None) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000960 locals = PyEval_GetLocals();
Victor Stinner41bb43a2013-10-29 01:19:37 +0100961 if (locals == NULL)
962 return NULL;
963 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000964 }
965 else if (locals == Py_None)
966 locals = globals;
Tim Peters9fa96be2001-08-17 23:04:59 +0000967
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000968 if (globals == NULL || locals == NULL) {
969 PyErr_SetString(PyExc_TypeError,
970 "eval must be given globals and locals "
971 "when called without a frame");
972 return NULL;
973 }
Georg Brandl77c85e62005-09-15 10:46:13 +0000974
Victor Stinnerb44562b2013-11-06 19:03:11 +0100975 if (_PyDict_GetItemId(globals, &PyId___builtins__) == NULL) {
976 if (_PyDict_SetItemId(globals, &PyId___builtins__,
977 PyEval_GetBuiltins()) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000978 return NULL;
979 }
Tim Peters9fa96be2001-08-17 23:04:59 +0000980
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000981 if (PyCode_Check(source)) {
982 if (PyCode_GetNumFree((PyCodeObject *)source) > 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000983 PyErr_SetString(PyExc_TypeError,
984 "code object passed to eval() may not contain free variables");
985 return NULL;
986 }
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000987 return PyEval_EvalCode(source, globals, locals);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000988 }
Tim Peters9fa96be2001-08-17 23:04:59 +0000989
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000990 cf.cf_flags = PyCF_SOURCE_IS_UTF8;
Martin Panter61d6e4a2015-11-07 02:56:11 +0000991 str = source_as_string(source, "eval", "string, bytes or code", &cf, &source_copy);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000992 if (str == NULL)
993 return NULL;
Just van Rossum3aaf42c2003-02-10 08:21:10 +0000994
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000995 while (*str == ' ' || *str == '\t')
996 str++;
Tim Peters9fa96be2001-08-17 23:04:59 +0000997
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000998 (void)PyEval_MergeCompilerFlags(&cf);
999 result = PyRun_StringFlags(str, Py_eval_input, globals, locals, &cf);
Martin Panter61d6e4a2015-11-07 02:56:11 +00001000 Py_XDECREF(source_copy);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001001 return result;
Guido van Rossum3f5da241990-12-20 15:06:42 +00001002}
1003
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001004/*[clinic input]
1005exec as builtin_exec
1006
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001007 source: object
1008 globals: object = None
1009 locals: object = None
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001010 /
1011
1012Execute the given source in the context of globals and locals.
1013
1014The source may be a string representing one or more Python statements
1015or a code object as returned by compile().
1016The globals must be a dictionary and locals can be any mapping,
1017defaulting to the current globals and locals.
1018If only globals is given, locals defaults to it.
1019[clinic start generated code]*/
1020
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001021static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001022builtin_exec_impl(PyObject *module, PyObject *source, PyObject *globals,
Larry Hastings89964c42015-04-14 18:07:59 -04001023 PyObject *locals)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001024/*[clinic end generated code: output=3c90efc6ab68ef5d input=01ca3e1c01692829]*/
Georg Brandl7cae87c2006-09-06 06:51:57 +00001025{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001026 PyObject *v;
Georg Brandl2cabc562008-08-28 07:57:16 +00001027
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001028 if (globals == Py_None) {
1029 globals = PyEval_GetGlobals();
1030 if (locals == Py_None) {
1031 locals = PyEval_GetLocals();
Victor Stinner41bb43a2013-10-29 01:19:37 +01001032 if (locals == NULL)
1033 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001034 }
1035 if (!globals || !locals) {
1036 PyErr_SetString(PyExc_SystemError,
1037 "globals and locals cannot be NULL");
1038 return NULL;
1039 }
1040 }
1041 else if (locals == Py_None)
1042 locals = globals;
Georg Brandl7cae87c2006-09-06 06:51:57 +00001043
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001044 if (!PyDict_Check(globals)) {
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001045 PyErr_Format(PyExc_TypeError, "exec() globals must be a dict, not %.100s",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001046 globals->ob_type->tp_name);
1047 return NULL;
1048 }
1049 if (!PyMapping_Check(locals)) {
1050 PyErr_Format(PyExc_TypeError,
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001051 "locals must be a mapping or None, not %.100s",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001052 locals->ob_type->tp_name);
1053 return NULL;
1054 }
Victor Stinnerb44562b2013-11-06 19:03:11 +01001055 if (_PyDict_GetItemId(globals, &PyId___builtins__) == NULL) {
1056 if (_PyDict_SetItemId(globals, &PyId___builtins__,
1057 PyEval_GetBuiltins()) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001058 return NULL;
1059 }
1060
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001061 if (PyCode_Check(source)) {
1062 if (PyCode_GetNumFree((PyCodeObject *)source) > 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001063 PyErr_SetString(PyExc_TypeError,
1064 "code object passed to exec() may not "
1065 "contain free variables");
1066 return NULL;
1067 }
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001068 v = PyEval_EvalCode(source, globals, locals);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001069 }
1070 else {
Martin Panter61d6e4a2015-11-07 02:56:11 +00001071 PyObject *source_copy;
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +02001072 const char *str;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001073 PyCompilerFlags cf;
1074 cf.cf_flags = PyCF_SOURCE_IS_UTF8;
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001075 str = source_as_string(source, "exec",
Martin Panter61d6e4a2015-11-07 02:56:11 +00001076 "string, bytes or code", &cf,
1077 &source_copy);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001078 if (str == NULL)
1079 return NULL;
1080 if (PyEval_MergeCompilerFlags(&cf))
1081 v = PyRun_StringFlags(str, Py_file_input, globals,
1082 locals, &cf);
1083 else
1084 v = PyRun_String(str, Py_file_input, globals, locals);
Martin Panter61d6e4a2015-11-07 02:56:11 +00001085 Py_XDECREF(source_copy);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001086 }
1087 if (v == NULL)
1088 return NULL;
1089 Py_DECREF(v);
1090 Py_RETURN_NONE;
Georg Brandl7cae87c2006-09-06 06:51:57 +00001091}
1092
Georg Brandl7cae87c2006-09-06 06:51:57 +00001093
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001094/* AC: cannot convert yet, as needs PEP 457 group support in inspect */
Guido van Rossum79f25d91997-04-29 20:08:16 +00001095static PyObject *
Serhiy Storchakaa5552f02017-12-15 13:11:11 +02001096builtin_getattr(PyObject *self, PyObject *const *args, Py_ssize_t nargs)
Guido van Rossum33894be1992-01-27 16:53:09 +00001097{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001098 PyObject *v, *result, *dflt = NULL;
1099 PyObject *name;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001100
Sylvain96c7c062017-06-15 17:05:23 +02001101 if (!_PyArg_UnpackStack(args, nargs, "getattr", 2, 3, &v, &name, &dflt))
1102 return NULL;
1103
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001104 if (!PyUnicode_Check(name)) {
1105 PyErr_SetString(PyExc_TypeError,
1106 "getattr(): attribute name must be string");
1107 return NULL;
1108 }
INADA Naoki378edee2018-01-16 20:52:41 +09001109 if (dflt != NULL) {
Serhiy Storchakaf320be72018-01-25 10:49:40 +02001110 if (_PyObject_LookupAttr(v, name, &result) == 0) {
INADA Naoki378edee2018-01-16 20:52:41 +09001111 Py_INCREF(dflt);
1112 return dflt;
1113 }
1114 }
1115 else {
1116 result = PyObject_GetAttr(v, name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001117 }
1118 return result;
Guido van Rossum9bfef441993-03-29 10:43:31 +00001119}
1120
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001121PyDoc_STRVAR(getattr_doc,
Guido van Rossum950ff291998-06-29 13:38:57 +00001122"getattr(object, name[, default]) -> value\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001123\n\
Guido van Rossum950ff291998-06-29 13:38:57 +00001124Get a named attribute from an object; getattr(x, 'y') is equivalent to x.y.\n\
1125When a default argument is given, it is returned when the attribute doesn't\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001126exist; without it, an exception is raised in that case.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001127
1128
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001129/*[clinic input]
1130globals as builtin_globals
1131
1132Return the dictionary containing the current scope's global variables.
1133
1134NOTE: Updates to this dictionary *will* affect name lookups in the current
1135global scope and vice-versa.
1136[clinic start generated code]*/
1137
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001138static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001139builtin_globals_impl(PyObject *module)
1140/*[clinic end generated code: output=e5dd1527067b94d2 input=9327576f92bb48ba]*/
Guido van Rossum872537c1995-07-07 22:43:42 +00001141{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001142 PyObject *d;
Guido van Rossum872537c1995-07-07 22:43:42 +00001143
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001144 d = PyEval_GetGlobals();
1145 Py_XINCREF(d);
1146 return d;
Guido van Rossum872537c1995-07-07 22:43:42 +00001147}
1148
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001149
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001150/*[clinic input]
1151hasattr as builtin_hasattr
1152
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001153 obj: object
1154 name: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001155 /
1156
1157Return whether the object has an attribute with the given name.
1158
1159This is done by calling getattr(obj, name) and catching AttributeError.
1160[clinic start generated code]*/
1161
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001162static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001163builtin_hasattr_impl(PyObject *module, PyObject *obj, PyObject *name)
1164/*[clinic end generated code: output=a7aff2090a4151e5 input=0faec9787d979542]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001165{
1166 PyObject *v;
1167
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001168 if (!PyUnicode_Check(name)) {
1169 PyErr_SetString(PyExc_TypeError,
1170 "hasattr(): attribute name must be string");
1171 return NULL;
1172 }
Serhiy Storchakaf320be72018-01-25 10:49:40 +02001173 if (_PyObject_LookupAttr(obj, name, &v) < 0) {
Benjamin Peterson17689992010-08-24 03:26:23 +00001174 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001175 }
Serhiy Storchakaf320be72018-01-25 10:49:40 +02001176 if (v == NULL) {
1177 Py_RETURN_FALSE;
1178 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001179 Py_DECREF(v);
Benjamin Peterson17689992010-08-24 03:26:23 +00001180 Py_RETURN_TRUE;
Guido van Rossum33894be1992-01-27 16:53:09 +00001181}
1182
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001183
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001184/* AC: gdb's integration with CPython relies on builtin_id having
1185 * the *exact* parameter names of "self" and "v", so we ensure we
1186 * preserve those name rather than using the AC defaults.
1187 */
1188/*[clinic input]
1189id as builtin_id
1190
Serhiy Storchaka24182a32016-05-05 16:21:35 +03001191 self: self(type="PyModuleDef *")
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001192 obj as v: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001193 /
1194
1195Return the identity of an object.
1196
1197This is guaranteed to be unique among simultaneously existing objects.
1198(CPython uses the object's memory address.)
1199[clinic start generated code]*/
1200
Guido van Rossum79f25d91997-04-29 20:08:16 +00001201static PyObject *
Serhiy Storchaka24182a32016-05-05 16:21:35 +03001202builtin_id(PyModuleDef *self, PyObject *v)
1203/*[clinic end generated code: output=0aa640785f697f65 input=5a534136419631f4]*/
Guido van Rossum5b722181993-03-30 17:46:03 +00001204{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001205 return PyLong_FromVoidPtr(v);
Guido van Rossum5b722181993-03-30 17:46:03 +00001206}
1207
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001208
Raymond Hettingera6c60372008-03-13 01:26:19 +00001209/* map object ************************************************************/
1210
1211typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001212 PyObject_HEAD
1213 PyObject *iters;
1214 PyObject *func;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001215} mapobject;
1216
Guido van Rossum79f25d91997-04-29 20:08:16 +00001217static PyObject *
Raymond Hettingera6c60372008-03-13 01:26:19 +00001218map_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
Guido van Rossum12d12c51993-10-26 17:58:25 +00001219{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001220 PyObject *it, *iters, *func;
1221 mapobject *lz;
1222 Py_ssize_t numargs, i;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001223
Serhiy Storchaka6cca5c82017-06-08 14:41:19 +03001224 if (type == &PyMap_Type && !_PyArg_NoKeywords("map", kwds))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001225 return NULL;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001226
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001227 numargs = PyTuple_Size(args);
1228 if (numargs < 2) {
1229 PyErr_SetString(PyExc_TypeError,
1230 "map() must have at least two arguments.");
1231 return NULL;
1232 }
Raymond Hettingera6c60372008-03-13 01:26:19 +00001233
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001234 iters = PyTuple_New(numargs-1);
1235 if (iters == NULL)
1236 return NULL;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001237
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001238 for (i=1 ; i<numargs ; i++) {
1239 /* Get iterator. */
1240 it = PyObject_GetIter(PyTuple_GET_ITEM(args, i));
1241 if (it == NULL) {
1242 Py_DECREF(iters);
1243 return NULL;
1244 }
1245 PyTuple_SET_ITEM(iters, i-1, it);
1246 }
Raymond Hettingera6c60372008-03-13 01:26:19 +00001247
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001248 /* create mapobject structure */
1249 lz = (mapobject *)type->tp_alloc(type, 0);
1250 if (lz == NULL) {
1251 Py_DECREF(iters);
1252 return NULL;
1253 }
1254 lz->iters = iters;
1255 func = PyTuple_GET_ITEM(args, 0);
1256 Py_INCREF(func);
1257 lz->func = func;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001258
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001259 return (PyObject *)lz;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001260}
1261
1262static void
1263map_dealloc(mapobject *lz)
1264{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001265 PyObject_GC_UnTrack(lz);
1266 Py_XDECREF(lz->iters);
1267 Py_XDECREF(lz->func);
1268 Py_TYPE(lz)->tp_free(lz);
Raymond Hettingera6c60372008-03-13 01:26:19 +00001269}
1270
1271static int
1272map_traverse(mapobject *lz, visitproc visit, void *arg)
1273{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001274 Py_VISIT(lz->iters);
1275 Py_VISIT(lz->func);
1276 return 0;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001277}
1278
1279static PyObject *
1280map_next(mapobject *lz)
1281{
Victor Stinnerbc08ab42016-12-15 12:40:53 +01001282 PyObject *small_stack[_PY_FASTCALL_SMALL_STACK];
Victor Stinnercdb5cee2016-08-24 01:45:13 +02001283 PyObject **stack;
1284 Py_ssize_t niters, nargs, i;
1285 PyObject *result = NULL;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001286
Victor Stinnercdb5cee2016-08-24 01:45:13 +02001287 niters = PyTuple_GET_SIZE(lz->iters);
1288 if (niters <= (Py_ssize_t)Py_ARRAY_LENGTH(small_stack)) {
1289 stack = small_stack;
1290 }
1291 else {
1292 stack = PyMem_Malloc(niters * sizeof(stack[0]));
1293 if (stack == NULL) {
1294 PyErr_NoMemory();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001295 return NULL;
1296 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001297 }
Victor Stinnercdb5cee2016-08-24 01:45:13 +02001298
1299 nargs = 0;
1300 for (i=0; i < niters; i++) {
1301 PyObject *it = PyTuple_GET_ITEM(lz->iters, i);
1302 PyObject *val = Py_TYPE(it)->tp_iternext(it);
1303 if (val == NULL) {
1304 goto exit;
1305 }
1306 stack[i] = val;
1307 nargs++;
1308 }
1309
1310 result = _PyObject_FastCall(lz->func, stack, nargs);
1311
1312exit:
1313 for (i=0; i < nargs; i++) {
1314 Py_DECREF(stack[i]);
1315 }
1316 if (stack != small_stack) {
1317 PyMem_Free(stack);
1318 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001319 return result;
Guido van Rossum12d12c51993-10-26 17:58:25 +00001320}
1321
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001322static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05301323map_reduce(mapobject *lz, PyObject *Py_UNUSED(ignored))
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001324{
1325 Py_ssize_t numargs = PyTuple_GET_SIZE(lz->iters);
1326 PyObject *args = PyTuple_New(numargs+1);
1327 Py_ssize_t i;
1328 if (args == NULL)
1329 return NULL;
1330 Py_INCREF(lz->func);
1331 PyTuple_SET_ITEM(args, 0, lz->func);
1332 for (i = 0; i<numargs; i++){
1333 PyObject *it = PyTuple_GET_ITEM(lz->iters, i);
1334 Py_INCREF(it);
1335 PyTuple_SET_ITEM(args, i+1, it);
1336 }
1337
1338 return Py_BuildValue("ON", Py_TYPE(lz), args);
1339}
1340
1341static PyMethodDef map_methods[] = {
1342 {"__reduce__", (PyCFunction)map_reduce, METH_NOARGS, reduce_doc},
1343 {NULL, NULL} /* sentinel */
1344};
1345
1346
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001347PyDoc_STRVAR(map_doc,
Raymond Hettingera6c60372008-03-13 01:26:19 +00001348"map(func, *iterables) --> map object\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001349\n\
Raymond Hettingera6c60372008-03-13 01:26:19 +00001350Make an iterator that computes the function using arguments from\n\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001351each of the iterables. Stops when the shortest iterable is exhausted.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001352
Raymond Hettingera6c60372008-03-13 01:26:19 +00001353PyTypeObject PyMap_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001354 PyVarObject_HEAD_INIT(&PyType_Type, 0)
1355 "map", /* tp_name */
1356 sizeof(mapobject), /* tp_basicsize */
1357 0, /* tp_itemsize */
1358 /* methods */
1359 (destructor)map_dealloc, /* tp_dealloc */
1360 0, /* tp_print */
1361 0, /* tp_getattr */
1362 0, /* tp_setattr */
1363 0, /* tp_reserved */
1364 0, /* tp_repr */
1365 0, /* tp_as_number */
1366 0, /* tp_as_sequence */
1367 0, /* tp_as_mapping */
1368 0, /* tp_hash */
1369 0, /* tp_call */
1370 0, /* tp_str */
1371 PyObject_GenericGetAttr, /* tp_getattro */
1372 0, /* tp_setattro */
1373 0, /* tp_as_buffer */
1374 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
1375 Py_TPFLAGS_BASETYPE, /* tp_flags */
1376 map_doc, /* tp_doc */
1377 (traverseproc)map_traverse, /* tp_traverse */
1378 0, /* tp_clear */
1379 0, /* tp_richcompare */
1380 0, /* tp_weaklistoffset */
1381 PyObject_SelfIter, /* tp_iter */
1382 (iternextfunc)map_next, /* tp_iternext */
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001383 map_methods, /* tp_methods */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001384 0, /* tp_members */
1385 0, /* tp_getset */
1386 0, /* tp_base */
1387 0, /* tp_dict */
1388 0, /* tp_descr_get */
1389 0, /* tp_descr_set */
1390 0, /* tp_dictoffset */
1391 0, /* tp_init */
1392 PyType_GenericAlloc, /* tp_alloc */
1393 map_new, /* tp_new */
1394 PyObject_GC_Del, /* tp_free */
Raymond Hettingera6c60372008-03-13 01:26:19 +00001395};
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001396
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001397
1398/* AC: cannot convert yet, as needs PEP 457 group support in inspect */
Guido van Rossum79f25d91997-04-29 20:08:16 +00001399static PyObject *
Serhiy Storchakaa5552f02017-12-15 13:11:11 +02001400builtin_next(PyObject *self, PyObject *const *args, Py_ssize_t nargs)
Georg Brandla18af4e2007-04-21 15:47:16 +00001401{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001402 PyObject *it, *res;
1403 PyObject *def = NULL;
Georg Brandla18af4e2007-04-21 15:47:16 +00001404
Sylvain96c7c062017-06-15 17:05:23 +02001405 if (!_PyArg_UnpackStack(args, nargs, "next", 1, 2, &it, &def))
1406 return NULL;
1407
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001408 if (!PyIter_Check(it)) {
1409 PyErr_Format(PyExc_TypeError,
Philip Jenvey50add042011-11-06 16:37:52 -08001410 "'%.200s' object is not an iterator",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001411 it->ob_type->tp_name);
1412 return NULL;
1413 }
1414
1415 res = (*it->ob_type->tp_iternext)(it);
1416 if (res != NULL) {
1417 return res;
1418 } else if (def != NULL) {
1419 if (PyErr_Occurred()) {
1420 if(!PyErr_ExceptionMatches(PyExc_StopIteration))
1421 return NULL;
1422 PyErr_Clear();
1423 }
1424 Py_INCREF(def);
1425 return def;
1426 } else if (PyErr_Occurred()) {
1427 return NULL;
1428 } else {
1429 PyErr_SetNone(PyExc_StopIteration);
1430 return NULL;
1431 }
Georg Brandla18af4e2007-04-21 15:47:16 +00001432}
1433
1434PyDoc_STRVAR(next_doc,
1435"next(iterator[, default])\n\
1436\n\
1437Return the next item from the iterator. If default is given and the iterator\n\
1438is exhausted, it is returned instead of raising StopIteration.");
1439
1440
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001441/*[clinic input]
1442setattr as builtin_setattr
1443
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001444 obj: object
1445 name: object
1446 value: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001447 /
1448
1449Sets the named attribute on the given object to the specified value.
1450
1451setattr(x, 'y', v) is equivalent to ``x.y = v''
1452[clinic start generated code]*/
1453
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001454static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001455builtin_setattr_impl(PyObject *module, PyObject *obj, PyObject *name,
Larry Hastings89964c42015-04-14 18:07:59 -04001456 PyObject *value)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001457/*[clinic end generated code: output=dc2ce1d1add9acb4 input=bd2b7ca6875a1899]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001458{
1459 if (PyObject_SetAttr(obj, name, value) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001460 return NULL;
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02001461 Py_RETURN_NONE;
Guido van Rossum33894be1992-01-27 16:53:09 +00001462}
1463
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001464
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001465/*[clinic input]
1466delattr as builtin_delattr
1467
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001468 obj: object
1469 name: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001470 /
1471
1472Deletes the named attribute from the given object.
1473
1474delattr(x, 'y') is equivalent to ``del x.y''
1475[clinic start generated code]*/
1476
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001477static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001478builtin_delattr_impl(PyObject *module, PyObject *obj, PyObject *name)
1479/*[clinic end generated code: output=85134bc58dff79fa input=db16685d6b4b9410]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001480{
1481 if (PyObject_SetAttr(obj, name, (PyObject *)NULL) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001482 return NULL;
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02001483 Py_RETURN_NONE;
Guido van Rossum14144fc1994-08-29 12:53:40 +00001484}
1485
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001486
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001487/*[clinic input]
1488hash as builtin_hash
1489
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001490 obj: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001491 /
1492
1493Return the hash value for the given object.
1494
1495Two objects that compare equal must also have the same hash value, but the
1496reverse is not necessarily true.
1497[clinic start generated code]*/
1498
Guido van Rossum79f25d91997-04-29 20:08:16 +00001499static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001500builtin_hash(PyObject *module, PyObject *obj)
1501/*[clinic end generated code: output=237668e9d7688db7 input=58c48be822bf9c54]*/
Guido van Rossum9bfef441993-03-29 10:43:31 +00001502{
Benjamin Peterson8f67d082010-10-17 20:54:53 +00001503 Py_hash_t x;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001504
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001505 x = PyObject_Hash(obj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001506 if (x == -1)
1507 return NULL;
Benjamin Peterson8f67d082010-10-17 20:54:53 +00001508 return PyLong_FromSsize_t(x);
Guido van Rossum9bfef441993-03-29 10:43:31 +00001509}
1510
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001511
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001512/*[clinic input]
1513hex as builtin_hex
1514
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001515 number: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001516 /
1517
1518Return the hexadecimal representation of an integer.
1519
1520 >>> hex(12648430)
1521 '0xc0ffee'
1522[clinic start generated code]*/
1523
Guido van Rossum79f25d91997-04-29 20:08:16 +00001524static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001525builtin_hex(PyObject *module, PyObject *number)
1526/*[clinic end generated code: output=e46b612169099408 input=e645aff5fc7d540e]*/
Guido van Rossum006bcd41991-10-24 14:54:44 +00001527{
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001528 return PyNumber_ToBase(number, 16);
Guido van Rossum006bcd41991-10-24 14:54:44 +00001529}
1530
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001531
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001532/* AC: cannot convert yet, as needs PEP 457 group support in inspect */
Guido van Rossum79f25d91997-04-29 20:08:16 +00001533static PyObject *
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001534builtin_iter(PyObject *self, PyObject *args)
1535{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001536 PyObject *v, *w = NULL;
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001537
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001538 if (!PyArg_UnpackTuple(args, "iter", 1, 2, &v, &w))
1539 return NULL;
1540 if (w == NULL)
1541 return PyObject_GetIter(v);
1542 if (!PyCallable_Check(v)) {
1543 PyErr_SetString(PyExc_TypeError,
1544 "iter(v, w): v must be callable");
1545 return NULL;
1546 }
1547 return PyCallIter_New(v, w);
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001548}
1549
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001550PyDoc_STRVAR(iter_doc,
Georg Brandld11ae5d2008-05-16 13:27:32 +00001551"iter(iterable) -> iterator\n\
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001552iter(callable, sentinel) -> iterator\n\
1553\n\
1554Get an iterator from an object. In the first form, the argument must\n\
1555supply its own iterator, or be a sequence.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001556In the second form, the callable is called until it returns the sentinel.");
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001557
1558
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001559/*[clinic input]
1560len as builtin_len
1561
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001562 obj: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001563 /
1564
1565Return the number of items in a container.
1566[clinic start generated code]*/
1567
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001568static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001569builtin_len(PyObject *module, PyObject *obj)
1570/*[clinic end generated code: output=fa7a270d314dfb6c input=bc55598da9e9c9b5]*/
Guido van Rossum3f5da241990-12-20 15:06:42 +00001571{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001572 Py_ssize_t res;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001573
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001574 res = PyObject_Size(obj);
Serhiy Storchaka813f9432017-04-16 09:21:44 +03001575 if (res < 0) {
1576 assert(PyErr_Occurred());
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001577 return NULL;
Serhiy Storchaka813f9432017-04-16 09:21:44 +03001578 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001579 return PyLong_FromSsize_t(res);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001580}
1581
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001582
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001583/*[clinic input]
1584locals as builtin_locals
1585
1586Return a dictionary containing the current scope's local variables.
1587
1588NOTE: Whether or not updates to this dictionary will affect name lookups in
1589the local scope and vice-versa is *implementation dependent* and not
1590covered by any backwards compatibility guarantees.
1591[clinic start generated code]*/
1592
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001593static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001594builtin_locals_impl(PyObject *module)
1595/*[clinic end generated code: output=b46c94015ce11448 input=7874018d478d5c4b]*/
Guido van Rossum872537c1995-07-07 22:43:42 +00001596{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001597 PyObject *d;
Guido van Rossum872537c1995-07-07 22:43:42 +00001598
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001599 d = PyEval_GetLocals();
1600 Py_XINCREF(d);
1601 return d;
Guido van Rossum872537c1995-07-07 22:43:42 +00001602}
1603
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001604
Guido van Rossum79f25d91997-04-29 20:08:16 +00001605static PyObject *
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001606min_max(PyObject *args, PyObject *kwds, int op)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001607{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001608 PyObject *v, *it, *item, *val, *maxitem, *maxval, *keyfunc=NULL;
Raymond Hettinger4d6018f2013-06-24 22:43:02 -07001609 PyObject *emptytuple, *defaultval = NULL;
1610 static char *kwlist[] = {"key", "default", NULL};
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001611 const char *name = op == Py_LT ? "min" : "max";
Raymond Hettinger4d6018f2013-06-24 22:43:02 -07001612 const int positional = PyTuple_Size(args) > 1;
1613 int ret;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001614
Raymond Hettinger4d6018f2013-06-24 22:43:02 -07001615 if (positional)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001616 v = args;
Serhiy Storchakac6792272013-10-19 21:03:34 +03001617 else if (!PyArg_UnpackTuple(args, name, 1, 1, &v))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001618 return NULL;
Tim Peters67d687a2002-04-29 21:27:32 +00001619
Raymond Hettinger4d6018f2013-06-24 22:43:02 -07001620 emptytuple = PyTuple_New(0);
1621 if (emptytuple == NULL)
1622 return NULL;
Oren Milman58cf7482017-08-21 20:19:07 +03001623 ret = PyArg_ParseTupleAndKeywords(emptytuple, kwds,
1624 (op == Py_LT) ? "|$OO:min" : "|$OO:max",
1625 kwlist, &keyfunc, &defaultval);
Raymond Hettinger4d6018f2013-06-24 22:43:02 -07001626 Py_DECREF(emptytuple);
1627 if (!ret)
1628 return NULL;
1629
1630 if (positional && defaultval != NULL) {
1631 PyErr_Format(PyExc_TypeError,
1632 "Cannot specify a default for %s() with multiple "
1633 "positional arguments", name);
1634 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001635 }
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001636
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001637 it = PyObject_GetIter(v);
1638 if (it == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001639 return NULL;
1640 }
Tim Petersc3074532001-05-03 07:00:32 +00001641
Alexander Marshalove22072f2018-07-24 10:58:21 +07001642 if (keyfunc == Py_None) {
1643 keyfunc = NULL;
1644 }
1645
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001646 maxitem = NULL; /* the result */
1647 maxval = NULL; /* the value associated with the result */
1648 while (( item = PyIter_Next(it) )) {
1649 /* get the value from the key function */
1650 if (keyfunc != NULL) {
Victor Stinnerde4ae3d2016-12-04 22:59:09 +01001651 val = PyObject_CallFunctionObjArgs(keyfunc, item, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001652 if (val == NULL)
1653 goto Fail_it_item;
1654 }
1655 /* no key function; the value is the item */
1656 else {
1657 val = item;
1658 Py_INCREF(val);
1659 }
Tim Petersc3074532001-05-03 07:00:32 +00001660
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001661 /* maximum value and item are unset; set them */
1662 if (maxval == NULL) {
1663 maxitem = item;
1664 maxval = val;
1665 }
1666 /* maximum value and item are set; update them as necessary */
1667 else {
1668 int cmp = PyObject_RichCompareBool(val, maxval, op);
1669 if (cmp < 0)
1670 goto Fail_it_item_and_val;
1671 else if (cmp > 0) {
1672 Py_DECREF(maxval);
1673 Py_DECREF(maxitem);
1674 maxval = val;
1675 maxitem = item;
1676 }
1677 else {
1678 Py_DECREF(item);
1679 Py_DECREF(val);
1680 }
1681 }
1682 }
1683 if (PyErr_Occurred())
1684 goto Fail_it;
1685 if (maxval == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001686 assert(maxitem == NULL);
Raymond Hettinger4d6018f2013-06-24 22:43:02 -07001687 if (defaultval != NULL) {
1688 Py_INCREF(defaultval);
1689 maxitem = defaultval;
1690 } else {
1691 PyErr_Format(PyExc_ValueError,
1692 "%s() arg is an empty sequence", name);
1693 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001694 }
1695 else
1696 Py_DECREF(maxval);
1697 Py_DECREF(it);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001698 return maxitem;
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001699
1700Fail_it_item_and_val:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001701 Py_DECREF(val);
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001702Fail_it_item:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001703 Py_DECREF(item);
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001704Fail_it:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001705 Py_XDECREF(maxval);
1706 Py_XDECREF(maxitem);
1707 Py_DECREF(it);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001708 return NULL;
Guido van Rossum3f5da241990-12-20 15:06:42 +00001709}
1710
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001711/* AC: cannot convert yet, waiting for *args support */
Guido van Rossum79f25d91997-04-29 20:08:16 +00001712static PyObject *
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001713builtin_min(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001714{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001715 return min_max(args, kwds, Py_LT);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001716}
1717
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001718PyDoc_STRVAR(min_doc,
Raymond Hettinger2a545822014-05-19 22:20:52 +01001719"min(iterable, *[, default=obj, key=func]) -> value\n\
1720min(arg1, arg2, *args, *[, key=func]) -> value\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001721\n\
Raymond Hettinger2a545822014-05-19 22:20:52 +01001722With a single iterable argument, return its smallest item. The\n\
1723default keyword-only argument specifies an object to return if\n\
1724the provided iterable is empty.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001725With two or more arguments, return the smallest argument.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001726
1727
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001728/* AC: cannot convert yet, waiting for *args support */
Guido van Rossum79f25d91997-04-29 20:08:16 +00001729static PyObject *
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001730builtin_max(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001731{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001732 return min_max(args, kwds, Py_GT);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001733}
1734
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001735PyDoc_STRVAR(max_doc,
Raymond Hettinger2a545822014-05-19 22:20:52 +01001736"max(iterable, *[, default=obj, key=func]) -> value\n\
1737max(arg1, arg2, *args, *[, key=func]) -> value\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001738\n\
Raymond Hettinger2a545822014-05-19 22:20:52 +01001739With a single iterable argument, return its biggest item. The\n\
1740default keyword-only argument specifies an object to return if\n\
1741the provided iterable is empty.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001742With two or more arguments, return the largest argument.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001743
1744
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001745/*[clinic input]
1746oct as builtin_oct
1747
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001748 number: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001749 /
1750
1751Return the octal representation of an integer.
1752
1753 >>> oct(342391)
1754 '0o1234567'
1755[clinic start generated code]*/
1756
Guido van Rossum79f25d91997-04-29 20:08:16 +00001757static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001758builtin_oct(PyObject *module, PyObject *number)
1759/*[clinic end generated code: output=40a34656b6875352 input=ad6b274af4016c72]*/
Guido van Rossum006bcd41991-10-24 14:54:44 +00001760{
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001761 return PyNumber_ToBase(number, 8);
Guido van Rossum006bcd41991-10-24 14:54:44 +00001762}
1763
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001764
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001765/*[clinic input]
1766ord as builtin_ord
1767
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001768 c: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001769 /
1770
1771Return the Unicode code point for a one-character string.
1772[clinic start generated code]*/
1773
Guido van Rossum79f25d91997-04-29 20:08:16 +00001774static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001775builtin_ord(PyObject *module, PyObject *c)
1776/*[clinic end generated code: output=4fa5e87a323bae71 input=3064e5d6203ad012]*/
Guido van Rossum3f5da241990-12-20 15:06:42 +00001777{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001778 long ord;
1779 Py_ssize_t size;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001780
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001781 if (PyBytes_Check(c)) {
1782 size = PyBytes_GET_SIZE(c);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001783 if (size == 1) {
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001784 ord = (long)((unsigned char)*PyBytes_AS_STRING(c));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001785 return PyLong_FromLong(ord);
1786 }
1787 }
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001788 else if (PyUnicode_Check(c)) {
1789 if (PyUnicode_READY(c) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001790 return NULL;
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001791 size = PyUnicode_GET_LENGTH(c);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001792 if (size == 1) {
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001793 ord = (long)PyUnicode_READ_CHAR(c, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001794 return PyLong_FromLong(ord);
1795 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001796 }
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001797 else if (PyByteArray_Check(c)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001798 /* XXX Hopefully this is temporary */
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001799 size = PyByteArray_GET_SIZE(c);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001800 if (size == 1) {
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001801 ord = (long)((unsigned char)*PyByteArray_AS_STRING(c));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001802 return PyLong_FromLong(ord);
1803 }
1804 }
1805 else {
1806 PyErr_Format(PyExc_TypeError,
1807 "ord() expected string of length 1, but " \
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001808 "%.200s found", c->ob_type->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001809 return NULL;
1810 }
Guido van Rossum09095f32000-03-10 23:00:52 +00001811
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001812 PyErr_Format(PyExc_TypeError,
1813 "ord() expected a character, "
1814 "but string of length %zd found",
1815 size);
1816 return NULL;
Guido van Rossum3f5da241990-12-20 15:06:42 +00001817}
1818
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001819
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001820/*[clinic input]
1821pow as builtin_pow
1822
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001823 x: object
1824 y: object
1825 z: object = None
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001826 /
1827
1828Equivalent to x**y (with two arguments) or x**y % z (with three arguments)
1829
1830Some types, such as ints, are able to use a more efficient algorithm when
1831invoked using the three argument form.
1832[clinic start generated code]*/
1833
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001834static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001835builtin_pow_impl(PyObject *module, PyObject *x, PyObject *y, PyObject *z)
1836/*[clinic end generated code: output=50a14d5d130d404b input=653d57d38d41fc07]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001837{
1838 return PyNumber_Power(x, y, z);
1839}
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001840
1841
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001842/* AC: cannot convert yet, waiting for *args support */
Guido van Rossum34343512006-11-30 22:13:52 +00001843static PyObject *
Serhiy Storchakaa5552f02017-12-15 13:11:11 +02001844builtin_print(PyObject *self, PyObject *const *args, Py_ssize_t nargs, PyObject *kwnames)
Guido van Rossum34343512006-11-30 22:13:52 +00001845{
INADA Naokibd584f12017-01-19 12:50:34 +01001846 static const char * const _keywords[] = {"sep", "end", "file", "flush", 0};
1847 static struct _PyArg_Parser _parser = {"|OOOO:print", _keywords, 0};
Georg Brandlbc3b6822012-01-13 19:41:25 +01001848 PyObject *sep = NULL, *end = NULL, *file = NULL, *flush = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001849 int i, err;
Guido van Rossum34343512006-11-30 22:13:52 +00001850
INADA Naokibd584f12017-01-19 12:50:34 +01001851 if (kwnames != NULL &&
1852 !_PyArg_ParseStackAndKeywords(args + nargs, 0, kwnames, &_parser,
1853 &sep, &end, &file, &flush)) {
Georg Brandlbc3b6822012-01-13 19:41:25 +01001854 return NULL;
INADA Naokibd584f12017-01-19 12:50:34 +01001855 }
1856
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001857 if (file == NULL || file == Py_None) {
Victor Stinnerbd303c12013-11-07 23:07:29 +01001858 file = _PySys_GetObjectId(&PyId_stdout);
Victor Stinner1e53bba2013-07-16 22:26:05 +02001859 if (file == NULL) {
1860 PyErr_SetString(PyExc_RuntimeError, "lost sys.stdout");
1861 return NULL;
1862 }
1863
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001864 /* sys.stdout may be None when FILE* stdout isn't connected */
1865 if (file == Py_None)
1866 Py_RETURN_NONE;
1867 }
Guido van Rossum34343512006-11-30 22:13:52 +00001868
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001869 if (sep == Py_None) {
1870 sep = NULL;
1871 }
1872 else if (sep && !PyUnicode_Check(sep)) {
1873 PyErr_Format(PyExc_TypeError,
1874 "sep must be None or a string, not %.200s",
1875 sep->ob_type->tp_name);
1876 return NULL;
1877 }
1878 if (end == Py_None) {
1879 end = NULL;
1880 }
1881 else if (end && !PyUnicode_Check(end)) {
1882 PyErr_Format(PyExc_TypeError,
1883 "end must be None or a string, not %.200s",
1884 end->ob_type->tp_name);
1885 return NULL;
1886 }
Guido van Rossum34343512006-11-30 22:13:52 +00001887
INADA Naokibd584f12017-01-19 12:50:34 +01001888 for (i = 0; i < nargs; i++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001889 if (i > 0) {
1890 if (sep == NULL)
1891 err = PyFile_WriteString(" ", file);
1892 else
1893 err = PyFile_WriteObject(sep, file,
1894 Py_PRINT_RAW);
1895 if (err)
1896 return NULL;
1897 }
INADA Naokibd584f12017-01-19 12:50:34 +01001898 err = PyFile_WriteObject(args[i], file, Py_PRINT_RAW);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001899 if (err)
1900 return NULL;
1901 }
Guido van Rossum34343512006-11-30 22:13:52 +00001902
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001903 if (end == NULL)
1904 err = PyFile_WriteString("\n", file);
1905 else
1906 err = PyFile_WriteObject(end, file, Py_PRINT_RAW);
1907 if (err)
1908 return NULL;
Guido van Rossum34343512006-11-30 22:13:52 +00001909
Georg Brandlbc3b6822012-01-13 19:41:25 +01001910 if (flush != NULL) {
1911 PyObject *tmp;
1912 int do_flush = PyObject_IsTrue(flush);
1913 if (do_flush == -1)
1914 return NULL;
1915 else if (do_flush) {
Victor Stinner3466bde2016-09-05 18:16:01 -07001916 tmp = _PyObject_CallMethodId(file, &PyId_flush, NULL);
Georg Brandlbc3b6822012-01-13 19:41:25 +01001917 if (tmp == NULL)
1918 return NULL;
1919 else
1920 Py_DECREF(tmp);
1921 }
1922 }
1923
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001924 Py_RETURN_NONE;
Guido van Rossum34343512006-11-30 22:13:52 +00001925}
1926
1927PyDoc_STRVAR(print_doc,
Senthil Kumarane9175bd2012-08-10 13:53:45 -07001928"print(value, ..., sep=' ', end='\\n', file=sys.stdout, flush=False)\n\
Guido van Rossum34343512006-11-30 22:13:52 +00001929\n\
1930Prints the values to a stream, or to sys.stdout by default.\n\
1931Optional keyword arguments:\n\
Senthil Kumarane9175bd2012-08-10 13:53:45 -07001932file: a file-like object (stream); defaults to the current sys.stdout.\n\
1933sep: string inserted between values, default a space.\n\
1934end: string appended after the last value, default a newline.\n\
1935flush: whether to forcibly flush the stream.");
Guido van Rossum34343512006-11-30 22:13:52 +00001936
1937
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001938/*[clinic input]
1939input as builtin_input
1940
1941 prompt: object(c_default="NULL") = None
1942 /
1943
1944Read a string from standard input. The trailing newline is stripped.
1945
1946The prompt string, if given, is printed to standard output without a
1947trailing newline before reading input.
1948
1949If the user hits EOF (*nix: Ctrl-D, Windows: Ctrl-Z+Return), raise EOFError.
1950On *nix systems, readline is used if available.
1951[clinic start generated code]*/
1952
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001953static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001954builtin_input_impl(PyObject *module, PyObject *prompt)
1955/*[clinic end generated code: output=83db5a191e7a0d60 input=5e8bb70c2908fe3c]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001956{
Victor Stinnerbd303c12013-11-07 23:07:29 +01001957 PyObject *fin = _PySys_GetObjectId(&PyId_stdin);
1958 PyObject *fout = _PySys_GetObjectId(&PyId_stdout);
1959 PyObject *ferr = _PySys_GetObjectId(&PyId_stderr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001960 PyObject *tmp;
1961 long fd;
1962 int tty;
Guido van Rossuma88a0332007-02-26 16:59:55 +00001963
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001964 /* Check that stdin/out/err are intact */
1965 if (fin == NULL || fin == Py_None) {
1966 PyErr_SetString(PyExc_RuntimeError,
1967 "input(): lost sys.stdin");
1968 return NULL;
1969 }
1970 if (fout == NULL || fout == Py_None) {
1971 PyErr_SetString(PyExc_RuntimeError,
1972 "input(): lost sys.stdout");
1973 return NULL;
1974 }
1975 if (ferr == NULL || ferr == Py_None) {
1976 PyErr_SetString(PyExc_RuntimeError,
1977 "input(): lost sys.stderr");
1978 return NULL;
1979 }
Guido van Rossumeba76962007-05-27 09:13:28 +00001980
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001981 /* First of all, flush stderr */
Victor Stinner3466bde2016-09-05 18:16:01 -07001982 tmp = _PyObject_CallMethodId(ferr, &PyId_flush, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001983 if (tmp == NULL)
1984 PyErr_Clear();
1985 else
1986 Py_DECREF(tmp);
Guido van Rossumeba76962007-05-27 09:13:28 +00001987
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001988 /* We should only use (GNU) readline if Python's sys.stdin and
1989 sys.stdout are the same as C's stdin and stdout, because we
1990 need to pass it those. */
Victor Stinner3466bde2016-09-05 18:16:01 -07001991 tmp = _PyObject_CallMethodId(fin, &PyId_fileno, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001992 if (tmp == NULL) {
1993 PyErr_Clear();
1994 tty = 0;
1995 }
1996 else {
1997 fd = PyLong_AsLong(tmp);
1998 Py_DECREF(tmp);
1999 if (fd < 0 && PyErr_Occurred())
2000 return NULL;
2001 tty = fd == fileno(stdin) && isatty(fd);
2002 }
2003 if (tty) {
Victor Stinner3466bde2016-09-05 18:16:01 -07002004 tmp = _PyObject_CallMethodId(fout, &PyId_fileno, NULL);
Martin Panterc9a6ab52015-10-10 01:25:38 +00002005 if (tmp == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002006 PyErr_Clear();
Martin Panterc9a6ab52015-10-10 01:25:38 +00002007 tty = 0;
2008 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002009 else {
2010 fd = PyLong_AsLong(tmp);
2011 Py_DECREF(tmp);
2012 if (fd < 0 && PyErr_Occurred())
2013 return NULL;
2014 tty = fd == fileno(stdout) && isatty(fd);
2015 }
2016 }
Guido van Rossumeba76962007-05-27 09:13:28 +00002017
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002018 /* If we're interactive, use (GNU) readline */
2019 if (tty) {
Antoine Pitrou0d776b12011-11-06 00:34:26 +01002020 PyObject *po = NULL;
Serhiy Storchakae2f92de2017-11-11 13:06:26 +02002021 const char *promptstr;
Antoine Pitrou0d776b12011-11-06 00:34:26 +01002022 char *s = NULL;
2023 PyObject *stdin_encoding = NULL, *stdin_errors = NULL;
2024 PyObject *stdout_encoding = NULL, *stdout_errors = NULL;
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +02002025 const char *stdin_encoding_str, *stdin_errors_str;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002026 PyObject *result;
Victor Stinnerc0f1a1a2011-02-23 12:07:37 +00002027 size_t len;
Martin v. Löwis4a7b5d52007-09-04 05:24:49 +00002028
Serhiy Storchakac2cf1282017-03-12 13:50:36 +02002029 /* stdin is a text stream, so it must have an encoding. */
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02002030 stdin_encoding = _PyObject_GetAttrId(fin, &PyId_encoding);
Antoine Pitrou5ee9d8a2011-11-06 00:38:45 +01002031 stdin_errors = _PyObject_GetAttrId(fin, &PyId_errors);
Serhiy Storchakac2cf1282017-03-12 13:50:36 +02002032 if (!stdin_encoding || !stdin_errors ||
2033 !PyUnicode_Check(stdin_encoding) ||
2034 !PyUnicode_Check(stdin_errors)) {
2035 tty = 0;
Antoine Pitrou0d776b12011-11-06 00:34:26 +01002036 goto _readline_errors;
Serhiy Storchakac2cf1282017-03-12 13:50:36 +02002037 }
Serhiy Storchaka06515832016-11-20 09:13:07 +02002038 stdin_encoding_str = PyUnicode_AsUTF8(stdin_encoding);
2039 stdin_errors_str = PyUnicode_AsUTF8(stdin_errors);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01002040 if (!stdin_encoding_str || !stdin_errors_str)
2041 goto _readline_errors;
Victor Stinner3466bde2016-09-05 18:16:01 -07002042 tmp = _PyObject_CallMethodId(fout, &PyId_flush, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002043 if (tmp == NULL)
2044 PyErr_Clear();
2045 else
2046 Py_DECREF(tmp);
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002047 if (prompt != NULL) {
Antoine Pitrou0d776b12011-11-06 00:34:26 +01002048 /* We have a prompt, encode it as stdout would */
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +02002049 const char *stdout_encoding_str, *stdout_errors_str;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002050 PyObject *stringpo;
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02002051 stdout_encoding = _PyObject_GetAttrId(fout, &PyId_encoding);
Antoine Pitrou5ee9d8a2011-11-06 00:38:45 +01002052 stdout_errors = _PyObject_GetAttrId(fout, &PyId_errors);
Serhiy Storchakac2cf1282017-03-12 13:50:36 +02002053 if (!stdout_encoding || !stdout_errors ||
2054 !PyUnicode_Check(stdout_encoding) ||
2055 !PyUnicode_Check(stdout_errors)) {
2056 tty = 0;
Antoine Pitrou0d776b12011-11-06 00:34:26 +01002057 goto _readline_errors;
Serhiy Storchakac2cf1282017-03-12 13:50:36 +02002058 }
Serhiy Storchaka06515832016-11-20 09:13:07 +02002059 stdout_encoding_str = PyUnicode_AsUTF8(stdout_encoding);
2060 stdout_errors_str = PyUnicode_AsUTF8(stdout_errors);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01002061 if (!stdout_encoding_str || !stdout_errors_str)
2062 goto _readline_errors;
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002063 stringpo = PyObject_Str(prompt);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01002064 if (stringpo == NULL)
2065 goto _readline_errors;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002066 po = PyUnicode_AsEncodedString(stringpo,
Antoine Pitrou0d776b12011-11-06 00:34:26 +01002067 stdout_encoding_str, stdout_errors_str);
2068 Py_CLEAR(stdout_encoding);
2069 Py_CLEAR(stdout_errors);
2070 Py_CLEAR(stringpo);
2071 if (po == NULL)
2072 goto _readline_errors;
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03002073 assert(PyBytes_Check(po));
2074 promptstr = PyBytes_AS_STRING(po);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002075 }
2076 else {
2077 po = NULL;
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002078 promptstr = "";
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002079 }
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002080 s = PyOS_Readline(stdin, stdout, promptstr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002081 if (s == NULL) {
Richard Oudkerk614c5782013-04-03 13:44:50 +01002082 PyErr_CheckSignals();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002083 if (!PyErr_Occurred())
2084 PyErr_SetNone(PyExc_KeyboardInterrupt);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01002085 goto _readline_errors;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002086 }
Victor Stinnerc0f1a1a2011-02-23 12:07:37 +00002087
2088 len = strlen(s);
2089 if (len == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002090 PyErr_SetNone(PyExc_EOFError);
2091 result = NULL;
2092 }
Victor Stinnerc0f1a1a2011-02-23 12:07:37 +00002093 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002094 if (len > PY_SSIZE_T_MAX) {
2095 PyErr_SetString(PyExc_OverflowError,
2096 "input: input too long");
2097 result = NULL;
2098 }
2099 else {
Victor Stinnerc0f1a1a2011-02-23 12:07:37 +00002100 len--; /* strip trailing '\n' */
2101 if (len != 0 && s[len-1] == '\r')
2102 len--; /* strip trailing '\r' */
Antoine Pitrou0d776b12011-11-06 00:34:26 +01002103 result = PyUnicode_Decode(s, len, stdin_encoding_str,
2104 stdin_errors_str);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002105 }
2106 }
2107 Py_DECREF(stdin_encoding);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01002108 Py_DECREF(stdin_errors);
2109 Py_XDECREF(po);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002110 PyMem_FREE(s);
2111 return result;
Serhiy Storchakac2cf1282017-03-12 13:50:36 +02002112
Antoine Pitrou0d776b12011-11-06 00:34:26 +01002113 _readline_errors:
2114 Py_XDECREF(stdin_encoding);
2115 Py_XDECREF(stdout_encoding);
2116 Py_XDECREF(stdin_errors);
2117 Py_XDECREF(stdout_errors);
2118 Py_XDECREF(po);
Serhiy Storchakac2cf1282017-03-12 13:50:36 +02002119 if (tty)
2120 return NULL;
2121
2122 PyErr_Clear();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002123 }
Guido van Rossumeba76962007-05-27 09:13:28 +00002124
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002125 /* Fallback if we're not interactive */
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002126 if (prompt != NULL) {
2127 if (PyFile_WriteObject(prompt, fout, Py_PRINT_RAW) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002128 return NULL;
2129 }
Victor Stinner3466bde2016-09-05 18:16:01 -07002130 tmp = _PyObject_CallMethodId(fout, &PyId_flush, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002131 if (tmp == NULL)
2132 PyErr_Clear();
2133 else
2134 Py_DECREF(tmp);
2135 return PyFile_GetLine(fin, -1);
Guido van Rossuma88a0332007-02-26 16:59:55 +00002136}
2137
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002138
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002139/*[clinic input]
2140repr as builtin_repr
2141
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03002142 obj: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002143 /
2144
2145Return the canonical string representation of the object.
2146
2147For many object types, including most builtins, eval(repr(obj)) == obj.
2148[clinic start generated code]*/
2149
Guido van Rossum79f25d91997-04-29 20:08:16 +00002150static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002151builtin_repr(PyObject *module, PyObject *obj)
2152/*[clinic end generated code: output=7ed3778c44fd0194 input=1c9e6d66d3e3be04]*/
Guido van Rossumc89705d1992-11-26 08:54:07 +00002153{
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002154 return PyObject_Repr(obj);
Guido van Rossumc89705d1992-11-26 08:54:07 +00002155}
2156
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002157
Serhiy Storchakaaca7f572017-11-15 17:51:14 +02002158/*[clinic input]
2159round as builtin_round
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002160
Serhiy Storchakaaca7f572017-11-15 17:51:14 +02002161 number: object
2162 ndigits: object = NULL
2163
2164Round a number to a given precision in decimal digits.
2165
2166The return value is an integer if ndigits is omitted or None. Otherwise
2167the return value has the same type as the number. ndigits may be negative.
2168[clinic start generated code]*/
2169
2170static PyObject *
2171builtin_round_impl(PyObject *module, PyObject *number, PyObject *ndigits)
2172/*[clinic end generated code: output=ff0d9dd176c02ede input=854bc3a217530c3d]*/
2173{
2174 PyObject *round, *result;
Alex Martelliae211f92007-08-22 23:21:33 +00002175
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002176 if (Py_TYPE(number)->tp_dict == NULL) {
2177 if (PyType_Ready(Py_TYPE(number)) < 0)
2178 return NULL;
2179 }
Guido van Rossum15d3d042007-08-24 02:02:45 +00002180
Benjamin Peterson214a7d22013-04-13 17:19:01 -04002181 round = _PyObject_LookupSpecial(number, &PyId___round__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002182 if (round == NULL) {
Benjamin Peterson214a7d22013-04-13 17:19:01 -04002183 if (!PyErr_Occurred())
2184 PyErr_Format(PyExc_TypeError,
2185 "type %.100s doesn't define __round__ method",
2186 Py_TYPE(number)->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002187 return NULL;
2188 }
Alex Martelliae211f92007-08-22 23:21:33 +00002189
Raymond Hettingerf0f1c232016-09-03 01:55:11 -07002190 if (ndigits == NULL || ndigits == Py_None)
Victor Stinnerf17c3de2016-12-06 18:46:19 +01002191 result = _PyObject_CallNoArg(round);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002192 else
Victor Stinnerde4ae3d2016-12-04 22:59:09 +01002193 result = PyObject_CallFunctionObjArgs(round, ndigits, NULL);
Benjamin Peterson214a7d22013-04-13 17:19:01 -04002194 Py_DECREF(round);
2195 return result;
Guido van Rossum9e51f9b1993-02-12 16:29:05 +00002196}
2197
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002198
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002199/*AC: we need to keep the kwds dict intact to easily call into the
2200 * list.sort method, which isn't currently supported in AC. So we just use
2201 * the initially generated signature with a custom implementation.
2202 */
2203/* [disabled clinic input]
2204sorted as builtin_sorted
2205
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03002206 iterable as seq: object
2207 key as keyfunc: object = None
2208 reverse: object = False
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002209
2210Return a new list containing all items from the iterable in ascending order.
2211
Raymond Hettinger7ea386e2016-08-25 21:11:50 -07002212A custom key function can be supplied to customize the sort order, and the
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002213reverse flag can be set to request the result in descending order.
2214[end disabled clinic input]*/
2215
2216PyDoc_STRVAR(builtin_sorted__doc__,
Serhiy Storchaka3a104252017-01-23 12:29:47 +02002217"sorted($module, iterable, /, *, key=None, reverse=False)\n"
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002218"--\n"
2219"\n"
2220"Return a new list containing all items from the iterable in ascending order.\n"
2221"\n"
Raymond Hettinger7ea386e2016-08-25 21:11:50 -07002222"A custom key function can be supplied to customize the sort order, and the\n"
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002223"reverse flag can be set to request the result in descending order.");
2224
2225#define BUILTIN_SORTED_METHODDEF \
Serhiy Storchaka6969eaf2017-07-03 21:20:15 +03002226 {"sorted", (PyCFunction)builtin_sorted, METH_FASTCALL | METH_KEYWORDS, builtin_sorted__doc__},
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002227
Raymond Hettinger64958a12003-12-17 20:43:33 +00002228static PyObject *
Serhiy Storchakaa5552f02017-12-15 13:11:11 +02002229builtin_sorted(PyObject *self, PyObject *const *args, Py_ssize_t nargs, PyObject *kwnames)
Raymond Hettinger64958a12003-12-17 20:43:33 +00002230{
Serhiy Storchaka7cf8beb2017-01-21 23:05:00 +02002231 PyObject *newlist, *v, *seq, *callable;
Victor Stinner5a60eca2017-01-17 15:17:49 +01002232
Serhiy Storchaka7cf8beb2017-01-21 23:05:00 +02002233 /* Keyword arguments are passed through list.sort() which will check
2234 them. */
2235 if (!_PyArg_UnpackStack(args, nargs, "sorted", 1, 1, &seq))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002236 return NULL;
Raymond Hettinger64958a12003-12-17 20:43:33 +00002237
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002238 newlist = PySequence_List(seq);
2239 if (newlist == NULL)
2240 return NULL;
Raymond Hettinger64958a12003-12-17 20:43:33 +00002241
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02002242 callable = _PyObject_GetAttrId(newlist, &PyId_sort);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002243 if (callable == NULL) {
2244 Py_DECREF(newlist);
2245 return NULL;
2246 }
Georg Brandl99d7e4e2005-08-31 22:21:15 +00002247
Serhiy Storchaka299dc232017-01-20 08:35:18 +02002248 assert(nargs >= 1);
Victor Stinner5a60eca2017-01-17 15:17:49 +01002249 v = _PyObject_FastCallKeywords(callable, args + 1, nargs - 1, kwnames);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002250 Py_DECREF(callable);
2251 if (v == NULL) {
2252 Py_DECREF(newlist);
2253 return NULL;
2254 }
2255 Py_DECREF(v);
2256 return newlist;
Raymond Hettinger64958a12003-12-17 20:43:33 +00002257}
2258
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002259
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002260/* AC: cannot convert yet, as needs PEP 457 group support in inspect */
Guido van Rossum79f25d91997-04-29 20:08:16 +00002261static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002262builtin_vars(PyObject *self, PyObject *args)
Guido van Rossum2d951851994-08-29 12:52:16 +00002263{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002264 PyObject *v = NULL;
2265 PyObject *d;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002266
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002267 if (!PyArg_UnpackTuple(args, "vars", 0, 1, &v))
2268 return NULL;
2269 if (v == NULL) {
2270 d = PyEval_GetLocals();
Victor Stinner41bb43a2013-10-29 01:19:37 +01002271 if (d == NULL)
2272 return NULL;
2273 Py_INCREF(d);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002274 }
2275 else {
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02002276 d = _PyObject_GetAttrId(v, &PyId___dict__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002277 if (d == NULL) {
2278 PyErr_SetString(PyExc_TypeError,
2279 "vars() argument must have __dict__ attribute");
2280 return NULL;
2281 }
2282 }
2283 return d;
Guido van Rossum2d951851994-08-29 12:52:16 +00002284}
2285
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002286PyDoc_STRVAR(vars_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002287"vars([object]) -> dictionary\n\
2288\n\
2289Without arguments, equivalent to locals().\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002290With an argument, equivalent to object.__dict__.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002291
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002292
2293/*[clinic input]
2294sum as builtin_sum
2295
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03002296 iterable: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002297 start: object(c_default="NULL") = 0
2298 /
2299
2300Return the sum of a 'start' value (default: 0) plus an iterable of numbers
2301
2302When the iterable is empty, return the start value.
2303This function is intended specifically for use with numeric values and may
2304reject non-numeric types.
2305[clinic start generated code]*/
2306
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002307static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002308builtin_sum_impl(PyObject *module, PyObject *iterable, PyObject *start)
2309/*[clinic end generated code: output=df758cec7d1d302f input=3b5b7a9d7611c73a]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002310{
2311 PyObject *result = start;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002312 PyObject *temp, *item, *iter;
Alex Martellia70b1912003-04-22 08:12:33 +00002313
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002314 iter = PyObject_GetIter(iterable);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002315 if (iter == NULL)
2316 return NULL;
Alex Martellia70b1912003-04-22 08:12:33 +00002317
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002318 if (result == NULL) {
2319 result = PyLong_FromLong(0);
2320 if (result == NULL) {
2321 Py_DECREF(iter);
2322 return NULL;
2323 }
2324 } else {
2325 /* reject string values for 'start' parameter */
2326 if (PyUnicode_Check(result)) {
2327 PyErr_SetString(PyExc_TypeError,
2328 "sum() can't sum strings [use ''.join(seq) instead]");
2329 Py_DECREF(iter);
2330 return NULL;
2331 }
Benjamin Petersonce071ca2011-07-29 14:23:47 -05002332 if (PyBytes_Check(result)) {
2333 PyErr_SetString(PyExc_TypeError,
2334 "sum() can't sum bytes [use b''.join(seq) instead]");
Benjamin Peterson405f32c2011-07-29 22:43:45 -05002335 Py_DECREF(iter);
Benjamin Petersonce071ca2011-07-29 14:23:47 -05002336 return NULL;
2337 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002338 if (PyByteArray_Check(result)) {
2339 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson4f921c22011-07-29 14:24:29 -05002340 "sum() can't sum bytearray [use b''.join(seq) instead]");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002341 Py_DECREF(iter);
2342 return NULL;
2343 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002344 Py_INCREF(result);
2345 }
Alex Martellia70b1912003-04-22 08:12:33 +00002346
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002347#ifndef SLOW_SUM
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002348 /* Fast addition by keeping temporary sums in C instead of new Python objects.
2349 Assumes all inputs are the same type. If the assumption fails, default
2350 to the more general routine.
2351 */
2352 if (PyLong_CheckExact(result)) {
2353 int overflow;
2354 long i_result = PyLong_AsLongAndOverflow(result, &overflow);
2355 /* If this already overflowed, don't even enter the loop. */
2356 if (overflow == 0) {
2357 Py_DECREF(result);
2358 result = NULL;
2359 }
2360 while(result == NULL) {
2361 item = PyIter_Next(iter);
2362 if (item == NULL) {
2363 Py_DECREF(iter);
2364 if (PyErr_Occurred())
2365 return NULL;
2366 return PyLong_FromLong(i_result);
2367 }
2368 if (PyLong_CheckExact(item)) {
2369 long b = PyLong_AsLongAndOverflow(item, &overflow);
2370 long x = i_result + b;
2371 if (overflow == 0 && ((x^i_result) >= 0 || (x^b) >= 0)) {
2372 i_result = x;
2373 Py_DECREF(item);
2374 continue;
2375 }
2376 }
2377 /* Either overflowed or is not an int. Restore real objects and process normally */
2378 result = PyLong_FromLong(i_result);
Christian Heimes704e2d32013-07-26 22:49:26 +02002379 if (result == NULL) {
2380 Py_DECREF(item);
2381 Py_DECREF(iter);
2382 return NULL;
2383 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002384 temp = PyNumber_Add(result, item);
2385 Py_DECREF(result);
2386 Py_DECREF(item);
2387 result = temp;
2388 if (result == NULL) {
2389 Py_DECREF(iter);
2390 return NULL;
2391 }
2392 }
2393 }
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002394
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002395 if (PyFloat_CheckExact(result)) {
2396 double f_result = PyFloat_AS_DOUBLE(result);
2397 Py_DECREF(result);
2398 result = NULL;
2399 while(result == NULL) {
2400 item = PyIter_Next(iter);
2401 if (item == NULL) {
2402 Py_DECREF(iter);
2403 if (PyErr_Occurred())
2404 return NULL;
2405 return PyFloat_FromDouble(f_result);
2406 }
2407 if (PyFloat_CheckExact(item)) {
2408 PyFPE_START_PROTECT("add", Py_DECREF(item); Py_DECREF(iter); return 0)
2409 f_result += PyFloat_AS_DOUBLE(item);
2410 PyFPE_END_PROTECT(f_result)
2411 Py_DECREF(item);
2412 continue;
2413 }
2414 if (PyLong_CheckExact(item)) {
2415 long value;
2416 int overflow;
2417 value = PyLong_AsLongAndOverflow(item, &overflow);
2418 if (!overflow) {
2419 PyFPE_START_PROTECT("add", Py_DECREF(item); Py_DECREF(iter); return 0)
2420 f_result += (double)value;
2421 PyFPE_END_PROTECT(f_result)
2422 Py_DECREF(item);
2423 continue;
2424 }
2425 }
2426 result = PyFloat_FromDouble(f_result);
2427 temp = PyNumber_Add(result, item);
2428 Py_DECREF(result);
2429 Py_DECREF(item);
2430 result = temp;
2431 if (result == NULL) {
2432 Py_DECREF(iter);
2433 return NULL;
2434 }
2435 }
2436 }
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002437#endif
2438
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002439 for(;;) {
2440 item = PyIter_Next(iter);
2441 if (item == NULL) {
2442 /* error, or end-of-sequence */
2443 if (PyErr_Occurred()) {
2444 Py_DECREF(result);
2445 result = NULL;
2446 }
2447 break;
2448 }
2449 /* It's tempting to use PyNumber_InPlaceAdd instead of
2450 PyNumber_Add here, to avoid quadratic running time
2451 when doing 'sum(list_of_lists, [])'. However, this
2452 would produce a change in behaviour: a snippet like
Mark Dickinson9acadc52009-10-26 14:19:42 +00002453
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002454 empty = []
2455 sum([[x] for x in range(10)], empty)
Mark Dickinson9acadc52009-10-26 14:19:42 +00002456
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002457 would change the value of empty. */
2458 temp = PyNumber_Add(result, item);
2459 Py_DECREF(result);
2460 Py_DECREF(item);
2461 result = temp;
2462 if (result == NULL)
2463 break;
2464 }
2465 Py_DECREF(iter);
2466 return result;
Alex Martellia70b1912003-04-22 08:12:33 +00002467}
2468
Alex Martellia70b1912003-04-22 08:12:33 +00002469
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002470/*[clinic input]
2471isinstance as builtin_isinstance
2472
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03002473 obj: object
2474 class_or_tuple: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002475 /
2476
2477Return whether an object is an instance of a class or of a subclass thereof.
2478
2479A tuple, as in ``isinstance(x, (A, B, ...))``, may be given as the target to
2480check against. This is equivalent to ``isinstance(x, A) or isinstance(x, B)
2481or ...`` etc.
2482[clinic start generated code]*/
2483
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002484static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002485builtin_isinstance_impl(PyObject *module, PyObject *obj,
Larry Hastings89964c42015-04-14 18:07:59 -04002486 PyObject *class_or_tuple)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002487/*[clinic end generated code: output=6faf01472c13b003 input=ffa743db1daf7549]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002488{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002489 int retval;
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002490
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002491 retval = PyObject_IsInstance(obj, class_or_tuple);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002492 if (retval < 0)
2493 return NULL;
2494 return PyBool_FromLong(retval);
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002495}
2496
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002497
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002498/*[clinic input]
2499issubclass as builtin_issubclass
2500
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03002501 cls: object
2502 class_or_tuple: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002503 /
2504
2505Return whether 'cls' is a derived from another class or is the same class.
2506
2507A tuple, as in ``issubclass(x, (A, B, ...))``, may be given as the target to
2508check against. This is equivalent to ``issubclass(x, A) or issubclass(x, B)
2509or ...`` etc.
2510[clinic start generated code]*/
2511
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002512static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002513builtin_issubclass_impl(PyObject *module, PyObject *cls,
Larry Hastings89964c42015-04-14 18:07:59 -04002514 PyObject *class_or_tuple)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002515/*[clinic end generated code: output=358412410cd7a250 input=af5f35e9ceaddaf6]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002516{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002517 int retval;
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002518
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002519 retval = PyObject_IsSubclass(cls, class_or_tuple);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002520 if (retval < 0)
2521 return NULL;
2522 return PyBool_FromLong(retval);
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002523}
2524
2525
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002526typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002527 PyObject_HEAD
2528 Py_ssize_t tuplesize;
2529 PyObject *ittuple; /* tuple of iterators */
2530 PyObject *result;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002531} zipobject;
2532
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002533static PyObject *
2534zip_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
Barry Warsawbd599b52000-08-03 15:45:29 +00002535{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002536 zipobject *lz;
2537 Py_ssize_t i;
2538 PyObject *ittuple; /* tuple of iterators */
2539 PyObject *result;
Serhiy Storchakabf623ae2017-04-19 20:03:52 +03002540 Py_ssize_t tuplesize;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002541
Serhiy Storchaka6cca5c82017-06-08 14:41:19 +03002542 if (type == &PyZip_Type && !_PyArg_NoKeywords("zip", kwds))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002543 return NULL;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002544
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002545 /* args must be a tuple */
2546 assert(PyTuple_Check(args));
Serhiy Storchakabf623ae2017-04-19 20:03:52 +03002547 tuplesize = PyTuple_GET_SIZE(args);
Barry Warsawbd599b52000-08-03 15:45:29 +00002548
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002549 /* obtain iterators */
2550 ittuple = PyTuple_New(tuplesize);
2551 if (ittuple == NULL)
2552 return NULL;
2553 for (i=0; i < tuplesize; ++i) {
2554 PyObject *item = PyTuple_GET_ITEM(args, i);
2555 PyObject *it = PyObject_GetIter(item);
2556 if (it == NULL) {
2557 if (PyErr_ExceptionMatches(PyExc_TypeError))
2558 PyErr_Format(PyExc_TypeError,
2559 "zip argument #%zd must support iteration",
2560 i+1);
2561 Py_DECREF(ittuple);
2562 return NULL;
2563 }
2564 PyTuple_SET_ITEM(ittuple, i, it);
2565 }
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002566
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002567 /* create a result holder */
2568 result = PyTuple_New(tuplesize);
2569 if (result == NULL) {
2570 Py_DECREF(ittuple);
2571 return NULL;
2572 }
2573 for (i=0 ; i < tuplesize ; i++) {
2574 Py_INCREF(Py_None);
2575 PyTuple_SET_ITEM(result, i, Py_None);
2576 }
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002577
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002578 /* create zipobject structure */
2579 lz = (zipobject *)type->tp_alloc(type, 0);
2580 if (lz == NULL) {
2581 Py_DECREF(ittuple);
2582 Py_DECREF(result);
2583 return NULL;
2584 }
2585 lz->ittuple = ittuple;
2586 lz->tuplesize = tuplesize;
2587 lz->result = result;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002588
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002589 return (PyObject *)lz;
Barry Warsawbd599b52000-08-03 15:45:29 +00002590}
2591
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002592static void
2593zip_dealloc(zipobject *lz)
2594{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002595 PyObject_GC_UnTrack(lz);
2596 Py_XDECREF(lz->ittuple);
2597 Py_XDECREF(lz->result);
2598 Py_TYPE(lz)->tp_free(lz);
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002599}
2600
2601static int
2602zip_traverse(zipobject *lz, visitproc visit, void *arg)
2603{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002604 Py_VISIT(lz->ittuple);
2605 Py_VISIT(lz->result);
2606 return 0;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002607}
2608
2609static PyObject *
2610zip_next(zipobject *lz)
2611{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002612 Py_ssize_t i;
2613 Py_ssize_t tuplesize = lz->tuplesize;
2614 PyObject *result = lz->result;
2615 PyObject *it;
2616 PyObject *item;
2617 PyObject *olditem;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002618
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002619 if (tuplesize == 0)
2620 return NULL;
2621 if (Py_REFCNT(result) == 1) {
2622 Py_INCREF(result);
2623 for (i=0 ; i < tuplesize ; i++) {
2624 it = PyTuple_GET_ITEM(lz->ittuple, i);
2625 item = (*Py_TYPE(it)->tp_iternext)(it);
Serhiy Storchaka278d03b2013-04-06 22:52:34 +03002626 if (item == NULL) {
2627 Py_DECREF(result);
2628 return NULL;
2629 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002630 olditem = PyTuple_GET_ITEM(result, i);
2631 PyTuple_SET_ITEM(result, i, item);
2632 Py_DECREF(olditem);
2633 }
2634 } else {
2635 result = PyTuple_New(tuplesize);
2636 if (result == NULL)
Serhiy Storchaka278d03b2013-04-06 22:52:34 +03002637 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002638 for (i=0 ; i < tuplesize ; i++) {
2639 it = PyTuple_GET_ITEM(lz->ittuple, i);
2640 item = (*Py_TYPE(it)->tp_iternext)(it);
Serhiy Storchaka278d03b2013-04-06 22:52:34 +03002641 if (item == NULL) {
2642 Py_DECREF(result);
2643 return NULL;
2644 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002645 PyTuple_SET_ITEM(result, i, item);
2646 }
2647 }
2648 return result;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002649}
Barry Warsawbd599b52000-08-03 15:45:29 +00002650
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002651static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05302652zip_reduce(zipobject *lz, PyObject *Py_UNUSED(ignored))
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002653{
2654 /* Just recreate the zip with the internal iterator tuple */
2655 return Py_BuildValue("OO", Py_TYPE(lz), lz->ittuple);
2656}
2657
2658static PyMethodDef zip_methods[] = {
2659 {"__reduce__", (PyCFunction)zip_reduce, METH_NOARGS, reduce_doc},
2660 {NULL, NULL} /* sentinel */
2661};
2662
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002663PyDoc_STRVAR(zip_doc,
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002664"zip(iter1 [,iter2 [...]]) --> zip object\n\
Barry Warsawbd599b52000-08-03 15:45:29 +00002665\n\
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002666Return a zip object whose .__next__() method returns a tuple where\n\
2667the i-th element comes from the i-th iterable argument. The .__next__()\n\
2668method continues until the shortest iterable in the argument sequence\n\
Georg Brandlced51db2008-12-04 18:28:38 +00002669is exhausted and then it raises StopIteration.");
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002670
2671PyTypeObject PyZip_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002672 PyVarObject_HEAD_INIT(&PyType_Type, 0)
2673 "zip", /* tp_name */
2674 sizeof(zipobject), /* tp_basicsize */
2675 0, /* tp_itemsize */
2676 /* methods */
2677 (destructor)zip_dealloc, /* tp_dealloc */
2678 0, /* tp_print */
2679 0, /* tp_getattr */
2680 0, /* tp_setattr */
2681 0, /* tp_reserved */
2682 0, /* tp_repr */
2683 0, /* tp_as_number */
2684 0, /* tp_as_sequence */
2685 0, /* tp_as_mapping */
2686 0, /* tp_hash */
2687 0, /* tp_call */
2688 0, /* tp_str */
2689 PyObject_GenericGetAttr, /* tp_getattro */
2690 0, /* tp_setattro */
2691 0, /* tp_as_buffer */
2692 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
2693 Py_TPFLAGS_BASETYPE, /* tp_flags */
2694 zip_doc, /* tp_doc */
2695 (traverseproc)zip_traverse, /* tp_traverse */
2696 0, /* tp_clear */
2697 0, /* tp_richcompare */
2698 0, /* tp_weaklistoffset */
2699 PyObject_SelfIter, /* tp_iter */
2700 (iternextfunc)zip_next, /* tp_iternext */
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002701 zip_methods, /* tp_methods */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002702 0, /* tp_members */
2703 0, /* tp_getset */
2704 0, /* tp_base */
2705 0, /* tp_dict */
2706 0, /* tp_descr_get */
2707 0, /* tp_descr_set */
2708 0, /* tp_dictoffset */
2709 0, /* tp_init */
2710 PyType_GenericAlloc, /* tp_alloc */
2711 zip_new, /* tp_new */
2712 PyObject_GC_Del, /* tp_free */
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002713};
Barry Warsawbd599b52000-08-03 15:45:29 +00002714
2715
Guido van Rossum79f25d91997-04-29 20:08:16 +00002716static PyMethodDef builtin_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002717 {"__build_class__", (PyCFunction)builtin___build_class__,
Serhiy Storchaka6969eaf2017-07-03 21:20:15 +03002718 METH_FASTCALL | METH_KEYWORDS, build_class_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002719 {"__import__", (PyCFunction)builtin___import__, METH_VARARGS | METH_KEYWORDS, import_doc},
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002720 BUILTIN_ABS_METHODDEF
2721 BUILTIN_ALL_METHODDEF
2722 BUILTIN_ANY_METHODDEF
2723 BUILTIN_ASCII_METHODDEF
2724 BUILTIN_BIN_METHODDEF
Barry Warsaw36c1d1f2017-10-05 12:11:18 -04002725 {"breakpoint", (PyCFunction)builtin_breakpoint, METH_FASTCALL | METH_KEYWORDS, breakpoint_doc},
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002726 BUILTIN_CALLABLE_METHODDEF
2727 BUILTIN_CHR_METHODDEF
2728 BUILTIN_COMPILE_METHODDEF
2729 BUILTIN_DELATTR_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002730 {"dir", builtin_dir, METH_VARARGS, dir_doc},
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002731 BUILTIN_DIVMOD_METHODDEF
2732 BUILTIN_EVAL_METHODDEF
2733 BUILTIN_EXEC_METHODDEF
2734 BUILTIN_FORMAT_METHODDEF
Victor Stinner84b388b2017-01-17 03:52:27 +01002735 {"getattr", (PyCFunction)builtin_getattr, METH_FASTCALL, getattr_doc},
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002736 BUILTIN_GLOBALS_METHODDEF
2737 BUILTIN_HASATTR_METHODDEF
2738 BUILTIN_HASH_METHODDEF
2739 BUILTIN_HEX_METHODDEF
2740 BUILTIN_ID_METHODDEF
2741 BUILTIN_INPUT_METHODDEF
2742 BUILTIN_ISINSTANCE_METHODDEF
2743 BUILTIN_ISSUBCLASS_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002744 {"iter", builtin_iter, METH_VARARGS, iter_doc},
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002745 BUILTIN_LEN_METHODDEF
2746 BUILTIN_LOCALS_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002747 {"max", (PyCFunction)builtin_max, METH_VARARGS | METH_KEYWORDS, max_doc},
2748 {"min", (PyCFunction)builtin_min, METH_VARARGS | METH_KEYWORDS, min_doc},
Victor Stinnerfda6d0a2017-01-17 04:09:14 +01002749 {"next", (PyCFunction)builtin_next, METH_FASTCALL, next_doc},
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002750 BUILTIN_OCT_METHODDEF
2751 BUILTIN_ORD_METHODDEF
2752 BUILTIN_POW_METHODDEF
Serhiy Storchaka6969eaf2017-07-03 21:20:15 +03002753 {"print", (PyCFunction)builtin_print, METH_FASTCALL | METH_KEYWORDS, print_doc},
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002754 BUILTIN_REPR_METHODDEF
Serhiy Storchakaaca7f572017-11-15 17:51:14 +02002755 BUILTIN_ROUND_METHODDEF
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002756 BUILTIN_SETATTR_METHODDEF
2757 BUILTIN_SORTED_METHODDEF
2758 BUILTIN_SUM_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002759 {"vars", builtin_vars, METH_VARARGS, vars_doc},
2760 {NULL, NULL},
Guido van Rossum3f5da241990-12-20 15:06:42 +00002761};
2762
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002763PyDoc_STRVAR(builtin_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002764"Built-in functions, exceptions, and other objects.\n\
2765\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002766Noteworthy: None is the `nil' object; Ellipsis represents `...' in slices.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002767
Martin v. Löwis1a214512008-06-11 05:26:20 +00002768static struct PyModuleDef builtinsmodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002769 PyModuleDef_HEAD_INIT,
2770 "builtins",
2771 builtin_doc,
2772 -1, /* multiple "initialization" just copies the module dict. */
2773 builtin_methods,
2774 NULL,
2775 NULL,
2776 NULL,
2777 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00002778};
2779
2780
Guido van Rossum25ce5661997-08-02 03:10:38 +00002781PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002782_PyBuiltin_Init(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +00002783{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002784 PyObject *mod, *dict, *debug;
Benjamin Peterson42124a72012-10-30 23:41:54 -04002785
2786 if (PyType_Ready(&PyFilter_Type) < 0 ||
2787 PyType_Ready(&PyMap_Type) < 0 ||
2788 PyType_Ready(&PyZip_Type) < 0)
2789 return NULL;
2790
Eric Snowd393c1b2017-09-14 12:18:12 -06002791 mod = _PyModule_CreateInitialized(&builtinsmodule, PYTHON_API_VERSION);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002792 if (mod == NULL)
2793 return NULL;
2794 dict = PyModule_GetDict(mod);
Tim Peters4b7625e2001-09-13 21:37:17 +00002795
Tim Peters7571a0f2003-03-23 17:52:28 +00002796#ifdef Py_TRACE_REFS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002797 /* "builtins" exposes a number of statically allocated objects
2798 * that, before this code was added in 2.3, never showed up in
2799 * the list of "all objects" maintained by Py_TRACE_REFS. As a
2800 * result, programs leaking references to None and False (etc)
2801 * couldn't be diagnosed by examining sys.getobjects(0).
2802 */
Tim Peters7571a0f2003-03-23 17:52:28 +00002803#define ADD_TO_ALL(OBJECT) _Py_AddToAllObjects((PyObject *)(OBJECT), 0)
2804#else
2805#define ADD_TO_ALL(OBJECT) (void)0
2806#endif
2807
Tim Peters4b7625e2001-09-13 21:37:17 +00002808#define SETBUILTIN(NAME, OBJECT) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002809 if (PyDict_SetItemString(dict, NAME, (PyObject *)OBJECT) < 0) \
2810 return NULL; \
2811 ADD_TO_ALL(OBJECT)
Tim Peters4b7625e2001-09-13 21:37:17 +00002812
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002813 SETBUILTIN("None", Py_None);
2814 SETBUILTIN("Ellipsis", Py_Ellipsis);
2815 SETBUILTIN("NotImplemented", Py_NotImplemented);
2816 SETBUILTIN("False", Py_False);
2817 SETBUILTIN("True", Py_True);
2818 SETBUILTIN("bool", &PyBool_Type);
2819 SETBUILTIN("memoryview", &PyMemoryView_Type);
2820 SETBUILTIN("bytearray", &PyByteArray_Type);
2821 SETBUILTIN("bytes", &PyBytes_Type);
2822 SETBUILTIN("classmethod", &PyClassMethod_Type);
2823 SETBUILTIN("complex", &PyComplex_Type);
2824 SETBUILTIN("dict", &PyDict_Type);
2825 SETBUILTIN("enumerate", &PyEnum_Type);
2826 SETBUILTIN("filter", &PyFilter_Type);
2827 SETBUILTIN("float", &PyFloat_Type);
2828 SETBUILTIN("frozenset", &PyFrozenSet_Type);
2829 SETBUILTIN("property", &PyProperty_Type);
2830 SETBUILTIN("int", &PyLong_Type);
2831 SETBUILTIN("list", &PyList_Type);
2832 SETBUILTIN("map", &PyMap_Type);
2833 SETBUILTIN("object", &PyBaseObject_Type);
2834 SETBUILTIN("range", &PyRange_Type);
2835 SETBUILTIN("reversed", &PyReversed_Type);
2836 SETBUILTIN("set", &PySet_Type);
2837 SETBUILTIN("slice", &PySlice_Type);
2838 SETBUILTIN("staticmethod", &PyStaticMethod_Type);
2839 SETBUILTIN("str", &PyUnicode_Type);
2840 SETBUILTIN("super", &PySuper_Type);
2841 SETBUILTIN("tuple", &PyTuple_Type);
2842 SETBUILTIN("type", &PyType_Type);
2843 SETBUILTIN("zip", &PyZip_Type);
2844 debug = PyBool_FromLong(Py_OptimizeFlag == 0);
2845 if (PyDict_SetItemString(dict, "__debug__", debug) < 0) {
Serhiy Storchakacfdfbb42016-06-18 09:44:03 +03002846 Py_DECREF(debug);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002847 return NULL;
2848 }
Serhiy Storchakacfdfbb42016-06-18 09:44:03 +03002849 Py_DECREF(debug);
Barry Warsaw757af0e1997-08-29 22:13:51 +00002850
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002851 return mod;
Tim Peters7571a0f2003-03-23 17:52:28 +00002852#undef ADD_TO_ALL
Tim Peters4b7625e2001-09-13 21:37:17 +00002853#undef SETBUILTIN
Guido van Rossum3f5da241990-12-20 15:06:42 +00002854}