blob: 88a4bf991d88a408b3daa09df6c49ef130bb4f07 [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
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001642 maxitem = NULL; /* the result */
1643 maxval = NULL; /* the value associated with the result */
1644 while (( item = PyIter_Next(it) )) {
1645 /* get the value from the key function */
1646 if (keyfunc != NULL) {
Victor Stinnerde4ae3d2016-12-04 22:59:09 +01001647 val = PyObject_CallFunctionObjArgs(keyfunc, item, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001648 if (val == NULL)
1649 goto Fail_it_item;
1650 }
1651 /* no key function; the value is the item */
1652 else {
1653 val = item;
1654 Py_INCREF(val);
1655 }
Tim Petersc3074532001-05-03 07:00:32 +00001656
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001657 /* maximum value and item are unset; set them */
1658 if (maxval == NULL) {
1659 maxitem = item;
1660 maxval = val;
1661 }
1662 /* maximum value and item are set; update them as necessary */
1663 else {
1664 int cmp = PyObject_RichCompareBool(val, maxval, op);
1665 if (cmp < 0)
1666 goto Fail_it_item_and_val;
1667 else if (cmp > 0) {
1668 Py_DECREF(maxval);
1669 Py_DECREF(maxitem);
1670 maxval = val;
1671 maxitem = item;
1672 }
1673 else {
1674 Py_DECREF(item);
1675 Py_DECREF(val);
1676 }
1677 }
1678 }
1679 if (PyErr_Occurred())
1680 goto Fail_it;
1681 if (maxval == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001682 assert(maxitem == NULL);
Raymond Hettinger4d6018f2013-06-24 22:43:02 -07001683 if (defaultval != NULL) {
1684 Py_INCREF(defaultval);
1685 maxitem = defaultval;
1686 } else {
1687 PyErr_Format(PyExc_ValueError,
1688 "%s() arg is an empty sequence", name);
1689 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001690 }
1691 else
1692 Py_DECREF(maxval);
1693 Py_DECREF(it);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001694 return maxitem;
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001695
1696Fail_it_item_and_val:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001697 Py_DECREF(val);
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001698Fail_it_item:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001699 Py_DECREF(item);
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001700Fail_it:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001701 Py_XDECREF(maxval);
1702 Py_XDECREF(maxitem);
1703 Py_DECREF(it);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001704 return NULL;
Guido van Rossum3f5da241990-12-20 15:06:42 +00001705}
1706
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001707/* AC: cannot convert yet, waiting for *args support */
Guido van Rossum79f25d91997-04-29 20:08:16 +00001708static PyObject *
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001709builtin_min(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001710{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001711 return min_max(args, kwds, Py_LT);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001712}
1713
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001714PyDoc_STRVAR(min_doc,
Raymond Hettinger2a545822014-05-19 22:20:52 +01001715"min(iterable, *[, default=obj, key=func]) -> value\n\
1716min(arg1, arg2, *args, *[, key=func]) -> value\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001717\n\
Raymond Hettinger2a545822014-05-19 22:20:52 +01001718With a single iterable argument, return its smallest item. The\n\
1719default keyword-only argument specifies an object to return if\n\
1720the provided iterable is empty.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001721With two or more arguments, return the smallest argument.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001722
1723
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001724/* AC: cannot convert yet, waiting for *args support */
Guido van Rossum79f25d91997-04-29 20:08:16 +00001725static PyObject *
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001726builtin_max(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001727{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001728 return min_max(args, kwds, Py_GT);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001729}
1730
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001731PyDoc_STRVAR(max_doc,
Raymond Hettinger2a545822014-05-19 22:20:52 +01001732"max(iterable, *[, default=obj, key=func]) -> value\n\
1733max(arg1, arg2, *args, *[, key=func]) -> value\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001734\n\
Raymond Hettinger2a545822014-05-19 22:20:52 +01001735With a single iterable argument, return its biggest item. The\n\
1736default keyword-only argument specifies an object to return if\n\
1737the provided iterable is empty.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001738With two or more arguments, return the largest argument.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001739
1740
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001741/*[clinic input]
1742oct as builtin_oct
1743
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001744 number: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001745 /
1746
1747Return the octal representation of an integer.
1748
1749 >>> oct(342391)
1750 '0o1234567'
1751[clinic start generated code]*/
1752
Guido van Rossum79f25d91997-04-29 20:08:16 +00001753static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001754builtin_oct(PyObject *module, PyObject *number)
1755/*[clinic end generated code: output=40a34656b6875352 input=ad6b274af4016c72]*/
Guido van Rossum006bcd41991-10-24 14:54:44 +00001756{
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001757 return PyNumber_ToBase(number, 8);
Guido van Rossum006bcd41991-10-24 14:54:44 +00001758}
1759
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001760
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001761/*[clinic input]
1762ord as builtin_ord
1763
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001764 c: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001765 /
1766
1767Return the Unicode code point for a one-character string.
1768[clinic start generated code]*/
1769
Guido van Rossum79f25d91997-04-29 20:08:16 +00001770static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001771builtin_ord(PyObject *module, PyObject *c)
1772/*[clinic end generated code: output=4fa5e87a323bae71 input=3064e5d6203ad012]*/
Guido van Rossum3f5da241990-12-20 15:06:42 +00001773{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001774 long ord;
1775 Py_ssize_t size;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001776
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001777 if (PyBytes_Check(c)) {
1778 size = PyBytes_GET_SIZE(c);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001779 if (size == 1) {
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001780 ord = (long)((unsigned char)*PyBytes_AS_STRING(c));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001781 return PyLong_FromLong(ord);
1782 }
1783 }
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001784 else if (PyUnicode_Check(c)) {
1785 if (PyUnicode_READY(c) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001786 return NULL;
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001787 size = PyUnicode_GET_LENGTH(c);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001788 if (size == 1) {
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001789 ord = (long)PyUnicode_READ_CHAR(c, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001790 return PyLong_FromLong(ord);
1791 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001792 }
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001793 else if (PyByteArray_Check(c)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001794 /* XXX Hopefully this is temporary */
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001795 size = PyByteArray_GET_SIZE(c);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001796 if (size == 1) {
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001797 ord = (long)((unsigned char)*PyByteArray_AS_STRING(c));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001798 return PyLong_FromLong(ord);
1799 }
1800 }
1801 else {
1802 PyErr_Format(PyExc_TypeError,
1803 "ord() expected string of length 1, but " \
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001804 "%.200s found", c->ob_type->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001805 return NULL;
1806 }
Guido van Rossum09095f32000-03-10 23:00:52 +00001807
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001808 PyErr_Format(PyExc_TypeError,
1809 "ord() expected a character, "
1810 "but string of length %zd found",
1811 size);
1812 return NULL;
Guido van Rossum3f5da241990-12-20 15:06:42 +00001813}
1814
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001815
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001816/*[clinic input]
1817pow as builtin_pow
1818
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001819 x: object
1820 y: object
1821 z: object = None
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001822 /
1823
1824Equivalent to x**y (with two arguments) or x**y % z (with three arguments)
1825
1826Some types, such as ints, are able to use a more efficient algorithm when
1827invoked using the three argument form.
1828[clinic start generated code]*/
1829
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001830static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001831builtin_pow_impl(PyObject *module, PyObject *x, PyObject *y, PyObject *z)
1832/*[clinic end generated code: output=50a14d5d130d404b input=653d57d38d41fc07]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001833{
1834 return PyNumber_Power(x, y, z);
1835}
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001836
1837
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001838/* AC: cannot convert yet, waiting for *args support */
Guido van Rossum34343512006-11-30 22:13:52 +00001839static PyObject *
Serhiy Storchakaa5552f02017-12-15 13:11:11 +02001840builtin_print(PyObject *self, PyObject *const *args, Py_ssize_t nargs, PyObject *kwnames)
Guido van Rossum34343512006-11-30 22:13:52 +00001841{
INADA Naokibd584f12017-01-19 12:50:34 +01001842 static const char * const _keywords[] = {"sep", "end", "file", "flush", 0};
1843 static struct _PyArg_Parser _parser = {"|OOOO:print", _keywords, 0};
Georg Brandlbc3b6822012-01-13 19:41:25 +01001844 PyObject *sep = NULL, *end = NULL, *file = NULL, *flush = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001845 int i, err;
Guido van Rossum34343512006-11-30 22:13:52 +00001846
INADA Naokibd584f12017-01-19 12:50:34 +01001847 if (kwnames != NULL &&
1848 !_PyArg_ParseStackAndKeywords(args + nargs, 0, kwnames, &_parser,
1849 &sep, &end, &file, &flush)) {
Georg Brandlbc3b6822012-01-13 19:41:25 +01001850 return NULL;
INADA Naokibd584f12017-01-19 12:50:34 +01001851 }
1852
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001853 if (file == NULL || file == Py_None) {
Victor Stinnerbd303c12013-11-07 23:07:29 +01001854 file = _PySys_GetObjectId(&PyId_stdout);
Victor Stinner1e53bba2013-07-16 22:26:05 +02001855 if (file == NULL) {
1856 PyErr_SetString(PyExc_RuntimeError, "lost sys.stdout");
1857 return NULL;
1858 }
1859
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001860 /* sys.stdout may be None when FILE* stdout isn't connected */
1861 if (file == Py_None)
1862 Py_RETURN_NONE;
1863 }
Guido van Rossum34343512006-11-30 22:13:52 +00001864
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001865 if (sep == Py_None) {
1866 sep = NULL;
1867 }
1868 else if (sep && !PyUnicode_Check(sep)) {
1869 PyErr_Format(PyExc_TypeError,
1870 "sep must be None or a string, not %.200s",
1871 sep->ob_type->tp_name);
1872 return NULL;
1873 }
1874 if (end == Py_None) {
1875 end = NULL;
1876 }
1877 else if (end && !PyUnicode_Check(end)) {
1878 PyErr_Format(PyExc_TypeError,
1879 "end must be None or a string, not %.200s",
1880 end->ob_type->tp_name);
1881 return NULL;
1882 }
Guido van Rossum34343512006-11-30 22:13:52 +00001883
INADA Naokibd584f12017-01-19 12:50:34 +01001884 for (i = 0; i < nargs; i++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001885 if (i > 0) {
1886 if (sep == NULL)
1887 err = PyFile_WriteString(" ", file);
1888 else
1889 err = PyFile_WriteObject(sep, file,
1890 Py_PRINT_RAW);
1891 if (err)
1892 return NULL;
1893 }
INADA Naokibd584f12017-01-19 12:50:34 +01001894 err = PyFile_WriteObject(args[i], file, Py_PRINT_RAW);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001895 if (err)
1896 return NULL;
1897 }
Guido van Rossum34343512006-11-30 22:13:52 +00001898
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001899 if (end == NULL)
1900 err = PyFile_WriteString("\n", file);
1901 else
1902 err = PyFile_WriteObject(end, file, Py_PRINT_RAW);
1903 if (err)
1904 return NULL;
Guido van Rossum34343512006-11-30 22:13:52 +00001905
Georg Brandlbc3b6822012-01-13 19:41:25 +01001906 if (flush != NULL) {
1907 PyObject *tmp;
1908 int do_flush = PyObject_IsTrue(flush);
1909 if (do_flush == -1)
1910 return NULL;
1911 else if (do_flush) {
Victor Stinner3466bde2016-09-05 18:16:01 -07001912 tmp = _PyObject_CallMethodId(file, &PyId_flush, NULL);
Georg Brandlbc3b6822012-01-13 19:41:25 +01001913 if (tmp == NULL)
1914 return NULL;
1915 else
1916 Py_DECREF(tmp);
1917 }
1918 }
1919
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001920 Py_RETURN_NONE;
Guido van Rossum34343512006-11-30 22:13:52 +00001921}
1922
1923PyDoc_STRVAR(print_doc,
Senthil Kumarane9175bd2012-08-10 13:53:45 -07001924"print(value, ..., sep=' ', end='\\n', file=sys.stdout, flush=False)\n\
Guido van Rossum34343512006-11-30 22:13:52 +00001925\n\
1926Prints the values to a stream, or to sys.stdout by default.\n\
1927Optional keyword arguments:\n\
Senthil Kumarane9175bd2012-08-10 13:53:45 -07001928file: a file-like object (stream); defaults to the current sys.stdout.\n\
1929sep: string inserted between values, default a space.\n\
1930end: string appended after the last value, default a newline.\n\
1931flush: whether to forcibly flush the stream.");
Guido van Rossum34343512006-11-30 22:13:52 +00001932
1933
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001934/*[clinic input]
1935input as builtin_input
1936
1937 prompt: object(c_default="NULL") = None
1938 /
1939
1940Read a string from standard input. The trailing newline is stripped.
1941
1942The prompt string, if given, is printed to standard output without a
1943trailing newline before reading input.
1944
1945If the user hits EOF (*nix: Ctrl-D, Windows: Ctrl-Z+Return), raise EOFError.
1946On *nix systems, readline is used if available.
1947[clinic start generated code]*/
1948
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001949static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001950builtin_input_impl(PyObject *module, PyObject *prompt)
1951/*[clinic end generated code: output=83db5a191e7a0d60 input=5e8bb70c2908fe3c]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001952{
Victor Stinnerbd303c12013-11-07 23:07:29 +01001953 PyObject *fin = _PySys_GetObjectId(&PyId_stdin);
1954 PyObject *fout = _PySys_GetObjectId(&PyId_stdout);
1955 PyObject *ferr = _PySys_GetObjectId(&PyId_stderr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001956 PyObject *tmp;
1957 long fd;
1958 int tty;
Guido van Rossuma88a0332007-02-26 16:59:55 +00001959
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001960 /* Check that stdin/out/err are intact */
1961 if (fin == NULL || fin == Py_None) {
1962 PyErr_SetString(PyExc_RuntimeError,
1963 "input(): lost sys.stdin");
1964 return NULL;
1965 }
1966 if (fout == NULL || fout == Py_None) {
1967 PyErr_SetString(PyExc_RuntimeError,
1968 "input(): lost sys.stdout");
1969 return NULL;
1970 }
1971 if (ferr == NULL || ferr == Py_None) {
1972 PyErr_SetString(PyExc_RuntimeError,
1973 "input(): lost sys.stderr");
1974 return NULL;
1975 }
Guido van Rossumeba76962007-05-27 09:13:28 +00001976
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001977 /* First of all, flush stderr */
Victor Stinner3466bde2016-09-05 18:16:01 -07001978 tmp = _PyObject_CallMethodId(ferr, &PyId_flush, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001979 if (tmp == NULL)
1980 PyErr_Clear();
1981 else
1982 Py_DECREF(tmp);
Guido van Rossumeba76962007-05-27 09:13:28 +00001983
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001984 /* We should only use (GNU) readline if Python's sys.stdin and
1985 sys.stdout are the same as C's stdin and stdout, because we
1986 need to pass it those. */
Victor Stinner3466bde2016-09-05 18:16:01 -07001987 tmp = _PyObject_CallMethodId(fin, &PyId_fileno, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001988 if (tmp == NULL) {
1989 PyErr_Clear();
1990 tty = 0;
1991 }
1992 else {
1993 fd = PyLong_AsLong(tmp);
1994 Py_DECREF(tmp);
1995 if (fd < 0 && PyErr_Occurred())
1996 return NULL;
1997 tty = fd == fileno(stdin) && isatty(fd);
1998 }
1999 if (tty) {
Victor Stinner3466bde2016-09-05 18:16:01 -07002000 tmp = _PyObject_CallMethodId(fout, &PyId_fileno, NULL);
Martin Panterc9a6ab52015-10-10 01:25:38 +00002001 if (tmp == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002002 PyErr_Clear();
Martin Panterc9a6ab52015-10-10 01:25:38 +00002003 tty = 0;
2004 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002005 else {
2006 fd = PyLong_AsLong(tmp);
2007 Py_DECREF(tmp);
2008 if (fd < 0 && PyErr_Occurred())
2009 return NULL;
2010 tty = fd == fileno(stdout) && isatty(fd);
2011 }
2012 }
Guido van Rossumeba76962007-05-27 09:13:28 +00002013
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002014 /* If we're interactive, use (GNU) readline */
2015 if (tty) {
Antoine Pitrou0d776b12011-11-06 00:34:26 +01002016 PyObject *po = NULL;
Serhiy Storchakae2f92de2017-11-11 13:06:26 +02002017 const char *promptstr;
Antoine Pitrou0d776b12011-11-06 00:34:26 +01002018 char *s = NULL;
2019 PyObject *stdin_encoding = NULL, *stdin_errors = NULL;
2020 PyObject *stdout_encoding = NULL, *stdout_errors = NULL;
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +02002021 const char *stdin_encoding_str, *stdin_errors_str;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002022 PyObject *result;
Victor Stinnerc0f1a1a2011-02-23 12:07:37 +00002023 size_t len;
Martin v. Löwis4a7b5d52007-09-04 05:24:49 +00002024
Serhiy Storchakac2cf1282017-03-12 13:50:36 +02002025 /* stdin is a text stream, so it must have an encoding. */
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02002026 stdin_encoding = _PyObject_GetAttrId(fin, &PyId_encoding);
Antoine Pitrou5ee9d8a2011-11-06 00:38:45 +01002027 stdin_errors = _PyObject_GetAttrId(fin, &PyId_errors);
Serhiy Storchakac2cf1282017-03-12 13:50:36 +02002028 if (!stdin_encoding || !stdin_errors ||
2029 !PyUnicode_Check(stdin_encoding) ||
2030 !PyUnicode_Check(stdin_errors)) {
2031 tty = 0;
Antoine Pitrou0d776b12011-11-06 00:34:26 +01002032 goto _readline_errors;
Serhiy Storchakac2cf1282017-03-12 13:50:36 +02002033 }
Serhiy Storchaka06515832016-11-20 09:13:07 +02002034 stdin_encoding_str = PyUnicode_AsUTF8(stdin_encoding);
2035 stdin_errors_str = PyUnicode_AsUTF8(stdin_errors);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01002036 if (!stdin_encoding_str || !stdin_errors_str)
2037 goto _readline_errors;
Victor Stinner3466bde2016-09-05 18:16:01 -07002038 tmp = _PyObject_CallMethodId(fout, &PyId_flush, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002039 if (tmp == NULL)
2040 PyErr_Clear();
2041 else
2042 Py_DECREF(tmp);
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002043 if (prompt != NULL) {
Antoine Pitrou0d776b12011-11-06 00:34:26 +01002044 /* We have a prompt, encode it as stdout would */
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +02002045 const char *stdout_encoding_str, *stdout_errors_str;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002046 PyObject *stringpo;
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02002047 stdout_encoding = _PyObject_GetAttrId(fout, &PyId_encoding);
Antoine Pitrou5ee9d8a2011-11-06 00:38:45 +01002048 stdout_errors = _PyObject_GetAttrId(fout, &PyId_errors);
Serhiy Storchakac2cf1282017-03-12 13:50:36 +02002049 if (!stdout_encoding || !stdout_errors ||
2050 !PyUnicode_Check(stdout_encoding) ||
2051 !PyUnicode_Check(stdout_errors)) {
2052 tty = 0;
Antoine Pitrou0d776b12011-11-06 00:34:26 +01002053 goto _readline_errors;
Serhiy Storchakac2cf1282017-03-12 13:50:36 +02002054 }
Serhiy Storchaka06515832016-11-20 09:13:07 +02002055 stdout_encoding_str = PyUnicode_AsUTF8(stdout_encoding);
2056 stdout_errors_str = PyUnicode_AsUTF8(stdout_errors);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01002057 if (!stdout_encoding_str || !stdout_errors_str)
2058 goto _readline_errors;
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002059 stringpo = PyObject_Str(prompt);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01002060 if (stringpo == NULL)
2061 goto _readline_errors;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002062 po = PyUnicode_AsEncodedString(stringpo,
Antoine Pitrou0d776b12011-11-06 00:34:26 +01002063 stdout_encoding_str, stdout_errors_str);
2064 Py_CLEAR(stdout_encoding);
2065 Py_CLEAR(stdout_errors);
2066 Py_CLEAR(stringpo);
2067 if (po == NULL)
2068 goto _readline_errors;
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03002069 assert(PyBytes_Check(po));
2070 promptstr = PyBytes_AS_STRING(po);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002071 }
2072 else {
2073 po = NULL;
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002074 promptstr = "";
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002075 }
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002076 s = PyOS_Readline(stdin, stdout, promptstr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002077 if (s == NULL) {
Richard Oudkerk614c5782013-04-03 13:44:50 +01002078 PyErr_CheckSignals();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002079 if (!PyErr_Occurred())
2080 PyErr_SetNone(PyExc_KeyboardInterrupt);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01002081 goto _readline_errors;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002082 }
Victor Stinnerc0f1a1a2011-02-23 12:07:37 +00002083
2084 len = strlen(s);
2085 if (len == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002086 PyErr_SetNone(PyExc_EOFError);
2087 result = NULL;
2088 }
Victor Stinnerc0f1a1a2011-02-23 12:07:37 +00002089 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002090 if (len > PY_SSIZE_T_MAX) {
2091 PyErr_SetString(PyExc_OverflowError,
2092 "input: input too long");
2093 result = NULL;
2094 }
2095 else {
Victor Stinnerc0f1a1a2011-02-23 12:07:37 +00002096 len--; /* strip trailing '\n' */
2097 if (len != 0 && s[len-1] == '\r')
2098 len--; /* strip trailing '\r' */
Antoine Pitrou0d776b12011-11-06 00:34:26 +01002099 result = PyUnicode_Decode(s, len, stdin_encoding_str,
2100 stdin_errors_str);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002101 }
2102 }
2103 Py_DECREF(stdin_encoding);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01002104 Py_DECREF(stdin_errors);
2105 Py_XDECREF(po);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002106 PyMem_FREE(s);
2107 return result;
Serhiy Storchakac2cf1282017-03-12 13:50:36 +02002108
Antoine Pitrou0d776b12011-11-06 00:34:26 +01002109 _readline_errors:
2110 Py_XDECREF(stdin_encoding);
2111 Py_XDECREF(stdout_encoding);
2112 Py_XDECREF(stdin_errors);
2113 Py_XDECREF(stdout_errors);
2114 Py_XDECREF(po);
Serhiy Storchakac2cf1282017-03-12 13:50:36 +02002115 if (tty)
2116 return NULL;
2117
2118 PyErr_Clear();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002119 }
Guido van Rossumeba76962007-05-27 09:13:28 +00002120
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002121 /* Fallback if we're not interactive */
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002122 if (prompt != NULL) {
2123 if (PyFile_WriteObject(prompt, fout, Py_PRINT_RAW) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002124 return NULL;
2125 }
Victor Stinner3466bde2016-09-05 18:16:01 -07002126 tmp = _PyObject_CallMethodId(fout, &PyId_flush, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002127 if (tmp == NULL)
2128 PyErr_Clear();
2129 else
2130 Py_DECREF(tmp);
2131 return PyFile_GetLine(fin, -1);
Guido van Rossuma88a0332007-02-26 16:59:55 +00002132}
2133
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002134
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002135/*[clinic input]
2136repr as builtin_repr
2137
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03002138 obj: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002139 /
2140
2141Return the canonical string representation of the object.
2142
2143For many object types, including most builtins, eval(repr(obj)) == obj.
2144[clinic start generated code]*/
2145
Guido van Rossum79f25d91997-04-29 20:08:16 +00002146static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002147builtin_repr(PyObject *module, PyObject *obj)
2148/*[clinic end generated code: output=7ed3778c44fd0194 input=1c9e6d66d3e3be04]*/
Guido van Rossumc89705d1992-11-26 08:54:07 +00002149{
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002150 return PyObject_Repr(obj);
Guido van Rossumc89705d1992-11-26 08:54:07 +00002151}
2152
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002153
Serhiy Storchakaaca7f572017-11-15 17:51:14 +02002154/*[clinic input]
2155round as builtin_round
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002156
Serhiy Storchakaaca7f572017-11-15 17:51:14 +02002157 number: object
2158 ndigits: object = NULL
2159
2160Round a number to a given precision in decimal digits.
2161
2162The return value is an integer if ndigits is omitted or None. Otherwise
2163the return value has the same type as the number. ndigits may be negative.
2164[clinic start generated code]*/
2165
2166static PyObject *
2167builtin_round_impl(PyObject *module, PyObject *number, PyObject *ndigits)
2168/*[clinic end generated code: output=ff0d9dd176c02ede input=854bc3a217530c3d]*/
2169{
2170 PyObject *round, *result;
Alex Martelliae211f92007-08-22 23:21:33 +00002171
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002172 if (Py_TYPE(number)->tp_dict == NULL) {
2173 if (PyType_Ready(Py_TYPE(number)) < 0)
2174 return NULL;
2175 }
Guido van Rossum15d3d042007-08-24 02:02:45 +00002176
Benjamin Peterson214a7d22013-04-13 17:19:01 -04002177 round = _PyObject_LookupSpecial(number, &PyId___round__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002178 if (round == NULL) {
Benjamin Peterson214a7d22013-04-13 17:19:01 -04002179 if (!PyErr_Occurred())
2180 PyErr_Format(PyExc_TypeError,
2181 "type %.100s doesn't define __round__ method",
2182 Py_TYPE(number)->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002183 return NULL;
2184 }
Alex Martelliae211f92007-08-22 23:21:33 +00002185
Raymond Hettingerf0f1c232016-09-03 01:55:11 -07002186 if (ndigits == NULL || ndigits == Py_None)
Victor Stinnerf17c3de2016-12-06 18:46:19 +01002187 result = _PyObject_CallNoArg(round);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002188 else
Victor Stinnerde4ae3d2016-12-04 22:59:09 +01002189 result = PyObject_CallFunctionObjArgs(round, ndigits, NULL);
Benjamin Peterson214a7d22013-04-13 17:19:01 -04002190 Py_DECREF(round);
2191 return result;
Guido van Rossum9e51f9b1993-02-12 16:29:05 +00002192}
2193
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002194
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002195/*AC: we need to keep the kwds dict intact to easily call into the
2196 * list.sort method, which isn't currently supported in AC. So we just use
2197 * the initially generated signature with a custom implementation.
2198 */
2199/* [disabled clinic input]
2200sorted as builtin_sorted
2201
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03002202 iterable as seq: object
2203 key as keyfunc: object = None
2204 reverse: object = False
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002205
2206Return a new list containing all items from the iterable in ascending order.
2207
Raymond Hettinger7ea386e2016-08-25 21:11:50 -07002208A custom key function can be supplied to customize the sort order, and the
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002209reverse flag can be set to request the result in descending order.
2210[end disabled clinic input]*/
2211
2212PyDoc_STRVAR(builtin_sorted__doc__,
Serhiy Storchaka3a104252017-01-23 12:29:47 +02002213"sorted($module, iterable, /, *, key=None, reverse=False)\n"
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002214"--\n"
2215"\n"
2216"Return a new list containing all items from the iterable in ascending order.\n"
2217"\n"
Raymond Hettinger7ea386e2016-08-25 21:11:50 -07002218"A custom key function can be supplied to customize the sort order, and the\n"
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002219"reverse flag can be set to request the result in descending order.");
2220
2221#define BUILTIN_SORTED_METHODDEF \
Serhiy Storchaka6969eaf2017-07-03 21:20:15 +03002222 {"sorted", (PyCFunction)builtin_sorted, METH_FASTCALL | METH_KEYWORDS, builtin_sorted__doc__},
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002223
Raymond Hettinger64958a12003-12-17 20:43:33 +00002224static PyObject *
Serhiy Storchakaa5552f02017-12-15 13:11:11 +02002225builtin_sorted(PyObject *self, PyObject *const *args, Py_ssize_t nargs, PyObject *kwnames)
Raymond Hettinger64958a12003-12-17 20:43:33 +00002226{
Serhiy Storchaka7cf8beb2017-01-21 23:05:00 +02002227 PyObject *newlist, *v, *seq, *callable;
Victor Stinner5a60eca2017-01-17 15:17:49 +01002228
Serhiy Storchaka7cf8beb2017-01-21 23:05:00 +02002229 /* Keyword arguments are passed through list.sort() which will check
2230 them. */
2231 if (!_PyArg_UnpackStack(args, nargs, "sorted", 1, 1, &seq))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002232 return NULL;
Raymond Hettinger64958a12003-12-17 20:43:33 +00002233
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002234 newlist = PySequence_List(seq);
2235 if (newlist == NULL)
2236 return NULL;
Raymond Hettinger64958a12003-12-17 20:43:33 +00002237
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02002238 callable = _PyObject_GetAttrId(newlist, &PyId_sort);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002239 if (callable == NULL) {
2240 Py_DECREF(newlist);
2241 return NULL;
2242 }
Georg Brandl99d7e4e2005-08-31 22:21:15 +00002243
Serhiy Storchaka299dc232017-01-20 08:35:18 +02002244 assert(nargs >= 1);
Victor Stinner5a60eca2017-01-17 15:17:49 +01002245 v = _PyObject_FastCallKeywords(callable, args + 1, nargs - 1, kwnames);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002246 Py_DECREF(callable);
2247 if (v == NULL) {
2248 Py_DECREF(newlist);
2249 return NULL;
2250 }
2251 Py_DECREF(v);
2252 return newlist;
Raymond Hettinger64958a12003-12-17 20:43:33 +00002253}
2254
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002255
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002256/* AC: cannot convert yet, as needs PEP 457 group support in inspect */
Guido van Rossum79f25d91997-04-29 20:08:16 +00002257static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002258builtin_vars(PyObject *self, PyObject *args)
Guido van Rossum2d951851994-08-29 12:52:16 +00002259{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002260 PyObject *v = NULL;
2261 PyObject *d;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002262
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002263 if (!PyArg_UnpackTuple(args, "vars", 0, 1, &v))
2264 return NULL;
2265 if (v == NULL) {
2266 d = PyEval_GetLocals();
Victor Stinner41bb43a2013-10-29 01:19:37 +01002267 if (d == NULL)
2268 return NULL;
2269 Py_INCREF(d);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002270 }
2271 else {
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02002272 d = _PyObject_GetAttrId(v, &PyId___dict__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002273 if (d == NULL) {
2274 PyErr_SetString(PyExc_TypeError,
2275 "vars() argument must have __dict__ attribute");
2276 return NULL;
2277 }
2278 }
2279 return d;
Guido van Rossum2d951851994-08-29 12:52:16 +00002280}
2281
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002282PyDoc_STRVAR(vars_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002283"vars([object]) -> dictionary\n\
2284\n\
2285Without arguments, equivalent to locals().\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002286With an argument, equivalent to object.__dict__.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002287
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002288
2289/*[clinic input]
2290sum as builtin_sum
2291
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03002292 iterable: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002293 start: object(c_default="NULL") = 0
2294 /
2295
2296Return the sum of a 'start' value (default: 0) plus an iterable of numbers
2297
2298When the iterable is empty, return the start value.
2299This function is intended specifically for use with numeric values and may
2300reject non-numeric types.
2301[clinic start generated code]*/
2302
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002303static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002304builtin_sum_impl(PyObject *module, PyObject *iterable, PyObject *start)
2305/*[clinic end generated code: output=df758cec7d1d302f input=3b5b7a9d7611c73a]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002306{
2307 PyObject *result = start;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002308 PyObject *temp, *item, *iter;
Alex Martellia70b1912003-04-22 08:12:33 +00002309
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002310 iter = PyObject_GetIter(iterable);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002311 if (iter == NULL)
2312 return NULL;
Alex Martellia70b1912003-04-22 08:12:33 +00002313
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002314 if (result == NULL) {
2315 result = PyLong_FromLong(0);
2316 if (result == NULL) {
2317 Py_DECREF(iter);
2318 return NULL;
2319 }
2320 } else {
2321 /* reject string values for 'start' parameter */
2322 if (PyUnicode_Check(result)) {
2323 PyErr_SetString(PyExc_TypeError,
2324 "sum() can't sum strings [use ''.join(seq) instead]");
2325 Py_DECREF(iter);
2326 return NULL;
2327 }
Benjamin Petersonce071ca2011-07-29 14:23:47 -05002328 if (PyBytes_Check(result)) {
2329 PyErr_SetString(PyExc_TypeError,
2330 "sum() can't sum bytes [use b''.join(seq) instead]");
Benjamin Peterson405f32c2011-07-29 22:43:45 -05002331 Py_DECREF(iter);
Benjamin Petersonce071ca2011-07-29 14:23:47 -05002332 return NULL;
2333 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002334 if (PyByteArray_Check(result)) {
2335 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson4f921c22011-07-29 14:24:29 -05002336 "sum() can't sum bytearray [use b''.join(seq) instead]");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002337 Py_DECREF(iter);
2338 return NULL;
2339 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002340 Py_INCREF(result);
2341 }
Alex Martellia70b1912003-04-22 08:12:33 +00002342
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002343#ifndef SLOW_SUM
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002344 /* Fast addition by keeping temporary sums in C instead of new Python objects.
2345 Assumes all inputs are the same type. If the assumption fails, default
2346 to the more general routine.
2347 */
2348 if (PyLong_CheckExact(result)) {
2349 int overflow;
2350 long i_result = PyLong_AsLongAndOverflow(result, &overflow);
2351 /* If this already overflowed, don't even enter the loop. */
2352 if (overflow == 0) {
2353 Py_DECREF(result);
2354 result = NULL;
2355 }
2356 while(result == NULL) {
2357 item = PyIter_Next(iter);
2358 if (item == NULL) {
2359 Py_DECREF(iter);
2360 if (PyErr_Occurred())
2361 return NULL;
2362 return PyLong_FromLong(i_result);
2363 }
2364 if (PyLong_CheckExact(item)) {
2365 long b = PyLong_AsLongAndOverflow(item, &overflow);
2366 long x = i_result + b;
2367 if (overflow == 0 && ((x^i_result) >= 0 || (x^b) >= 0)) {
2368 i_result = x;
2369 Py_DECREF(item);
2370 continue;
2371 }
2372 }
2373 /* Either overflowed or is not an int. Restore real objects and process normally */
2374 result = PyLong_FromLong(i_result);
Christian Heimes704e2d32013-07-26 22:49:26 +02002375 if (result == NULL) {
2376 Py_DECREF(item);
2377 Py_DECREF(iter);
2378 return NULL;
2379 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002380 temp = PyNumber_Add(result, item);
2381 Py_DECREF(result);
2382 Py_DECREF(item);
2383 result = temp;
2384 if (result == NULL) {
2385 Py_DECREF(iter);
2386 return NULL;
2387 }
2388 }
2389 }
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002390
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002391 if (PyFloat_CheckExact(result)) {
2392 double f_result = PyFloat_AS_DOUBLE(result);
2393 Py_DECREF(result);
2394 result = NULL;
2395 while(result == NULL) {
2396 item = PyIter_Next(iter);
2397 if (item == NULL) {
2398 Py_DECREF(iter);
2399 if (PyErr_Occurred())
2400 return NULL;
2401 return PyFloat_FromDouble(f_result);
2402 }
2403 if (PyFloat_CheckExact(item)) {
2404 PyFPE_START_PROTECT("add", Py_DECREF(item); Py_DECREF(iter); return 0)
2405 f_result += PyFloat_AS_DOUBLE(item);
2406 PyFPE_END_PROTECT(f_result)
2407 Py_DECREF(item);
2408 continue;
2409 }
2410 if (PyLong_CheckExact(item)) {
2411 long value;
2412 int overflow;
2413 value = PyLong_AsLongAndOverflow(item, &overflow);
2414 if (!overflow) {
2415 PyFPE_START_PROTECT("add", Py_DECREF(item); Py_DECREF(iter); return 0)
2416 f_result += (double)value;
2417 PyFPE_END_PROTECT(f_result)
2418 Py_DECREF(item);
2419 continue;
2420 }
2421 }
2422 result = PyFloat_FromDouble(f_result);
2423 temp = PyNumber_Add(result, item);
2424 Py_DECREF(result);
2425 Py_DECREF(item);
2426 result = temp;
2427 if (result == NULL) {
2428 Py_DECREF(iter);
2429 return NULL;
2430 }
2431 }
2432 }
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002433#endif
2434
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002435 for(;;) {
2436 item = PyIter_Next(iter);
2437 if (item == NULL) {
2438 /* error, or end-of-sequence */
2439 if (PyErr_Occurred()) {
2440 Py_DECREF(result);
2441 result = NULL;
2442 }
2443 break;
2444 }
2445 /* It's tempting to use PyNumber_InPlaceAdd instead of
2446 PyNumber_Add here, to avoid quadratic running time
2447 when doing 'sum(list_of_lists, [])'. However, this
2448 would produce a change in behaviour: a snippet like
Mark Dickinson9acadc52009-10-26 14:19:42 +00002449
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002450 empty = []
2451 sum([[x] for x in range(10)], empty)
Mark Dickinson9acadc52009-10-26 14:19:42 +00002452
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002453 would change the value of empty. */
2454 temp = PyNumber_Add(result, item);
2455 Py_DECREF(result);
2456 Py_DECREF(item);
2457 result = temp;
2458 if (result == NULL)
2459 break;
2460 }
2461 Py_DECREF(iter);
2462 return result;
Alex Martellia70b1912003-04-22 08:12:33 +00002463}
2464
Alex Martellia70b1912003-04-22 08:12:33 +00002465
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002466/*[clinic input]
2467isinstance as builtin_isinstance
2468
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03002469 obj: object
2470 class_or_tuple: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002471 /
2472
2473Return whether an object is an instance of a class or of a subclass thereof.
2474
2475A tuple, as in ``isinstance(x, (A, B, ...))``, may be given as the target to
2476check against. This is equivalent to ``isinstance(x, A) or isinstance(x, B)
2477or ...`` etc.
2478[clinic start generated code]*/
2479
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002480static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002481builtin_isinstance_impl(PyObject *module, PyObject *obj,
Larry Hastings89964c42015-04-14 18:07:59 -04002482 PyObject *class_or_tuple)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002483/*[clinic end generated code: output=6faf01472c13b003 input=ffa743db1daf7549]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002484{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002485 int retval;
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002486
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002487 retval = PyObject_IsInstance(obj, class_or_tuple);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002488 if (retval < 0)
2489 return NULL;
2490 return PyBool_FromLong(retval);
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002491}
2492
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002493
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002494/*[clinic input]
2495issubclass as builtin_issubclass
2496
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03002497 cls: object
2498 class_or_tuple: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002499 /
2500
2501Return whether 'cls' is a derived from another class or is the same class.
2502
2503A tuple, as in ``issubclass(x, (A, B, ...))``, may be given as the target to
2504check against. This is equivalent to ``issubclass(x, A) or issubclass(x, B)
2505or ...`` etc.
2506[clinic start generated code]*/
2507
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002508static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002509builtin_issubclass_impl(PyObject *module, PyObject *cls,
Larry Hastings89964c42015-04-14 18:07:59 -04002510 PyObject *class_or_tuple)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002511/*[clinic end generated code: output=358412410cd7a250 input=af5f35e9ceaddaf6]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002512{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002513 int retval;
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002514
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002515 retval = PyObject_IsSubclass(cls, class_or_tuple);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002516 if (retval < 0)
2517 return NULL;
2518 return PyBool_FromLong(retval);
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002519}
2520
2521
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002522typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002523 PyObject_HEAD
2524 Py_ssize_t tuplesize;
2525 PyObject *ittuple; /* tuple of iterators */
2526 PyObject *result;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002527} zipobject;
2528
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002529static PyObject *
2530zip_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
Barry Warsawbd599b52000-08-03 15:45:29 +00002531{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002532 zipobject *lz;
2533 Py_ssize_t i;
2534 PyObject *ittuple; /* tuple of iterators */
2535 PyObject *result;
Serhiy Storchakabf623ae2017-04-19 20:03:52 +03002536 Py_ssize_t tuplesize;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002537
Serhiy Storchaka6cca5c82017-06-08 14:41:19 +03002538 if (type == &PyZip_Type && !_PyArg_NoKeywords("zip", kwds))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002539 return NULL;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002540
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002541 /* args must be a tuple */
2542 assert(PyTuple_Check(args));
Serhiy Storchakabf623ae2017-04-19 20:03:52 +03002543 tuplesize = PyTuple_GET_SIZE(args);
Barry Warsawbd599b52000-08-03 15:45:29 +00002544
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002545 /* obtain iterators */
2546 ittuple = PyTuple_New(tuplesize);
2547 if (ittuple == NULL)
2548 return NULL;
2549 for (i=0; i < tuplesize; ++i) {
2550 PyObject *item = PyTuple_GET_ITEM(args, i);
2551 PyObject *it = PyObject_GetIter(item);
2552 if (it == NULL) {
2553 if (PyErr_ExceptionMatches(PyExc_TypeError))
2554 PyErr_Format(PyExc_TypeError,
2555 "zip argument #%zd must support iteration",
2556 i+1);
2557 Py_DECREF(ittuple);
2558 return NULL;
2559 }
2560 PyTuple_SET_ITEM(ittuple, i, it);
2561 }
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002562
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002563 /* create a result holder */
2564 result = PyTuple_New(tuplesize);
2565 if (result == NULL) {
2566 Py_DECREF(ittuple);
2567 return NULL;
2568 }
2569 for (i=0 ; i < tuplesize ; i++) {
2570 Py_INCREF(Py_None);
2571 PyTuple_SET_ITEM(result, i, Py_None);
2572 }
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002573
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002574 /* create zipobject structure */
2575 lz = (zipobject *)type->tp_alloc(type, 0);
2576 if (lz == NULL) {
2577 Py_DECREF(ittuple);
2578 Py_DECREF(result);
2579 return NULL;
2580 }
2581 lz->ittuple = ittuple;
2582 lz->tuplesize = tuplesize;
2583 lz->result = result;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002584
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002585 return (PyObject *)lz;
Barry Warsawbd599b52000-08-03 15:45:29 +00002586}
2587
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002588static void
2589zip_dealloc(zipobject *lz)
2590{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002591 PyObject_GC_UnTrack(lz);
2592 Py_XDECREF(lz->ittuple);
2593 Py_XDECREF(lz->result);
2594 Py_TYPE(lz)->tp_free(lz);
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002595}
2596
2597static int
2598zip_traverse(zipobject *lz, visitproc visit, void *arg)
2599{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002600 Py_VISIT(lz->ittuple);
2601 Py_VISIT(lz->result);
2602 return 0;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002603}
2604
2605static PyObject *
2606zip_next(zipobject *lz)
2607{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002608 Py_ssize_t i;
2609 Py_ssize_t tuplesize = lz->tuplesize;
2610 PyObject *result = lz->result;
2611 PyObject *it;
2612 PyObject *item;
2613 PyObject *olditem;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002614
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002615 if (tuplesize == 0)
2616 return NULL;
2617 if (Py_REFCNT(result) == 1) {
2618 Py_INCREF(result);
2619 for (i=0 ; i < tuplesize ; i++) {
2620 it = PyTuple_GET_ITEM(lz->ittuple, i);
2621 item = (*Py_TYPE(it)->tp_iternext)(it);
Serhiy Storchaka278d03b2013-04-06 22:52:34 +03002622 if (item == NULL) {
2623 Py_DECREF(result);
2624 return NULL;
2625 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002626 olditem = PyTuple_GET_ITEM(result, i);
2627 PyTuple_SET_ITEM(result, i, item);
2628 Py_DECREF(olditem);
2629 }
2630 } else {
2631 result = PyTuple_New(tuplesize);
2632 if (result == NULL)
Serhiy Storchaka278d03b2013-04-06 22:52:34 +03002633 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002634 for (i=0 ; i < tuplesize ; i++) {
2635 it = PyTuple_GET_ITEM(lz->ittuple, i);
2636 item = (*Py_TYPE(it)->tp_iternext)(it);
Serhiy Storchaka278d03b2013-04-06 22:52:34 +03002637 if (item == NULL) {
2638 Py_DECREF(result);
2639 return NULL;
2640 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002641 PyTuple_SET_ITEM(result, i, item);
2642 }
2643 }
2644 return result;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002645}
Barry Warsawbd599b52000-08-03 15:45:29 +00002646
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002647static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05302648zip_reduce(zipobject *lz, PyObject *Py_UNUSED(ignored))
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002649{
2650 /* Just recreate the zip with the internal iterator tuple */
2651 return Py_BuildValue("OO", Py_TYPE(lz), lz->ittuple);
2652}
2653
2654static PyMethodDef zip_methods[] = {
2655 {"__reduce__", (PyCFunction)zip_reduce, METH_NOARGS, reduce_doc},
2656 {NULL, NULL} /* sentinel */
2657};
2658
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002659PyDoc_STRVAR(zip_doc,
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002660"zip(iter1 [,iter2 [...]]) --> zip object\n\
Barry Warsawbd599b52000-08-03 15:45:29 +00002661\n\
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002662Return a zip object whose .__next__() method returns a tuple where\n\
2663the i-th element comes from the i-th iterable argument. The .__next__()\n\
2664method continues until the shortest iterable in the argument sequence\n\
Georg Brandlced51db2008-12-04 18:28:38 +00002665is exhausted and then it raises StopIteration.");
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002666
2667PyTypeObject PyZip_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002668 PyVarObject_HEAD_INIT(&PyType_Type, 0)
2669 "zip", /* tp_name */
2670 sizeof(zipobject), /* tp_basicsize */
2671 0, /* tp_itemsize */
2672 /* methods */
2673 (destructor)zip_dealloc, /* tp_dealloc */
2674 0, /* tp_print */
2675 0, /* tp_getattr */
2676 0, /* tp_setattr */
2677 0, /* tp_reserved */
2678 0, /* tp_repr */
2679 0, /* tp_as_number */
2680 0, /* tp_as_sequence */
2681 0, /* tp_as_mapping */
2682 0, /* tp_hash */
2683 0, /* tp_call */
2684 0, /* tp_str */
2685 PyObject_GenericGetAttr, /* tp_getattro */
2686 0, /* tp_setattro */
2687 0, /* tp_as_buffer */
2688 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
2689 Py_TPFLAGS_BASETYPE, /* tp_flags */
2690 zip_doc, /* tp_doc */
2691 (traverseproc)zip_traverse, /* tp_traverse */
2692 0, /* tp_clear */
2693 0, /* tp_richcompare */
2694 0, /* tp_weaklistoffset */
2695 PyObject_SelfIter, /* tp_iter */
2696 (iternextfunc)zip_next, /* tp_iternext */
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002697 zip_methods, /* tp_methods */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002698 0, /* tp_members */
2699 0, /* tp_getset */
2700 0, /* tp_base */
2701 0, /* tp_dict */
2702 0, /* tp_descr_get */
2703 0, /* tp_descr_set */
2704 0, /* tp_dictoffset */
2705 0, /* tp_init */
2706 PyType_GenericAlloc, /* tp_alloc */
2707 zip_new, /* tp_new */
2708 PyObject_GC_Del, /* tp_free */
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002709};
Barry Warsawbd599b52000-08-03 15:45:29 +00002710
2711
Guido van Rossum79f25d91997-04-29 20:08:16 +00002712static PyMethodDef builtin_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002713 {"__build_class__", (PyCFunction)builtin___build_class__,
Serhiy Storchaka6969eaf2017-07-03 21:20:15 +03002714 METH_FASTCALL | METH_KEYWORDS, build_class_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002715 {"__import__", (PyCFunction)builtin___import__, METH_VARARGS | METH_KEYWORDS, import_doc},
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002716 BUILTIN_ABS_METHODDEF
2717 BUILTIN_ALL_METHODDEF
2718 BUILTIN_ANY_METHODDEF
2719 BUILTIN_ASCII_METHODDEF
2720 BUILTIN_BIN_METHODDEF
Barry Warsaw36c1d1f2017-10-05 12:11:18 -04002721 {"breakpoint", (PyCFunction)builtin_breakpoint, METH_FASTCALL | METH_KEYWORDS, breakpoint_doc},
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002722 BUILTIN_CALLABLE_METHODDEF
2723 BUILTIN_CHR_METHODDEF
2724 BUILTIN_COMPILE_METHODDEF
2725 BUILTIN_DELATTR_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002726 {"dir", builtin_dir, METH_VARARGS, dir_doc},
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002727 BUILTIN_DIVMOD_METHODDEF
2728 BUILTIN_EVAL_METHODDEF
2729 BUILTIN_EXEC_METHODDEF
2730 BUILTIN_FORMAT_METHODDEF
Victor Stinner84b388b2017-01-17 03:52:27 +01002731 {"getattr", (PyCFunction)builtin_getattr, METH_FASTCALL, getattr_doc},
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002732 BUILTIN_GLOBALS_METHODDEF
2733 BUILTIN_HASATTR_METHODDEF
2734 BUILTIN_HASH_METHODDEF
2735 BUILTIN_HEX_METHODDEF
2736 BUILTIN_ID_METHODDEF
2737 BUILTIN_INPUT_METHODDEF
2738 BUILTIN_ISINSTANCE_METHODDEF
2739 BUILTIN_ISSUBCLASS_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002740 {"iter", builtin_iter, METH_VARARGS, iter_doc},
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002741 BUILTIN_LEN_METHODDEF
2742 BUILTIN_LOCALS_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002743 {"max", (PyCFunction)builtin_max, METH_VARARGS | METH_KEYWORDS, max_doc},
2744 {"min", (PyCFunction)builtin_min, METH_VARARGS | METH_KEYWORDS, min_doc},
Victor Stinnerfda6d0a2017-01-17 04:09:14 +01002745 {"next", (PyCFunction)builtin_next, METH_FASTCALL, next_doc},
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002746 BUILTIN_OCT_METHODDEF
2747 BUILTIN_ORD_METHODDEF
2748 BUILTIN_POW_METHODDEF
Serhiy Storchaka6969eaf2017-07-03 21:20:15 +03002749 {"print", (PyCFunction)builtin_print, METH_FASTCALL | METH_KEYWORDS, print_doc},
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002750 BUILTIN_REPR_METHODDEF
Serhiy Storchakaaca7f572017-11-15 17:51:14 +02002751 BUILTIN_ROUND_METHODDEF
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002752 BUILTIN_SETATTR_METHODDEF
2753 BUILTIN_SORTED_METHODDEF
2754 BUILTIN_SUM_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002755 {"vars", builtin_vars, METH_VARARGS, vars_doc},
2756 {NULL, NULL},
Guido van Rossum3f5da241990-12-20 15:06:42 +00002757};
2758
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002759PyDoc_STRVAR(builtin_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002760"Built-in functions, exceptions, and other objects.\n\
2761\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002762Noteworthy: None is the `nil' object; Ellipsis represents `...' in slices.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002763
Martin v. Löwis1a214512008-06-11 05:26:20 +00002764static struct PyModuleDef builtinsmodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002765 PyModuleDef_HEAD_INIT,
2766 "builtins",
2767 builtin_doc,
2768 -1, /* multiple "initialization" just copies the module dict. */
2769 builtin_methods,
2770 NULL,
2771 NULL,
2772 NULL,
2773 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00002774};
2775
2776
Guido van Rossum25ce5661997-08-02 03:10:38 +00002777PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002778_PyBuiltin_Init(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +00002779{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002780 PyObject *mod, *dict, *debug;
Benjamin Peterson42124a72012-10-30 23:41:54 -04002781
2782 if (PyType_Ready(&PyFilter_Type) < 0 ||
2783 PyType_Ready(&PyMap_Type) < 0 ||
2784 PyType_Ready(&PyZip_Type) < 0)
2785 return NULL;
2786
Eric Snowd393c1b2017-09-14 12:18:12 -06002787 mod = _PyModule_CreateInitialized(&builtinsmodule, PYTHON_API_VERSION);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002788 if (mod == NULL)
2789 return NULL;
2790 dict = PyModule_GetDict(mod);
Tim Peters4b7625e2001-09-13 21:37:17 +00002791
Tim Peters7571a0f2003-03-23 17:52:28 +00002792#ifdef Py_TRACE_REFS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002793 /* "builtins" exposes a number of statically allocated objects
2794 * that, before this code was added in 2.3, never showed up in
2795 * the list of "all objects" maintained by Py_TRACE_REFS. As a
2796 * result, programs leaking references to None and False (etc)
2797 * couldn't be diagnosed by examining sys.getobjects(0).
2798 */
Tim Peters7571a0f2003-03-23 17:52:28 +00002799#define ADD_TO_ALL(OBJECT) _Py_AddToAllObjects((PyObject *)(OBJECT), 0)
2800#else
2801#define ADD_TO_ALL(OBJECT) (void)0
2802#endif
2803
Tim Peters4b7625e2001-09-13 21:37:17 +00002804#define SETBUILTIN(NAME, OBJECT) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002805 if (PyDict_SetItemString(dict, NAME, (PyObject *)OBJECT) < 0) \
2806 return NULL; \
2807 ADD_TO_ALL(OBJECT)
Tim Peters4b7625e2001-09-13 21:37:17 +00002808
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002809 SETBUILTIN("None", Py_None);
2810 SETBUILTIN("Ellipsis", Py_Ellipsis);
2811 SETBUILTIN("NotImplemented", Py_NotImplemented);
2812 SETBUILTIN("False", Py_False);
2813 SETBUILTIN("True", Py_True);
2814 SETBUILTIN("bool", &PyBool_Type);
2815 SETBUILTIN("memoryview", &PyMemoryView_Type);
2816 SETBUILTIN("bytearray", &PyByteArray_Type);
2817 SETBUILTIN("bytes", &PyBytes_Type);
2818 SETBUILTIN("classmethod", &PyClassMethod_Type);
2819 SETBUILTIN("complex", &PyComplex_Type);
2820 SETBUILTIN("dict", &PyDict_Type);
2821 SETBUILTIN("enumerate", &PyEnum_Type);
2822 SETBUILTIN("filter", &PyFilter_Type);
2823 SETBUILTIN("float", &PyFloat_Type);
2824 SETBUILTIN("frozenset", &PyFrozenSet_Type);
2825 SETBUILTIN("property", &PyProperty_Type);
2826 SETBUILTIN("int", &PyLong_Type);
2827 SETBUILTIN("list", &PyList_Type);
2828 SETBUILTIN("map", &PyMap_Type);
2829 SETBUILTIN("object", &PyBaseObject_Type);
2830 SETBUILTIN("range", &PyRange_Type);
2831 SETBUILTIN("reversed", &PyReversed_Type);
2832 SETBUILTIN("set", &PySet_Type);
2833 SETBUILTIN("slice", &PySlice_Type);
2834 SETBUILTIN("staticmethod", &PyStaticMethod_Type);
2835 SETBUILTIN("str", &PyUnicode_Type);
2836 SETBUILTIN("super", &PySuper_Type);
2837 SETBUILTIN("tuple", &PyTuple_Type);
2838 SETBUILTIN("type", &PyType_Type);
2839 SETBUILTIN("zip", &PyZip_Type);
2840 debug = PyBool_FromLong(Py_OptimizeFlag == 0);
2841 if (PyDict_SetItemString(dict, "__debug__", debug) < 0) {
Serhiy Storchakacfdfbb42016-06-18 09:44:03 +03002842 Py_DECREF(debug);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002843 return NULL;
2844 }
Serhiy Storchakacfdfbb42016-06-18 09:44:03 +03002845 Py_DECREF(debug);
Barry Warsaw757af0e1997-08-29 22:13:51 +00002846
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002847 return mod;
Tim Peters7571a0f2003-03-23 17:52:28 +00002848#undef ADD_TO_ALL
Tim Peters4b7625e2001-09-13 21:37:17 +00002849#undef SETBUILTIN
Guido van Rossum3f5da241990-12-20 15:06:42 +00002850}