blob: 7fc2261ec643136a5eccb2a724ccde4e8af2f29b [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 }
74 meth = _PyObject_GetAttrId(base, &PyId___mro_entries__);
75 if (!meth) {
76 if (!PyErr_ExceptionMatches(PyExc_AttributeError)) {
77 goto error;
78 }
79 PyErr_Clear();
80 if (new_bases) {
81 if (PyList_Append(new_bases, base) < 0) {
82 goto error;
83 }
84 }
85 continue;
86 }
87 new_base = _PyObject_FastCall(meth, stack, 1);
88 Py_DECREF(meth);
89 if (!new_base) {
90 goto error;
91 }
92 if (!PyTuple_Check(new_base)) {
93 PyErr_SetString(PyExc_TypeError,
94 "__mro_entries__ must return a tuple");
95 Py_DECREF(new_base);
96 goto error;
97 }
98 if (!new_bases) {
99 /* If this is a first successful replacement, create new_bases list and
100 copy previously encountered bases. */
101 if (!(new_bases = PyList_New(i))) {
102 goto error;
103 }
104 for (j = 0; j < i; j++) {
105 base = args[j];
106 PyList_SET_ITEM(new_bases, j, base);
107 Py_INCREF(base);
108 }
109 }
110 j = PyList_GET_SIZE(new_bases);
111 if (PyList_SetSlice(new_bases, j, j, new_base) < 0) {
112 goto error;
113 }
114 Py_DECREF(new_base);
115 }
116 if (!new_bases) {
117 return bases;
118 }
119 result = PyList_AsTuple(new_bases);
120 Py_DECREF(new_bases);
121 return result;
122
123error:
124 Py_XDECREF(new_bases);
125 return NULL;
126}
127
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000128/* AC: cannot convert yet, waiting for *args support */
Guido van Rossum79f25d91997-04-29 20:08:16 +0000129static PyObject *
Serhiy Storchakaa5552f02017-12-15 13:11:11 +0200130builtin___build_class__(PyObject *self, PyObject *const *args, Py_ssize_t nargs,
Victor Stinner773dc6d2017-01-16 23:46:26 +0100131 PyObject *kwnames)
Guido van Rossum52cc1d82007-03-18 15:41:51 +0000132{
Ivan Levkivskyi2b5fd1e2017-12-14 23:32:56 +0100133 PyObject *func, *name, *bases, *mkw, *meta, *winner, *prep, *ns, *orig_bases;
Nick Coghlan19d24672016-12-05 16:47:55 +1000134 PyObject *cls = NULL, *cell = NULL;
Victor Stinner0c39b1b2015-03-18 15:02:06 +0100135 int isclass = 0; /* initialize to prevent gcc warning */
Guido van Rossum52cc1d82007-03-18 15:41:51 +0000136
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000137 if (nargs < 2) {
138 PyErr_SetString(PyExc_TypeError,
139 "__build_class__: not enough arguments");
140 return NULL;
141 }
Victor Stinner773dc6d2017-01-16 23:46:26 +0100142 func = args[0]; /* Better be callable */
Benjamin Petersone8e14592013-05-16 14:37:25 -0500143 if (!PyFunction_Check(func)) {
144 PyErr_SetString(PyExc_TypeError,
Zachary Ware9b338722014-08-05 14:01:10 -0500145 "__build_class__: func must be a function");
Benjamin Petersone8e14592013-05-16 14:37:25 -0500146 return NULL;
147 }
Victor Stinner773dc6d2017-01-16 23:46:26 +0100148 name = args[1];
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000149 if (!PyUnicode_Check(name)) {
150 PyErr_SetString(PyExc_TypeError,
151 "__build_class__: name is not a string");
152 return NULL;
153 }
Ivan Levkivskyi2b5fd1e2017-12-14 23:32:56 +0100154 orig_bases = _PyStack_AsTupleSlice(args, nargs, 2, nargs);
155 if (orig_bases == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000156 return NULL;
Guido van Rossum52cc1d82007-03-18 15:41:51 +0000157
Ivan Levkivskyi2b5fd1e2017-12-14 23:32:56 +0100158 bases = update_bases(orig_bases, args + 2, nargs - 2);
159 if (bases == NULL) {
160 Py_DECREF(orig_bases);
161 return NULL;
162 }
163
Victor Stinner773dc6d2017-01-16 23:46:26 +0100164 if (kwnames == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000165 meta = NULL;
166 mkw = NULL;
167 }
168 else {
Victor Stinner773dc6d2017-01-16 23:46:26 +0100169 mkw = _PyStack_AsDict(args + nargs, kwnames);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000170 if (mkw == NULL) {
171 Py_DECREF(bases);
172 return NULL;
Guido van Rossum52cc1d82007-03-18 15:41:51 +0000173 }
Victor Stinner773dc6d2017-01-16 23:46:26 +0100174
Victor Stinnerae9f1612013-11-06 22:46:51 +0100175 meta = _PyDict_GetItemId(mkw, &PyId_metaclass);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000176 if (meta != NULL) {
177 Py_INCREF(meta);
Victor Stinnerae9f1612013-11-06 22:46:51 +0100178 if (_PyDict_DelItemId(mkw, &PyId_metaclass) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000179 Py_DECREF(meta);
180 Py_DECREF(mkw);
181 Py_DECREF(bases);
182 return NULL;
183 }
Nick Coghlande31b192011-10-23 22:04:16 +1000184 /* metaclass is explicitly given, check if it's indeed a class */
185 isclass = PyType_Check(meta);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000186 }
187 }
188 if (meta == NULL) {
Nick Coghlande31b192011-10-23 22:04:16 +1000189 /* if there are no bases, use type: */
190 if (PyTuple_GET_SIZE(bases) == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000191 meta = (PyObject *) (&PyType_Type);
Nick Coghlande31b192011-10-23 22:04:16 +1000192 }
193 /* else get the type of the first base */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000194 else {
195 PyObject *base0 = PyTuple_GET_ITEM(bases, 0);
196 meta = (PyObject *) (base0->ob_type);
197 }
198 Py_INCREF(meta);
Nick Coghlande31b192011-10-23 22:04:16 +1000199 isclass = 1; /* meta is really a class */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000200 }
Nick Coghlan9715d262011-10-23 22:36:42 +1000201
Nick Coghlande31b192011-10-23 22:04:16 +1000202 if (isclass) {
203 /* meta is really a class, so check for a more derived
204 metaclass, or possible metaclass conflicts: */
205 winner = (PyObject *)_PyType_CalculateMetaclass((PyTypeObject *)meta,
206 bases);
207 if (winner == NULL) {
208 Py_DECREF(meta);
209 Py_XDECREF(mkw);
210 Py_DECREF(bases);
211 return NULL;
212 }
213 if (winner != meta) {
214 Py_DECREF(meta);
215 meta = winner;
216 Py_INCREF(meta);
217 }
218 }
219 /* else: meta is not a class, so we cannot do the metaclass
220 calculation, so we will use the explicitly given object as it is */
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +0200221 prep = _PyObject_GetAttrId(meta, &PyId___prepare__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000222 if (prep == NULL) {
223 if (PyErr_ExceptionMatches(PyExc_AttributeError)) {
224 PyErr_Clear();
Eric Snow4f29e752016-09-08 15:11:11 -0700225 ns = PyDict_New();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000226 }
227 else {
228 Py_DECREF(meta);
229 Py_XDECREF(mkw);
230 Py_DECREF(bases);
231 return NULL;
232 }
233 }
234 else {
Victor Stinner463b86a2016-08-22 23:33:13 +0200235 PyObject *pargs[2] = {name, bases};
236 ns = _PyObject_FastCallDict(prep, pargs, 2, mkw);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000237 Py_DECREF(prep);
238 }
239 if (ns == NULL) {
240 Py_DECREF(meta);
241 Py_XDECREF(mkw);
242 Py_DECREF(bases);
243 return NULL;
244 }
Oren Milman5837d042017-09-27 17:04:37 +0300245 if (!PyMapping_Check(ns)) {
246 PyErr_Format(PyExc_TypeError,
247 "%.200s.__prepare__() must return a mapping, not %.200s",
248 isclass ? ((PyTypeObject *)meta)->tp_name : "<metaclass>",
249 Py_TYPE(ns)->tp_name);
250 goto error;
251 }
Nick Coghlan19d24672016-12-05 16:47:55 +1000252 cell = PyEval_EvalCodeEx(PyFunction_GET_CODE(func), PyFunction_GET_GLOBALS(func), ns,
Benjamin Petersone8e14592013-05-16 14:37:25 -0500253 NULL, 0, NULL, 0, NULL, 0, NULL,
254 PyFunction_GET_CLOSURE(func));
Nick Coghlan19d24672016-12-05 16:47:55 +1000255 if (cell != NULL) {
Ivan Levkivskyi2b5fd1e2017-12-14 23:32:56 +0100256 if (bases != orig_bases) {
257 if (PyMapping_SetItemString(ns, "__orig_bases__", orig_bases) < 0) {
258 goto error;
259 }
260 }
Victor Stinnerd1c2a8e2016-08-23 01:34:35 +0200261 PyObject *margs[3] = {name, bases, ns};
262 cls = _PyObject_FastCallDict(meta, margs, 3, mkw);
Nick Coghlan19d24672016-12-05 16:47:55 +1000263 if (cls != NULL && PyType_Check(cls) && PyCell_Check(cell)) {
264 PyObject *cell_cls = PyCell_GET(cell);
265 if (cell_cls != cls) {
266 /* TODO: In 3.7, DeprecationWarning will become RuntimeError.
267 * At that point, cell_error won't be needed.
268 */
269 int cell_error;
270 if (cell_cls == NULL) {
271 const char *msg =
272 "__class__ not set defining %.200R as %.200R. "
273 "Was __classcell__ propagated to type.__new__?";
274 cell_error = PyErr_WarnFormat(
275 PyExc_DeprecationWarning, 1, msg, name, cls);
276 } else {
277 const char *msg =
278 "__class__ set to %.200R defining %.200R as %.200R";
279 PyErr_Format(PyExc_TypeError, msg, cell_cls, name, cls);
280 cell_error = 1;
281 }
282 if (cell_error) {
283 Py_DECREF(cls);
284 cls = NULL;
285 goto error;
286 } else {
287 /* Fill in the cell, since type.__new__ didn't do it */
288 PyCell_Set(cell, cls);
289 }
290 }
291 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000292 }
Nick Coghlan19d24672016-12-05 16:47:55 +1000293error:
294 Py_XDECREF(cell);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000295 Py_DECREF(ns);
296 Py_DECREF(meta);
297 Py_XDECREF(mkw);
298 Py_DECREF(bases);
Ivan Levkivskyi2b5fd1e2017-12-14 23:32:56 +0100299 if (bases != orig_bases) {
300 Py_DECREF(orig_bases);
301 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000302 return cls;
Guido van Rossum52cc1d82007-03-18 15:41:51 +0000303}
304
305PyDoc_STRVAR(build_class_doc,
306"__build_class__(func, name, *bases, metaclass=None, **kwds) -> class\n\
307\n\
308Internal helper function used by the class statement.");
309
310static PyObject *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000311builtin___import__(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000312{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000313 static char *kwlist[] = {"name", "globals", "locals", "fromlist",
314 "level", 0};
Victor Stinnerfe93faf2011-03-14 15:54:52 -0400315 PyObject *name, *globals = NULL, *locals = NULL, *fromlist = NULL;
Brett Cannonfd074152012-04-14 14:10:13 -0400316 int level = 0;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000317
Victor Stinnerfe93faf2011-03-14 15:54:52 -0400318 if (!PyArg_ParseTupleAndKeywords(args, kwds, "U|OOOi:__import__",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000319 kwlist, &name, &globals, &locals, &fromlist, &level))
320 return NULL;
Victor Stinnerfe93faf2011-03-14 15:54:52 -0400321 return PyImport_ImportModuleLevelObject(name, globals, locals,
322 fromlist, level);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000323}
324
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000325PyDoc_STRVAR(import_doc,
Brett Cannoncb4996a2012-08-06 16:34:44 -0400326"__import__(name, globals=None, locals=None, fromlist=(), level=0) -> module\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000327\n\
Brett Cannon5305a992010-09-27 21:08:38 +0000328Import a module. Because this function is meant for use by the Python\n\
329interpreter and not for general use it is better to use\n\
330importlib.import_module() to programmatically import a module.\n\
331\n\
332The globals argument is only used to determine the context;\n\
333they are not modified. The locals argument is unused. The fromlist\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000334should be a list of names to emulate ``from name import ...'', or an\n\
335empty list to emulate ``import name''.\n\
336When importing a module from a package, note that __import__('A.B', ...)\n\
337returns package A when fromlist is empty, but its submodule B when\n\
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000338fromlist is not empty. Level is used to determine whether to perform \n\
Brett Cannon722d3ae2012-07-30 17:45:54 -0400339absolute or relative imports. 0 is absolute while a positive number\n\
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000340is the number of parent directories to search relative to the current module.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000341
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000342
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000343/*[clinic input]
344abs as builtin_abs
345
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300346 x: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000347 /
348
349Return the absolute value of the argument.
350[clinic start generated code]*/
351
Guido van Rossum79f25d91997-04-29 20:08:16 +0000352static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300353builtin_abs(PyObject *module, PyObject *x)
354/*[clinic end generated code: output=b1b433b9e51356f5 input=bed4ca14e29c20d1]*/
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000355{
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000356 return PyNumber_Absolute(x);
Guido van Rossum3f5da241990-12-20 15:06:42 +0000357}
358
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000359/*[clinic input]
360all as builtin_all
361
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300362 iterable: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000363 /
364
365Return True if bool(x) is True for all values x in the iterable.
366
367If the iterable is empty, return True.
368[clinic start generated code]*/
369
Raymond Hettinger96229b12005-03-11 06:49:40 +0000370static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300371builtin_all(PyObject *module, PyObject *iterable)
372/*[clinic end generated code: output=ca2a7127276f79b3 input=1a7c5d1bc3438a21]*/
Raymond Hettinger96229b12005-03-11 06:49:40 +0000373{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000374 PyObject *it, *item;
375 PyObject *(*iternext)(PyObject *);
376 int cmp;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000377
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000378 it = PyObject_GetIter(iterable);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000379 if (it == NULL)
380 return NULL;
381 iternext = *Py_TYPE(it)->tp_iternext;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000382
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000383 for (;;) {
384 item = iternext(it);
385 if (item == NULL)
386 break;
387 cmp = PyObject_IsTrue(item);
388 Py_DECREF(item);
389 if (cmp < 0) {
390 Py_DECREF(it);
391 return NULL;
392 }
393 if (cmp == 0) {
394 Py_DECREF(it);
395 Py_RETURN_FALSE;
396 }
397 }
398 Py_DECREF(it);
399 if (PyErr_Occurred()) {
400 if (PyErr_ExceptionMatches(PyExc_StopIteration))
401 PyErr_Clear();
402 else
403 return NULL;
404 }
405 Py_RETURN_TRUE;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000406}
407
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000408/*[clinic input]
409any as builtin_any
410
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300411 iterable: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000412 /
413
414Return True if bool(x) is True for any x in the iterable.
415
416If the iterable is empty, return False.
417[clinic start generated code]*/
418
Raymond Hettinger96229b12005-03-11 06:49:40 +0000419static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300420builtin_any(PyObject *module, PyObject *iterable)
421/*[clinic end generated code: output=fa65684748caa60e input=41d7451c23384f24]*/
Raymond Hettinger96229b12005-03-11 06:49:40 +0000422{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000423 PyObject *it, *item;
424 PyObject *(*iternext)(PyObject *);
425 int cmp;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000426
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000427 it = PyObject_GetIter(iterable);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000428 if (it == NULL)
429 return NULL;
430 iternext = *Py_TYPE(it)->tp_iternext;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000431
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000432 for (;;) {
433 item = iternext(it);
434 if (item == NULL)
435 break;
436 cmp = PyObject_IsTrue(item);
437 Py_DECREF(item);
438 if (cmp < 0) {
439 Py_DECREF(it);
440 return NULL;
441 }
Raymond Hettinger5098b582015-10-09 00:42:47 -0400442 if (cmp > 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000443 Py_DECREF(it);
444 Py_RETURN_TRUE;
445 }
446 }
447 Py_DECREF(it);
448 if (PyErr_Occurred()) {
449 if (PyErr_ExceptionMatches(PyExc_StopIteration))
450 PyErr_Clear();
451 else
452 return NULL;
453 }
454 Py_RETURN_FALSE;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000455}
456
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000457/*[clinic input]
458ascii as builtin_ascii
459
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300460 obj: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000461 /
462
463Return an ASCII-only representation of an object.
464
465As repr(), return a string containing a printable representation of an
466object, but escape the non-ASCII characters in the string returned by
467repr() using \\x, \\u or \\U escapes. This generates a string similar
468to that returned by repr() in Python 2.
469[clinic start generated code]*/
470
Georg Brandl559e5d72008-06-11 18:37:52 +0000471static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300472builtin_ascii(PyObject *module, PyObject *obj)
473/*[clinic end generated code: output=6d37b3f0984c7eb9 input=4c62732e1b3a3cc9]*/
Georg Brandl559e5d72008-06-11 18:37:52 +0000474{
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000475 return PyObject_ASCII(obj);
Georg Brandl559e5d72008-06-11 18:37:52 +0000476}
477
Georg Brandl559e5d72008-06-11 18:37:52 +0000478
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000479/*[clinic input]
480bin as builtin_bin
481
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300482 number: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000483 /
484
485Return the binary representation of an integer.
486
487 >>> bin(2796202)
488 '0b1010101010101010101010'
489[clinic start generated code]*/
490
Guido van Rossum79f25d91997-04-29 20:08:16 +0000491static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300492builtin_bin(PyObject *module, PyObject *number)
493/*[clinic end generated code: output=b6fc4ad5e649f4f7 input=53f8a0264bacaf90]*/
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000494{
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000495 return PyNumber_ToBase(number, 2);
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000496}
497
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000498
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000499/*[clinic input]
500callable as builtin_callable
501
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300502 obj: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000503 /
504
505Return whether the object is callable (i.e., some kind of function).
506
507Note that classes are callable, as are instances of classes with a
508__call__() method.
509[clinic start generated code]*/
510
Antoine Pitroue71362d2010-11-27 22:00:11 +0000511static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300512builtin_callable(PyObject *module, PyObject *obj)
513/*[clinic end generated code: output=2b095d59d934cb7e input=1423bab99cc41f58]*/
Antoine Pitroue71362d2010-11-27 22:00:11 +0000514{
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000515 return PyBool_FromLong((long)PyCallable_Check(obj));
Antoine Pitroue71362d2010-11-27 22:00:11 +0000516}
517
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400518static PyObject *
Serhiy Storchakaa5552f02017-12-15 13:11:11 +0200519builtin_breakpoint(PyObject *self, PyObject *const *args, Py_ssize_t nargs, PyObject *keywords)
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400520{
521 PyObject *hook = PySys_GetObject("breakpointhook");
522
523 if (hook == NULL) {
524 PyErr_SetString(PyExc_RuntimeError, "lost sys.breakpointhook");
525 return NULL;
526 }
527 Py_INCREF(hook);
528 PyObject *retval = _PyObject_FastCallKeywords(hook, args, nargs, keywords);
529 Py_DECREF(hook);
530 return retval;
531}
532
533PyDoc_STRVAR(breakpoint_doc,
534"breakpoint(*args, **kws)\n\
535\n\
536Call sys.breakpointhook(*args, **kws). sys.breakpointhook() must accept\n\
537whatever arguments are passed.\n\
538\n\
539By default, this drops you into the pdb debugger.");
Antoine Pitroue71362d2010-11-27 22:00:11 +0000540
Raymond Hettinger17301e92008-03-13 00:19:26 +0000541typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000542 PyObject_HEAD
543 PyObject *func;
544 PyObject *it;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000545} filterobject;
546
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000547static PyObject *
Raymond Hettinger17301e92008-03-13 00:19:26 +0000548filter_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
Guido van Rossum12d12c51993-10-26 17:58:25 +0000549{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000550 PyObject *func, *seq;
551 PyObject *it;
552 filterobject *lz;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000553
Serhiy Storchaka6cca5c82017-06-08 14:41:19 +0300554 if (type == &PyFilter_Type && !_PyArg_NoKeywords("filter", kwds))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000555 return NULL;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000556
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000557 if (!PyArg_UnpackTuple(args, "filter", 2, 2, &func, &seq))
558 return NULL;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000559
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000560 /* Get iterator. */
561 it = PyObject_GetIter(seq);
562 if (it == NULL)
563 return NULL;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000564
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000565 /* create filterobject structure */
566 lz = (filterobject *)type->tp_alloc(type, 0);
567 if (lz == NULL) {
568 Py_DECREF(it);
569 return NULL;
570 }
571 Py_INCREF(func);
572 lz->func = func;
573 lz->it = it;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000574
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000575 return (PyObject *)lz;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000576}
577
578static void
579filter_dealloc(filterobject *lz)
580{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000581 PyObject_GC_UnTrack(lz);
582 Py_XDECREF(lz->func);
583 Py_XDECREF(lz->it);
584 Py_TYPE(lz)->tp_free(lz);
Raymond Hettinger17301e92008-03-13 00:19:26 +0000585}
586
587static int
588filter_traverse(filterobject *lz, visitproc visit, void *arg)
589{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000590 Py_VISIT(lz->it);
591 Py_VISIT(lz->func);
592 return 0;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000593}
594
595static PyObject *
596filter_next(filterobject *lz)
597{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000598 PyObject *item;
599 PyObject *it = lz->it;
600 long ok;
601 PyObject *(*iternext)(PyObject *);
Raymond Hettingerbd5f0e82015-10-09 01:34:08 -0400602 int checktrue = lz->func == Py_None || lz->func == (PyObject *)&PyBool_Type;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000603
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000604 iternext = *Py_TYPE(it)->tp_iternext;
605 for (;;) {
606 item = iternext(it);
607 if (item == NULL)
608 return NULL;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000609
Raymond Hettingerbd5f0e82015-10-09 01:34:08 -0400610 if (checktrue) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000611 ok = PyObject_IsTrue(item);
612 } else {
613 PyObject *good;
Victor Stinnerde4ae3d2016-12-04 22:59:09 +0100614 good = PyObject_CallFunctionObjArgs(lz->func, item, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000615 if (good == NULL) {
616 Py_DECREF(item);
617 return NULL;
618 }
619 ok = PyObject_IsTrue(good);
620 Py_DECREF(good);
621 }
Antoine Pitrou6f430e42012-08-15 23:18:25 +0200622 if (ok > 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000623 return item;
624 Py_DECREF(item);
Antoine Pitrou6f430e42012-08-15 23:18:25 +0200625 if (ok < 0)
626 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000627 }
Guido van Rossum12d12c51993-10-26 17:58:25 +0000628}
629
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +0000630static PyObject *
631filter_reduce(filterobject *lz)
632{
633 return Py_BuildValue("O(OO)", Py_TYPE(lz), lz->func, lz->it);
634}
635
636PyDoc_STRVAR(reduce_doc, "Return state information for pickling.");
637
638static PyMethodDef filter_methods[] = {
639 {"__reduce__", (PyCFunction)filter_reduce, METH_NOARGS, reduce_doc},
640 {NULL, NULL} /* sentinel */
641};
642
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000643PyDoc_STRVAR(filter_doc,
Georg Brandld11ae5d2008-05-16 13:27:32 +0000644"filter(function or None, iterable) --> filter object\n\
Guido van Rossumc1f779c2007-07-03 08:25:58 +0000645\n\
Georg Brandld11ae5d2008-05-16 13:27:32 +0000646Return an iterator yielding those items of iterable for which function(item)\n\
Raymond Hettinger17301e92008-03-13 00:19:26 +0000647is true. If function is None, return the items that are true.");
648
649PyTypeObject PyFilter_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000650 PyVarObject_HEAD_INIT(&PyType_Type, 0)
651 "filter", /* tp_name */
652 sizeof(filterobject), /* tp_basicsize */
653 0, /* tp_itemsize */
654 /* methods */
655 (destructor)filter_dealloc, /* tp_dealloc */
656 0, /* tp_print */
657 0, /* tp_getattr */
658 0, /* tp_setattr */
659 0, /* tp_reserved */
660 0, /* tp_repr */
661 0, /* tp_as_number */
662 0, /* tp_as_sequence */
663 0, /* tp_as_mapping */
664 0, /* tp_hash */
665 0, /* tp_call */
666 0, /* tp_str */
667 PyObject_GenericGetAttr, /* tp_getattro */
668 0, /* tp_setattro */
669 0, /* tp_as_buffer */
670 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
671 Py_TPFLAGS_BASETYPE, /* tp_flags */
672 filter_doc, /* tp_doc */
673 (traverseproc)filter_traverse, /* tp_traverse */
674 0, /* tp_clear */
675 0, /* tp_richcompare */
676 0, /* tp_weaklistoffset */
677 PyObject_SelfIter, /* tp_iter */
678 (iternextfunc)filter_next, /* tp_iternext */
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +0000679 filter_methods, /* tp_methods */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000680 0, /* tp_members */
681 0, /* tp_getset */
682 0, /* tp_base */
683 0, /* tp_dict */
684 0, /* tp_descr_get */
685 0, /* tp_descr_set */
686 0, /* tp_dictoffset */
687 0, /* tp_init */
688 PyType_GenericAlloc, /* tp_alloc */
689 filter_new, /* tp_new */
690 PyObject_GC_Del, /* tp_free */
Raymond Hettinger17301e92008-03-13 00:19:26 +0000691};
692
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000693
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000694/*[clinic input]
695format as builtin_format
696
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300697 value: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000698 format_spec: unicode(c_default="NULL") = ''
699 /
700
701Return value.__format__(format_spec)
702
Amit Kumar2e6bb442017-05-29 06:32:26 +0530703format_spec defaults to the empty string.
704See the Format Specification Mini-Language section of help('FORMATTING') for
705details.
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000706[clinic start generated code]*/
707
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000708static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300709builtin_format_impl(PyObject *module, PyObject *value, PyObject *format_spec)
Amit Kumar2e6bb442017-05-29 06:32:26 +0530710/*[clinic end generated code: output=2f40bdfa4954b077 input=88339c93ea522b33]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000711{
Eric Smith8fd3eba2008-02-17 19:48:00 +0000712 return PyObject_Format(value, format_spec);
Eric Smith8c663262007-08-25 02:26:07 +0000713}
714
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000715/*[clinic input]
716chr as builtin_chr
717
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300718 i: int
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000719 /
720
721Return a Unicode string of one character with ordinal i; 0 <= i <= 0x10ffff.
722[clinic start generated code]*/
723
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000724static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300725builtin_chr_impl(PyObject *module, int i)
726/*[clinic end generated code: output=c733afcd200afcb7 input=3f604ef45a70750d]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000727{
728 return PyUnicode_FromOrdinal(i);
729}
Guido van Rossum09095f32000-03-10 23:00:52 +0000730
731
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +0200732static const char *
Martin Pantereeb896c2015-11-07 02:32:21 +0000733source_as_string(PyObject *cmd, const char *funcname, const char *what, PyCompilerFlags *cf, PyObject **cmd_copy)
Guido van Rossumf15a29f2007-05-04 00:41:39 +0000734{
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +0200735 const char *str;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000736 Py_ssize_t size;
Martin Pantereeb896c2015-11-07 02:32:21 +0000737 Py_buffer view;
Guido van Rossumf15a29f2007-05-04 00:41:39 +0000738
Martin Pantereeb896c2015-11-07 02:32:21 +0000739 *cmd_copy = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000740 if (PyUnicode_Check(cmd)) {
741 cf->cf_flags |= PyCF_IGNORE_COOKIE;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200742 str = PyUnicode_AsUTF8AndSize(cmd, &size);
743 if (str == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000744 return NULL;
745 }
Martin Pantereeb896c2015-11-07 02:32:21 +0000746 else if (PyBytes_Check(cmd)) {
747 str = PyBytes_AS_STRING(cmd);
748 size = PyBytes_GET_SIZE(cmd);
749 }
750 else if (PyByteArray_Check(cmd)) {
751 str = PyByteArray_AS_STRING(cmd);
752 size = PyByteArray_GET_SIZE(cmd);
753 }
754 else if (PyObject_GetBuffer(cmd, &view, PyBUF_SIMPLE) == 0) {
755 /* Copy to NUL-terminated buffer. */
756 *cmd_copy = PyBytes_FromStringAndSize(
757 (const char *)view.buf, view.len);
758 PyBuffer_Release(&view);
759 if (*cmd_copy == NULL) {
760 return NULL;
761 }
762 str = PyBytes_AS_STRING(*cmd_copy);
763 size = PyBytes_GET_SIZE(*cmd_copy);
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +0200764 }
765 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000766 PyErr_Format(PyExc_TypeError,
767 "%s() arg 1 must be a %s object",
768 funcname, what);
769 return NULL;
770 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200771
Serhiy Storchaka3dd3e262015-02-03 01:25:42 +0200772 if (strlen(str) != (size_t)size) {
Serhiy Storchakad8a14472014-09-06 20:07:17 +0300773 PyErr_SetString(PyExc_ValueError,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000774 "source code string cannot contain null bytes");
Martin Pantereeb896c2015-11-07 02:32:21 +0000775 Py_CLEAR(*cmd_copy);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000776 return NULL;
777 }
778 return str;
Guido van Rossumf15a29f2007-05-04 00:41:39 +0000779}
780
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000781/*[clinic input]
782compile as builtin_compile
783
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300784 source: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000785 filename: object(converter="PyUnicode_FSDecoder")
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300786 mode: str
787 flags: int = 0
Serhiy Storchaka202fda52017-03-12 10:10:47 +0200788 dont_inherit: bool(accept={int}) = False
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300789 optimize: int = -1
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000790
791Compile source into a code object that can be executed by exec() or eval().
792
793The source code may represent a Python module, statement or expression.
794The filename will be used for run-time error messages.
795The mode must be 'exec' to compile a module, 'single' to compile a
796single (interactive) statement, or 'eval' to compile an expression.
797The flags argument, if present, controls which future statements influence
798the compilation of the code.
Serhiy Storchaka8b2e8b62015-05-30 11:30:39 +0300799The dont_inherit argument, if true, stops the compilation inheriting
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000800the effects of any future statements in effect in the code calling
Serhiy Storchaka8b2e8b62015-05-30 11:30:39 +0300801compile; if absent or false these statements do influence the compilation,
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000802in addition to any features explicitly specified.
803[clinic start generated code]*/
804
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000805static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300806builtin_compile_impl(PyObject *module, PyObject *source, PyObject *filename,
807 const char *mode, int flags, int dont_inherit,
808 int optimize)
Serhiy Storchaka202fda52017-03-12 10:10:47 +0200809/*[clinic end generated code: output=1fa176e33452bb63 input=0ff726f595eb9fcd]*/
Guido van Rossum5b722181993-03-30 17:46:03 +0000810{
Martin Panter61d6e4a2015-11-07 02:56:11 +0000811 PyObject *source_copy;
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +0200812 const char *str;
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000813 int compile_mode = -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000814 int is_ast;
815 PyCompilerFlags cf;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000816 int start[] = {Py_file_input, Py_eval_input, Py_single_input};
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000817 PyObject *result;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000818
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000819 cf.cf_flags = flags | PyCF_SOURCE_IS_UTF8;
Tim Peters6cd6a822001-08-17 22:11:27 +0000820
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000821 if (flags &
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000822 ~(PyCF_MASK | PyCF_MASK_OBSOLETE | PyCF_DONT_IMPLY_DEDENT | PyCF_ONLY_AST))
823 {
824 PyErr_SetString(PyExc_ValueError,
825 "compile(): unrecognised flags");
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000826 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000827 }
828 /* XXX Warn if (supplied_flags & PyCF_MASK_OBSOLETE) != 0? */
Tim Peters6cd6a822001-08-17 22:11:27 +0000829
Georg Brandl8334fd92010-12-04 10:26:46 +0000830 if (optimize < -1 || optimize > 2) {
831 PyErr_SetString(PyExc_ValueError,
832 "compile(): invalid optimize value");
833 goto error;
834 }
835
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000836 if (!dont_inherit) {
837 PyEval_MergeCompilerFlags(&cf);
838 }
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000839
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000840 if (strcmp(mode, "exec") == 0)
841 compile_mode = 0;
842 else if (strcmp(mode, "eval") == 0)
843 compile_mode = 1;
844 else if (strcmp(mode, "single") == 0)
845 compile_mode = 2;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000846 else {
847 PyErr_SetString(PyExc_ValueError,
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000848 "compile() mode must be 'exec', 'eval' or 'single'");
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000849 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000850 }
Neal Norwitzdb4115f2008-03-31 04:20:05 +0000851
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000852 is_ast = PyAST_Check(source);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000853 if (is_ast == -1)
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000854 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000855 if (is_ast) {
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000856 if (flags & PyCF_ONLY_AST) {
857 Py_INCREF(source);
858 result = source;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000859 }
860 else {
861 PyArena *arena;
862 mod_ty mod;
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000863
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000864 arena = PyArena_New();
Stefan Krah07795df2012-08-20 17:19:50 +0200865 if (arena == NULL)
866 goto error;
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000867 mod = PyAST_obj2mod(source, arena, compile_mode);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000868 if (mod == NULL) {
869 PyArena_Free(arena);
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000870 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000871 }
Benjamin Peterson832bfe22011-08-09 16:15:04 -0500872 if (!PyAST_Validate(mod)) {
873 PyArena_Free(arena);
874 goto error;
875 }
Victor Stinner14e461d2013-08-26 22:28:21 +0200876 result = (PyObject*)PyAST_CompileObject(mod, filename,
877 &cf, optimize, arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000878 PyArena_Free(arena);
879 }
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000880 goto finally;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000881 }
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000882
Martin Panter61d6e4a2015-11-07 02:56:11 +0000883 str = source_as_string(source, "compile", "string, bytes or AST", &cf, &source_copy);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000884 if (str == NULL)
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000885 goto error;
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000886
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000887 result = Py_CompileStringObject(str, filename, start[compile_mode], &cf, optimize);
Martin Panter61d6e4a2015-11-07 02:56:11 +0000888 Py_XDECREF(source_copy);
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000889 goto finally;
890
891error:
892 result = NULL;
893finally:
Victor Stinner14e461d2013-08-26 22:28:21 +0200894 Py_DECREF(filename);
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000895 return result;
Guido van Rossum5b722181993-03-30 17:46:03 +0000896}
897
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000898/* AC: cannot convert yet, as needs PEP 457 group support in inspect */
Guido van Rossum79f25d91997-04-29 20:08:16 +0000899static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000900builtin_dir(PyObject *self, PyObject *args)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000901{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000902 PyObject *arg = NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000903
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000904 if (!PyArg_UnpackTuple(args, "dir", 0, 1, &arg))
905 return NULL;
906 return PyObject_Dir(arg);
Guido van Rossum3f5da241990-12-20 15:06:42 +0000907}
908
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000909PyDoc_STRVAR(dir_doc,
Tim Peters5d2b77c2001-09-03 05:47:38 +0000910"dir([object]) -> list of strings\n"
911"\n"
Georg Brandle32b4222007-03-10 22:13:27 +0000912"If called without an argument, return the names in the current scope.\n"
913"Else, return an alphabetized list of names comprising (some of) the attributes\n"
914"of the given object, and of attributes reachable from it.\n"
915"If the object supplies a method named __dir__, it will be used; otherwise\n"
916"the default dir() logic is used and returns:\n"
917" for a module object: the module's attributes.\n"
918" for a class object: its attributes, and recursively the attributes\n"
919" of its bases.\n"
Guido van Rossumd8faa362007-04-27 19:54:29 +0000920" for any other object: its attributes, its class's attributes, and\n"
Georg Brandle32b4222007-03-10 22:13:27 +0000921" recursively the attributes of its class's base classes.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000922
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000923/*[clinic input]
924divmod as builtin_divmod
Guido van Rossum6a00cd81995-01-07 12:39:01 +0000925
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300926 x: object
927 y: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000928 /
929
Zachary Ware7f227d92016-04-28 14:39:50 -0500930Return the tuple (x//y, x%y). Invariant: div*y + mod == x.
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000931[clinic start generated code]*/
932
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000933static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300934builtin_divmod_impl(PyObject *module, PyObject *x, PyObject *y)
935/*[clinic end generated code: output=b06d8a5f6e0c745e input=175ad9c84ff41a85]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000936{
937 return PyNumber_Divmod(x, y);
938}
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000939
940
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000941/*[clinic input]
942eval as builtin_eval
943
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300944 source: object
945 globals: object = None
946 locals: object = None
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000947 /
948
949Evaluate the given source in the context of globals and locals.
950
951The source may be a string representing a Python expression
952or a code object as returned by compile().
953The globals must be a dictionary and locals can be any mapping,
954defaulting to the current globals and locals.
955If only globals is given, locals defaults to it.
956[clinic start generated code]*/
957
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000958static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300959builtin_eval_impl(PyObject *module, PyObject *source, PyObject *globals,
Larry Hastings89964c42015-04-14 18:07:59 -0400960 PyObject *locals)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300961/*[clinic end generated code: output=0a0824aa70093116 input=11ee718a8640e527]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000962{
Martin Panter61d6e4a2015-11-07 02:56:11 +0000963 PyObject *result, *source_copy;
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +0200964 const char *str;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000965 PyCompilerFlags cf;
Guido van Rossum590baa41993-11-30 13:40:46 +0000966
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000967 if (locals != Py_None && !PyMapping_Check(locals)) {
968 PyErr_SetString(PyExc_TypeError, "locals must be a mapping");
969 return NULL;
970 }
971 if (globals != Py_None && !PyDict_Check(globals)) {
972 PyErr_SetString(PyExc_TypeError, PyMapping_Check(globals) ?
973 "globals must be a real dict; try eval(expr, {}, mapping)"
974 : "globals must be a dict");
975 return NULL;
976 }
977 if (globals == Py_None) {
978 globals = PyEval_GetGlobals();
Victor Stinner41bb43a2013-10-29 01:19:37 +0100979 if (locals == Py_None) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000980 locals = PyEval_GetLocals();
Victor Stinner41bb43a2013-10-29 01:19:37 +0100981 if (locals == NULL)
982 return NULL;
983 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000984 }
985 else if (locals == Py_None)
986 locals = globals;
Tim Peters9fa96be2001-08-17 23:04:59 +0000987
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000988 if (globals == NULL || locals == NULL) {
989 PyErr_SetString(PyExc_TypeError,
990 "eval must be given globals and locals "
991 "when called without a frame");
992 return NULL;
993 }
Georg Brandl77c85e62005-09-15 10:46:13 +0000994
Victor Stinnerb44562b2013-11-06 19:03:11 +0100995 if (_PyDict_GetItemId(globals, &PyId___builtins__) == NULL) {
996 if (_PyDict_SetItemId(globals, &PyId___builtins__,
997 PyEval_GetBuiltins()) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000998 return NULL;
999 }
Tim Peters9fa96be2001-08-17 23:04:59 +00001000
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001001 if (PyCode_Check(source)) {
1002 if (PyCode_GetNumFree((PyCodeObject *)source) > 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001003 PyErr_SetString(PyExc_TypeError,
1004 "code object passed to eval() may not contain free variables");
1005 return NULL;
1006 }
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001007 return PyEval_EvalCode(source, globals, locals);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001008 }
Tim Peters9fa96be2001-08-17 23:04:59 +00001009
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001010 cf.cf_flags = PyCF_SOURCE_IS_UTF8;
Martin Panter61d6e4a2015-11-07 02:56:11 +00001011 str = source_as_string(source, "eval", "string, bytes or code", &cf, &source_copy);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001012 if (str == NULL)
1013 return NULL;
Just van Rossum3aaf42c2003-02-10 08:21:10 +00001014
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001015 while (*str == ' ' || *str == '\t')
1016 str++;
Tim Peters9fa96be2001-08-17 23:04:59 +00001017
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001018 (void)PyEval_MergeCompilerFlags(&cf);
1019 result = PyRun_StringFlags(str, Py_eval_input, globals, locals, &cf);
Martin Panter61d6e4a2015-11-07 02:56:11 +00001020 Py_XDECREF(source_copy);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001021 return result;
Guido van Rossum3f5da241990-12-20 15:06:42 +00001022}
1023
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001024/*[clinic input]
1025exec as builtin_exec
1026
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001027 source: object
1028 globals: object = None
1029 locals: object = None
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001030 /
1031
1032Execute the given source in the context of globals and locals.
1033
1034The source may be a string representing one or more Python statements
1035or a code object as returned by compile().
1036The globals must be a dictionary and locals can be any mapping,
1037defaulting to the current globals and locals.
1038If only globals is given, locals defaults to it.
1039[clinic start generated code]*/
1040
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001041static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001042builtin_exec_impl(PyObject *module, PyObject *source, PyObject *globals,
Larry Hastings89964c42015-04-14 18:07:59 -04001043 PyObject *locals)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001044/*[clinic end generated code: output=3c90efc6ab68ef5d input=01ca3e1c01692829]*/
Georg Brandl7cae87c2006-09-06 06:51:57 +00001045{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001046 PyObject *v;
Georg Brandl2cabc562008-08-28 07:57:16 +00001047
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001048 if (globals == Py_None) {
1049 globals = PyEval_GetGlobals();
1050 if (locals == Py_None) {
1051 locals = PyEval_GetLocals();
Victor Stinner41bb43a2013-10-29 01:19:37 +01001052 if (locals == NULL)
1053 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001054 }
1055 if (!globals || !locals) {
1056 PyErr_SetString(PyExc_SystemError,
1057 "globals and locals cannot be NULL");
1058 return NULL;
1059 }
1060 }
1061 else if (locals == Py_None)
1062 locals = globals;
Georg Brandl7cae87c2006-09-06 06:51:57 +00001063
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001064 if (!PyDict_Check(globals)) {
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001065 PyErr_Format(PyExc_TypeError, "exec() globals must be a dict, not %.100s",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001066 globals->ob_type->tp_name);
1067 return NULL;
1068 }
1069 if (!PyMapping_Check(locals)) {
1070 PyErr_Format(PyExc_TypeError,
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001071 "locals must be a mapping or None, not %.100s",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001072 locals->ob_type->tp_name);
1073 return NULL;
1074 }
Victor Stinnerb44562b2013-11-06 19:03:11 +01001075 if (_PyDict_GetItemId(globals, &PyId___builtins__) == NULL) {
1076 if (_PyDict_SetItemId(globals, &PyId___builtins__,
1077 PyEval_GetBuiltins()) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001078 return NULL;
1079 }
1080
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001081 if (PyCode_Check(source)) {
1082 if (PyCode_GetNumFree((PyCodeObject *)source) > 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001083 PyErr_SetString(PyExc_TypeError,
1084 "code object passed to exec() may not "
1085 "contain free variables");
1086 return NULL;
1087 }
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001088 v = PyEval_EvalCode(source, globals, locals);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001089 }
1090 else {
Martin Panter61d6e4a2015-11-07 02:56:11 +00001091 PyObject *source_copy;
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +02001092 const char *str;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001093 PyCompilerFlags cf;
1094 cf.cf_flags = PyCF_SOURCE_IS_UTF8;
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001095 str = source_as_string(source, "exec",
Martin Panter61d6e4a2015-11-07 02:56:11 +00001096 "string, bytes or code", &cf,
1097 &source_copy);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001098 if (str == NULL)
1099 return NULL;
1100 if (PyEval_MergeCompilerFlags(&cf))
1101 v = PyRun_StringFlags(str, Py_file_input, globals,
1102 locals, &cf);
1103 else
1104 v = PyRun_String(str, Py_file_input, globals, locals);
Martin Panter61d6e4a2015-11-07 02:56:11 +00001105 Py_XDECREF(source_copy);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001106 }
1107 if (v == NULL)
1108 return NULL;
1109 Py_DECREF(v);
1110 Py_RETURN_NONE;
Georg Brandl7cae87c2006-09-06 06:51:57 +00001111}
1112
Georg Brandl7cae87c2006-09-06 06:51:57 +00001113
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001114/* AC: cannot convert yet, as needs PEP 457 group support in inspect */
Guido van Rossum79f25d91997-04-29 20:08:16 +00001115static PyObject *
Serhiy Storchakaa5552f02017-12-15 13:11:11 +02001116builtin_getattr(PyObject *self, PyObject *const *args, Py_ssize_t nargs)
Guido van Rossum33894be1992-01-27 16:53:09 +00001117{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001118 PyObject *v, *result, *dflt = NULL;
1119 PyObject *name;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001120
Sylvain96c7c062017-06-15 17:05:23 +02001121 if (!_PyArg_UnpackStack(args, nargs, "getattr", 2, 3, &v, &name, &dflt))
1122 return NULL;
1123
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001124 if (!PyUnicode_Check(name)) {
1125 PyErr_SetString(PyExc_TypeError,
1126 "getattr(): attribute name must be string");
1127 return NULL;
1128 }
INADA Naoki378edee2018-01-16 20:52:41 +09001129 if (dflt != NULL) {
1130 result = _PyObject_GetAttrWithoutError(v, name);
1131 if (result == NULL && !PyErr_Occurred()) {
1132 Py_INCREF(dflt);
1133 return dflt;
1134 }
1135 }
1136 else {
1137 result = PyObject_GetAttr(v, name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001138 }
1139 return result;
Guido van Rossum9bfef441993-03-29 10:43:31 +00001140}
1141
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001142PyDoc_STRVAR(getattr_doc,
Guido van Rossum950ff291998-06-29 13:38:57 +00001143"getattr(object, name[, default]) -> value\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001144\n\
Guido van Rossum950ff291998-06-29 13:38:57 +00001145Get a named attribute from an object; getattr(x, 'y') is equivalent to x.y.\n\
1146When a default argument is given, it is returned when the attribute doesn't\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001147exist; without it, an exception is raised in that case.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001148
1149
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001150/*[clinic input]
1151globals as builtin_globals
1152
1153Return the dictionary containing the current scope's global variables.
1154
1155NOTE: Updates to this dictionary *will* affect name lookups in the current
1156global scope and vice-versa.
1157[clinic start generated code]*/
1158
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001159static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001160builtin_globals_impl(PyObject *module)
1161/*[clinic end generated code: output=e5dd1527067b94d2 input=9327576f92bb48ba]*/
Guido van Rossum872537c1995-07-07 22:43:42 +00001162{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001163 PyObject *d;
Guido van Rossum872537c1995-07-07 22:43:42 +00001164
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001165 d = PyEval_GetGlobals();
1166 Py_XINCREF(d);
1167 return d;
Guido van Rossum872537c1995-07-07 22:43:42 +00001168}
1169
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001170
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001171/*[clinic input]
1172hasattr as builtin_hasattr
1173
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001174 obj: object
1175 name: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001176 /
1177
1178Return whether the object has an attribute with the given name.
1179
1180This is done by calling getattr(obj, name) and catching AttributeError.
1181[clinic start generated code]*/
1182
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001183static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001184builtin_hasattr_impl(PyObject *module, PyObject *obj, PyObject *name)
1185/*[clinic end generated code: output=a7aff2090a4151e5 input=0faec9787d979542]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001186{
1187 PyObject *v;
1188
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001189 if (!PyUnicode_Check(name)) {
1190 PyErr_SetString(PyExc_TypeError,
1191 "hasattr(): attribute name must be string");
1192 return NULL;
1193 }
INADA Naoki378edee2018-01-16 20:52:41 +09001194 v = _PyObject_GetAttrWithoutError(obj, name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001195 if (v == NULL) {
INADA Naoki378edee2018-01-16 20:52:41 +09001196 if (!PyErr_Occurred()) {
Benjamin Peterson17689992010-08-24 03:26:23 +00001197 Py_RETURN_FALSE;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001198 }
Benjamin Peterson17689992010-08-24 03:26:23 +00001199 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001200 }
1201 Py_DECREF(v);
Benjamin Peterson17689992010-08-24 03:26:23 +00001202 Py_RETURN_TRUE;
Guido van Rossum33894be1992-01-27 16:53:09 +00001203}
1204
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001205
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001206/* AC: gdb's integration with CPython relies on builtin_id having
1207 * the *exact* parameter names of "self" and "v", so we ensure we
1208 * preserve those name rather than using the AC defaults.
1209 */
1210/*[clinic input]
1211id as builtin_id
1212
Serhiy Storchaka24182a32016-05-05 16:21:35 +03001213 self: self(type="PyModuleDef *")
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001214 obj as v: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001215 /
1216
1217Return the identity of an object.
1218
1219This is guaranteed to be unique among simultaneously existing objects.
1220(CPython uses the object's memory address.)
1221[clinic start generated code]*/
1222
Guido van Rossum79f25d91997-04-29 20:08:16 +00001223static PyObject *
Serhiy Storchaka24182a32016-05-05 16:21:35 +03001224builtin_id(PyModuleDef *self, PyObject *v)
1225/*[clinic end generated code: output=0aa640785f697f65 input=5a534136419631f4]*/
Guido van Rossum5b722181993-03-30 17:46:03 +00001226{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001227 return PyLong_FromVoidPtr(v);
Guido van Rossum5b722181993-03-30 17:46:03 +00001228}
1229
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001230
Raymond Hettingera6c60372008-03-13 01:26:19 +00001231/* map object ************************************************************/
1232
1233typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001234 PyObject_HEAD
1235 PyObject *iters;
1236 PyObject *func;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001237} mapobject;
1238
Guido van Rossum79f25d91997-04-29 20:08:16 +00001239static PyObject *
Raymond Hettingera6c60372008-03-13 01:26:19 +00001240map_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
Guido van Rossum12d12c51993-10-26 17:58:25 +00001241{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001242 PyObject *it, *iters, *func;
1243 mapobject *lz;
1244 Py_ssize_t numargs, i;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001245
Serhiy Storchaka6cca5c82017-06-08 14:41:19 +03001246 if (type == &PyMap_Type && !_PyArg_NoKeywords("map", kwds))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001247 return NULL;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001248
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001249 numargs = PyTuple_Size(args);
1250 if (numargs < 2) {
1251 PyErr_SetString(PyExc_TypeError,
1252 "map() must have at least two arguments.");
1253 return NULL;
1254 }
Raymond Hettingera6c60372008-03-13 01:26:19 +00001255
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001256 iters = PyTuple_New(numargs-1);
1257 if (iters == NULL)
1258 return NULL;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001259
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001260 for (i=1 ; i<numargs ; i++) {
1261 /* Get iterator. */
1262 it = PyObject_GetIter(PyTuple_GET_ITEM(args, i));
1263 if (it == NULL) {
1264 Py_DECREF(iters);
1265 return NULL;
1266 }
1267 PyTuple_SET_ITEM(iters, i-1, it);
1268 }
Raymond Hettingera6c60372008-03-13 01:26:19 +00001269
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001270 /* create mapobject structure */
1271 lz = (mapobject *)type->tp_alloc(type, 0);
1272 if (lz == NULL) {
1273 Py_DECREF(iters);
1274 return NULL;
1275 }
1276 lz->iters = iters;
1277 func = PyTuple_GET_ITEM(args, 0);
1278 Py_INCREF(func);
1279 lz->func = func;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001280
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001281 return (PyObject *)lz;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001282}
1283
1284static void
1285map_dealloc(mapobject *lz)
1286{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001287 PyObject_GC_UnTrack(lz);
1288 Py_XDECREF(lz->iters);
1289 Py_XDECREF(lz->func);
1290 Py_TYPE(lz)->tp_free(lz);
Raymond Hettingera6c60372008-03-13 01:26:19 +00001291}
1292
1293static int
1294map_traverse(mapobject *lz, visitproc visit, void *arg)
1295{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001296 Py_VISIT(lz->iters);
1297 Py_VISIT(lz->func);
1298 return 0;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001299}
1300
1301static PyObject *
1302map_next(mapobject *lz)
1303{
Victor Stinnerbc08ab42016-12-15 12:40:53 +01001304 PyObject *small_stack[_PY_FASTCALL_SMALL_STACK];
Victor Stinnercdb5cee2016-08-24 01:45:13 +02001305 PyObject **stack;
1306 Py_ssize_t niters, nargs, i;
1307 PyObject *result = NULL;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001308
Victor Stinnercdb5cee2016-08-24 01:45:13 +02001309 niters = PyTuple_GET_SIZE(lz->iters);
1310 if (niters <= (Py_ssize_t)Py_ARRAY_LENGTH(small_stack)) {
1311 stack = small_stack;
1312 }
1313 else {
1314 stack = PyMem_Malloc(niters * sizeof(stack[0]));
1315 if (stack == NULL) {
1316 PyErr_NoMemory();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001317 return NULL;
1318 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001319 }
Victor Stinnercdb5cee2016-08-24 01:45:13 +02001320
1321 nargs = 0;
1322 for (i=0; i < niters; i++) {
1323 PyObject *it = PyTuple_GET_ITEM(lz->iters, i);
1324 PyObject *val = Py_TYPE(it)->tp_iternext(it);
1325 if (val == NULL) {
1326 goto exit;
1327 }
1328 stack[i] = val;
1329 nargs++;
1330 }
1331
1332 result = _PyObject_FastCall(lz->func, stack, nargs);
1333
1334exit:
1335 for (i=0; i < nargs; i++) {
1336 Py_DECREF(stack[i]);
1337 }
1338 if (stack != small_stack) {
1339 PyMem_Free(stack);
1340 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001341 return result;
Guido van Rossum12d12c51993-10-26 17:58:25 +00001342}
1343
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001344static PyObject *
1345map_reduce(mapobject *lz)
1346{
1347 Py_ssize_t numargs = PyTuple_GET_SIZE(lz->iters);
1348 PyObject *args = PyTuple_New(numargs+1);
1349 Py_ssize_t i;
1350 if (args == NULL)
1351 return NULL;
1352 Py_INCREF(lz->func);
1353 PyTuple_SET_ITEM(args, 0, lz->func);
1354 for (i = 0; i<numargs; i++){
1355 PyObject *it = PyTuple_GET_ITEM(lz->iters, i);
1356 Py_INCREF(it);
1357 PyTuple_SET_ITEM(args, i+1, it);
1358 }
1359
1360 return Py_BuildValue("ON", Py_TYPE(lz), args);
1361}
1362
1363static PyMethodDef map_methods[] = {
1364 {"__reduce__", (PyCFunction)map_reduce, METH_NOARGS, reduce_doc},
1365 {NULL, NULL} /* sentinel */
1366};
1367
1368
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001369PyDoc_STRVAR(map_doc,
Raymond Hettingera6c60372008-03-13 01:26:19 +00001370"map(func, *iterables) --> map object\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001371\n\
Raymond Hettingera6c60372008-03-13 01:26:19 +00001372Make an iterator that computes the function using arguments from\n\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001373each of the iterables. Stops when the shortest iterable is exhausted.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001374
Raymond Hettingera6c60372008-03-13 01:26:19 +00001375PyTypeObject PyMap_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001376 PyVarObject_HEAD_INIT(&PyType_Type, 0)
1377 "map", /* tp_name */
1378 sizeof(mapobject), /* tp_basicsize */
1379 0, /* tp_itemsize */
1380 /* methods */
1381 (destructor)map_dealloc, /* tp_dealloc */
1382 0, /* tp_print */
1383 0, /* tp_getattr */
1384 0, /* tp_setattr */
1385 0, /* tp_reserved */
1386 0, /* tp_repr */
1387 0, /* tp_as_number */
1388 0, /* tp_as_sequence */
1389 0, /* tp_as_mapping */
1390 0, /* tp_hash */
1391 0, /* tp_call */
1392 0, /* tp_str */
1393 PyObject_GenericGetAttr, /* tp_getattro */
1394 0, /* tp_setattro */
1395 0, /* tp_as_buffer */
1396 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
1397 Py_TPFLAGS_BASETYPE, /* tp_flags */
1398 map_doc, /* tp_doc */
1399 (traverseproc)map_traverse, /* tp_traverse */
1400 0, /* tp_clear */
1401 0, /* tp_richcompare */
1402 0, /* tp_weaklistoffset */
1403 PyObject_SelfIter, /* tp_iter */
1404 (iternextfunc)map_next, /* tp_iternext */
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001405 map_methods, /* tp_methods */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001406 0, /* tp_members */
1407 0, /* tp_getset */
1408 0, /* tp_base */
1409 0, /* tp_dict */
1410 0, /* tp_descr_get */
1411 0, /* tp_descr_set */
1412 0, /* tp_dictoffset */
1413 0, /* tp_init */
1414 PyType_GenericAlloc, /* tp_alloc */
1415 map_new, /* tp_new */
1416 PyObject_GC_Del, /* tp_free */
Raymond Hettingera6c60372008-03-13 01:26:19 +00001417};
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001418
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001419
1420/* AC: cannot convert yet, as needs PEP 457 group support in inspect */
Guido van Rossum79f25d91997-04-29 20:08:16 +00001421static PyObject *
Serhiy Storchakaa5552f02017-12-15 13:11:11 +02001422builtin_next(PyObject *self, PyObject *const *args, Py_ssize_t nargs)
Georg Brandla18af4e2007-04-21 15:47:16 +00001423{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001424 PyObject *it, *res;
1425 PyObject *def = NULL;
Georg Brandla18af4e2007-04-21 15:47:16 +00001426
Sylvain96c7c062017-06-15 17:05:23 +02001427 if (!_PyArg_UnpackStack(args, nargs, "next", 1, 2, &it, &def))
1428 return NULL;
1429
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001430 if (!PyIter_Check(it)) {
1431 PyErr_Format(PyExc_TypeError,
Philip Jenvey50add042011-11-06 16:37:52 -08001432 "'%.200s' object is not an iterator",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001433 it->ob_type->tp_name);
1434 return NULL;
1435 }
1436
1437 res = (*it->ob_type->tp_iternext)(it);
1438 if (res != NULL) {
1439 return res;
1440 } else if (def != NULL) {
1441 if (PyErr_Occurred()) {
1442 if(!PyErr_ExceptionMatches(PyExc_StopIteration))
1443 return NULL;
1444 PyErr_Clear();
1445 }
1446 Py_INCREF(def);
1447 return def;
1448 } else if (PyErr_Occurred()) {
1449 return NULL;
1450 } else {
1451 PyErr_SetNone(PyExc_StopIteration);
1452 return NULL;
1453 }
Georg Brandla18af4e2007-04-21 15:47:16 +00001454}
1455
1456PyDoc_STRVAR(next_doc,
1457"next(iterator[, default])\n\
1458\n\
1459Return the next item from the iterator. If default is given and the iterator\n\
1460is exhausted, it is returned instead of raising StopIteration.");
1461
1462
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001463/*[clinic input]
1464setattr as builtin_setattr
1465
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001466 obj: object
1467 name: object
1468 value: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001469 /
1470
1471Sets the named attribute on the given object to the specified value.
1472
1473setattr(x, 'y', v) is equivalent to ``x.y = v''
1474[clinic start generated code]*/
1475
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001476static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001477builtin_setattr_impl(PyObject *module, PyObject *obj, PyObject *name,
Larry Hastings89964c42015-04-14 18:07:59 -04001478 PyObject *value)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001479/*[clinic end generated code: output=dc2ce1d1add9acb4 input=bd2b7ca6875a1899]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001480{
1481 if (PyObject_SetAttr(obj, name, value) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001482 return NULL;
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02001483 Py_RETURN_NONE;
Guido van Rossum33894be1992-01-27 16:53:09 +00001484}
1485
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001486
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001487/*[clinic input]
1488delattr as builtin_delattr
1489
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001490 obj: object
1491 name: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001492 /
1493
1494Deletes the named attribute from the given object.
1495
1496delattr(x, 'y') is equivalent to ``del x.y''
1497[clinic start generated code]*/
1498
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001499static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001500builtin_delattr_impl(PyObject *module, PyObject *obj, PyObject *name)
1501/*[clinic end generated code: output=85134bc58dff79fa input=db16685d6b4b9410]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001502{
1503 if (PyObject_SetAttr(obj, name, (PyObject *)NULL) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001504 return NULL;
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02001505 Py_RETURN_NONE;
Guido van Rossum14144fc1994-08-29 12:53:40 +00001506}
1507
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001508
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001509/*[clinic input]
1510hash as builtin_hash
1511
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001512 obj: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001513 /
1514
1515Return the hash value for the given object.
1516
1517Two objects that compare equal must also have the same hash value, but the
1518reverse is not necessarily true.
1519[clinic start generated code]*/
1520
Guido van Rossum79f25d91997-04-29 20:08:16 +00001521static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001522builtin_hash(PyObject *module, PyObject *obj)
1523/*[clinic end generated code: output=237668e9d7688db7 input=58c48be822bf9c54]*/
Guido van Rossum9bfef441993-03-29 10:43:31 +00001524{
Benjamin Peterson8f67d082010-10-17 20:54:53 +00001525 Py_hash_t x;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001526
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001527 x = PyObject_Hash(obj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001528 if (x == -1)
1529 return NULL;
Benjamin Peterson8f67d082010-10-17 20:54:53 +00001530 return PyLong_FromSsize_t(x);
Guido van Rossum9bfef441993-03-29 10:43:31 +00001531}
1532
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001533
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001534/*[clinic input]
1535hex as builtin_hex
1536
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001537 number: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001538 /
1539
1540Return the hexadecimal representation of an integer.
1541
1542 >>> hex(12648430)
1543 '0xc0ffee'
1544[clinic start generated code]*/
1545
Guido van Rossum79f25d91997-04-29 20:08:16 +00001546static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001547builtin_hex(PyObject *module, PyObject *number)
1548/*[clinic end generated code: output=e46b612169099408 input=e645aff5fc7d540e]*/
Guido van Rossum006bcd41991-10-24 14:54:44 +00001549{
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001550 return PyNumber_ToBase(number, 16);
Guido van Rossum006bcd41991-10-24 14:54:44 +00001551}
1552
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001553
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001554/* AC: cannot convert yet, as needs PEP 457 group support in inspect */
Guido van Rossum79f25d91997-04-29 20:08:16 +00001555static PyObject *
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001556builtin_iter(PyObject *self, PyObject *args)
1557{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001558 PyObject *v, *w = NULL;
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001559
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001560 if (!PyArg_UnpackTuple(args, "iter", 1, 2, &v, &w))
1561 return NULL;
1562 if (w == NULL)
1563 return PyObject_GetIter(v);
1564 if (!PyCallable_Check(v)) {
1565 PyErr_SetString(PyExc_TypeError,
1566 "iter(v, w): v must be callable");
1567 return NULL;
1568 }
1569 return PyCallIter_New(v, w);
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001570}
1571
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001572PyDoc_STRVAR(iter_doc,
Georg Brandld11ae5d2008-05-16 13:27:32 +00001573"iter(iterable) -> iterator\n\
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001574iter(callable, sentinel) -> iterator\n\
1575\n\
1576Get an iterator from an object. In the first form, the argument must\n\
1577supply its own iterator, or be a sequence.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001578In the second form, the callable is called until it returns the sentinel.");
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001579
1580
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001581/*[clinic input]
1582len as builtin_len
1583
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001584 obj: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001585 /
1586
1587Return the number of items in a container.
1588[clinic start generated code]*/
1589
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001590static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001591builtin_len(PyObject *module, PyObject *obj)
1592/*[clinic end generated code: output=fa7a270d314dfb6c input=bc55598da9e9c9b5]*/
Guido van Rossum3f5da241990-12-20 15:06:42 +00001593{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001594 Py_ssize_t res;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001595
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001596 res = PyObject_Size(obj);
Serhiy Storchaka813f9432017-04-16 09:21:44 +03001597 if (res < 0) {
1598 assert(PyErr_Occurred());
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001599 return NULL;
Serhiy Storchaka813f9432017-04-16 09:21:44 +03001600 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001601 return PyLong_FromSsize_t(res);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001602}
1603
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001604
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001605/*[clinic input]
1606locals as builtin_locals
1607
1608Return a dictionary containing the current scope's local variables.
1609
1610NOTE: Whether or not updates to this dictionary will affect name lookups in
1611the local scope and vice-versa is *implementation dependent* and not
1612covered by any backwards compatibility guarantees.
1613[clinic start generated code]*/
1614
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001615static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001616builtin_locals_impl(PyObject *module)
1617/*[clinic end generated code: output=b46c94015ce11448 input=7874018d478d5c4b]*/
Guido van Rossum872537c1995-07-07 22:43:42 +00001618{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001619 PyObject *d;
Guido van Rossum872537c1995-07-07 22:43:42 +00001620
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001621 d = PyEval_GetLocals();
1622 Py_XINCREF(d);
1623 return d;
Guido van Rossum872537c1995-07-07 22:43:42 +00001624}
1625
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001626
Guido van Rossum79f25d91997-04-29 20:08:16 +00001627static PyObject *
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001628min_max(PyObject *args, PyObject *kwds, int op)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001629{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001630 PyObject *v, *it, *item, *val, *maxitem, *maxval, *keyfunc=NULL;
Raymond Hettinger4d6018f2013-06-24 22:43:02 -07001631 PyObject *emptytuple, *defaultval = NULL;
1632 static char *kwlist[] = {"key", "default", NULL};
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001633 const char *name = op == Py_LT ? "min" : "max";
Raymond Hettinger4d6018f2013-06-24 22:43:02 -07001634 const int positional = PyTuple_Size(args) > 1;
1635 int ret;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001636
Raymond Hettinger4d6018f2013-06-24 22:43:02 -07001637 if (positional)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001638 v = args;
Serhiy Storchakac6792272013-10-19 21:03:34 +03001639 else if (!PyArg_UnpackTuple(args, name, 1, 1, &v))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001640 return NULL;
Tim Peters67d687a2002-04-29 21:27:32 +00001641
Raymond Hettinger4d6018f2013-06-24 22:43:02 -07001642 emptytuple = PyTuple_New(0);
1643 if (emptytuple == NULL)
1644 return NULL;
Oren Milman58cf7482017-08-21 20:19:07 +03001645 ret = PyArg_ParseTupleAndKeywords(emptytuple, kwds,
1646 (op == Py_LT) ? "|$OO:min" : "|$OO:max",
1647 kwlist, &keyfunc, &defaultval);
Raymond Hettinger4d6018f2013-06-24 22:43:02 -07001648 Py_DECREF(emptytuple);
1649 if (!ret)
1650 return NULL;
1651
1652 if (positional && defaultval != NULL) {
1653 PyErr_Format(PyExc_TypeError,
1654 "Cannot specify a default for %s() with multiple "
1655 "positional arguments", name);
1656 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001657 }
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001658
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001659 it = PyObject_GetIter(v);
1660 if (it == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001661 return NULL;
1662 }
Tim Petersc3074532001-05-03 07:00:32 +00001663
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001664 maxitem = NULL; /* the result */
1665 maxval = NULL; /* the value associated with the result */
1666 while (( item = PyIter_Next(it) )) {
1667 /* get the value from the key function */
1668 if (keyfunc != NULL) {
Victor Stinnerde4ae3d2016-12-04 22:59:09 +01001669 val = PyObject_CallFunctionObjArgs(keyfunc, item, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001670 if (val == NULL)
1671 goto Fail_it_item;
1672 }
1673 /* no key function; the value is the item */
1674 else {
1675 val = item;
1676 Py_INCREF(val);
1677 }
Tim Petersc3074532001-05-03 07:00:32 +00001678
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001679 /* maximum value and item are unset; set them */
1680 if (maxval == NULL) {
1681 maxitem = item;
1682 maxval = val;
1683 }
1684 /* maximum value and item are set; update them as necessary */
1685 else {
1686 int cmp = PyObject_RichCompareBool(val, maxval, op);
1687 if (cmp < 0)
1688 goto Fail_it_item_and_val;
1689 else if (cmp > 0) {
1690 Py_DECREF(maxval);
1691 Py_DECREF(maxitem);
1692 maxval = val;
1693 maxitem = item;
1694 }
1695 else {
1696 Py_DECREF(item);
1697 Py_DECREF(val);
1698 }
1699 }
1700 }
1701 if (PyErr_Occurred())
1702 goto Fail_it;
1703 if (maxval == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001704 assert(maxitem == NULL);
Raymond Hettinger4d6018f2013-06-24 22:43:02 -07001705 if (defaultval != NULL) {
1706 Py_INCREF(defaultval);
1707 maxitem = defaultval;
1708 } else {
1709 PyErr_Format(PyExc_ValueError,
1710 "%s() arg is an empty sequence", name);
1711 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001712 }
1713 else
1714 Py_DECREF(maxval);
1715 Py_DECREF(it);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001716 return maxitem;
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001717
1718Fail_it_item_and_val:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001719 Py_DECREF(val);
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001720Fail_it_item:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001721 Py_DECREF(item);
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001722Fail_it:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001723 Py_XDECREF(maxval);
1724 Py_XDECREF(maxitem);
1725 Py_DECREF(it);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001726 return NULL;
Guido van Rossum3f5da241990-12-20 15:06:42 +00001727}
1728
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001729/* AC: cannot convert yet, waiting for *args support */
Guido van Rossum79f25d91997-04-29 20:08:16 +00001730static PyObject *
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001731builtin_min(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001732{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001733 return min_max(args, kwds, Py_LT);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001734}
1735
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001736PyDoc_STRVAR(min_doc,
Raymond Hettinger2a545822014-05-19 22:20:52 +01001737"min(iterable, *[, default=obj, key=func]) -> value\n\
1738min(arg1, arg2, *args, *[, key=func]) -> value\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001739\n\
Raymond Hettinger2a545822014-05-19 22:20:52 +01001740With a single iterable argument, return its smallest item. The\n\
1741default keyword-only argument specifies an object to return if\n\
1742the provided iterable is empty.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001743With two or more arguments, return the smallest argument.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001744
1745
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001746/* AC: cannot convert yet, waiting for *args support */
Guido van Rossum79f25d91997-04-29 20:08:16 +00001747static PyObject *
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001748builtin_max(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001749{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001750 return min_max(args, kwds, Py_GT);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001751}
1752
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001753PyDoc_STRVAR(max_doc,
Raymond Hettinger2a545822014-05-19 22:20:52 +01001754"max(iterable, *[, default=obj, key=func]) -> value\n\
1755max(arg1, arg2, *args, *[, key=func]) -> value\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001756\n\
Raymond Hettinger2a545822014-05-19 22:20:52 +01001757With a single iterable argument, return its biggest item. The\n\
1758default keyword-only argument specifies an object to return if\n\
1759the provided iterable is empty.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001760With two or more arguments, return the largest argument.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001761
1762
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001763/*[clinic input]
1764oct as builtin_oct
1765
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001766 number: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001767 /
1768
1769Return the octal representation of an integer.
1770
1771 >>> oct(342391)
1772 '0o1234567'
1773[clinic start generated code]*/
1774
Guido van Rossum79f25d91997-04-29 20:08:16 +00001775static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001776builtin_oct(PyObject *module, PyObject *number)
1777/*[clinic end generated code: output=40a34656b6875352 input=ad6b274af4016c72]*/
Guido van Rossum006bcd41991-10-24 14:54:44 +00001778{
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001779 return PyNumber_ToBase(number, 8);
Guido van Rossum006bcd41991-10-24 14:54:44 +00001780}
1781
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001782
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001783/*[clinic input]
1784ord as builtin_ord
1785
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001786 c: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001787 /
1788
1789Return the Unicode code point for a one-character string.
1790[clinic start generated code]*/
1791
Guido van Rossum79f25d91997-04-29 20:08:16 +00001792static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001793builtin_ord(PyObject *module, PyObject *c)
1794/*[clinic end generated code: output=4fa5e87a323bae71 input=3064e5d6203ad012]*/
Guido van Rossum3f5da241990-12-20 15:06:42 +00001795{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001796 long ord;
1797 Py_ssize_t size;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001798
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001799 if (PyBytes_Check(c)) {
1800 size = PyBytes_GET_SIZE(c);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001801 if (size == 1) {
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001802 ord = (long)((unsigned char)*PyBytes_AS_STRING(c));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001803 return PyLong_FromLong(ord);
1804 }
1805 }
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001806 else if (PyUnicode_Check(c)) {
1807 if (PyUnicode_READY(c) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001808 return NULL;
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001809 size = PyUnicode_GET_LENGTH(c);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001810 if (size == 1) {
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001811 ord = (long)PyUnicode_READ_CHAR(c, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001812 return PyLong_FromLong(ord);
1813 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001814 }
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001815 else if (PyByteArray_Check(c)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001816 /* XXX Hopefully this is temporary */
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001817 size = PyByteArray_GET_SIZE(c);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001818 if (size == 1) {
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001819 ord = (long)((unsigned char)*PyByteArray_AS_STRING(c));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001820 return PyLong_FromLong(ord);
1821 }
1822 }
1823 else {
1824 PyErr_Format(PyExc_TypeError,
1825 "ord() expected string of length 1, but " \
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001826 "%.200s found", c->ob_type->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001827 return NULL;
1828 }
Guido van Rossum09095f32000-03-10 23:00:52 +00001829
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001830 PyErr_Format(PyExc_TypeError,
1831 "ord() expected a character, "
1832 "but string of length %zd found",
1833 size);
1834 return NULL;
Guido van Rossum3f5da241990-12-20 15:06:42 +00001835}
1836
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001837
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001838/*[clinic input]
1839pow as builtin_pow
1840
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001841 x: object
1842 y: object
1843 z: object = None
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001844 /
1845
1846Equivalent to x**y (with two arguments) or x**y % z (with three arguments)
1847
1848Some types, such as ints, are able to use a more efficient algorithm when
1849invoked using the three argument form.
1850[clinic start generated code]*/
1851
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001852static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001853builtin_pow_impl(PyObject *module, PyObject *x, PyObject *y, PyObject *z)
1854/*[clinic end generated code: output=50a14d5d130d404b input=653d57d38d41fc07]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001855{
1856 return PyNumber_Power(x, y, z);
1857}
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001858
1859
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001860/* AC: cannot convert yet, waiting for *args support */
Guido van Rossum34343512006-11-30 22:13:52 +00001861static PyObject *
Serhiy Storchakaa5552f02017-12-15 13:11:11 +02001862builtin_print(PyObject *self, PyObject *const *args, Py_ssize_t nargs, PyObject *kwnames)
Guido van Rossum34343512006-11-30 22:13:52 +00001863{
INADA Naokibd584f12017-01-19 12:50:34 +01001864 static const char * const _keywords[] = {"sep", "end", "file", "flush", 0};
1865 static struct _PyArg_Parser _parser = {"|OOOO:print", _keywords, 0};
Georg Brandlbc3b6822012-01-13 19:41:25 +01001866 PyObject *sep = NULL, *end = NULL, *file = NULL, *flush = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001867 int i, err;
Guido van Rossum34343512006-11-30 22:13:52 +00001868
INADA Naokibd584f12017-01-19 12:50:34 +01001869 if (kwnames != NULL &&
1870 !_PyArg_ParseStackAndKeywords(args + nargs, 0, kwnames, &_parser,
1871 &sep, &end, &file, &flush)) {
Georg Brandlbc3b6822012-01-13 19:41:25 +01001872 return NULL;
INADA Naokibd584f12017-01-19 12:50:34 +01001873 }
1874
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001875 if (file == NULL || file == Py_None) {
Victor Stinnerbd303c12013-11-07 23:07:29 +01001876 file = _PySys_GetObjectId(&PyId_stdout);
Victor Stinner1e53bba2013-07-16 22:26:05 +02001877 if (file == NULL) {
1878 PyErr_SetString(PyExc_RuntimeError, "lost sys.stdout");
1879 return NULL;
1880 }
1881
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001882 /* sys.stdout may be None when FILE* stdout isn't connected */
1883 if (file == Py_None)
1884 Py_RETURN_NONE;
1885 }
Guido van Rossum34343512006-11-30 22:13:52 +00001886
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001887 if (sep == Py_None) {
1888 sep = NULL;
1889 }
1890 else if (sep && !PyUnicode_Check(sep)) {
1891 PyErr_Format(PyExc_TypeError,
1892 "sep must be None or a string, not %.200s",
1893 sep->ob_type->tp_name);
1894 return NULL;
1895 }
1896 if (end == Py_None) {
1897 end = NULL;
1898 }
1899 else if (end && !PyUnicode_Check(end)) {
1900 PyErr_Format(PyExc_TypeError,
1901 "end must be None or a string, not %.200s",
1902 end->ob_type->tp_name);
1903 return NULL;
1904 }
Guido van Rossum34343512006-11-30 22:13:52 +00001905
INADA Naokibd584f12017-01-19 12:50:34 +01001906 for (i = 0; i < nargs; i++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001907 if (i > 0) {
1908 if (sep == NULL)
1909 err = PyFile_WriteString(" ", file);
1910 else
1911 err = PyFile_WriteObject(sep, file,
1912 Py_PRINT_RAW);
1913 if (err)
1914 return NULL;
1915 }
INADA Naokibd584f12017-01-19 12:50:34 +01001916 err = PyFile_WriteObject(args[i], file, Py_PRINT_RAW);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001917 if (err)
1918 return NULL;
1919 }
Guido van Rossum34343512006-11-30 22:13:52 +00001920
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001921 if (end == NULL)
1922 err = PyFile_WriteString("\n", file);
1923 else
1924 err = PyFile_WriteObject(end, file, Py_PRINT_RAW);
1925 if (err)
1926 return NULL;
Guido van Rossum34343512006-11-30 22:13:52 +00001927
Georg Brandlbc3b6822012-01-13 19:41:25 +01001928 if (flush != NULL) {
1929 PyObject *tmp;
1930 int do_flush = PyObject_IsTrue(flush);
1931 if (do_flush == -1)
1932 return NULL;
1933 else if (do_flush) {
Victor Stinner3466bde2016-09-05 18:16:01 -07001934 tmp = _PyObject_CallMethodId(file, &PyId_flush, NULL);
Georg Brandlbc3b6822012-01-13 19:41:25 +01001935 if (tmp == NULL)
1936 return NULL;
1937 else
1938 Py_DECREF(tmp);
1939 }
1940 }
1941
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001942 Py_RETURN_NONE;
Guido van Rossum34343512006-11-30 22:13:52 +00001943}
1944
1945PyDoc_STRVAR(print_doc,
Senthil Kumarane9175bd2012-08-10 13:53:45 -07001946"print(value, ..., sep=' ', end='\\n', file=sys.stdout, flush=False)\n\
Guido van Rossum34343512006-11-30 22:13:52 +00001947\n\
1948Prints the values to a stream, or to sys.stdout by default.\n\
1949Optional keyword arguments:\n\
Senthil Kumarane9175bd2012-08-10 13:53:45 -07001950file: a file-like object (stream); defaults to the current sys.stdout.\n\
1951sep: string inserted between values, default a space.\n\
1952end: string appended after the last value, default a newline.\n\
1953flush: whether to forcibly flush the stream.");
Guido van Rossum34343512006-11-30 22:13:52 +00001954
1955
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001956/*[clinic input]
1957input as builtin_input
1958
1959 prompt: object(c_default="NULL") = None
1960 /
1961
1962Read a string from standard input. The trailing newline is stripped.
1963
1964The prompt string, if given, is printed to standard output without a
1965trailing newline before reading input.
1966
1967If the user hits EOF (*nix: Ctrl-D, Windows: Ctrl-Z+Return), raise EOFError.
1968On *nix systems, readline is used if available.
1969[clinic start generated code]*/
1970
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001971static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001972builtin_input_impl(PyObject *module, PyObject *prompt)
1973/*[clinic end generated code: output=83db5a191e7a0d60 input=5e8bb70c2908fe3c]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001974{
Victor Stinnerbd303c12013-11-07 23:07:29 +01001975 PyObject *fin = _PySys_GetObjectId(&PyId_stdin);
1976 PyObject *fout = _PySys_GetObjectId(&PyId_stdout);
1977 PyObject *ferr = _PySys_GetObjectId(&PyId_stderr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001978 PyObject *tmp;
1979 long fd;
1980 int tty;
Guido van Rossuma88a0332007-02-26 16:59:55 +00001981
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001982 /* Check that stdin/out/err are intact */
1983 if (fin == NULL || fin == Py_None) {
1984 PyErr_SetString(PyExc_RuntimeError,
1985 "input(): lost sys.stdin");
1986 return NULL;
1987 }
1988 if (fout == NULL || fout == Py_None) {
1989 PyErr_SetString(PyExc_RuntimeError,
1990 "input(): lost sys.stdout");
1991 return NULL;
1992 }
1993 if (ferr == NULL || ferr == Py_None) {
1994 PyErr_SetString(PyExc_RuntimeError,
1995 "input(): lost sys.stderr");
1996 return NULL;
1997 }
Guido van Rossumeba76962007-05-27 09:13:28 +00001998
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001999 /* First of all, flush stderr */
Victor Stinner3466bde2016-09-05 18:16:01 -07002000 tmp = _PyObject_CallMethodId(ferr, &PyId_flush, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002001 if (tmp == NULL)
2002 PyErr_Clear();
2003 else
2004 Py_DECREF(tmp);
Guido van Rossumeba76962007-05-27 09:13:28 +00002005
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002006 /* We should only use (GNU) readline if Python's sys.stdin and
2007 sys.stdout are the same as C's stdin and stdout, because we
2008 need to pass it those. */
Victor Stinner3466bde2016-09-05 18:16:01 -07002009 tmp = _PyObject_CallMethodId(fin, &PyId_fileno, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002010 if (tmp == NULL) {
2011 PyErr_Clear();
2012 tty = 0;
2013 }
2014 else {
2015 fd = PyLong_AsLong(tmp);
2016 Py_DECREF(tmp);
2017 if (fd < 0 && PyErr_Occurred())
2018 return NULL;
2019 tty = fd == fileno(stdin) && isatty(fd);
2020 }
2021 if (tty) {
Victor Stinner3466bde2016-09-05 18:16:01 -07002022 tmp = _PyObject_CallMethodId(fout, &PyId_fileno, NULL);
Martin Panterc9a6ab52015-10-10 01:25:38 +00002023 if (tmp == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002024 PyErr_Clear();
Martin Panterc9a6ab52015-10-10 01:25:38 +00002025 tty = 0;
2026 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002027 else {
2028 fd = PyLong_AsLong(tmp);
2029 Py_DECREF(tmp);
2030 if (fd < 0 && PyErr_Occurred())
2031 return NULL;
2032 tty = fd == fileno(stdout) && isatty(fd);
2033 }
2034 }
Guido van Rossumeba76962007-05-27 09:13:28 +00002035
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002036 /* If we're interactive, use (GNU) readline */
2037 if (tty) {
Antoine Pitrou0d776b12011-11-06 00:34:26 +01002038 PyObject *po = NULL;
Serhiy Storchakae2f92de2017-11-11 13:06:26 +02002039 const char *promptstr;
Antoine Pitrou0d776b12011-11-06 00:34:26 +01002040 char *s = NULL;
2041 PyObject *stdin_encoding = NULL, *stdin_errors = NULL;
2042 PyObject *stdout_encoding = NULL, *stdout_errors = NULL;
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +02002043 const char *stdin_encoding_str, *stdin_errors_str;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002044 PyObject *result;
Victor Stinnerc0f1a1a2011-02-23 12:07:37 +00002045 size_t len;
Martin v. Löwis4a7b5d52007-09-04 05:24:49 +00002046
Serhiy Storchakac2cf1282017-03-12 13:50:36 +02002047 /* stdin is a text stream, so it must have an encoding. */
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02002048 stdin_encoding = _PyObject_GetAttrId(fin, &PyId_encoding);
Antoine Pitrou5ee9d8a2011-11-06 00:38:45 +01002049 stdin_errors = _PyObject_GetAttrId(fin, &PyId_errors);
Serhiy Storchakac2cf1282017-03-12 13:50:36 +02002050 if (!stdin_encoding || !stdin_errors ||
2051 !PyUnicode_Check(stdin_encoding) ||
2052 !PyUnicode_Check(stdin_errors)) {
2053 tty = 0;
Antoine Pitrou0d776b12011-11-06 00:34:26 +01002054 goto _readline_errors;
Serhiy Storchakac2cf1282017-03-12 13:50:36 +02002055 }
Serhiy Storchaka06515832016-11-20 09:13:07 +02002056 stdin_encoding_str = PyUnicode_AsUTF8(stdin_encoding);
2057 stdin_errors_str = PyUnicode_AsUTF8(stdin_errors);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01002058 if (!stdin_encoding_str || !stdin_errors_str)
2059 goto _readline_errors;
Victor Stinner3466bde2016-09-05 18:16:01 -07002060 tmp = _PyObject_CallMethodId(fout, &PyId_flush, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002061 if (tmp == NULL)
2062 PyErr_Clear();
2063 else
2064 Py_DECREF(tmp);
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002065 if (prompt != NULL) {
Antoine Pitrou0d776b12011-11-06 00:34:26 +01002066 /* We have a prompt, encode it as stdout would */
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +02002067 const char *stdout_encoding_str, *stdout_errors_str;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002068 PyObject *stringpo;
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02002069 stdout_encoding = _PyObject_GetAttrId(fout, &PyId_encoding);
Antoine Pitrou5ee9d8a2011-11-06 00:38:45 +01002070 stdout_errors = _PyObject_GetAttrId(fout, &PyId_errors);
Serhiy Storchakac2cf1282017-03-12 13:50:36 +02002071 if (!stdout_encoding || !stdout_errors ||
2072 !PyUnicode_Check(stdout_encoding) ||
2073 !PyUnicode_Check(stdout_errors)) {
2074 tty = 0;
Antoine Pitrou0d776b12011-11-06 00:34:26 +01002075 goto _readline_errors;
Serhiy Storchakac2cf1282017-03-12 13:50:36 +02002076 }
Serhiy Storchaka06515832016-11-20 09:13:07 +02002077 stdout_encoding_str = PyUnicode_AsUTF8(stdout_encoding);
2078 stdout_errors_str = PyUnicode_AsUTF8(stdout_errors);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01002079 if (!stdout_encoding_str || !stdout_errors_str)
2080 goto _readline_errors;
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002081 stringpo = PyObject_Str(prompt);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01002082 if (stringpo == NULL)
2083 goto _readline_errors;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002084 po = PyUnicode_AsEncodedString(stringpo,
Antoine Pitrou0d776b12011-11-06 00:34:26 +01002085 stdout_encoding_str, stdout_errors_str);
2086 Py_CLEAR(stdout_encoding);
2087 Py_CLEAR(stdout_errors);
2088 Py_CLEAR(stringpo);
2089 if (po == NULL)
2090 goto _readline_errors;
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03002091 assert(PyBytes_Check(po));
2092 promptstr = PyBytes_AS_STRING(po);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002093 }
2094 else {
2095 po = NULL;
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002096 promptstr = "";
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002097 }
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002098 s = PyOS_Readline(stdin, stdout, promptstr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002099 if (s == NULL) {
Richard Oudkerk614c5782013-04-03 13:44:50 +01002100 PyErr_CheckSignals();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002101 if (!PyErr_Occurred())
2102 PyErr_SetNone(PyExc_KeyboardInterrupt);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01002103 goto _readline_errors;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002104 }
Victor Stinnerc0f1a1a2011-02-23 12:07:37 +00002105
2106 len = strlen(s);
2107 if (len == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002108 PyErr_SetNone(PyExc_EOFError);
2109 result = NULL;
2110 }
Victor Stinnerc0f1a1a2011-02-23 12:07:37 +00002111 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002112 if (len > PY_SSIZE_T_MAX) {
2113 PyErr_SetString(PyExc_OverflowError,
2114 "input: input too long");
2115 result = NULL;
2116 }
2117 else {
Victor Stinnerc0f1a1a2011-02-23 12:07:37 +00002118 len--; /* strip trailing '\n' */
2119 if (len != 0 && s[len-1] == '\r')
2120 len--; /* strip trailing '\r' */
Antoine Pitrou0d776b12011-11-06 00:34:26 +01002121 result = PyUnicode_Decode(s, len, stdin_encoding_str,
2122 stdin_errors_str);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002123 }
2124 }
2125 Py_DECREF(stdin_encoding);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01002126 Py_DECREF(stdin_errors);
2127 Py_XDECREF(po);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002128 PyMem_FREE(s);
2129 return result;
Serhiy Storchakac2cf1282017-03-12 13:50:36 +02002130
Antoine Pitrou0d776b12011-11-06 00:34:26 +01002131 _readline_errors:
2132 Py_XDECREF(stdin_encoding);
2133 Py_XDECREF(stdout_encoding);
2134 Py_XDECREF(stdin_errors);
2135 Py_XDECREF(stdout_errors);
2136 Py_XDECREF(po);
Serhiy Storchakac2cf1282017-03-12 13:50:36 +02002137 if (tty)
2138 return NULL;
2139
2140 PyErr_Clear();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002141 }
Guido van Rossumeba76962007-05-27 09:13:28 +00002142
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002143 /* Fallback if we're not interactive */
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002144 if (prompt != NULL) {
2145 if (PyFile_WriteObject(prompt, fout, Py_PRINT_RAW) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002146 return NULL;
2147 }
Victor Stinner3466bde2016-09-05 18:16:01 -07002148 tmp = _PyObject_CallMethodId(fout, &PyId_flush, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002149 if (tmp == NULL)
2150 PyErr_Clear();
2151 else
2152 Py_DECREF(tmp);
2153 return PyFile_GetLine(fin, -1);
Guido van Rossuma88a0332007-02-26 16:59:55 +00002154}
2155
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002156
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002157/*[clinic input]
2158repr as builtin_repr
2159
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03002160 obj: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002161 /
2162
2163Return the canonical string representation of the object.
2164
2165For many object types, including most builtins, eval(repr(obj)) == obj.
2166[clinic start generated code]*/
2167
Guido van Rossum79f25d91997-04-29 20:08:16 +00002168static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002169builtin_repr(PyObject *module, PyObject *obj)
2170/*[clinic end generated code: output=7ed3778c44fd0194 input=1c9e6d66d3e3be04]*/
Guido van Rossumc89705d1992-11-26 08:54:07 +00002171{
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002172 return PyObject_Repr(obj);
Guido van Rossumc89705d1992-11-26 08:54:07 +00002173}
2174
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002175
Serhiy Storchakaaca7f572017-11-15 17:51:14 +02002176/*[clinic input]
2177round as builtin_round
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002178
Serhiy Storchakaaca7f572017-11-15 17:51:14 +02002179 number: object
2180 ndigits: object = NULL
2181
2182Round a number to a given precision in decimal digits.
2183
2184The return value is an integer if ndigits is omitted or None. Otherwise
2185the return value has the same type as the number. ndigits may be negative.
2186[clinic start generated code]*/
2187
2188static PyObject *
2189builtin_round_impl(PyObject *module, PyObject *number, PyObject *ndigits)
2190/*[clinic end generated code: output=ff0d9dd176c02ede input=854bc3a217530c3d]*/
2191{
2192 PyObject *round, *result;
Alex Martelliae211f92007-08-22 23:21:33 +00002193
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002194 if (Py_TYPE(number)->tp_dict == NULL) {
2195 if (PyType_Ready(Py_TYPE(number)) < 0)
2196 return NULL;
2197 }
Guido van Rossum15d3d042007-08-24 02:02:45 +00002198
Benjamin Peterson214a7d22013-04-13 17:19:01 -04002199 round = _PyObject_LookupSpecial(number, &PyId___round__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002200 if (round == NULL) {
Benjamin Peterson214a7d22013-04-13 17:19:01 -04002201 if (!PyErr_Occurred())
2202 PyErr_Format(PyExc_TypeError,
2203 "type %.100s doesn't define __round__ method",
2204 Py_TYPE(number)->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002205 return NULL;
2206 }
Alex Martelliae211f92007-08-22 23:21:33 +00002207
Raymond Hettingerf0f1c232016-09-03 01:55:11 -07002208 if (ndigits == NULL || ndigits == Py_None)
Victor Stinnerf17c3de2016-12-06 18:46:19 +01002209 result = _PyObject_CallNoArg(round);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002210 else
Victor Stinnerde4ae3d2016-12-04 22:59:09 +01002211 result = PyObject_CallFunctionObjArgs(round, ndigits, NULL);
Benjamin Peterson214a7d22013-04-13 17:19:01 -04002212 Py_DECREF(round);
2213 return result;
Guido van Rossum9e51f9b1993-02-12 16:29:05 +00002214}
2215
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002216
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002217/*AC: we need to keep the kwds dict intact to easily call into the
2218 * list.sort method, which isn't currently supported in AC. So we just use
2219 * the initially generated signature with a custom implementation.
2220 */
2221/* [disabled clinic input]
2222sorted as builtin_sorted
2223
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03002224 iterable as seq: object
2225 key as keyfunc: object = None
2226 reverse: object = False
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002227
2228Return a new list containing all items from the iterable in ascending order.
2229
Raymond Hettinger7ea386e2016-08-25 21:11:50 -07002230A custom key function can be supplied to customize the sort order, and the
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002231reverse flag can be set to request the result in descending order.
2232[end disabled clinic input]*/
2233
2234PyDoc_STRVAR(builtin_sorted__doc__,
Serhiy Storchaka3a104252017-01-23 12:29:47 +02002235"sorted($module, iterable, /, *, key=None, reverse=False)\n"
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002236"--\n"
2237"\n"
2238"Return a new list containing all items from the iterable in ascending order.\n"
2239"\n"
Raymond Hettinger7ea386e2016-08-25 21:11:50 -07002240"A custom key function can be supplied to customize the sort order, and the\n"
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002241"reverse flag can be set to request the result in descending order.");
2242
2243#define BUILTIN_SORTED_METHODDEF \
Serhiy Storchaka6969eaf2017-07-03 21:20:15 +03002244 {"sorted", (PyCFunction)builtin_sorted, METH_FASTCALL | METH_KEYWORDS, builtin_sorted__doc__},
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002245
Raymond Hettinger64958a12003-12-17 20:43:33 +00002246static PyObject *
Serhiy Storchakaa5552f02017-12-15 13:11:11 +02002247builtin_sorted(PyObject *self, PyObject *const *args, Py_ssize_t nargs, PyObject *kwnames)
Raymond Hettinger64958a12003-12-17 20:43:33 +00002248{
Serhiy Storchaka7cf8beb2017-01-21 23:05:00 +02002249 PyObject *newlist, *v, *seq, *callable;
Victor Stinner5a60eca2017-01-17 15:17:49 +01002250
Serhiy Storchaka7cf8beb2017-01-21 23:05:00 +02002251 /* Keyword arguments are passed through list.sort() which will check
2252 them. */
2253 if (!_PyArg_UnpackStack(args, nargs, "sorted", 1, 1, &seq))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002254 return NULL;
Raymond Hettinger64958a12003-12-17 20:43:33 +00002255
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002256 newlist = PySequence_List(seq);
2257 if (newlist == NULL)
2258 return NULL;
Raymond Hettinger64958a12003-12-17 20:43:33 +00002259
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02002260 callable = _PyObject_GetAttrId(newlist, &PyId_sort);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002261 if (callable == NULL) {
2262 Py_DECREF(newlist);
2263 return NULL;
2264 }
Georg Brandl99d7e4e2005-08-31 22:21:15 +00002265
Serhiy Storchaka299dc232017-01-20 08:35:18 +02002266 assert(nargs >= 1);
Victor Stinner5a60eca2017-01-17 15:17:49 +01002267 v = _PyObject_FastCallKeywords(callable, args + 1, nargs - 1, kwnames);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002268 Py_DECREF(callable);
2269 if (v == NULL) {
2270 Py_DECREF(newlist);
2271 return NULL;
2272 }
2273 Py_DECREF(v);
2274 return newlist;
Raymond Hettinger64958a12003-12-17 20:43:33 +00002275}
2276
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002277
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002278/* AC: cannot convert yet, as needs PEP 457 group support in inspect */
Guido van Rossum79f25d91997-04-29 20:08:16 +00002279static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002280builtin_vars(PyObject *self, PyObject *args)
Guido van Rossum2d951851994-08-29 12:52:16 +00002281{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002282 PyObject *v = NULL;
2283 PyObject *d;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002284
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002285 if (!PyArg_UnpackTuple(args, "vars", 0, 1, &v))
2286 return NULL;
2287 if (v == NULL) {
2288 d = PyEval_GetLocals();
Victor Stinner41bb43a2013-10-29 01:19:37 +01002289 if (d == NULL)
2290 return NULL;
2291 Py_INCREF(d);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002292 }
2293 else {
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02002294 d = _PyObject_GetAttrId(v, &PyId___dict__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002295 if (d == NULL) {
2296 PyErr_SetString(PyExc_TypeError,
2297 "vars() argument must have __dict__ attribute");
2298 return NULL;
2299 }
2300 }
2301 return d;
Guido van Rossum2d951851994-08-29 12:52:16 +00002302}
2303
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002304PyDoc_STRVAR(vars_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002305"vars([object]) -> dictionary\n\
2306\n\
2307Without arguments, equivalent to locals().\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002308With an argument, equivalent to object.__dict__.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002309
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002310
2311/*[clinic input]
2312sum as builtin_sum
2313
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03002314 iterable: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002315 start: object(c_default="NULL") = 0
2316 /
2317
2318Return the sum of a 'start' value (default: 0) plus an iterable of numbers
2319
2320When the iterable is empty, return the start value.
2321This function is intended specifically for use with numeric values and may
2322reject non-numeric types.
2323[clinic start generated code]*/
2324
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002325static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002326builtin_sum_impl(PyObject *module, PyObject *iterable, PyObject *start)
2327/*[clinic end generated code: output=df758cec7d1d302f input=3b5b7a9d7611c73a]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002328{
2329 PyObject *result = start;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002330 PyObject *temp, *item, *iter;
Alex Martellia70b1912003-04-22 08:12:33 +00002331
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002332 iter = PyObject_GetIter(iterable);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002333 if (iter == NULL)
2334 return NULL;
Alex Martellia70b1912003-04-22 08:12:33 +00002335
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002336 if (result == NULL) {
2337 result = PyLong_FromLong(0);
2338 if (result == NULL) {
2339 Py_DECREF(iter);
2340 return NULL;
2341 }
2342 } else {
2343 /* reject string values for 'start' parameter */
2344 if (PyUnicode_Check(result)) {
2345 PyErr_SetString(PyExc_TypeError,
2346 "sum() can't sum strings [use ''.join(seq) instead]");
2347 Py_DECREF(iter);
2348 return NULL;
2349 }
Benjamin Petersonce071ca2011-07-29 14:23:47 -05002350 if (PyBytes_Check(result)) {
2351 PyErr_SetString(PyExc_TypeError,
2352 "sum() can't sum bytes [use b''.join(seq) instead]");
Benjamin Peterson405f32c2011-07-29 22:43:45 -05002353 Py_DECREF(iter);
Benjamin Petersonce071ca2011-07-29 14:23:47 -05002354 return NULL;
2355 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002356 if (PyByteArray_Check(result)) {
2357 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson4f921c22011-07-29 14:24:29 -05002358 "sum() can't sum bytearray [use b''.join(seq) instead]");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002359 Py_DECREF(iter);
2360 return NULL;
2361 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002362 Py_INCREF(result);
2363 }
Alex Martellia70b1912003-04-22 08:12:33 +00002364
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002365#ifndef SLOW_SUM
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002366 /* Fast addition by keeping temporary sums in C instead of new Python objects.
2367 Assumes all inputs are the same type. If the assumption fails, default
2368 to the more general routine.
2369 */
2370 if (PyLong_CheckExact(result)) {
2371 int overflow;
2372 long i_result = PyLong_AsLongAndOverflow(result, &overflow);
2373 /* If this already overflowed, don't even enter the loop. */
2374 if (overflow == 0) {
2375 Py_DECREF(result);
2376 result = NULL;
2377 }
2378 while(result == NULL) {
2379 item = PyIter_Next(iter);
2380 if (item == NULL) {
2381 Py_DECREF(iter);
2382 if (PyErr_Occurred())
2383 return NULL;
2384 return PyLong_FromLong(i_result);
2385 }
2386 if (PyLong_CheckExact(item)) {
2387 long b = PyLong_AsLongAndOverflow(item, &overflow);
2388 long x = i_result + b;
2389 if (overflow == 0 && ((x^i_result) >= 0 || (x^b) >= 0)) {
2390 i_result = x;
2391 Py_DECREF(item);
2392 continue;
2393 }
2394 }
2395 /* Either overflowed or is not an int. Restore real objects and process normally */
2396 result = PyLong_FromLong(i_result);
Christian Heimes704e2d32013-07-26 22:49:26 +02002397 if (result == NULL) {
2398 Py_DECREF(item);
2399 Py_DECREF(iter);
2400 return NULL;
2401 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002402 temp = PyNumber_Add(result, item);
2403 Py_DECREF(result);
2404 Py_DECREF(item);
2405 result = temp;
2406 if (result == NULL) {
2407 Py_DECREF(iter);
2408 return NULL;
2409 }
2410 }
2411 }
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002412
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002413 if (PyFloat_CheckExact(result)) {
2414 double f_result = PyFloat_AS_DOUBLE(result);
2415 Py_DECREF(result);
2416 result = NULL;
2417 while(result == NULL) {
2418 item = PyIter_Next(iter);
2419 if (item == NULL) {
2420 Py_DECREF(iter);
2421 if (PyErr_Occurred())
2422 return NULL;
2423 return PyFloat_FromDouble(f_result);
2424 }
2425 if (PyFloat_CheckExact(item)) {
2426 PyFPE_START_PROTECT("add", Py_DECREF(item); Py_DECREF(iter); return 0)
2427 f_result += PyFloat_AS_DOUBLE(item);
2428 PyFPE_END_PROTECT(f_result)
2429 Py_DECREF(item);
2430 continue;
2431 }
2432 if (PyLong_CheckExact(item)) {
2433 long value;
2434 int overflow;
2435 value = PyLong_AsLongAndOverflow(item, &overflow);
2436 if (!overflow) {
2437 PyFPE_START_PROTECT("add", Py_DECREF(item); Py_DECREF(iter); return 0)
2438 f_result += (double)value;
2439 PyFPE_END_PROTECT(f_result)
2440 Py_DECREF(item);
2441 continue;
2442 }
2443 }
2444 result = PyFloat_FromDouble(f_result);
2445 temp = PyNumber_Add(result, item);
2446 Py_DECREF(result);
2447 Py_DECREF(item);
2448 result = temp;
2449 if (result == NULL) {
2450 Py_DECREF(iter);
2451 return NULL;
2452 }
2453 }
2454 }
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002455#endif
2456
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002457 for(;;) {
2458 item = PyIter_Next(iter);
2459 if (item == NULL) {
2460 /* error, or end-of-sequence */
2461 if (PyErr_Occurred()) {
2462 Py_DECREF(result);
2463 result = NULL;
2464 }
2465 break;
2466 }
2467 /* It's tempting to use PyNumber_InPlaceAdd instead of
2468 PyNumber_Add here, to avoid quadratic running time
2469 when doing 'sum(list_of_lists, [])'. However, this
2470 would produce a change in behaviour: a snippet like
Mark Dickinson9acadc52009-10-26 14:19:42 +00002471
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002472 empty = []
2473 sum([[x] for x in range(10)], empty)
Mark Dickinson9acadc52009-10-26 14:19:42 +00002474
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002475 would change the value of empty. */
2476 temp = PyNumber_Add(result, item);
2477 Py_DECREF(result);
2478 Py_DECREF(item);
2479 result = temp;
2480 if (result == NULL)
2481 break;
2482 }
2483 Py_DECREF(iter);
2484 return result;
Alex Martellia70b1912003-04-22 08:12:33 +00002485}
2486
Alex Martellia70b1912003-04-22 08:12:33 +00002487
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002488/*[clinic input]
2489isinstance as builtin_isinstance
2490
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03002491 obj: object
2492 class_or_tuple: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002493 /
2494
2495Return whether an object is an instance of a class or of a subclass thereof.
2496
2497A tuple, as in ``isinstance(x, (A, B, ...))``, may be given as the target to
2498check against. This is equivalent to ``isinstance(x, A) or isinstance(x, B)
2499or ...`` etc.
2500[clinic start generated code]*/
2501
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002502static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002503builtin_isinstance_impl(PyObject *module, PyObject *obj,
Larry Hastings89964c42015-04-14 18:07:59 -04002504 PyObject *class_or_tuple)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002505/*[clinic end generated code: output=6faf01472c13b003 input=ffa743db1daf7549]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002506{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002507 int retval;
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002508
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002509 retval = PyObject_IsInstance(obj, class_or_tuple);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002510 if (retval < 0)
2511 return NULL;
2512 return PyBool_FromLong(retval);
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002513}
2514
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002515
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002516/*[clinic input]
2517issubclass as builtin_issubclass
2518
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03002519 cls: object
2520 class_or_tuple: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002521 /
2522
2523Return whether 'cls' is a derived from another class or is the same class.
2524
2525A tuple, as in ``issubclass(x, (A, B, ...))``, may be given as the target to
2526check against. This is equivalent to ``issubclass(x, A) or issubclass(x, B)
2527or ...`` etc.
2528[clinic start generated code]*/
2529
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002530static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002531builtin_issubclass_impl(PyObject *module, PyObject *cls,
Larry Hastings89964c42015-04-14 18:07:59 -04002532 PyObject *class_or_tuple)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002533/*[clinic end generated code: output=358412410cd7a250 input=af5f35e9ceaddaf6]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002534{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002535 int retval;
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002536
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002537 retval = PyObject_IsSubclass(cls, class_or_tuple);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002538 if (retval < 0)
2539 return NULL;
2540 return PyBool_FromLong(retval);
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002541}
2542
2543
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002544typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002545 PyObject_HEAD
2546 Py_ssize_t tuplesize;
2547 PyObject *ittuple; /* tuple of iterators */
2548 PyObject *result;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002549} zipobject;
2550
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002551static PyObject *
2552zip_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
Barry Warsawbd599b52000-08-03 15:45:29 +00002553{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002554 zipobject *lz;
2555 Py_ssize_t i;
2556 PyObject *ittuple; /* tuple of iterators */
2557 PyObject *result;
Serhiy Storchakabf623ae2017-04-19 20:03:52 +03002558 Py_ssize_t tuplesize;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002559
Serhiy Storchaka6cca5c82017-06-08 14:41:19 +03002560 if (type == &PyZip_Type && !_PyArg_NoKeywords("zip", kwds))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002561 return NULL;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002562
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002563 /* args must be a tuple */
2564 assert(PyTuple_Check(args));
Serhiy Storchakabf623ae2017-04-19 20:03:52 +03002565 tuplesize = PyTuple_GET_SIZE(args);
Barry Warsawbd599b52000-08-03 15:45:29 +00002566
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002567 /* obtain iterators */
2568 ittuple = PyTuple_New(tuplesize);
2569 if (ittuple == NULL)
2570 return NULL;
2571 for (i=0; i < tuplesize; ++i) {
2572 PyObject *item = PyTuple_GET_ITEM(args, i);
2573 PyObject *it = PyObject_GetIter(item);
2574 if (it == NULL) {
2575 if (PyErr_ExceptionMatches(PyExc_TypeError))
2576 PyErr_Format(PyExc_TypeError,
2577 "zip argument #%zd must support iteration",
2578 i+1);
2579 Py_DECREF(ittuple);
2580 return NULL;
2581 }
2582 PyTuple_SET_ITEM(ittuple, i, it);
2583 }
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002584
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002585 /* create a result holder */
2586 result = PyTuple_New(tuplesize);
2587 if (result == NULL) {
2588 Py_DECREF(ittuple);
2589 return NULL;
2590 }
2591 for (i=0 ; i < tuplesize ; i++) {
2592 Py_INCREF(Py_None);
2593 PyTuple_SET_ITEM(result, i, Py_None);
2594 }
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002595
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002596 /* create zipobject structure */
2597 lz = (zipobject *)type->tp_alloc(type, 0);
2598 if (lz == NULL) {
2599 Py_DECREF(ittuple);
2600 Py_DECREF(result);
2601 return NULL;
2602 }
2603 lz->ittuple = ittuple;
2604 lz->tuplesize = tuplesize;
2605 lz->result = result;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002606
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002607 return (PyObject *)lz;
Barry Warsawbd599b52000-08-03 15:45:29 +00002608}
2609
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002610static void
2611zip_dealloc(zipobject *lz)
2612{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002613 PyObject_GC_UnTrack(lz);
2614 Py_XDECREF(lz->ittuple);
2615 Py_XDECREF(lz->result);
2616 Py_TYPE(lz)->tp_free(lz);
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002617}
2618
2619static int
2620zip_traverse(zipobject *lz, visitproc visit, void *arg)
2621{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002622 Py_VISIT(lz->ittuple);
2623 Py_VISIT(lz->result);
2624 return 0;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002625}
2626
2627static PyObject *
2628zip_next(zipobject *lz)
2629{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002630 Py_ssize_t i;
2631 Py_ssize_t tuplesize = lz->tuplesize;
2632 PyObject *result = lz->result;
2633 PyObject *it;
2634 PyObject *item;
2635 PyObject *olditem;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002636
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002637 if (tuplesize == 0)
2638 return NULL;
2639 if (Py_REFCNT(result) == 1) {
2640 Py_INCREF(result);
2641 for (i=0 ; i < tuplesize ; i++) {
2642 it = PyTuple_GET_ITEM(lz->ittuple, i);
2643 item = (*Py_TYPE(it)->tp_iternext)(it);
Serhiy Storchaka278d03b2013-04-06 22:52:34 +03002644 if (item == NULL) {
2645 Py_DECREF(result);
2646 return NULL;
2647 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002648 olditem = PyTuple_GET_ITEM(result, i);
2649 PyTuple_SET_ITEM(result, i, item);
2650 Py_DECREF(olditem);
2651 }
2652 } else {
2653 result = PyTuple_New(tuplesize);
2654 if (result == NULL)
Serhiy Storchaka278d03b2013-04-06 22:52:34 +03002655 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002656 for (i=0 ; i < tuplesize ; i++) {
2657 it = PyTuple_GET_ITEM(lz->ittuple, i);
2658 item = (*Py_TYPE(it)->tp_iternext)(it);
Serhiy Storchaka278d03b2013-04-06 22:52:34 +03002659 if (item == NULL) {
2660 Py_DECREF(result);
2661 return NULL;
2662 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002663 PyTuple_SET_ITEM(result, i, item);
2664 }
2665 }
2666 return result;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002667}
Barry Warsawbd599b52000-08-03 15:45:29 +00002668
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002669static PyObject *
2670zip_reduce(zipobject *lz)
2671{
2672 /* Just recreate the zip with the internal iterator tuple */
2673 return Py_BuildValue("OO", Py_TYPE(lz), lz->ittuple);
2674}
2675
2676static PyMethodDef zip_methods[] = {
2677 {"__reduce__", (PyCFunction)zip_reduce, METH_NOARGS, reduce_doc},
2678 {NULL, NULL} /* sentinel */
2679};
2680
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002681PyDoc_STRVAR(zip_doc,
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002682"zip(iter1 [,iter2 [...]]) --> zip object\n\
Barry Warsawbd599b52000-08-03 15:45:29 +00002683\n\
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002684Return a zip object whose .__next__() method returns a tuple where\n\
2685the i-th element comes from the i-th iterable argument. The .__next__()\n\
2686method continues until the shortest iterable in the argument sequence\n\
Georg Brandlced51db2008-12-04 18:28:38 +00002687is exhausted and then it raises StopIteration.");
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002688
2689PyTypeObject PyZip_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002690 PyVarObject_HEAD_INIT(&PyType_Type, 0)
2691 "zip", /* tp_name */
2692 sizeof(zipobject), /* tp_basicsize */
2693 0, /* tp_itemsize */
2694 /* methods */
2695 (destructor)zip_dealloc, /* tp_dealloc */
2696 0, /* tp_print */
2697 0, /* tp_getattr */
2698 0, /* tp_setattr */
2699 0, /* tp_reserved */
2700 0, /* tp_repr */
2701 0, /* tp_as_number */
2702 0, /* tp_as_sequence */
2703 0, /* tp_as_mapping */
2704 0, /* tp_hash */
2705 0, /* tp_call */
2706 0, /* tp_str */
2707 PyObject_GenericGetAttr, /* tp_getattro */
2708 0, /* tp_setattro */
2709 0, /* tp_as_buffer */
2710 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
2711 Py_TPFLAGS_BASETYPE, /* tp_flags */
2712 zip_doc, /* tp_doc */
2713 (traverseproc)zip_traverse, /* tp_traverse */
2714 0, /* tp_clear */
2715 0, /* tp_richcompare */
2716 0, /* tp_weaklistoffset */
2717 PyObject_SelfIter, /* tp_iter */
2718 (iternextfunc)zip_next, /* tp_iternext */
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002719 zip_methods, /* tp_methods */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002720 0, /* tp_members */
2721 0, /* tp_getset */
2722 0, /* tp_base */
2723 0, /* tp_dict */
2724 0, /* tp_descr_get */
2725 0, /* tp_descr_set */
2726 0, /* tp_dictoffset */
2727 0, /* tp_init */
2728 PyType_GenericAlloc, /* tp_alloc */
2729 zip_new, /* tp_new */
2730 PyObject_GC_Del, /* tp_free */
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002731};
Barry Warsawbd599b52000-08-03 15:45:29 +00002732
2733
Guido van Rossum79f25d91997-04-29 20:08:16 +00002734static PyMethodDef builtin_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002735 {"__build_class__", (PyCFunction)builtin___build_class__,
Serhiy Storchaka6969eaf2017-07-03 21:20:15 +03002736 METH_FASTCALL | METH_KEYWORDS, build_class_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002737 {"__import__", (PyCFunction)builtin___import__, METH_VARARGS | METH_KEYWORDS, import_doc},
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002738 BUILTIN_ABS_METHODDEF
2739 BUILTIN_ALL_METHODDEF
2740 BUILTIN_ANY_METHODDEF
2741 BUILTIN_ASCII_METHODDEF
2742 BUILTIN_BIN_METHODDEF
Barry Warsaw36c1d1f2017-10-05 12:11:18 -04002743 {"breakpoint", (PyCFunction)builtin_breakpoint, METH_FASTCALL | METH_KEYWORDS, breakpoint_doc},
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002744 BUILTIN_CALLABLE_METHODDEF
2745 BUILTIN_CHR_METHODDEF
2746 BUILTIN_COMPILE_METHODDEF
2747 BUILTIN_DELATTR_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002748 {"dir", builtin_dir, METH_VARARGS, dir_doc},
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002749 BUILTIN_DIVMOD_METHODDEF
2750 BUILTIN_EVAL_METHODDEF
2751 BUILTIN_EXEC_METHODDEF
2752 BUILTIN_FORMAT_METHODDEF
Victor Stinner84b388b2017-01-17 03:52:27 +01002753 {"getattr", (PyCFunction)builtin_getattr, METH_FASTCALL, getattr_doc},
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002754 BUILTIN_GLOBALS_METHODDEF
2755 BUILTIN_HASATTR_METHODDEF
2756 BUILTIN_HASH_METHODDEF
2757 BUILTIN_HEX_METHODDEF
2758 BUILTIN_ID_METHODDEF
2759 BUILTIN_INPUT_METHODDEF
2760 BUILTIN_ISINSTANCE_METHODDEF
2761 BUILTIN_ISSUBCLASS_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002762 {"iter", builtin_iter, METH_VARARGS, iter_doc},
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002763 BUILTIN_LEN_METHODDEF
2764 BUILTIN_LOCALS_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002765 {"max", (PyCFunction)builtin_max, METH_VARARGS | METH_KEYWORDS, max_doc},
2766 {"min", (PyCFunction)builtin_min, METH_VARARGS | METH_KEYWORDS, min_doc},
Victor Stinnerfda6d0a2017-01-17 04:09:14 +01002767 {"next", (PyCFunction)builtin_next, METH_FASTCALL, next_doc},
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002768 BUILTIN_OCT_METHODDEF
2769 BUILTIN_ORD_METHODDEF
2770 BUILTIN_POW_METHODDEF
Serhiy Storchaka6969eaf2017-07-03 21:20:15 +03002771 {"print", (PyCFunction)builtin_print, METH_FASTCALL | METH_KEYWORDS, print_doc},
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002772 BUILTIN_REPR_METHODDEF
Serhiy Storchakaaca7f572017-11-15 17:51:14 +02002773 BUILTIN_ROUND_METHODDEF
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002774 BUILTIN_SETATTR_METHODDEF
2775 BUILTIN_SORTED_METHODDEF
2776 BUILTIN_SUM_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002777 {"vars", builtin_vars, METH_VARARGS, vars_doc},
2778 {NULL, NULL},
Guido van Rossum3f5da241990-12-20 15:06:42 +00002779};
2780
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002781PyDoc_STRVAR(builtin_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002782"Built-in functions, exceptions, and other objects.\n\
2783\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002784Noteworthy: None is the `nil' object; Ellipsis represents `...' in slices.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002785
Martin v. Löwis1a214512008-06-11 05:26:20 +00002786static struct PyModuleDef builtinsmodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002787 PyModuleDef_HEAD_INIT,
2788 "builtins",
2789 builtin_doc,
2790 -1, /* multiple "initialization" just copies the module dict. */
2791 builtin_methods,
2792 NULL,
2793 NULL,
2794 NULL,
2795 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00002796};
2797
2798
Guido van Rossum25ce5661997-08-02 03:10:38 +00002799PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002800_PyBuiltin_Init(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +00002801{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002802 PyObject *mod, *dict, *debug;
Benjamin Peterson42124a72012-10-30 23:41:54 -04002803
2804 if (PyType_Ready(&PyFilter_Type) < 0 ||
2805 PyType_Ready(&PyMap_Type) < 0 ||
2806 PyType_Ready(&PyZip_Type) < 0)
2807 return NULL;
2808
Eric Snowd393c1b2017-09-14 12:18:12 -06002809 mod = _PyModule_CreateInitialized(&builtinsmodule, PYTHON_API_VERSION);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002810 if (mod == NULL)
2811 return NULL;
2812 dict = PyModule_GetDict(mod);
Tim Peters4b7625e2001-09-13 21:37:17 +00002813
Tim Peters7571a0f2003-03-23 17:52:28 +00002814#ifdef Py_TRACE_REFS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002815 /* "builtins" exposes a number of statically allocated objects
2816 * that, before this code was added in 2.3, never showed up in
2817 * the list of "all objects" maintained by Py_TRACE_REFS. As a
2818 * result, programs leaking references to None and False (etc)
2819 * couldn't be diagnosed by examining sys.getobjects(0).
2820 */
Tim Peters7571a0f2003-03-23 17:52:28 +00002821#define ADD_TO_ALL(OBJECT) _Py_AddToAllObjects((PyObject *)(OBJECT), 0)
2822#else
2823#define ADD_TO_ALL(OBJECT) (void)0
2824#endif
2825
Tim Peters4b7625e2001-09-13 21:37:17 +00002826#define SETBUILTIN(NAME, OBJECT) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002827 if (PyDict_SetItemString(dict, NAME, (PyObject *)OBJECT) < 0) \
2828 return NULL; \
2829 ADD_TO_ALL(OBJECT)
Tim Peters4b7625e2001-09-13 21:37:17 +00002830
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002831 SETBUILTIN("None", Py_None);
2832 SETBUILTIN("Ellipsis", Py_Ellipsis);
2833 SETBUILTIN("NotImplemented", Py_NotImplemented);
2834 SETBUILTIN("False", Py_False);
2835 SETBUILTIN("True", Py_True);
2836 SETBUILTIN("bool", &PyBool_Type);
2837 SETBUILTIN("memoryview", &PyMemoryView_Type);
2838 SETBUILTIN("bytearray", &PyByteArray_Type);
2839 SETBUILTIN("bytes", &PyBytes_Type);
2840 SETBUILTIN("classmethod", &PyClassMethod_Type);
2841 SETBUILTIN("complex", &PyComplex_Type);
2842 SETBUILTIN("dict", &PyDict_Type);
2843 SETBUILTIN("enumerate", &PyEnum_Type);
2844 SETBUILTIN("filter", &PyFilter_Type);
2845 SETBUILTIN("float", &PyFloat_Type);
2846 SETBUILTIN("frozenset", &PyFrozenSet_Type);
2847 SETBUILTIN("property", &PyProperty_Type);
2848 SETBUILTIN("int", &PyLong_Type);
2849 SETBUILTIN("list", &PyList_Type);
2850 SETBUILTIN("map", &PyMap_Type);
2851 SETBUILTIN("object", &PyBaseObject_Type);
2852 SETBUILTIN("range", &PyRange_Type);
2853 SETBUILTIN("reversed", &PyReversed_Type);
2854 SETBUILTIN("set", &PySet_Type);
2855 SETBUILTIN("slice", &PySlice_Type);
2856 SETBUILTIN("staticmethod", &PyStaticMethod_Type);
2857 SETBUILTIN("str", &PyUnicode_Type);
2858 SETBUILTIN("super", &PySuper_Type);
2859 SETBUILTIN("tuple", &PyTuple_Type);
2860 SETBUILTIN("type", &PyType_Type);
2861 SETBUILTIN("zip", &PyZip_Type);
2862 debug = PyBool_FromLong(Py_OptimizeFlag == 0);
2863 if (PyDict_SetItemString(dict, "__debug__", debug) < 0) {
Serhiy Storchakacfdfbb42016-06-18 09:44:03 +03002864 Py_DECREF(debug);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002865 return NULL;
2866 }
Serhiy Storchakacfdfbb42016-06-18 09:44:03 +03002867 Py_DECREF(debug);
Barry Warsaw757af0e1997-08-29 22:13:51 +00002868
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002869 return mod;
Tim Peters7571a0f2003-03-23 17:52:28 +00002870#undef ADD_TO_ALL
Tim Peters4b7625e2001-09-13 21:37:17 +00002871#undef SETBUILTIN
Guido van Rossum3f5da241990-12-20 15:06:42 +00002872}