blob: 63f19986760088a6a39df8d9839bb14659c50dc6 [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";
Mark Hammondef8b6542001-05-13 08:04:26 +000032
Victor Stinnerbd303c12013-11-07 23:07:29 +010033_Py_IDENTIFIER(__builtins__);
34_Py_IDENTIFIER(__dict__);
35_Py_IDENTIFIER(__prepare__);
36_Py_IDENTIFIER(__round__);
37_Py_IDENTIFIER(encoding);
38_Py_IDENTIFIER(errors);
Martin v. Löwisbd928fe2011-10-14 10:20:37 +020039_Py_IDENTIFIER(fileno);
40_Py_IDENTIFIER(flush);
Victor Stinnerbd303c12013-11-07 23:07:29 +010041_Py_IDENTIFIER(metaclass);
42_Py_IDENTIFIER(sort);
43_Py_IDENTIFIER(stdin);
44_Py_IDENTIFIER(stdout);
45_Py_IDENTIFIER(stderr);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +020046
Serhiy Storchaka1009bf12015-04-03 23:53:51 +030047#include "clinic/bltinmodule.c.h"
48
Nick Coghlanf9e227e2014-08-17 14:01:19 +100049/* AC: cannot convert yet, waiting for *args support */
Guido van Rossum79f25d91997-04-29 20:08:16 +000050static PyObject *
Victor Stinner773dc6d2017-01-16 23:46:26 +010051builtin___build_class__(PyObject *self, PyObject **args, Py_ssize_t nargs,
52 PyObject *kwnames)
Guido van Rossum52cc1d82007-03-18 15:41:51 +000053{
Nick Coghlan19d24672016-12-05 16:47:55 +100054 PyObject *func, *name, *bases, *mkw, *meta, *winner, *prep, *ns;
55 PyObject *cls = NULL, *cell = NULL;
Victor Stinner0c39b1b2015-03-18 15:02:06 +010056 int isclass = 0; /* initialize to prevent gcc warning */
Guido van Rossum52cc1d82007-03-18 15:41:51 +000057
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000058 if (nargs < 2) {
59 PyErr_SetString(PyExc_TypeError,
60 "__build_class__: not enough arguments");
61 return NULL;
62 }
Victor Stinner773dc6d2017-01-16 23:46:26 +010063 func = args[0]; /* Better be callable */
Benjamin Petersone8e14592013-05-16 14:37:25 -050064 if (!PyFunction_Check(func)) {
65 PyErr_SetString(PyExc_TypeError,
Zachary Ware9b338722014-08-05 14:01:10 -050066 "__build_class__: func must be a function");
Benjamin Petersone8e14592013-05-16 14:37:25 -050067 return NULL;
68 }
Victor Stinner773dc6d2017-01-16 23:46:26 +010069 name = args[1];
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000070 if (!PyUnicode_Check(name)) {
71 PyErr_SetString(PyExc_TypeError,
72 "__build_class__: name is not a string");
73 return NULL;
74 }
Victor Stinner773dc6d2017-01-16 23:46:26 +010075 bases = _PyStack_AsTupleSlice(args, nargs, 2, nargs);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000076 if (bases == NULL)
77 return NULL;
Guido van Rossum52cc1d82007-03-18 15:41:51 +000078
Victor Stinner773dc6d2017-01-16 23:46:26 +010079 if (kwnames == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000080 meta = NULL;
81 mkw = NULL;
82 }
83 else {
Victor Stinner773dc6d2017-01-16 23:46:26 +010084 mkw = _PyStack_AsDict(args + nargs, kwnames);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000085 if (mkw == NULL) {
86 Py_DECREF(bases);
87 return NULL;
Guido van Rossum52cc1d82007-03-18 15:41:51 +000088 }
Victor Stinner773dc6d2017-01-16 23:46:26 +010089
Victor Stinnerae9f1612013-11-06 22:46:51 +010090 meta = _PyDict_GetItemId(mkw, &PyId_metaclass);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000091 if (meta != NULL) {
92 Py_INCREF(meta);
Victor Stinnerae9f1612013-11-06 22:46:51 +010093 if (_PyDict_DelItemId(mkw, &PyId_metaclass) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000094 Py_DECREF(meta);
95 Py_DECREF(mkw);
96 Py_DECREF(bases);
97 return NULL;
98 }
Nick Coghlande31b192011-10-23 22:04:16 +100099 /* metaclass is explicitly given, check if it's indeed a class */
100 isclass = PyType_Check(meta);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000101 }
102 }
103 if (meta == NULL) {
Nick Coghlande31b192011-10-23 22:04:16 +1000104 /* if there are no bases, use type: */
105 if (PyTuple_GET_SIZE(bases) == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000106 meta = (PyObject *) (&PyType_Type);
Nick Coghlande31b192011-10-23 22:04:16 +1000107 }
108 /* else get the type of the first base */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000109 else {
110 PyObject *base0 = PyTuple_GET_ITEM(bases, 0);
111 meta = (PyObject *) (base0->ob_type);
112 }
113 Py_INCREF(meta);
Nick Coghlande31b192011-10-23 22:04:16 +1000114 isclass = 1; /* meta is really a class */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000115 }
Nick Coghlan9715d262011-10-23 22:36:42 +1000116
Nick Coghlande31b192011-10-23 22:04:16 +1000117 if (isclass) {
118 /* meta is really a class, so check for a more derived
119 metaclass, or possible metaclass conflicts: */
120 winner = (PyObject *)_PyType_CalculateMetaclass((PyTypeObject *)meta,
121 bases);
122 if (winner == NULL) {
123 Py_DECREF(meta);
124 Py_XDECREF(mkw);
125 Py_DECREF(bases);
126 return NULL;
127 }
128 if (winner != meta) {
129 Py_DECREF(meta);
130 meta = winner;
131 Py_INCREF(meta);
132 }
133 }
134 /* else: meta is not a class, so we cannot do the metaclass
135 calculation, so we will use the explicitly given object as it is */
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +0200136 prep = _PyObject_GetAttrId(meta, &PyId___prepare__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000137 if (prep == NULL) {
138 if (PyErr_ExceptionMatches(PyExc_AttributeError)) {
139 PyErr_Clear();
Eric Snow4f29e752016-09-08 15:11:11 -0700140 ns = PyDict_New();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000141 }
142 else {
143 Py_DECREF(meta);
144 Py_XDECREF(mkw);
145 Py_DECREF(bases);
146 return NULL;
147 }
148 }
149 else {
Victor Stinner463b86a2016-08-22 23:33:13 +0200150 PyObject *pargs[2] = {name, bases};
151 ns = _PyObject_FastCallDict(prep, pargs, 2, mkw);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000152 Py_DECREF(prep);
153 }
154 if (ns == NULL) {
155 Py_DECREF(meta);
156 Py_XDECREF(mkw);
157 Py_DECREF(bases);
158 return NULL;
159 }
Nick Coghlan19d24672016-12-05 16:47:55 +1000160 cell = PyEval_EvalCodeEx(PyFunction_GET_CODE(func), PyFunction_GET_GLOBALS(func), ns,
Benjamin Petersone8e14592013-05-16 14:37:25 -0500161 NULL, 0, NULL, 0, NULL, 0, NULL,
162 PyFunction_GET_CLOSURE(func));
Nick Coghlan19d24672016-12-05 16:47:55 +1000163 if (cell != NULL) {
Victor Stinnerd1c2a8e2016-08-23 01:34:35 +0200164 PyObject *margs[3] = {name, bases, ns};
165 cls = _PyObject_FastCallDict(meta, margs, 3, mkw);
Nick Coghlan19d24672016-12-05 16:47:55 +1000166 if (cls != NULL && PyType_Check(cls) && PyCell_Check(cell)) {
167 PyObject *cell_cls = PyCell_GET(cell);
168 if (cell_cls != cls) {
169 /* TODO: In 3.7, DeprecationWarning will become RuntimeError.
170 * At that point, cell_error won't be needed.
171 */
172 int cell_error;
173 if (cell_cls == NULL) {
174 const char *msg =
175 "__class__ not set defining %.200R as %.200R. "
176 "Was __classcell__ propagated to type.__new__?";
177 cell_error = PyErr_WarnFormat(
178 PyExc_DeprecationWarning, 1, msg, name, cls);
179 } else {
180 const char *msg =
181 "__class__ set to %.200R defining %.200R as %.200R";
182 PyErr_Format(PyExc_TypeError, msg, cell_cls, name, cls);
183 cell_error = 1;
184 }
185 if (cell_error) {
186 Py_DECREF(cls);
187 cls = NULL;
188 goto error;
189 } else {
190 /* Fill in the cell, since type.__new__ didn't do it */
191 PyCell_Set(cell, cls);
192 }
193 }
194 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000195 }
Nick Coghlan19d24672016-12-05 16:47:55 +1000196error:
197 Py_XDECREF(cell);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000198 Py_DECREF(ns);
199 Py_DECREF(meta);
200 Py_XDECREF(mkw);
201 Py_DECREF(bases);
202 return cls;
Guido van Rossum52cc1d82007-03-18 15:41:51 +0000203}
204
205PyDoc_STRVAR(build_class_doc,
206"__build_class__(func, name, *bases, metaclass=None, **kwds) -> class\n\
207\n\
208Internal helper function used by the class statement.");
209
210static PyObject *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000211builtin___import__(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000212{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000213 static char *kwlist[] = {"name", "globals", "locals", "fromlist",
214 "level", 0};
Victor Stinnerfe93faf2011-03-14 15:54:52 -0400215 PyObject *name, *globals = NULL, *locals = NULL, *fromlist = NULL;
Brett Cannonfd074152012-04-14 14:10:13 -0400216 int level = 0;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000217
Victor Stinnerfe93faf2011-03-14 15:54:52 -0400218 if (!PyArg_ParseTupleAndKeywords(args, kwds, "U|OOOi:__import__",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000219 kwlist, &name, &globals, &locals, &fromlist, &level))
220 return NULL;
Victor Stinnerfe93faf2011-03-14 15:54:52 -0400221 return PyImport_ImportModuleLevelObject(name, globals, locals,
222 fromlist, level);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000223}
224
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000225PyDoc_STRVAR(import_doc,
Brett Cannoncb4996a2012-08-06 16:34:44 -0400226"__import__(name, globals=None, locals=None, fromlist=(), level=0) -> module\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000227\n\
Brett Cannon5305a992010-09-27 21:08:38 +0000228Import a module. Because this function is meant for use by the Python\n\
229interpreter and not for general use it is better to use\n\
230importlib.import_module() to programmatically import a module.\n\
231\n\
232The globals argument is only used to determine the context;\n\
233they are not modified. The locals argument is unused. The fromlist\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000234should be a list of names to emulate ``from name import ...'', or an\n\
235empty list to emulate ``import name''.\n\
236When importing a module from a package, note that __import__('A.B', ...)\n\
237returns package A when fromlist is empty, but its submodule B when\n\
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000238fromlist is not empty. Level is used to determine whether to perform \n\
Brett Cannon722d3ae2012-07-30 17:45:54 -0400239absolute or relative imports. 0 is absolute while a positive number\n\
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000240is the number of parent directories to search relative to the current module.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000241
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000242
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000243/*[clinic input]
244abs as builtin_abs
245
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300246 x: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000247 /
248
249Return the absolute value of the argument.
250[clinic start generated code]*/
251
Guido van Rossum79f25d91997-04-29 20:08:16 +0000252static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300253builtin_abs(PyObject *module, PyObject *x)
254/*[clinic end generated code: output=b1b433b9e51356f5 input=bed4ca14e29c20d1]*/
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000255{
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000256 return PyNumber_Absolute(x);
Guido van Rossum3f5da241990-12-20 15:06:42 +0000257}
258
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000259/*[clinic input]
260all as builtin_all
261
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300262 iterable: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000263 /
264
265Return True if bool(x) is True for all values x in the iterable.
266
267If the iterable is empty, return True.
268[clinic start generated code]*/
269
Raymond Hettinger96229b12005-03-11 06:49:40 +0000270static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300271builtin_all(PyObject *module, PyObject *iterable)
272/*[clinic end generated code: output=ca2a7127276f79b3 input=1a7c5d1bc3438a21]*/
Raymond Hettinger96229b12005-03-11 06:49:40 +0000273{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000274 PyObject *it, *item;
275 PyObject *(*iternext)(PyObject *);
276 int cmp;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000277
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000278 it = PyObject_GetIter(iterable);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000279 if (it == NULL)
280 return NULL;
281 iternext = *Py_TYPE(it)->tp_iternext;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000282
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000283 for (;;) {
284 item = iternext(it);
285 if (item == NULL)
286 break;
287 cmp = PyObject_IsTrue(item);
288 Py_DECREF(item);
289 if (cmp < 0) {
290 Py_DECREF(it);
291 return NULL;
292 }
293 if (cmp == 0) {
294 Py_DECREF(it);
295 Py_RETURN_FALSE;
296 }
297 }
298 Py_DECREF(it);
299 if (PyErr_Occurred()) {
300 if (PyErr_ExceptionMatches(PyExc_StopIteration))
301 PyErr_Clear();
302 else
303 return NULL;
304 }
305 Py_RETURN_TRUE;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000306}
307
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000308/*[clinic input]
309any as builtin_any
310
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300311 iterable: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000312 /
313
314Return True if bool(x) is True for any x in the iterable.
315
316If the iterable is empty, return False.
317[clinic start generated code]*/
318
Raymond Hettinger96229b12005-03-11 06:49:40 +0000319static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300320builtin_any(PyObject *module, PyObject *iterable)
321/*[clinic end generated code: output=fa65684748caa60e input=41d7451c23384f24]*/
Raymond Hettinger96229b12005-03-11 06:49:40 +0000322{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000323 PyObject *it, *item;
324 PyObject *(*iternext)(PyObject *);
325 int cmp;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000326
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000327 it = PyObject_GetIter(iterable);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000328 if (it == NULL)
329 return NULL;
330 iternext = *Py_TYPE(it)->tp_iternext;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000331
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000332 for (;;) {
333 item = iternext(it);
334 if (item == NULL)
335 break;
336 cmp = PyObject_IsTrue(item);
337 Py_DECREF(item);
338 if (cmp < 0) {
339 Py_DECREF(it);
340 return NULL;
341 }
Raymond Hettinger5098b582015-10-09 00:42:47 -0400342 if (cmp > 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000343 Py_DECREF(it);
344 Py_RETURN_TRUE;
345 }
346 }
347 Py_DECREF(it);
348 if (PyErr_Occurred()) {
349 if (PyErr_ExceptionMatches(PyExc_StopIteration))
350 PyErr_Clear();
351 else
352 return NULL;
353 }
354 Py_RETURN_FALSE;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000355}
356
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000357/*[clinic input]
358ascii as builtin_ascii
359
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300360 obj: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000361 /
362
363Return an ASCII-only representation of an object.
364
365As repr(), return a string containing a printable representation of an
366object, but escape the non-ASCII characters in the string returned by
367repr() using \\x, \\u or \\U escapes. This generates a string similar
368to that returned by repr() in Python 2.
369[clinic start generated code]*/
370
Georg Brandl559e5d72008-06-11 18:37:52 +0000371static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300372builtin_ascii(PyObject *module, PyObject *obj)
373/*[clinic end generated code: output=6d37b3f0984c7eb9 input=4c62732e1b3a3cc9]*/
Georg Brandl559e5d72008-06-11 18:37:52 +0000374{
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000375 return PyObject_ASCII(obj);
Georg Brandl559e5d72008-06-11 18:37:52 +0000376}
377
Georg Brandl559e5d72008-06-11 18:37:52 +0000378
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000379/*[clinic input]
380bin as builtin_bin
381
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300382 number: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000383 /
384
385Return the binary representation of an integer.
386
387 >>> bin(2796202)
388 '0b1010101010101010101010'
389[clinic start generated code]*/
390
Guido van Rossum79f25d91997-04-29 20:08:16 +0000391static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300392builtin_bin(PyObject *module, PyObject *number)
393/*[clinic end generated code: output=b6fc4ad5e649f4f7 input=53f8a0264bacaf90]*/
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000394{
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000395 return PyNumber_ToBase(number, 2);
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000396}
397
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000398
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000399/*[clinic input]
400callable as builtin_callable
401
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300402 obj: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000403 /
404
405Return whether the object is callable (i.e., some kind of function).
406
407Note that classes are callable, as are instances of classes with a
408__call__() method.
409[clinic start generated code]*/
410
Antoine Pitroue71362d2010-11-27 22:00:11 +0000411static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300412builtin_callable(PyObject *module, PyObject *obj)
413/*[clinic end generated code: output=2b095d59d934cb7e input=1423bab99cc41f58]*/
Antoine Pitroue71362d2010-11-27 22:00:11 +0000414{
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000415 return PyBool_FromLong((long)PyCallable_Check(obj));
Antoine Pitroue71362d2010-11-27 22:00:11 +0000416}
417
Antoine Pitroue71362d2010-11-27 22:00:11 +0000418
Raymond Hettinger17301e92008-03-13 00:19:26 +0000419typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000420 PyObject_HEAD
421 PyObject *func;
422 PyObject *it;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000423} filterobject;
424
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000425static PyObject *
Raymond Hettinger17301e92008-03-13 00:19:26 +0000426filter_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
Guido van Rossum12d12c51993-10-26 17:58:25 +0000427{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000428 PyObject *func, *seq;
429 PyObject *it;
430 filterobject *lz;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000431
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000432 if (type == &PyFilter_Type && !_PyArg_NoKeywords("filter()", kwds))
433 return NULL;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000434
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000435 if (!PyArg_UnpackTuple(args, "filter", 2, 2, &func, &seq))
436 return NULL;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000437
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000438 /* Get iterator. */
439 it = PyObject_GetIter(seq);
440 if (it == NULL)
441 return NULL;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000442
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000443 /* create filterobject structure */
444 lz = (filterobject *)type->tp_alloc(type, 0);
445 if (lz == NULL) {
446 Py_DECREF(it);
447 return NULL;
448 }
449 Py_INCREF(func);
450 lz->func = func;
451 lz->it = it;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000452
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000453 return (PyObject *)lz;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000454}
455
456static void
457filter_dealloc(filterobject *lz)
458{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000459 PyObject_GC_UnTrack(lz);
460 Py_XDECREF(lz->func);
461 Py_XDECREF(lz->it);
462 Py_TYPE(lz)->tp_free(lz);
Raymond Hettinger17301e92008-03-13 00:19:26 +0000463}
464
465static int
466filter_traverse(filterobject *lz, visitproc visit, void *arg)
467{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000468 Py_VISIT(lz->it);
469 Py_VISIT(lz->func);
470 return 0;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000471}
472
473static PyObject *
474filter_next(filterobject *lz)
475{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000476 PyObject *item;
477 PyObject *it = lz->it;
478 long ok;
479 PyObject *(*iternext)(PyObject *);
Raymond Hettingerbd5f0e82015-10-09 01:34:08 -0400480 int checktrue = lz->func == Py_None || lz->func == (PyObject *)&PyBool_Type;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000481
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000482 iternext = *Py_TYPE(it)->tp_iternext;
483 for (;;) {
484 item = iternext(it);
485 if (item == NULL)
486 return NULL;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000487
Raymond Hettingerbd5f0e82015-10-09 01:34:08 -0400488 if (checktrue) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000489 ok = PyObject_IsTrue(item);
490 } else {
491 PyObject *good;
Victor Stinnerde4ae3d2016-12-04 22:59:09 +0100492 good = PyObject_CallFunctionObjArgs(lz->func, item, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000493 if (good == NULL) {
494 Py_DECREF(item);
495 return NULL;
496 }
497 ok = PyObject_IsTrue(good);
498 Py_DECREF(good);
499 }
Antoine Pitrou6f430e42012-08-15 23:18:25 +0200500 if (ok > 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000501 return item;
502 Py_DECREF(item);
Antoine Pitrou6f430e42012-08-15 23:18:25 +0200503 if (ok < 0)
504 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000505 }
Guido van Rossum12d12c51993-10-26 17:58:25 +0000506}
507
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +0000508static PyObject *
509filter_reduce(filterobject *lz)
510{
511 return Py_BuildValue("O(OO)", Py_TYPE(lz), lz->func, lz->it);
512}
513
514PyDoc_STRVAR(reduce_doc, "Return state information for pickling.");
515
516static PyMethodDef filter_methods[] = {
517 {"__reduce__", (PyCFunction)filter_reduce, METH_NOARGS, reduce_doc},
518 {NULL, NULL} /* sentinel */
519};
520
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000521PyDoc_STRVAR(filter_doc,
Georg Brandld11ae5d2008-05-16 13:27:32 +0000522"filter(function or None, iterable) --> filter object\n\
Guido van Rossumc1f779c2007-07-03 08:25:58 +0000523\n\
Georg Brandld11ae5d2008-05-16 13:27:32 +0000524Return an iterator yielding those items of iterable for which function(item)\n\
Raymond Hettinger17301e92008-03-13 00:19:26 +0000525is true. If function is None, return the items that are true.");
526
527PyTypeObject PyFilter_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000528 PyVarObject_HEAD_INIT(&PyType_Type, 0)
529 "filter", /* tp_name */
530 sizeof(filterobject), /* tp_basicsize */
531 0, /* tp_itemsize */
532 /* methods */
533 (destructor)filter_dealloc, /* tp_dealloc */
534 0, /* tp_print */
535 0, /* tp_getattr */
536 0, /* tp_setattr */
537 0, /* tp_reserved */
538 0, /* tp_repr */
539 0, /* tp_as_number */
540 0, /* tp_as_sequence */
541 0, /* tp_as_mapping */
542 0, /* tp_hash */
543 0, /* tp_call */
544 0, /* tp_str */
545 PyObject_GenericGetAttr, /* tp_getattro */
546 0, /* tp_setattro */
547 0, /* tp_as_buffer */
548 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
549 Py_TPFLAGS_BASETYPE, /* tp_flags */
550 filter_doc, /* tp_doc */
551 (traverseproc)filter_traverse, /* tp_traverse */
552 0, /* tp_clear */
553 0, /* tp_richcompare */
554 0, /* tp_weaklistoffset */
555 PyObject_SelfIter, /* tp_iter */
556 (iternextfunc)filter_next, /* tp_iternext */
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +0000557 filter_methods, /* tp_methods */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000558 0, /* tp_members */
559 0, /* tp_getset */
560 0, /* tp_base */
561 0, /* tp_dict */
562 0, /* tp_descr_get */
563 0, /* tp_descr_set */
564 0, /* tp_dictoffset */
565 0, /* tp_init */
566 PyType_GenericAlloc, /* tp_alloc */
567 filter_new, /* tp_new */
568 PyObject_GC_Del, /* tp_free */
Raymond Hettinger17301e92008-03-13 00:19:26 +0000569};
570
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000571
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000572/*[clinic input]
573format as builtin_format
574
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300575 value: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000576 format_spec: unicode(c_default="NULL") = ''
577 /
578
579Return value.__format__(format_spec)
580
581format_spec defaults to the empty string
582[clinic start generated code]*/
583
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000584static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300585builtin_format_impl(PyObject *module, PyObject *value, PyObject *format_spec)
586/*[clinic end generated code: output=2f40bdfa4954b077 input=6325e751a1b29b86]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000587{
Eric Smith8fd3eba2008-02-17 19:48:00 +0000588 return PyObject_Format(value, format_spec);
Eric Smith8c663262007-08-25 02:26:07 +0000589}
590
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000591/*[clinic input]
592chr as builtin_chr
593
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300594 i: int
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000595 /
596
597Return a Unicode string of one character with ordinal i; 0 <= i <= 0x10ffff.
598[clinic start generated code]*/
599
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000600static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300601builtin_chr_impl(PyObject *module, int i)
602/*[clinic end generated code: output=c733afcd200afcb7 input=3f604ef45a70750d]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000603{
604 return PyUnicode_FromOrdinal(i);
605}
Guido van Rossum09095f32000-03-10 23:00:52 +0000606
607
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +0200608static const char *
Martin Pantereeb896c2015-11-07 02:32:21 +0000609source_as_string(PyObject *cmd, const char *funcname, const char *what, PyCompilerFlags *cf, PyObject **cmd_copy)
Guido van Rossumf15a29f2007-05-04 00:41:39 +0000610{
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +0200611 const char *str;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000612 Py_ssize_t size;
Martin Pantereeb896c2015-11-07 02:32:21 +0000613 Py_buffer view;
Guido van Rossumf15a29f2007-05-04 00:41:39 +0000614
Martin Pantereeb896c2015-11-07 02:32:21 +0000615 *cmd_copy = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000616 if (PyUnicode_Check(cmd)) {
617 cf->cf_flags |= PyCF_IGNORE_COOKIE;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200618 str = PyUnicode_AsUTF8AndSize(cmd, &size);
619 if (str == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000620 return NULL;
621 }
Martin Pantereeb896c2015-11-07 02:32:21 +0000622 else if (PyBytes_Check(cmd)) {
623 str = PyBytes_AS_STRING(cmd);
624 size = PyBytes_GET_SIZE(cmd);
625 }
626 else if (PyByteArray_Check(cmd)) {
627 str = PyByteArray_AS_STRING(cmd);
628 size = PyByteArray_GET_SIZE(cmd);
629 }
630 else if (PyObject_GetBuffer(cmd, &view, PyBUF_SIMPLE) == 0) {
631 /* Copy to NUL-terminated buffer. */
632 *cmd_copy = PyBytes_FromStringAndSize(
633 (const char *)view.buf, view.len);
634 PyBuffer_Release(&view);
635 if (*cmd_copy == NULL) {
636 return NULL;
637 }
638 str = PyBytes_AS_STRING(*cmd_copy);
639 size = PyBytes_GET_SIZE(*cmd_copy);
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +0200640 }
641 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000642 PyErr_Format(PyExc_TypeError,
643 "%s() arg 1 must be a %s object",
644 funcname, what);
645 return NULL;
646 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200647
Serhiy Storchaka3dd3e262015-02-03 01:25:42 +0200648 if (strlen(str) != (size_t)size) {
Serhiy Storchakad8a14472014-09-06 20:07:17 +0300649 PyErr_SetString(PyExc_ValueError,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000650 "source code string cannot contain null bytes");
Martin Pantereeb896c2015-11-07 02:32:21 +0000651 Py_CLEAR(*cmd_copy);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000652 return NULL;
653 }
654 return str;
Guido van Rossumf15a29f2007-05-04 00:41:39 +0000655}
656
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000657/*[clinic input]
658compile as builtin_compile
659
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300660 source: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000661 filename: object(converter="PyUnicode_FSDecoder")
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300662 mode: str
663 flags: int = 0
Serhiy Storchaka8b2e8b62015-05-30 11:30:39 +0300664 dont_inherit: int(c_default="0") = False
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300665 optimize: int = -1
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000666
667Compile source into a code object that can be executed by exec() or eval().
668
669The source code may represent a Python module, statement or expression.
670The filename will be used for run-time error messages.
671The mode must be 'exec' to compile a module, 'single' to compile a
672single (interactive) statement, or 'eval' to compile an expression.
673The flags argument, if present, controls which future statements influence
674the compilation of the code.
Serhiy Storchaka8b2e8b62015-05-30 11:30:39 +0300675The dont_inherit argument, if true, stops the compilation inheriting
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000676the effects of any future statements in effect in the code calling
Serhiy Storchaka8b2e8b62015-05-30 11:30:39 +0300677compile; if absent or false these statements do influence the compilation,
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000678in addition to any features explicitly specified.
679[clinic start generated code]*/
680
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000681static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300682builtin_compile_impl(PyObject *module, PyObject *source, PyObject *filename,
683 const char *mode, int flags, int dont_inherit,
684 int optimize)
685/*[clinic end generated code: output=1fa176e33452bb63 input=9d53e8cfb3c86414]*/
Guido van Rossum5b722181993-03-30 17:46:03 +0000686{
Martin Panter61d6e4a2015-11-07 02:56:11 +0000687 PyObject *source_copy;
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +0200688 const char *str;
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000689 int compile_mode = -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000690 int is_ast;
691 PyCompilerFlags cf;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000692 int start[] = {Py_file_input, Py_eval_input, Py_single_input};
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000693 PyObject *result;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000694
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000695 cf.cf_flags = flags | PyCF_SOURCE_IS_UTF8;
Tim Peters6cd6a822001-08-17 22:11:27 +0000696
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000697 if (flags &
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000698 ~(PyCF_MASK | PyCF_MASK_OBSOLETE | PyCF_DONT_IMPLY_DEDENT | PyCF_ONLY_AST))
699 {
700 PyErr_SetString(PyExc_ValueError,
701 "compile(): unrecognised flags");
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000702 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000703 }
704 /* XXX Warn if (supplied_flags & PyCF_MASK_OBSOLETE) != 0? */
Tim Peters6cd6a822001-08-17 22:11:27 +0000705
Georg Brandl8334fd92010-12-04 10:26:46 +0000706 if (optimize < -1 || optimize > 2) {
707 PyErr_SetString(PyExc_ValueError,
708 "compile(): invalid optimize value");
709 goto error;
710 }
711
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000712 if (!dont_inherit) {
713 PyEval_MergeCompilerFlags(&cf);
714 }
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000715
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000716 if (strcmp(mode, "exec") == 0)
717 compile_mode = 0;
718 else if (strcmp(mode, "eval") == 0)
719 compile_mode = 1;
720 else if (strcmp(mode, "single") == 0)
721 compile_mode = 2;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000722 else {
723 PyErr_SetString(PyExc_ValueError,
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000724 "compile() mode must be 'exec', 'eval' or 'single'");
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000725 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000726 }
Neal Norwitzdb4115f2008-03-31 04:20:05 +0000727
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000728 is_ast = PyAST_Check(source);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000729 if (is_ast == -1)
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000730 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000731 if (is_ast) {
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000732 if (flags & PyCF_ONLY_AST) {
733 Py_INCREF(source);
734 result = source;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000735 }
736 else {
737 PyArena *arena;
738 mod_ty mod;
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000739
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000740 arena = PyArena_New();
Stefan Krah07795df2012-08-20 17:19:50 +0200741 if (arena == NULL)
742 goto error;
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000743 mod = PyAST_obj2mod(source, arena, compile_mode);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000744 if (mod == NULL) {
745 PyArena_Free(arena);
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000746 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000747 }
Benjamin Peterson832bfe22011-08-09 16:15:04 -0500748 if (!PyAST_Validate(mod)) {
749 PyArena_Free(arena);
750 goto error;
751 }
Victor Stinner14e461d2013-08-26 22:28:21 +0200752 result = (PyObject*)PyAST_CompileObject(mod, filename,
753 &cf, optimize, arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000754 PyArena_Free(arena);
755 }
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000756 goto finally;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000757 }
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000758
Martin Panter61d6e4a2015-11-07 02:56:11 +0000759 str = source_as_string(source, "compile", "string, bytes or AST", &cf, &source_copy);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000760 if (str == NULL)
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000761 goto error;
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000762
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000763 result = Py_CompileStringObject(str, filename, start[compile_mode], &cf, optimize);
Martin Panter61d6e4a2015-11-07 02:56:11 +0000764 Py_XDECREF(source_copy);
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000765 goto finally;
766
767error:
768 result = NULL;
769finally:
Victor Stinner14e461d2013-08-26 22:28:21 +0200770 Py_DECREF(filename);
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000771 return result;
Guido van Rossum5b722181993-03-30 17:46:03 +0000772}
773
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000774/* AC: cannot convert yet, as needs PEP 457 group support in inspect */
Guido van Rossum79f25d91997-04-29 20:08:16 +0000775static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000776builtin_dir(PyObject *self, PyObject *args)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000777{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000778 PyObject *arg = NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000779
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000780 if (!PyArg_UnpackTuple(args, "dir", 0, 1, &arg))
781 return NULL;
782 return PyObject_Dir(arg);
Guido van Rossum3f5da241990-12-20 15:06:42 +0000783}
784
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000785PyDoc_STRVAR(dir_doc,
Tim Peters5d2b77c2001-09-03 05:47:38 +0000786"dir([object]) -> list of strings\n"
787"\n"
Georg Brandle32b4222007-03-10 22:13:27 +0000788"If called without an argument, return the names in the current scope.\n"
789"Else, return an alphabetized list of names comprising (some of) the attributes\n"
790"of the given object, and of attributes reachable from it.\n"
791"If the object supplies a method named __dir__, it will be used; otherwise\n"
792"the default dir() logic is used and returns:\n"
793" for a module object: the module's attributes.\n"
794" for a class object: its attributes, and recursively the attributes\n"
795" of its bases.\n"
Guido van Rossumd8faa362007-04-27 19:54:29 +0000796" for any other object: its attributes, its class's attributes, and\n"
Georg Brandle32b4222007-03-10 22:13:27 +0000797" recursively the attributes of its class's base classes.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000798
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000799/*[clinic input]
800divmod as builtin_divmod
Guido van Rossum6a00cd81995-01-07 12:39:01 +0000801
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300802 x: object
803 y: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000804 /
805
Zachary Ware7f227d92016-04-28 14:39:50 -0500806Return the tuple (x//y, x%y). Invariant: div*y + mod == x.
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000807[clinic start generated code]*/
808
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000809static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300810builtin_divmod_impl(PyObject *module, PyObject *x, PyObject *y)
811/*[clinic end generated code: output=b06d8a5f6e0c745e input=175ad9c84ff41a85]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000812{
813 return PyNumber_Divmod(x, y);
814}
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000815
816
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000817/*[clinic input]
818eval as builtin_eval
819
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300820 source: object
821 globals: object = None
822 locals: object = None
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000823 /
824
825Evaluate the given source in the context of globals and locals.
826
827The source may be a string representing a Python expression
828or a code object as returned by compile().
829The globals must be a dictionary and locals can be any mapping,
830defaulting to the current globals and locals.
831If only globals is given, locals defaults to it.
832[clinic start generated code]*/
833
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000834static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300835builtin_eval_impl(PyObject *module, PyObject *source, PyObject *globals,
Larry Hastings89964c42015-04-14 18:07:59 -0400836 PyObject *locals)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300837/*[clinic end generated code: output=0a0824aa70093116 input=11ee718a8640e527]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000838{
Martin Panter61d6e4a2015-11-07 02:56:11 +0000839 PyObject *result, *source_copy;
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +0200840 const char *str;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000841 PyCompilerFlags cf;
Guido van Rossum590baa41993-11-30 13:40:46 +0000842
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000843 if (locals != Py_None && !PyMapping_Check(locals)) {
844 PyErr_SetString(PyExc_TypeError, "locals must be a mapping");
845 return NULL;
846 }
847 if (globals != Py_None && !PyDict_Check(globals)) {
848 PyErr_SetString(PyExc_TypeError, PyMapping_Check(globals) ?
849 "globals must be a real dict; try eval(expr, {}, mapping)"
850 : "globals must be a dict");
851 return NULL;
852 }
853 if (globals == Py_None) {
854 globals = PyEval_GetGlobals();
Victor Stinner41bb43a2013-10-29 01:19:37 +0100855 if (locals == Py_None) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000856 locals = PyEval_GetLocals();
Victor Stinner41bb43a2013-10-29 01:19:37 +0100857 if (locals == NULL)
858 return NULL;
859 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000860 }
861 else if (locals == Py_None)
862 locals = globals;
Tim Peters9fa96be2001-08-17 23:04:59 +0000863
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000864 if (globals == NULL || locals == NULL) {
865 PyErr_SetString(PyExc_TypeError,
866 "eval must be given globals and locals "
867 "when called without a frame");
868 return NULL;
869 }
Georg Brandl77c85e62005-09-15 10:46:13 +0000870
Victor Stinnerb44562b2013-11-06 19:03:11 +0100871 if (_PyDict_GetItemId(globals, &PyId___builtins__) == NULL) {
872 if (_PyDict_SetItemId(globals, &PyId___builtins__,
873 PyEval_GetBuiltins()) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000874 return NULL;
875 }
Tim Peters9fa96be2001-08-17 23:04:59 +0000876
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000877 if (PyCode_Check(source)) {
878 if (PyCode_GetNumFree((PyCodeObject *)source) > 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000879 PyErr_SetString(PyExc_TypeError,
880 "code object passed to eval() may not contain free variables");
881 return NULL;
882 }
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000883 return PyEval_EvalCode(source, globals, locals);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000884 }
Tim Peters9fa96be2001-08-17 23:04:59 +0000885
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000886 cf.cf_flags = PyCF_SOURCE_IS_UTF8;
Martin Panter61d6e4a2015-11-07 02:56:11 +0000887 str = source_as_string(source, "eval", "string, bytes or code", &cf, &source_copy);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000888 if (str == NULL)
889 return NULL;
Just van Rossum3aaf42c2003-02-10 08:21:10 +0000890
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000891 while (*str == ' ' || *str == '\t')
892 str++;
Tim Peters9fa96be2001-08-17 23:04:59 +0000893
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000894 (void)PyEval_MergeCompilerFlags(&cf);
895 result = PyRun_StringFlags(str, Py_eval_input, globals, locals, &cf);
Martin Panter61d6e4a2015-11-07 02:56:11 +0000896 Py_XDECREF(source_copy);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000897 return result;
Guido van Rossum3f5da241990-12-20 15:06:42 +0000898}
899
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000900/*[clinic input]
901exec as builtin_exec
902
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300903 source: object
904 globals: object = None
905 locals: object = None
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000906 /
907
908Execute the given source in the context of globals and locals.
909
910The source may be a string representing one or more Python statements
911or a code object as returned by compile().
912The globals must be a dictionary and locals can be any mapping,
913defaulting to the current globals and locals.
914If only globals is given, locals defaults to it.
915[clinic start generated code]*/
916
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000917static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300918builtin_exec_impl(PyObject *module, PyObject *source, PyObject *globals,
Larry Hastings89964c42015-04-14 18:07:59 -0400919 PyObject *locals)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300920/*[clinic end generated code: output=3c90efc6ab68ef5d input=01ca3e1c01692829]*/
Georg Brandl7cae87c2006-09-06 06:51:57 +0000921{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000922 PyObject *v;
Georg Brandl2cabc562008-08-28 07:57:16 +0000923
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000924 if (globals == Py_None) {
925 globals = PyEval_GetGlobals();
926 if (locals == Py_None) {
927 locals = PyEval_GetLocals();
Victor Stinner41bb43a2013-10-29 01:19:37 +0100928 if (locals == NULL)
929 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000930 }
931 if (!globals || !locals) {
932 PyErr_SetString(PyExc_SystemError,
933 "globals and locals cannot be NULL");
934 return NULL;
935 }
936 }
937 else if (locals == Py_None)
938 locals = globals;
Georg Brandl7cae87c2006-09-06 06:51:57 +0000939
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000940 if (!PyDict_Check(globals)) {
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000941 PyErr_Format(PyExc_TypeError, "exec() globals must be a dict, not %.100s",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000942 globals->ob_type->tp_name);
943 return NULL;
944 }
945 if (!PyMapping_Check(locals)) {
946 PyErr_Format(PyExc_TypeError,
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000947 "locals must be a mapping or None, not %.100s",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000948 locals->ob_type->tp_name);
949 return NULL;
950 }
Victor Stinnerb44562b2013-11-06 19:03:11 +0100951 if (_PyDict_GetItemId(globals, &PyId___builtins__) == NULL) {
952 if (_PyDict_SetItemId(globals, &PyId___builtins__,
953 PyEval_GetBuiltins()) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000954 return NULL;
955 }
956
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000957 if (PyCode_Check(source)) {
958 if (PyCode_GetNumFree((PyCodeObject *)source) > 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000959 PyErr_SetString(PyExc_TypeError,
960 "code object passed to exec() may not "
961 "contain free variables");
962 return NULL;
963 }
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000964 v = PyEval_EvalCode(source, globals, locals);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000965 }
966 else {
Martin Panter61d6e4a2015-11-07 02:56:11 +0000967 PyObject *source_copy;
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +0200968 const char *str;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000969 PyCompilerFlags cf;
970 cf.cf_flags = PyCF_SOURCE_IS_UTF8;
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000971 str = source_as_string(source, "exec",
Martin Panter61d6e4a2015-11-07 02:56:11 +0000972 "string, bytes or code", &cf,
973 &source_copy);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000974 if (str == NULL)
975 return NULL;
976 if (PyEval_MergeCompilerFlags(&cf))
977 v = PyRun_StringFlags(str, Py_file_input, globals,
978 locals, &cf);
979 else
980 v = PyRun_String(str, Py_file_input, globals, locals);
Martin Panter61d6e4a2015-11-07 02:56:11 +0000981 Py_XDECREF(source_copy);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000982 }
983 if (v == NULL)
984 return NULL;
985 Py_DECREF(v);
986 Py_RETURN_NONE;
Georg Brandl7cae87c2006-09-06 06:51:57 +0000987}
988
Georg Brandl7cae87c2006-09-06 06:51:57 +0000989
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000990/* AC: cannot convert yet, as needs PEP 457 group support in inspect */
Guido van Rossum79f25d91997-04-29 20:08:16 +0000991static PyObject *
Victor Stinner84b388b2017-01-17 03:52:27 +0100992builtin_getattr(PyObject *self, PyObject **args, Py_ssize_t nargs,
993 PyObject *kwnames)
Guido van Rossum33894be1992-01-27 16:53:09 +0000994{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000995 PyObject *v, *result, *dflt = NULL;
996 PyObject *name;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000997
Victor Stinner84b388b2017-01-17 03:52:27 +0100998 if (!_PyArg_UnpackStack(args, nargs, "getattr", 2, 3, &v, &name, &dflt))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000999 return NULL;
Martin v. Löwis5b222132007-06-10 09:51:05 +00001000
Victor Stinner84b388b2017-01-17 03:52:27 +01001001 if (!_PyArg_NoStackKeywords("getattr", kwnames)) {
1002 return NULL;
1003 }
1004
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001005 if (!PyUnicode_Check(name)) {
1006 PyErr_SetString(PyExc_TypeError,
1007 "getattr(): attribute name must be string");
1008 return NULL;
1009 }
1010 result = PyObject_GetAttr(v, name);
1011 if (result == NULL && dflt != NULL &&
1012 PyErr_ExceptionMatches(PyExc_AttributeError))
1013 {
1014 PyErr_Clear();
1015 Py_INCREF(dflt);
1016 result = dflt;
1017 }
1018 return result;
Guido van Rossum9bfef441993-03-29 10:43:31 +00001019}
1020
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001021PyDoc_STRVAR(getattr_doc,
Guido van Rossum950ff291998-06-29 13:38:57 +00001022"getattr(object, name[, default]) -> value\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001023\n\
Guido van Rossum950ff291998-06-29 13:38:57 +00001024Get a named attribute from an object; getattr(x, 'y') is equivalent to x.y.\n\
1025When a default argument is given, it is returned when the attribute doesn't\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001026exist; without it, an exception is raised in that case.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001027
1028
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001029/*[clinic input]
1030globals as builtin_globals
1031
1032Return the dictionary containing the current scope's global variables.
1033
1034NOTE: Updates to this dictionary *will* affect name lookups in the current
1035global scope and vice-versa.
1036[clinic start generated code]*/
1037
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001038static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001039builtin_globals_impl(PyObject *module)
1040/*[clinic end generated code: output=e5dd1527067b94d2 input=9327576f92bb48ba]*/
Guido van Rossum872537c1995-07-07 22:43:42 +00001041{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001042 PyObject *d;
Guido van Rossum872537c1995-07-07 22:43:42 +00001043
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001044 d = PyEval_GetGlobals();
1045 Py_XINCREF(d);
1046 return d;
Guido van Rossum872537c1995-07-07 22:43:42 +00001047}
1048
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001049
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001050/*[clinic input]
1051hasattr as builtin_hasattr
1052
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001053 obj: object
1054 name: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001055 /
1056
1057Return whether the object has an attribute with the given name.
1058
1059This is done by calling getattr(obj, name) and catching AttributeError.
1060[clinic start generated code]*/
1061
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001062static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001063builtin_hasattr_impl(PyObject *module, PyObject *obj, PyObject *name)
1064/*[clinic end generated code: output=a7aff2090a4151e5 input=0faec9787d979542]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001065{
1066 PyObject *v;
1067
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001068 if (!PyUnicode_Check(name)) {
1069 PyErr_SetString(PyExc_TypeError,
1070 "hasattr(): attribute name must be string");
1071 return NULL;
1072 }
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001073 v = PyObject_GetAttr(obj, name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001074 if (v == NULL) {
Benjamin Peterson17689992010-08-24 03:26:23 +00001075 if (PyErr_ExceptionMatches(PyExc_AttributeError)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001076 PyErr_Clear();
Benjamin Peterson17689992010-08-24 03:26:23 +00001077 Py_RETURN_FALSE;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001078 }
Benjamin Peterson17689992010-08-24 03:26:23 +00001079 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001080 }
1081 Py_DECREF(v);
Benjamin Peterson17689992010-08-24 03:26:23 +00001082 Py_RETURN_TRUE;
Guido van Rossum33894be1992-01-27 16:53:09 +00001083}
1084
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001085
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001086/* AC: gdb's integration with CPython relies on builtin_id having
1087 * the *exact* parameter names of "self" and "v", so we ensure we
1088 * preserve those name rather than using the AC defaults.
1089 */
1090/*[clinic input]
1091id as builtin_id
1092
Serhiy Storchaka24182a32016-05-05 16:21:35 +03001093 self: self(type="PyModuleDef *")
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001094 obj as v: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001095 /
1096
1097Return the identity of an object.
1098
1099This is guaranteed to be unique among simultaneously existing objects.
1100(CPython uses the object's memory address.)
1101[clinic start generated code]*/
1102
Guido van Rossum79f25d91997-04-29 20:08:16 +00001103static PyObject *
Serhiy Storchaka24182a32016-05-05 16:21:35 +03001104builtin_id(PyModuleDef *self, PyObject *v)
1105/*[clinic end generated code: output=0aa640785f697f65 input=5a534136419631f4]*/
Guido van Rossum5b722181993-03-30 17:46:03 +00001106{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001107 return PyLong_FromVoidPtr(v);
Guido van Rossum5b722181993-03-30 17:46:03 +00001108}
1109
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001110
Raymond Hettingera6c60372008-03-13 01:26:19 +00001111/* map object ************************************************************/
1112
1113typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001114 PyObject_HEAD
1115 PyObject *iters;
1116 PyObject *func;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001117} mapobject;
1118
Guido van Rossum79f25d91997-04-29 20:08:16 +00001119static PyObject *
Raymond Hettingera6c60372008-03-13 01:26:19 +00001120map_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
Guido van Rossum12d12c51993-10-26 17:58:25 +00001121{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001122 PyObject *it, *iters, *func;
1123 mapobject *lz;
1124 Py_ssize_t numargs, i;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001125
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001126 if (type == &PyMap_Type && !_PyArg_NoKeywords("map()", kwds))
1127 return NULL;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001128
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001129 numargs = PyTuple_Size(args);
1130 if (numargs < 2) {
1131 PyErr_SetString(PyExc_TypeError,
1132 "map() must have at least two arguments.");
1133 return NULL;
1134 }
Raymond Hettingera6c60372008-03-13 01:26:19 +00001135
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001136 iters = PyTuple_New(numargs-1);
1137 if (iters == NULL)
1138 return NULL;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001139
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001140 for (i=1 ; i<numargs ; i++) {
1141 /* Get iterator. */
1142 it = PyObject_GetIter(PyTuple_GET_ITEM(args, i));
1143 if (it == NULL) {
1144 Py_DECREF(iters);
1145 return NULL;
1146 }
1147 PyTuple_SET_ITEM(iters, i-1, it);
1148 }
Raymond Hettingera6c60372008-03-13 01:26:19 +00001149
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001150 /* create mapobject structure */
1151 lz = (mapobject *)type->tp_alloc(type, 0);
1152 if (lz == NULL) {
1153 Py_DECREF(iters);
1154 return NULL;
1155 }
1156 lz->iters = iters;
1157 func = PyTuple_GET_ITEM(args, 0);
1158 Py_INCREF(func);
1159 lz->func = func;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001160
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001161 return (PyObject *)lz;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001162}
1163
1164static void
1165map_dealloc(mapobject *lz)
1166{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001167 PyObject_GC_UnTrack(lz);
1168 Py_XDECREF(lz->iters);
1169 Py_XDECREF(lz->func);
1170 Py_TYPE(lz)->tp_free(lz);
Raymond Hettingera6c60372008-03-13 01:26:19 +00001171}
1172
1173static int
1174map_traverse(mapobject *lz, visitproc visit, void *arg)
1175{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001176 Py_VISIT(lz->iters);
1177 Py_VISIT(lz->func);
1178 return 0;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001179}
1180
1181static PyObject *
1182map_next(mapobject *lz)
1183{
Victor Stinnerbc08ab42016-12-15 12:40:53 +01001184 PyObject *small_stack[_PY_FASTCALL_SMALL_STACK];
Victor Stinnercdb5cee2016-08-24 01:45:13 +02001185 PyObject **stack;
1186 Py_ssize_t niters, nargs, i;
1187 PyObject *result = NULL;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001188
Victor Stinnercdb5cee2016-08-24 01:45:13 +02001189 niters = PyTuple_GET_SIZE(lz->iters);
1190 if (niters <= (Py_ssize_t)Py_ARRAY_LENGTH(small_stack)) {
1191 stack = small_stack;
1192 }
1193 else {
1194 stack = PyMem_Malloc(niters * sizeof(stack[0]));
1195 if (stack == NULL) {
1196 PyErr_NoMemory();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001197 return NULL;
1198 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001199 }
Victor Stinnercdb5cee2016-08-24 01:45:13 +02001200
1201 nargs = 0;
1202 for (i=0; i < niters; i++) {
1203 PyObject *it = PyTuple_GET_ITEM(lz->iters, i);
1204 PyObject *val = Py_TYPE(it)->tp_iternext(it);
1205 if (val == NULL) {
1206 goto exit;
1207 }
1208 stack[i] = val;
1209 nargs++;
1210 }
1211
1212 result = _PyObject_FastCall(lz->func, stack, nargs);
1213
1214exit:
1215 for (i=0; i < nargs; i++) {
1216 Py_DECREF(stack[i]);
1217 }
1218 if (stack != small_stack) {
1219 PyMem_Free(stack);
1220 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001221 return result;
Guido van Rossum12d12c51993-10-26 17:58:25 +00001222}
1223
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001224static PyObject *
1225map_reduce(mapobject *lz)
1226{
1227 Py_ssize_t numargs = PyTuple_GET_SIZE(lz->iters);
1228 PyObject *args = PyTuple_New(numargs+1);
1229 Py_ssize_t i;
1230 if (args == NULL)
1231 return NULL;
1232 Py_INCREF(lz->func);
1233 PyTuple_SET_ITEM(args, 0, lz->func);
1234 for (i = 0; i<numargs; i++){
1235 PyObject *it = PyTuple_GET_ITEM(lz->iters, i);
1236 Py_INCREF(it);
1237 PyTuple_SET_ITEM(args, i+1, it);
1238 }
1239
1240 return Py_BuildValue("ON", Py_TYPE(lz), args);
1241}
1242
1243static PyMethodDef map_methods[] = {
1244 {"__reduce__", (PyCFunction)map_reduce, METH_NOARGS, reduce_doc},
1245 {NULL, NULL} /* sentinel */
1246};
1247
1248
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001249PyDoc_STRVAR(map_doc,
Raymond Hettingera6c60372008-03-13 01:26:19 +00001250"map(func, *iterables) --> map object\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001251\n\
Raymond Hettingera6c60372008-03-13 01:26:19 +00001252Make an iterator that computes the function using arguments from\n\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001253each of the iterables. Stops when the shortest iterable is exhausted.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001254
Raymond Hettingera6c60372008-03-13 01:26:19 +00001255PyTypeObject PyMap_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001256 PyVarObject_HEAD_INIT(&PyType_Type, 0)
1257 "map", /* tp_name */
1258 sizeof(mapobject), /* tp_basicsize */
1259 0, /* tp_itemsize */
1260 /* methods */
1261 (destructor)map_dealloc, /* tp_dealloc */
1262 0, /* tp_print */
1263 0, /* tp_getattr */
1264 0, /* tp_setattr */
1265 0, /* tp_reserved */
1266 0, /* tp_repr */
1267 0, /* tp_as_number */
1268 0, /* tp_as_sequence */
1269 0, /* tp_as_mapping */
1270 0, /* tp_hash */
1271 0, /* tp_call */
1272 0, /* tp_str */
1273 PyObject_GenericGetAttr, /* tp_getattro */
1274 0, /* tp_setattro */
1275 0, /* tp_as_buffer */
1276 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
1277 Py_TPFLAGS_BASETYPE, /* tp_flags */
1278 map_doc, /* tp_doc */
1279 (traverseproc)map_traverse, /* tp_traverse */
1280 0, /* tp_clear */
1281 0, /* tp_richcompare */
1282 0, /* tp_weaklistoffset */
1283 PyObject_SelfIter, /* tp_iter */
1284 (iternextfunc)map_next, /* tp_iternext */
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001285 map_methods, /* tp_methods */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001286 0, /* tp_members */
1287 0, /* tp_getset */
1288 0, /* tp_base */
1289 0, /* tp_dict */
1290 0, /* tp_descr_get */
1291 0, /* tp_descr_set */
1292 0, /* tp_dictoffset */
1293 0, /* tp_init */
1294 PyType_GenericAlloc, /* tp_alloc */
1295 map_new, /* tp_new */
1296 PyObject_GC_Del, /* tp_free */
Raymond Hettingera6c60372008-03-13 01:26:19 +00001297};
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001298
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001299
1300/* AC: cannot convert yet, as needs PEP 457 group support in inspect */
Guido van Rossum79f25d91997-04-29 20:08:16 +00001301static PyObject *
Victor Stinnerfda6d0a2017-01-17 04:09:14 +01001302builtin_next(PyObject *self, PyObject **args, Py_ssize_t nargs,
1303 PyObject *kwnames)
Georg Brandla18af4e2007-04-21 15:47:16 +00001304{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001305 PyObject *it, *res;
1306 PyObject *def = NULL;
Georg Brandla18af4e2007-04-21 15:47:16 +00001307
Victor Stinnerfda6d0a2017-01-17 04:09:14 +01001308 if (!_PyArg_UnpackStack(args, nargs, "next", 1, 2, &it, &def))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001309 return NULL;
Victor Stinnerfda6d0a2017-01-17 04:09:14 +01001310
1311 if (!_PyArg_NoStackKeywords("next", kwnames)) {
1312 return NULL;
1313 }
1314
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001315 if (!PyIter_Check(it)) {
1316 PyErr_Format(PyExc_TypeError,
Philip Jenvey50add042011-11-06 16:37:52 -08001317 "'%.200s' object is not an iterator",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001318 it->ob_type->tp_name);
1319 return NULL;
1320 }
1321
1322 res = (*it->ob_type->tp_iternext)(it);
1323 if (res != NULL) {
1324 return res;
1325 } else if (def != NULL) {
1326 if (PyErr_Occurred()) {
1327 if(!PyErr_ExceptionMatches(PyExc_StopIteration))
1328 return NULL;
1329 PyErr_Clear();
1330 }
1331 Py_INCREF(def);
1332 return def;
1333 } else if (PyErr_Occurred()) {
1334 return NULL;
1335 } else {
1336 PyErr_SetNone(PyExc_StopIteration);
1337 return NULL;
1338 }
Georg Brandla18af4e2007-04-21 15:47:16 +00001339}
1340
1341PyDoc_STRVAR(next_doc,
1342"next(iterator[, default])\n\
1343\n\
1344Return the next item from the iterator. If default is given and the iterator\n\
1345is exhausted, it is returned instead of raising StopIteration.");
1346
1347
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001348/*[clinic input]
1349setattr as builtin_setattr
1350
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001351 obj: object
1352 name: object
1353 value: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001354 /
1355
1356Sets the named attribute on the given object to the specified value.
1357
1358setattr(x, 'y', v) is equivalent to ``x.y = v''
1359[clinic start generated code]*/
1360
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001361static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001362builtin_setattr_impl(PyObject *module, PyObject *obj, PyObject *name,
Larry Hastings89964c42015-04-14 18:07:59 -04001363 PyObject *value)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001364/*[clinic end generated code: output=dc2ce1d1add9acb4 input=bd2b7ca6875a1899]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001365{
1366 if (PyObject_SetAttr(obj, name, value) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001367 return NULL;
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02001368 Py_RETURN_NONE;
Guido van Rossum33894be1992-01-27 16:53:09 +00001369}
1370
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001371
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001372/*[clinic input]
1373delattr as builtin_delattr
1374
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001375 obj: object
1376 name: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001377 /
1378
1379Deletes the named attribute from the given object.
1380
1381delattr(x, 'y') is equivalent to ``del x.y''
1382[clinic start generated code]*/
1383
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001384static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001385builtin_delattr_impl(PyObject *module, PyObject *obj, PyObject *name)
1386/*[clinic end generated code: output=85134bc58dff79fa input=db16685d6b4b9410]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001387{
1388 if (PyObject_SetAttr(obj, name, (PyObject *)NULL) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001389 return NULL;
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02001390 Py_RETURN_NONE;
Guido van Rossum14144fc1994-08-29 12:53:40 +00001391}
1392
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001393
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001394/*[clinic input]
1395hash as builtin_hash
1396
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001397 obj: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001398 /
1399
1400Return the hash value for the given object.
1401
1402Two objects that compare equal must also have the same hash value, but the
1403reverse is not necessarily true.
1404[clinic start generated code]*/
1405
Guido van Rossum79f25d91997-04-29 20:08:16 +00001406static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001407builtin_hash(PyObject *module, PyObject *obj)
1408/*[clinic end generated code: output=237668e9d7688db7 input=58c48be822bf9c54]*/
Guido van Rossum9bfef441993-03-29 10:43:31 +00001409{
Benjamin Peterson8f67d082010-10-17 20:54:53 +00001410 Py_hash_t x;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001411
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001412 x = PyObject_Hash(obj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001413 if (x == -1)
1414 return NULL;
Benjamin Peterson8f67d082010-10-17 20:54:53 +00001415 return PyLong_FromSsize_t(x);
Guido van Rossum9bfef441993-03-29 10:43:31 +00001416}
1417
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001418
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001419/*[clinic input]
1420hex as builtin_hex
1421
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001422 number: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001423 /
1424
1425Return the hexadecimal representation of an integer.
1426
1427 >>> hex(12648430)
1428 '0xc0ffee'
1429[clinic start generated code]*/
1430
Guido van Rossum79f25d91997-04-29 20:08:16 +00001431static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001432builtin_hex(PyObject *module, PyObject *number)
1433/*[clinic end generated code: output=e46b612169099408 input=e645aff5fc7d540e]*/
Guido van Rossum006bcd41991-10-24 14:54:44 +00001434{
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001435 return PyNumber_ToBase(number, 16);
Guido van Rossum006bcd41991-10-24 14:54:44 +00001436}
1437
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001438
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001439/* AC: cannot convert yet, as needs PEP 457 group support in inspect */
Guido van Rossum79f25d91997-04-29 20:08:16 +00001440static PyObject *
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001441builtin_iter(PyObject *self, PyObject *args)
1442{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001443 PyObject *v, *w = NULL;
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001444
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001445 if (!PyArg_UnpackTuple(args, "iter", 1, 2, &v, &w))
1446 return NULL;
1447 if (w == NULL)
1448 return PyObject_GetIter(v);
1449 if (!PyCallable_Check(v)) {
1450 PyErr_SetString(PyExc_TypeError,
1451 "iter(v, w): v must be callable");
1452 return NULL;
1453 }
1454 return PyCallIter_New(v, w);
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001455}
1456
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001457PyDoc_STRVAR(iter_doc,
Georg Brandld11ae5d2008-05-16 13:27:32 +00001458"iter(iterable) -> iterator\n\
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001459iter(callable, sentinel) -> iterator\n\
1460\n\
1461Get an iterator from an object. In the first form, the argument must\n\
1462supply its own iterator, or be a sequence.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001463In the second form, the callable is called until it returns the sentinel.");
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001464
1465
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001466/*[clinic input]
1467len as builtin_len
1468
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001469 obj: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001470 /
1471
1472Return the number of items in a container.
1473[clinic start generated code]*/
1474
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001475static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001476builtin_len(PyObject *module, PyObject *obj)
1477/*[clinic end generated code: output=fa7a270d314dfb6c input=bc55598da9e9c9b5]*/
Guido van Rossum3f5da241990-12-20 15:06:42 +00001478{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001479 Py_ssize_t res;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001480
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001481 res = PyObject_Size(obj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001482 if (res < 0 && PyErr_Occurred())
1483 return NULL;
1484 return PyLong_FromSsize_t(res);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001485}
1486
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001487
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001488/*[clinic input]
1489locals as builtin_locals
1490
1491Return a dictionary containing the current scope's local variables.
1492
1493NOTE: Whether or not updates to this dictionary will affect name lookups in
1494the local scope and vice-versa is *implementation dependent* and not
1495covered by any backwards compatibility guarantees.
1496[clinic start generated code]*/
1497
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001498static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001499builtin_locals_impl(PyObject *module)
1500/*[clinic end generated code: output=b46c94015ce11448 input=7874018d478d5c4b]*/
Guido van Rossum872537c1995-07-07 22:43:42 +00001501{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001502 PyObject *d;
Guido van Rossum872537c1995-07-07 22:43:42 +00001503
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001504 d = PyEval_GetLocals();
1505 Py_XINCREF(d);
1506 return d;
Guido van Rossum872537c1995-07-07 22:43:42 +00001507}
1508
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001509
Guido van Rossum79f25d91997-04-29 20:08:16 +00001510static PyObject *
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001511min_max(PyObject *args, PyObject *kwds, int op)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001512{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001513 PyObject *v, *it, *item, *val, *maxitem, *maxval, *keyfunc=NULL;
Raymond Hettinger4d6018f2013-06-24 22:43:02 -07001514 PyObject *emptytuple, *defaultval = NULL;
1515 static char *kwlist[] = {"key", "default", NULL};
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001516 const char *name = op == Py_LT ? "min" : "max";
Raymond Hettinger4d6018f2013-06-24 22:43:02 -07001517 const int positional = PyTuple_Size(args) > 1;
1518 int ret;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001519
Raymond Hettinger4d6018f2013-06-24 22:43:02 -07001520 if (positional)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001521 v = args;
Serhiy Storchakac6792272013-10-19 21:03:34 +03001522 else if (!PyArg_UnpackTuple(args, name, 1, 1, &v))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001523 return NULL;
Tim Peters67d687a2002-04-29 21:27:32 +00001524
Raymond Hettinger4d6018f2013-06-24 22:43:02 -07001525 emptytuple = PyTuple_New(0);
1526 if (emptytuple == NULL)
1527 return NULL;
1528 ret = PyArg_ParseTupleAndKeywords(emptytuple, kwds, "|$OO", kwlist,
1529 &keyfunc, &defaultval);
1530 Py_DECREF(emptytuple);
1531 if (!ret)
1532 return NULL;
1533
1534 if (positional && defaultval != NULL) {
1535 PyErr_Format(PyExc_TypeError,
1536 "Cannot specify a default for %s() with multiple "
1537 "positional arguments", name);
1538 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001539 }
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001540
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001541 it = PyObject_GetIter(v);
1542 if (it == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001543 return NULL;
1544 }
Tim Petersc3074532001-05-03 07:00:32 +00001545
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001546 maxitem = NULL; /* the result */
1547 maxval = NULL; /* the value associated with the result */
1548 while (( item = PyIter_Next(it) )) {
1549 /* get the value from the key function */
1550 if (keyfunc != NULL) {
Victor Stinnerde4ae3d2016-12-04 22:59:09 +01001551 val = PyObject_CallFunctionObjArgs(keyfunc, item, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001552 if (val == NULL)
1553 goto Fail_it_item;
1554 }
1555 /* no key function; the value is the item */
1556 else {
1557 val = item;
1558 Py_INCREF(val);
1559 }
Tim Petersc3074532001-05-03 07:00:32 +00001560
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001561 /* maximum value and item are unset; set them */
1562 if (maxval == NULL) {
1563 maxitem = item;
1564 maxval = val;
1565 }
1566 /* maximum value and item are set; update them as necessary */
1567 else {
1568 int cmp = PyObject_RichCompareBool(val, maxval, op);
1569 if (cmp < 0)
1570 goto Fail_it_item_and_val;
1571 else if (cmp > 0) {
1572 Py_DECREF(maxval);
1573 Py_DECREF(maxitem);
1574 maxval = val;
1575 maxitem = item;
1576 }
1577 else {
1578 Py_DECREF(item);
1579 Py_DECREF(val);
1580 }
1581 }
1582 }
1583 if (PyErr_Occurred())
1584 goto Fail_it;
1585 if (maxval == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001586 assert(maxitem == NULL);
Raymond Hettinger4d6018f2013-06-24 22:43:02 -07001587 if (defaultval != NULL) {
1588 Py_INCREF(defaultval);
1589 maxitem = defaultval;
1590 } else {
1591 PyErr_Format(PyExc_ValueError,
1592 "%s() arg is an empty sequence", name);
1593 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001594 }
1595 else
1596 Py_DECREF(maxval);
1597 Py_DECREF(it);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001598 return maxitem;
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001599
1600Fail_it_item_and_val:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001601 Py_DECREF(val);
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001602Fail_it_item:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001603 Py_DECREF(item);
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001604Fail_it:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001605 Py_XDECREF(maxval);
1606 Py_XDECREF(maxitem);
1607 Py_DECREF(it);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001608 return NULL;
Guido van Rossum3f5da241990-12-20 15:06:42 +00001609}
1610
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001611/* AC: cannot convert yet, waiting for *args support */
Guido van Rossum79f25d91997-04-29 20:08:16 +00001612static PyObject *
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001613builtin_min(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001614{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001615 return min_max(args, kwds, Py_LT);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001616}
1617
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001618PyDoc_STRVAR(min_doc,
Raymond Hettinger2a545822014-05-19 22:20:52 +01001619"min(iterable, *[, default=obj, key=func]) -> value\n\
1620min(arg1, arg2, *args, *[, key=func]) -> value\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001621\n\
Raymond Hettinger2a545822014-05-19 22:20:52 +01001622With a single iterable argument, return its smallest item. The\n\
1623default keyword-only argument specifies an object to return if\n\
1624the provided iterable is empty.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001625With two or more arguments, return the smallest argument.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001626
1627
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001628/* AC: cannot convert yet, waiting for *args support */
Guido van Rossum79f25d91997-04-29 20:08:16 +00001629static PyObject *
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001630builtin_max(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001631{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001632 return min_max(args, kwds, Py_GT);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001633}
1634
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001635PyDoc_STRVAR(max_doc,
Raymond Hettinger2a545822014-05-19 22:20:52 +01001636"max(iterable, *[, default=obj, key=func]) -> value\n\
1637max(arg1, arg2, *args, *[, key=func]) -> value\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001638\n\
Raymond Hettinger2a545822014-05-19 22:20:52 +01001639With a single iterable argument, return its biggest item. The\n\
1640default keyword-only argument specifies an object to return if\n\
1641the provided iterable is empty.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001642With two or more arguments, return the largest argument.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001643
1644
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001645/*[clinic input]
1646oct as builtin_oct
1647
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001648 number: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001649 /
1650
1651Return the octal representation of an integer.
1652
1653 >>> oct(342391)
1654 '0o1234567'
1655[clinic start generated code]*/
1656
Guido van Rossum79f25d91997-04-29 20:08:16 +00001657static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001658builtin_oct(PyObject *module, PyObject *number)
1659/*[clinic end generated code: output=40a34656b6875352 input=ad6b274af4016c72]*/
Guido van Rossum006bcd41991-10-24 14:54:44 +00001660{
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001661 return PyNumber_ToBase(number, 8);
Guido van Rossum006bcd41991-10-24 14:54:44 +00001662}
1663
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001664
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001665/*[clinic input]
1666ord as builtin_ord
1667
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001668 c: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001669 /
1670
1671Return the Unicode code point for a one-character string.
1672[clinic start generated code]*/
1673
Guido van Rossum79f25d91997-04-29 20:08:16 +00001674static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001675builtin_ord(PyObject *module, PyObject *c)
1676/*[clinic end generated code: output=4fa5e87a323bae71 input=3064e5d6203ad012]*/
Guido van Rossum3f5da241990-12-20 15:06:42 +00001677{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001678 long ord;
1679 Py_ssize_t size;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001680
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001681 if (PyBytes_Check(c)) {
1682 size = PyBytes_GET_SIZE(c);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001683 if (size == 1) {
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001684 ord = (long)((unsigned char)*PyBytes_AS_STRING(c));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001685 return PyLong_FromLong(ord);
1686 }
1687 }
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001688 else if (PyUnicode_Check(c)) {
1689 if (PyUnicode_READY(c) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001690 return NULL;
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001691 size = PyUnicode_GET_LENGTH(c);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001692 if (size == 1) {
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001693 ord = (long)PyUnicode_READ_CHAR(c, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001694 return PyLong_FromLong(ord);
1695 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001696 }
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001697 else if (PyByteArray_Check(c)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001698 /* XXX Hopefully this is temporary */
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001699 size = PyByteArray_GET_SIZE(c);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001700 if (size == 1) {
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001701 ord = (long)((unsigned char)*PyByteArray_AS_STRING(c));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001702 return PyLong_FromLong(ord);
1703 }
1704 }
1705 else {
1706 PyErr_Format(PyExc_TypeError,
1707 "ord() expected string of length 1, but " \
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001708 "%.200s found", c->ob_type->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001709 return NULL;
1710 }
Guido van Rossum09095f32000-03-10 23:00:52 +00001711
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001712 PyErr_Format(PyExc_TypeError,
1713 "ord() expected a character, "
1714 "but string of length %zd found",
1715 size);
1716 return NULL;
Guido van Rossum3f5da241990-12-20 15:06:42 +00001717}
1718
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001719
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001720/*[clinic input]
1721pow as builtin_pow
1722
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001723 x: object
1724 y: object
1725 z: object = None
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001726 /
1727
1728Equivalent to x**y (with two arguments) or x**y % z (with three arguments)
1729
1730Some types, such as ints, are able to use a more efficient algorithm when
1731invoked using the three argument form.
1732[clinic start generated code]*/
1733
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001734static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001735builtin_pow_impl(PyObject *module, PyObject *x, PyObject *y, PyObject *z)
1736/*[clinic end generated code: output=50a14d5d130d404b input=653d57d38d41fc07]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001737{
1738 return PyNumber_Power(x, y, z);
1739}
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001740
1741
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001742/* AC: cannot convert yet, waiting for *args support */
Guido van Rossum34343512006-11-30 22:13:52 +00001743static PyObject *
INADA Naokibd584f12017-01-19 12:50:34 +01001744builtin_print(PyObject *self, PyObject **args, Py_ssize_t nargs, PyObject *kwnames)
Guido van Rossum34343512006-11-30 22:13:52 +00001745{
INADA Naokibd584f12017-01-19 12:50:34 +01001746 static const char * const _keywords[] = {"sep", "end", "file", "flush", 0};
1747 static struct _PyArg_Parser _parser = {"|OOOO:print", _keywords, 0};
Georg Brandlbc3b6822012-01-13 19:41:25 +01001748 PyObject *sep = NULL, *end = NULL, *file = NULL, *flush = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001749 int i, err;
Guido van Rossum34343512006-11-30 22:13:52 +00001750
INADA Naokibd584f12017-01-19 12:50:34 +01001751 if (kwnames != NULL &&
1752 !_PyArg_ParseStackAndKeywords(args + nargs, 0, kwnames, &_parser,
1753 &sep, &end, &file, &flush)) {
Georg Brandlbc3b6822012-01-13 19:41:25 +01001754 return NULL;
INADA Naokibd584f12017-01-19 12:50:34 +01001755 }
1756
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001757 if (file == NULL || file == Py_None) {
Victor Stinnerbd303c12013-11-07 23:07:29 +01001758 file = _PySys_GetObjectId(&PyId_stdout);
Victor Stinner1e53bba2013-07-16 22:26:05 +02001759 if (file == NULL) {
1760 PyErr_SetString(PyExc_RuntimeError, "lost sys.stdout");
1761 return NULL;
1762 }
1763
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001764 /* sys.stdout may be None when FILE* stdout isn't connected */
1765 if (file == Py_None)
1766 Py_RETURN_NONE;
1767 }
Guido van Rossum34343512006-11-30 22:13:52 +00001768
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001769 if (sep == Py_None) {
1770 sep = NULL;
1771 }
1772 else if (sep && !PyUnicode_Check(sep)) {
1773 PyErr_Format(PyExc_TypeError,
1774 "sep must be None or a string, not %.200s",
1775 sep->ob_type->tp_name);
1776 return NULL;
1777 }
1778 if (end == Py_None) {
1779 end = NULL;
1780 }
1781 else if (end && !PyUnicode_Check(end)) {
1782 PyErr_Format(PyExc_TypeError,
1783 "end must be None or a string, not %.200s",
1784 end->ob_type->tp_name);
1785 return NULL;
1786 }
Guido van Rossum34343512006-11-30 22:13:52 +00001787
INADA Naokibd584f12017-01-19 12:50:34 +01001788 for (i = 0; i < nargs; i++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001789 if (i > 0) {
1790 if (sep == NULL)
1791 err = PyFile_WriteString(" ", file);
1792 else
1793 err = PyFile_WriteObject(sep, file,
1794 Py_PRINT_RAW);
1795 if (err)
1796 return NULL;
1797 }
INADA Naokibd584f12017-01-19 12:50:34 +01001798 err = PyFile_WriteObject(args[i], file, Py_PRINT_RAW);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001799 if (err)
1800 return NULL;
1801 }
Guido van Rossum34343512006-11-30 22:13:52 +00001802
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001803 if (end == NULL)
1804 err = PyFile_WriteString("\n", file);
1805 else
1806 err = PyFile_WriteObject(end, file, Py_PRINT_RAW);
1807 if (err)
1808 return NULL;
Guido van Rossum34343512006-11-30 22:13:52 +00001809
Georg Brandlbc3b6822012-01-13 19:41:25 +01001810 if (flush != NULL) {
1811 PyObject *tmp;
1812 int do_flush = PyObject_IsTrue(flush);
1813 if (do_flush == -1)
1814 return NULL;
1815 else if (do_flush) {
Victor Stinner3466bde2016-09-05 18:16:01 -07001816 tmp = _PyObject_CallMethodId(file, &PyId_flush, NULL);
Georg Brandlbc3b6822012-01-13 19:41:25 +01001817 if (tmp == NULL)
1818 return NULL;
1819 else
1820 Py_DECREF(tmp);
1821 }
1822 }
1823
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001824 Py_RETURN_NONE;
Guido van Rossum34343512006-11-30 22:13:52 +00001825}
1826
1827PyDoc_STRVAR(print_doc,
Senthil Kumarane9175bd2012-08-10 13:53:45 -07001828"print(value, ..., sep=' ', end='\\n', file=sys.stdout, flush=False)\n\
Guido van Rossum34343512006-11-30 22:13:52 +00001829\n\
1830Prints the values to a stream, or to sys.stdout by default.\n\
1831Optional keyword arguments:\n\
Senthil Kumarane9175bd2012-08-10 13:53:45 -07001832file: a file-like object (stream); defaults to the current sys.stdout.\n\
1833sep: string inserted between values, default a space.\n\
1834end: string appended after the last value, default a newline.\n\
1835flush: whether to forcibly flush the stream.");
Guido van Rossum34343512006-11-30 22:13:52 +00001836
1837
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001838/*[clinic input]
1839input as builtin_input
1840
1841 prompt: object(c_default="NULL") = None
1842 /
1843
1844Read a string from standard input. The trailing newline is stripped.
1845
1846The prompt string, if given, is printed to standard output without a
1847trailing newline before reading input.
1848
1849If the user hits EOF (*nix: Ctrl-D, Windows: Ctrl-Z+Return), raise EOFError.
1850On *nix systems, readline is used if available.
1851[clinic start generated code]*/
1852
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001853static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001854builtin_input_impl(PyObject *module, PyObject *prompt)
1855/*[clinic end generated code: output=83db5a191e7a0d60 input=5e8bb70c2908fe3c]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001856{
Victor Stinnerbd303c12013-11-07 23:07:29 +01001857 PyObject *fin = _PySys_GetObjectId(&PyId_stdin);
1858 PyObject *fout = _PySys_GetObjectId(&PyId_stdout);
1859 PyObject *ferr = _PySys_GetObjectId(&PyId_stderr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001860 PyObject *tmp;
1861 long fd;
1862 int tty;
Guido van Rossuma88a0332007-02-26 16:59:55 +00001863
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001864 /* Check that stdin/out/err are intact */
1865 if (fin == NULL || fin == Py_None) {
1866 PyErr_SetString(PyExc_RuntimeError,
1867 "input(): lost sys.stdin");
1868 return NULL;
1869 }
1870 if (fout == NULL || fout == Py_None) {
1871 PyErr_SetString(PyExc_RuntimeError,
1872 "input(): lost sys.stdout");
1873 return NULL;
1874 }
1875 if (ferr == NULL || ferr == Py_None) {
1876 PyErr_SetString(PyExc_RuntimeError,
1877 "input(): lost sys.stderr");
1878 return NULL;
1879 }
Guido van Rossumeba76962007-05-27 09:13:28 +00001880
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001881 /* First of all, flush stderr */
Victor Stinner3466bde2016-09-05 18:16:01 -07001882 tmp = _PyObject_CallMethodId(ferr, &PyId_flush, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001883 if (tmp == NULL)
1884 PyErr_Clear();
1885 else
1886 Py_DECREF(tmp);
Guido van Rossumeba76962007-05-27 09:13:28 +00001887
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001888 /* We should only use (GNU) readline if Python's sys.stdin and
1889 sys.stdout are the same as C's stdin and stdout, because we
1890 need to pass it those. */
Victor Stinner3466bde2016-09-05 18:16:01 -07001891 tmp = _PyObject_CallMethodId(fin, &PyId_fileno, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001892 if (tmp == NULL) {
1893 PyErr_Clear();
1894 tty = 0;
1895 }
1896 else {
1897 fd = PyLong_AsLong(tmp);
1898 Py_DECREF(tmp);
1899 if (fd < 0 && PyErr_Occurred())
1900 return NULL;
1901 tty = fd == fileno(stdin) && isatty(fd);
1902 }
1903 if (tty) {
Victor Stinner3466bde2016-09-05 18:16:01 -07001904 tmp = _PyObject_CallMethodId(fout, &PyId_fileno, NULL);
Martin Panterc9a6ab52015-10-10 01:25:38 +00001905 if (tmp == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001906 PyErr_Clear();
Martin Panterc9a6ab52015-10-10 01:25:38 +00001907 tty = 0;
1908 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001909 else {
1910 fd = PyLong_AsLong(tmp);
1911 Py_DECREF(tmp);
1912 if (fd < 0 && PyErr_Occurred())
1913 return NULL;
1914 tty = fd == fileno(stdout) && isatty(fd);
1915 }
1916 }
Guido van Rossumeba76962007-05-27 09:13:28 +00001917
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001918 /* If we're interactive, use (GNU) readline */
1919 if (tty) {
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001920 PyObject *po = NULL;
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001921 char *promptstr;
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001922 char *s = NULL;
1923 PyObject *stdin_encoding = NULL, *stdin_errors = NULL;
1924 PyObject *stdout_encoding = NULL, *stdout_errors = NULL;
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +02001925 const char *stdin_encoding_str, *stdin_errors_str;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001926 PyObject *result;
Victor Stinnerc0f1a1a2011-02-23 12:07:37 +00001927 size_t len;
Martin v. Löwis4a7b5d52007-09-04 05:24:49 +00001928
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02001929 stdin_encoding = _PyObject_GetAttrId(fin, &PyId_encoding);
Antoine Pitrou5ee9d8a2011-11-06 00:38:45 +01001930 stdin_errors = _PyObject_GetAttrId(fin, &PyId_errors);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001931 if (!stdin_encoding || !stdin_errors)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001932 /* stdin is a text stream, so it must have an
1933 encoding. */
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001934 goto _readline_errors;
Serhiy Storchaka06515832016-11-20 09:13:07 +02001935 stdin_encoding_str = PyUnicode_AsUTF8(stdin_encoding);
1936 stdin_errors_str = PyUnicode_AsUTF8(stdin_errors);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001937 if (!stdin_encoding_str || !stdin_errors_str)
1938 goto _readline_errors;
Victor Stinner3466bde2016-09-05 18:16:01 -07001939 tmp = _PyObject_CallMethodId(fout, &PyId_flush, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001940 if (tmp == NULL)
1941 PyErr_Clear();
1942 else
1943 Py_DECREF(tmp);
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001944 if (prompt != NULL) {
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001945 /* We have a prompt, encode it as stdout would */
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +02001946 const char *stdout_encoding_str, *stdout_errors_str;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001947 PyObject *stringpo;
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02001948 stdout_encoding = _PyObject_GetAttrId(fout, &PyId_encoding);
Antoine Pitrou5ee9d8a2011-11-06 00:38:45 +01001949 stdout_errors = _PyObject_GetAttrId(fout, &PyId_errors);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001950 if (!stdout_encoding || !stdout_errors)
1951 goto _readline_errors;
Serhiy Storchaka06515832016-11-20 09:13:07 +02001952 stdout_encoding_str = PyUnicode_AsUTF8(stdout_encoding);
1953 stdout_errors_str = PyUnicode_AsUTF8(stdout_errors);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001954 if (!stdout_encoding_str || !stdout_errors_str)
1955 goto _readline_errors;
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001956 stringpo = PyObject_Str(prompt);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001957 if (stringpo == NULL)
1958 goto _readline_errors;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001959 po = PyUnicode_AsEncodedString(stringpo,
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001960 stdout_encoding_str, stdout_errors_str);
1961 Py_CLEAR(stdout_encoding);
1962 Py_CLEAR(stdout_errors);
1963 Py_CLEAR(stringpo);
1964 if (po == NULL)
1965 goto _readline_errors;
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03001966 assert(PyBytes_Check(po));
1967 promptstr = PyBytes_AS_STRING(po);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001968 }
1969 else {
1970 po = NULL;
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001971 promptstr = "";
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001972 }
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001973 s = PyOS_Readline(stdin, stdout, promptstr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001974 if (s == NULL) {
Richard Oudkerk614c5782013-04-03 13:44:50 +01001975 PyErr_CheckSignals();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001976 if (!PyErr_Occurred())
1977 PyErr_SetNone(PyExc_KeyboardInterrupt);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001978 goto _readline_errors;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001979 }
Victor Stinnerc0f1a1a2011-02-23 12:07:37 +00001980
1981 len = strlen(s);
1982 if (len == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001983 PyErr_SetNone(PyExc_EOFError);
1984 result = NULL;
1985 }
Victor Stinnerc0f1a1a2011-02-23 12:07:37 +00001986 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001987 if (len > PY_SSIZE_T_MAX) {
1988 PyErr_SetString(PyExc_OverflowError,
1989 "input: input too long");
1990 result = NULL;
1991 }
1992 else {
Victor Stinnerc0f1a1a2011-02-23 12:07:37 +00001993 len--; /* strip trailing '\n' */
1994 if (len != 0 && s[len-1] == '\r')
1995 len--; /* strip trailing '\r' */
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001996 result = PyUnicode_Decode(s, len, stdin_encoding_str,
1997 stdin_errors_str);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001998 }
1999 }
2000 Py_DECREF(stdin_encoding);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01002001 Py_DECREF(stdin_errors);
2002 Py_XDECREF(po);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002003 PyMem_FREE(s);
2004 return result;
Antoine Pitrou0d776b12011-11-06 00:34:26 +01002005 _readline_errors:
2006 Py_XDECREF(stdin_encoding);
2007 Py_XDECREF(stdout_encoding);
2008 Py_XDECREF(stdin_errors);
2009 Py_XDECREF(stdout_errors);
2010 Py_XDECREF(po);
2011 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002012 }
Guido van Rossumeba76962007-05-27 09:13:28 +00002013
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002014 /* Fallback if we're not interactive */
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002015 if (prompt != NULL) {
2016 if (PyFile_WriteObject(prompt, fout, Py_PRINT_RAW) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002017 return NULL;
2018 }
Victor Stinner3466bde2016-09-05 18:16:01 -07002019 tmp = _PyObject_CallMethodId(fout, &PyId_flush, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002020 if (tmp == NULL)
2021 PyErr_Clear();
2022 else
2023 Py_DECREF(tmp);
2024 return PyFile_GetLine(fin, -1);
Guido van Rossuma88a0332007-02-26 16:59:55 +00002025}
2026
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002027
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002028/*[clinic input]
2029repr as builtin_repr
2030
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03002031 obj: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002032 /
2033
2034Return the canonical string representation of the object.
2035
2036For many object types, including most builtins, eval(repr(obj)) == obj.
2037[clinic start generated code]*/
2038
Guido van Rossum79f25d91997-04-29 20:08:16 +00002039static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002040builtin_repr(PyObject *module, PyObject *obj)
2041/*[clinic end generated code: output=7ed3778c44fd0194 input=1c9e6d66d3e3be04]*/
Guido van Rossumc89705d1992-11-26 08:54:07 +00002042{
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002043 return PyObject_Repr(obj);
Guido van Rossumc89705d1992-11-26 08:54:07 +00002044}
2045
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002046
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002047/* AC: cannot convert yet, as needs PEP 457 group support in inspect
2048 * or a semantic change to accept None for "ndigits"
2049 */
Guido van Rossum79f25d91997-04-29 20:08:16 +00002050static PyObject *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002051builtin_round(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum9e51f9b1993-02-12 16:29:05 +00002052{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002053 PyObject *ndigits = NULL;
2054 static char *kwlist[] = {"number", "ndigits", 0};
Benjamin Peterson214a7d22013-04-13 17:19:01 -04002055 PyObject *number, *round, *result;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002056
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002057 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|O:round",
2058 kwlist, &number, &ndigits))
2059 return NULL;
Alex Martelliae211f92007-08-22 23:21:33 +00002060
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002061 if (Py_TYPE(number)->tp_dict == NULL) {
2062 if (PyType_Ready(Py_TYPE(number)) < 0)
2063 return NULL;
2064 }
Guido van Rossum15d3d042007-08-24 02:02:45 +00002065
Benjamin Peterson214a7d22013-04-13 17:19:01 -04002066 round = _PyObject_LookupSpecial(number, &PyId___round__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002067 if (round == NULL) {
Benjamin Peterson214a7d22013-04-13 17:19:01 -04002068 if (!PyErr_Occurred())
2069 PyErr_Format(PyExc_TypeError,
2070 "type %.100s doesn't define __round__ method",
2071 Py_TYPE(number)->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002072 return NULL;
2073 }
Alex Martelliae211f92007-08-22 23:21:33 +00002074
Raymond Hettingerf0f1c232016-09-03 01:55:11 -07002075 if (ndigits == NULL || ndigits == Py_None)
Victor Stinnerf17c3de2016-12-06 18:46:19 +01002076 result = _PyObject_CallNoArg(round);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002077 else
Victor Stinnerde4ae3d2016-12-04 22:59:09 +01002078 result = PyObject_CallFunctionObjArgs(round, ndigits, NULL);
Benjamin Peterson214a7d22013-04-13 17:19:01 -04002079 Py_DECREF(round);
2080 return result;
Guido van Rossum9e51f9b1993-02-12 16:29:05 +00002081}
2082
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002083PyDoc_STRVAR(round_doc,
Mark Dickinson1124e712009-01-28 21:25:58 +00002084"round(number[, ndigits]) -> number\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002085\n\
2086Round a number to a given precision in decimal digits (default 0 digits).\n\
Mark Dickinson0d748c22008-07-05 11:29:03 +00002087This returns an int when called with one argument, otherwise the\n\
Georg Brandl809ddaa2008-07-01 20:39:59 +00002088same type as the number. ndigits may be negative.");
Guido van Rossum2fa33db2007-08-23 22:07:24 +00002089
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002090
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002091/*AC: we need to keep the kwds dict intact to easily call into the
2092 * list.sort method, which isn't currently supported in AC. So we just use
2093 * the initially generated signature with a custom implementation.
2094 */
2095/* [disabled clinic input]
2096sorted as builtin_sorted
2097
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03002098 iterable as seq: object
2099 key as keyfunc: object = None
2100 reverse: object = False
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002101
2102Return a new list containing all items from the iterable in ascending order.
2103
Raymond Hettinger7ea386e2016-08-25 21:11:50 -07002104A custom key function can be supplied to customize the sort order, and the
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002105reverse flag can be set to request the result in descending order.
2106[end disabled clinic input]*/
2107
2108PyDoc_STRVAR(builtin_sorted__doc__,
Serhiy Storchaka3a104252017-01-23 12:29:47 +02002109"sorted($module, iterable, /, *, key=None, reverse=False)\n"
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002110"--\n"
2111"\n"
2112"Return a new list containing all items from the iterable in ascending order.\n"
2113"\n"
Raymond Hettinger7ea386e2016-08-25 21:11:50 -07002114"A custom key function can be supplied to customize the sort order, and the\n"
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002115"reverse flag can be set to request the result in descending order.");
2116
2117#define BUILTIN_SORTED_METHODDEF \
Victor Stinner5a60eca2017-01-17 15:17:49 +01002118 {"sorted", (PyCFunction)builtin_sorted, METH_FASTCALL, builtin_sorted__doc__},
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002119
Raymond Hettinger64958a12003-12-17 20:43:33 +00002120static PyObject *
Victor Stinner5a60eca2017-01-17 15:17:49 +01002121builtin_sorted(PyObject *self, PyObject **args, Py_ssize_t nargs, PyObject *kwnames)
Raymond Hettinger64958a12003-12-17 20:43:33 +00002122{
Serhiy Storchaka7cf8beb2017-01-21 23:05:00 +02002123 PyObject *newlist, *v, *seq, *callable;
Victor Stinner5a60eca2017-01-17 15:17:49 +01002124
Serhiy Storchaka7cf8beb2017-01-21 23:05:00 +02002125 /* Keyword arguments are passed through list.sort() which will check
2126 them. */
2127 if (!_PyArg_UnpackStack(args, nargs, "sorted", 1, 1, &seq))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002128 return NULL;
Raymond Hettinger64958a12003-12-17 20:43:33 +00002129
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002130 newlist = PySequence_List(seq);
2131 if (newlist == NULL)
2132 return NULL;
Raymond Hettinger64958a12003-12-17 20:43:33 +00002133
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02002134 callable = _PyObject_GetAttrId(newlist, &PyId_sort);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002135 if (callable == NULL) {
2136 Py_DECREF(newlist);
2137 return NULL;
2138 }
Georg Brandl99d7e4e2005-08-31 22:21:15 +00002139
Serhiy Storchaka299dc232017-01-20 08:35:18 +02002140 assert(nargs >= 1);
Victor Stinner5a60eca2017-01-17 15:17:49 +01002141 v = _PyObject_FastCallKeywords(callable, args + 1, nargs - 1, kwnames);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002142 Py_DECREF(callable);
2143 if (v == NULL) {
2144 Py_DECREF(newlist);
2145 return NULL;
2146 }
2147 Py_DECREF(v);
2148 return newlist;
Raymond Hettinger64958a12003-12-17 20:43:33 +00002149}
2150
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002151
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002152/* AC: cannot convert yet, as needs PEP 457 group support in inspect */
Guido van Rossum79f25d91997-04-29 20:08:16 +00002153static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002154builtin_vars(PyObject *self, PyObject *args)
Guido van Rossum2d951851994-08-29 12:52:16 +00002155{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002156 PyObject *v = NULL;
2157 PyObject *d;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002158
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002159 if (!PyArg_UnpackTuple(args, "vars", 0, 1, &v))
2160 return NULL;
2161 if (v == NULL) {
2162 d = PyEval_GetLocals();
Victor Stinner41bb43a2013-10-29 01:19:37 +01002163 if (d == NULL)
2164 return NULL;
2165 Py_INCREF(d);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002166 }
2167 else {
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02002168 d = _PyObject_GetAttrId(v, &PyId___dict__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002169 if (d == NULL) {
2170 PyErr_SetString(PyExc_TypeError,
2171 "vars() argument must have __dict__ attribute");
2172 return NULL;
2173 }
2174 }
2175 return d;
Guido van Rossum2d951851994-08-29 12:52:16 +00002176}
2177
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002178PyDoc_STRVAR(vars_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002179"vars([object]) -> dictionary\n\
2180\n\
2181Without arguments, equivalent to locals().\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002182With an argument, equivalent to object.__dict__.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002183
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002184
2185/*[clinic input]
2186sum as builtin_sum
2187
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03002188 iterable: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002189 start: object(c_default="NULL") = 0
2190 /
2191
2192Return the sum of a 'start' value (default: 0) plus an iterable of numbers
2193
2194When the iterable is empty, return the start value.
2195This function is intended specifically for use with numeric values and may
2196reject non-numeric types.
2197[clinic start generated code]*/
2198
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002199static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002200builtin_sum_impl(PyObject *module, PyObject *iterable, PyObject *start)
2201/*[clinic end generated code: output=df758cec7d1d302f input=3b5b7a9d7611c73a]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002202{
2203 PyObject *result = start;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002204 PyObject *temp, *item, *iter;
Alex Martellia70b1912003-04-22 08:12:33 +00002205
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002206 iter = PyObject_GetIter(iterable);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002207 if (iter == NULL)
2208 return NULL;
Alex Martellia70b1912003-04-22 08:12:33 +00002209
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002210 if (result == NULL) {
2211 result = PyLong_FromLong(0);
2212 if (result == NULL) {
2213 Py_DECREF(iter);
2214 return NULL;
2215 }
2216 } else {
2217 /* reject string values for 'start' parameter */
2218 if (PyUnicode_Check(result)) {
2219 PyErr_SetString(PyExc_TypeError,
2220 "sum() can't sum strings [use ''.join(seq) instead]");
2221 Py_DECREF(iter);
2222 return NULL;
2223 }
Benjamin Petersonce071ca2011-07-29 14:23:47 -05002224 if (PyBytes_Check(result)) {
2225 PyErr_SetString(PyExc_TypeError,
2226 "sum() can't sum bytes [use b''.join(seq) instead]");
Benjamin Peterson405f32c2011-07-29 22:43:45 -05002227 Py_DECREF(iter);
Benjamin Petersonce071ca2011-07-29 14:23:47 -05002228 return NULL;
2229 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002230 if (PyByteArray_Check(result)) {
2231 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson4f921c22011-07-29 14:24:29 -05002232 "sum() can't sum bytearray [use b''.join(seq) instead]");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002233 Py_DECREF(iter);
2234 return NULL;
2235 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002236 Py_INCREF(result);
2237 }
Alex Martellia70b1912003-04-22 08:12:33 +00002238
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002239#ifndef SLOW_SUM
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002240 /* Fast addition by keeping temporary sums in C instead of new Python objects.
2241 Assumes all inputs are the same type. If the assumption fails, default
2242 to the more general routine.
2243 */
2244 if (PyLong_CheckExact(result)) {
2245 int overflow;
2246 long i_result = PyLong_AsLongAndOverflow(result, &overflow);
2247 /* If this already overflowed, don't even enter the loop. */
2248 if (overflow == 0) {
2249 Py_DECREF(result);
2250 result = NULL;
2251 }
2252 while(result == NULL) {
2253 item = PyIter_Next(iter);
2254 if (item == NULL) {
2255 Py_DECREF(iter);
2256 if (PyErr_Occurred())
2257 return NULL;
2258 return PyLong_FromLong(i_result);
2259 }
2260 if (PyLong_CheckExact(item)) {
2261 long b = PyLong_AsLongAndOverflow(item, &overflow);
2262 long x = i_result + b;
2263 if (overflow == 0 && ((x^i_result) >= 0 || (x^b) >= 0)) {
2264 i_result = x;
2265 Py_DECREF(item);
2266 continue;
2267 }
2268 }
2269 /* Either overflowed or is not an int. Restore real objects and process normally */
2270 result = PyLong_FromLong(i_result);
Christian Heimes704e2d32013-07-26 22:49:26 +02002271 if (result == NULL) {
2272 Py_DECREF(item);
2273 Py_DECREF(iter);
2274 return NULL;
2275 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002276 temp = PyNumber_Add(result, item);
2277 Py_DECREF(result);
2278 Py_DECREF(item);
2279 result = temp;
2280 if (result == NULL) {
2281 Py_DECREF(iter);
2282 return NULL;
2283 }
2284 }
2285 }
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002286
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002287 if (PyFloat_CheckExact(result)) {
2288 double f_result = PyFloat_AS_DOUBLE(result);
2289 Py_DECREF(result);
2290 result = NULL;
2291 while(result == NULL) {
2292 item = PyIter_Next(iter);
2293 if (item == NULL) {
2294 Py_DECREF(iter);
2295 if (PyErr_Occurred())
2296 return NULL;
2297 return PyFloat_FromDouble(f_result);
2298 }
2299 if (PyFloat_CheckExact(item)) {
2300 PyFPE_START_PROTECT("add", Py_DECREF(item); Py_DECREF(iter); return 0)
2301 f_result += PyFloat_AS_DOUBLE(item);
2302 PyFPE_END_PROTECT(f_result)
2303 Py_DECREF(item);
2304 continue;
2305 }
2306 if (PyLong_CheckExact(item)) {
2307 long value;
2308 int overflow;
2309 value = PyLong_AsLongAndOverflow(item, &overflow);
2310 if (!overflow) {
2311 PyFPE_START_PROTECT("add", Py_DECREF(item); Py_DECREF(iter); return 0)
2312 f_result += (double)value;
2313 PyFPE_END_PROTECT(f_result)
2314 Py_DECREF(item);
2315 continue;
2316 }
2317 }
2318 result = PyFloat_FromDouble(f_result);
2319 temp = PyNumber_Add(result, item);
2320 Py_DECREF(result);
2321 Py_DECREF(item);
2322 result = temp;
2323 if (result == NULL) {
2324 Py_DECREF(iter);
2325 return NULL;
2326 }
2327 }
2328 }
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002329#endif
2330
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002331 for(;;) {
2332 item = PyIter_Next(iter);
2333 if (item == NULL) {
2334 /* error, or end-of-sequence */
2335 if (PyErr_Occurred()) {
2336 Py_DECREF(result);
2337 result = NULL;
2338 }
2339 break;
2340 }
2341 /* It's tempting to use PyNumber_InPlaceAdd instead of
2342 PyNumber_Add here, to avoid quadratic running time
2343 when doing 'sum(list_of_lists, [])'. However, this
2344 would produce a change in behaviour: a snippet like
Mark Dickinson9acadc52009-10-26 14:19:42 +00002345
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002346 empty = []
2347 sum([[x] for x in range(10)], empty)
Mark Dickinson9acadc52009-10-26 14:19:42 +00002348
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002349 would change the value of empty. */
2350 temp = PyNumber_Add(result, item);
2351 Py_DECREF(result);
2352 Py_DECREF(item);
2353 result = temp;
2354 if (result == NULL)
2355 break;
2356 }
2357 Py_DECREF(iter);
2358 return result;
Alex Martellia70b1912003-04-22 08:12:33 +00002359}
2360
Alex Martellia70b1912003-04-22 08:12:33 +00002361
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002362/*[clinic input]
2363isinstance as builtin_isinstance
2364
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03002365 obj: object
2366 class_or_tuple: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002367 /
2368
2369Return whether an object is an instance of a class or of a subclass thereof.
2370
2371A tuple, as in ``isinstance(x, (A, B, ...))``, may be given as the target to
2372check against. This is equivalent to ``isinstance(x, A) or isinstance(x, B)
2373or ...`` etc.
2374[clinic start generated code]*/
2375
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002376static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002377builtin_isinstance_impl(PyObject *module, PyObject *obj,
Larry Hastings89964c42015-04-14 18:07:59 -04002378 PyObject *class_or_tuple)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002379/*[clinic end generated code: output=6faf01472c13b003 input=ffa743db1daf7549]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002380{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002381 int retval;
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002382
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002383 retval = PyObject_IsInstance(obj, class_or_tuple);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002384 if (retval < 0)
2385 return NULL;
2386 return PyBool_FromLong(retval);
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002387}
2388
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002389
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002390/*[clinic input]
2391issubclass as builtin_issubclass
2392
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03002393 cls: object
2394 class_or_tuple: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002395 /
2396
2397Return whether 'cls' is a derived from another class or is the same class.
2398
2399A tuple, as in ``issubclass(x, (A, B, ...))``, may be given as the target to
2400check against. This is equivalent to ``issubclass(x, A) or issubclass(x, B)
2401or ...`` etc.
2402[clinic start generated code]*/
2403
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002404static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002405builtin_issubclass_impl(PyObject *module, PyObject *cls,
Larry Hastings89964c42015-04-14 18:07:59 -04002406 PyObject *class_or_tuple)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002407/*[clinic end generated code: output=358412410cd7a250 input=af5f35e9ceaddaf6]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002408{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002409 int retval;
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002410
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002411 retval = PyObject_IsSubclass(cls, class_or_tuple);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002412 if (retval < 0)
2413 return NULL;
2414 return PyBool_FromLong(retval);
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002415}
2416
2417
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002418typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002419 PyObject_HEAD
2420 Py_ssize_t tuplesize;
2421 PyObject *ittuple; /* tuple of iterators */
2422 PyObject *result;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002423} zipobject;
2424
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002425static PyObject *
2426zip_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
Barry Warsawbd599b52000-08-03 15:45:29 +00002427{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002428 zipobject *lz;
2429 Py_ssize_t i;
2430 PyObject *ittuple; /* tuple of iterators */
2431 PyObject *result;
2432 Py_ssize_t tuplesize = PySequence_Length(args);
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002433
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002434 if (type == &PyZip_Type && !_PyArg_NoKeywords("zip()", kwds))
2435 return NULL;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002436
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002437 /* args must be a tuple */
2438 assert(PyTuple_Check(args));
Barry Warsawbd599b52000-08-03 15:45:29 +00002439
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002440 /* obtain iterators */
2441 ittuple = PyTuple_New(tuplesize);
2442 if (ittuple == NULL)
2443 return NULL;
2444 for (i=0; i < tuplesize; ++i) {
2445 PyObject *item = PyTuple_GET_ITEM(args, i);
2446 PyObject *it = PyObject_GetIter(item);
2447 if (it == NULL) {
2448 if (PyErr_ExceptionMatches(PyExc_TypeError))
2449 PyErr_Format(PyExc_TypeError,
2450 "zip argument #%zd must support iteration",
2451 i+1);
2452 Py_DECREF(ittuple);
2453 return NULL;
2454 }
2455 PyTuple_SET_ITEM(ittuple, i, it);
2456 }
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002457
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002458 /* create a result holder */
2459 result = PyTuple_New(tuplesize);
2460 if (result == NULL) {
2461 Py_DECREF(ittuple);
2462 return NULL;
2463 }
2464 for (i=0 ; i < tuplesize ; i++) {
2465 Py_INCREF(Py_None);
2466 PyTuple_SET_ITEM(result, i, Py_None);
2467 }
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002468
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002469 /* create zipobject structure */
2470 lz = (zipobject *)type->tp_alloc(type, 0);
2471 if (lz == NULL) {
2472 Py_DECREF(ittuple);
2473 Py_DECREF(result);
2474 return NULL;
2475 }
2476 lz->ittuple = ittuple;
2477 lz->tuplesize = tuplesize;
2478 lz->result = result;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002479
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002480 return (PyObject *)lz;
Barry Warsawbd599b52000-08-03 15:45:29 +00002481}
2482
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002483static void
2484zip_dealloc(zipobject *lz)
2485{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002486 PyObject_GC_UnTrack(lz);
2487 Py_XDECREF(lz->ittuple);
2488 Py_XDECREF(lz->result);
2489 Py_TYPE(lz)->tp_free(lz);
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002490}
2491
2492static int
2493zip_traverse(zipobject *lz, visitproc visit, void *arg)
2494{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002495 Py_VISIT(lz->ittuple);
2496 Py_VISIT(lz->result);
2497 return 0;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002498}
2499
2500static PyObject *
2501zip_next(zipobject *lz)
2502{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002503 Py_ssize_t i;
2504 Py_ssize_t tuplesize = lz->tuplesize;
2505 PyObject *result = lz->result;
2506 PyObject *it;
2507 PyObject *item;
2508 PyObject *olditem;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002509
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002510 if (tuplesize == 0)
2511 return NULL;
2512 if (Py_REFCNT(result) == 1) {
2513 Py_INCREF(result);
2514 for (i=0 ; i < tuplesize ; i++) {
2515 it = PyTuple_GET_ITEM(lz->ittuple, i);
2516 item = (*Py_TYPE(it)->tp_iternext)(it);
Serhiy Storchaka278d03b2013-04-06 22:52:34 +03002517 if (item == NULL) {
2518 Py_DECREF(result);
2519 return NULL;
2520 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002521 olditem = PyTuple_GET_ITEM(result, i);
2522 PyTuple_SET_ITEM(result, i, item);
2523 Py_DECREF(olditem);
2524 }
2525 } else {
2526 result = PyTuple_New(tuplesize);
2527 if (result == NULL)
Serhiy Storchaka278d03b2013-04-06 22:52:34 +03002528 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002529 for (i=0 ; i < tuplesize ; i++) {
2530 it = PyTuple_GET_ITEM(lz->ittuple, i);
2531 item = (*Py_TYPE(it)->tp_iternext)(it);
Serhiy Storchaka278d03b2013-04-06 22:52:34 +03002532 if (item == NULL) {
2533 Py_DECREF(result);
2534 return NULL;
2535 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002536 PyTuple_SET_ITEM(result, i, item);
2537 }
2538 }
2539 return result;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002540}
Barry Warsawbd599b52000-08-03 15:45:29 +00002541
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002542static PyObject *
2543zip_reduce(zipobject *lz)
2544{
2545 /* Just recreate the zip with the internal iterator tuple */
2546 return Py_BuildValue("OO", Py_TYPE(lz), lz->ittuple);
2547}
2548
2549static PyMethodDef zip_methods[] = {
2550 {"__reduce__", (PyCFunction)zip_reduce, METH_NOARGS, reduce_doc},
2551 {NULL, NULL} /* sentinel */
2552};
2553
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002554PyDoc_STRVAR(zip_doc,
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002555"zip(iter1 [,iter2 [...]]) --> zip object\n\
Barry Warsawbd599b52000-08-03 15:45:29 +00002556\n\
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002557Return a zip object whose .__next__() method returns a tuple where\n\
2558the i-th element comes from the i-th iterable argument. The .__next__()\n\
2559method continues until the shortest iterable in the argument sequence\n\
Georg Brandlced51db2008-12-04 18:28:38 +00002560is exhausted and then it raises StopIteration.");
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002561
2562PyTypeObject PyZip_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002563 PyVarObject_HEAD_INIT(&PyType_Type, 0)
2564 "zip", /* tp_name */
2565 sizeof(zipobject), /* tp_basicsize */
2566 0, /* tp_itemsize */
2567 /* methods */
2568 (destructor)zip_dealloc, /* tp_dealloc */
2569 0, /* tp_print */
2570 0, /* tp_getattr */
2571 0, /* tp_setattr */
2572 0, /* tp_reserved */
2573 0, /* tp_repr */
2574 0, /* tp_as_number */
2575 0, /* tp_as_sequence */
2576 0, /* tp_as_mapping */
2577 0, /* tp_hash */
2578 0, /* tp_call */
2579 0, /* tp_str */
2580 PyObject_GenericGetAttr, /* tp_getattro */
2581 0, /* tp_setattro */
2582 0, /* tp_as_buffer */
2583 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
2584 Py_TPFLAGS_BASETYPE, /* tp_flags */
2585 zip_doc, /* tp_doc */
2586 (traverseproc)zip_traverse, /* tp_traverse */
2587 0, /* tp_clear */
2588 0, /* tp_richcompare */
2589 0, /* tp_weaklistoffset */
2590 PyObject_SelfIter, /* tp_iter */
2591 (iternextfunc)zip_next, /* tp_iternext */
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002592 zip_methods, /* tp_methods */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002593 0, /* tp_members */
2594 0, /* tp_getset */
2595 0, /* tp_base */
2596 0, /* tp_dict */
2597 0, /* tp_descr_get */
2598 0, /* tp_descr_set */
2599 0, /* tp_dictoffset */
2600 0, /* tp_init */
2601 PyType_GenericAlloc, /* tp_alloc */
2602 zip_new, /* tp_new */
2603 PyObject_GC_Del, /* tp_free */
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002604};
Barry Warsawbd599b52000-08-03 15:45:29 +00002605
2606
Guido van Rossum79f25d91997-04-29 20:08:16 +00002607static PyMethodDef builtin_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002608 {"__build_class__", (PyCFunction)builtin___build_class__,
Victor Stinner773dc6d2017-01-16 23:46:26 +01002609 METH_FASTCALL, build_class_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002610 {"__import__", (PyCFunction)builtin___import__, METH_VARARGS | METH_KEYWORDS, import_doc},
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002611 BUILTIN_ABS_METHODDEF
2612 BUILTIN_ALL_METHODDEF
2613 BUILTIN_ANY_METHODDEF
2614 BUILTIN_ASCII_METHODDEF
2615 BUILTIN_BIN_METHODDEF
2616 BUILTIN_CALLABLE_METHODDEF
2617 BUILTIN_CHR_METHODDEF
2618 BUILTIN_COMPILE_METHODDEF
2619 BUILTIN_DELATTR_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002620 {"dir", builtin_dir, METH_VARARGS, dir_doc},
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002621 BUILTIN_DIVMOD_METHODDEF
2622 BUILTIN_EVAL_METHODDEF
2623 BUILTIN_EXEC_METHODDEF
2624 BUILTIN_FORMAT_METHODDEF
Victor Stinner84b388b2017-01-17 03:52:27 +01002625 {"getattr", (PyCFunction)builtin_getattr, METH_FASTCALL, getattr_doc},
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002626 BUILTIN_GLOBALS_METHODDEF
2627 BUILTIN_HASATTR_METHODDEF
2628 BUILTIN_HASH_METHODDEF
2629 BUILTIN_HEX_METHODDEF
2630 BUILTIN_ID_METHODDEF
2631 BUILTIN_INPUT_METHODDEF
2632 BUILTIN_ISINSTANCE_METHODDEF
2633 BUILTIN_ISSUBCLASS_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002634 {"iter", builtin_iter, METH_VARARGS, iter_doc},
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002635 BUILTIN_LEN_METHODDEF
2636 BUILTIN_LOCALS_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002637 {"max", (PyCFunction)builtin_max, METH_VARARGS | METH_KEYWORDS, max_doc},
2638 {"min", (PyCFunction)builtin_min, METH_VARARGS | METH_KEYWORDS, min_doc},
Victor Stinnerfda6d0a2017-01-17 04:09:14 +01002639 {"next", (PyCFunction)builtin_next, METH_FASTCALL, next_doc},
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002640 BUILTIN_OCT_METHODDEF
2641 BUILTIN_ORD_METHODDEF
2642 BUILTIN_POW_METHODDEF
INADA Naokibd584f12017-01-19 12:50:34 +01002643 {"print", (PyCFunction)builtin_print, METH_FASTCALL, print_doc},
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002644 BUILTIN_REPR_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002645 {"round", (PyCFunction)builtin_round, METH_VARARGS | METH_KEYWORDS, round_doc},
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002646 BUILTIN_SETATTR_METHODDEF
2647 BUILTIN_SORTED_METHODDEF
2648 BUILTIN_SUM_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002649 {"vars", builtin_vars, METH_VARARGS, vars_doc},
2650 {NULL, NULL},
Guido van Rossum3f5da241990-12-20 15:06:42 +00002651};
2652
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002653PyDoc_STRVAR(builtin_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002654"Built-in functions, exceptions, and other objects.\n\
2655\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002656Noteworthy: None is the `nil' object; Ellipsis represents `...' in slices.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002657
Martin v. Löwis1a214512008-06-11 05:26:20 +00002658static struct PyModuleDef builtinsmodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002659 PyModuleDef_HEAD_INIT,
2660 "builtins",
2661 builtin_doc,
2662 -1, /* multiple "initialization" just copies the module dict. */
2663 builtin_methods,
2664 NULL,
2665 NULL,
2666 NULL,
2667 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00002668};
2669
2670
Guido van Rossum25ce5661997-08-02 03:10:38 +00002671PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002672_PyBuiltin_Init(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +00002673{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002674 PyObject *mod, *dict, *debug;
Benjamin Peterson42124a72012-10-30 23:41:54 -04002675
2676 if (PyType_Ready(&PyFilter_Type) < 0 ||
2677 PyType_Ready(&PyMap_Type) < 0 ||
2678 PyType_Ready(&PyZip_Type) < 0)
2679 return NULL;
2680
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002681 mod = PyModule_Create(&builtinsmodule);
2682 if (mod == NULL)
2683 return NULL;
2684 dict = PyModule_GetDict(mod);
Tim Peters4b7625e2001-09-13 21:37:17 +00002685
Tim Peters7571a0f2003-03-23 17:52:28 +00002686#ifdef Py_TRACE_REFS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002687 /* "builtins" exposes a number of statically allocated objects
2688 * that, before this code was added in 2.3, never showed up in
2689 * the list of "all objects" maintained by Py_TRACE_REFS. As a
2690 * result, programs leaking references to None and False (etc)
2691 * couldn't be diagnosed by examining sys.getobjects(0).
2692 */
Tim Peters7571a0f2003-03-23 17:52:28 +00002693#define ADD_TO_ALL(OBJECT) _Py_AddToAllObjects((PyObject *)(OBJECT), 0)
2694#else
2695#define ADD_TO_ALL(OBJECT) (void)0
2696#endif
2697
Tim Peters4b7625e2001-09-13 21:37:17 +00002698#define SETBUILTIN(NAME, OBJECT) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002699 if (PyDict_SetItemString(dict, NAME, (PyObject *)OBJECT) < 0) \
2700 return NULL; \
2701 ADD_TO_ALL(OBJECT)
Tim Peters4b7625e2001-09-13 21:37:17 +00002702
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002703 SETBUILTIN("None", Py_None);
2704 SETBUILTIN("Ellipsis", Py_Ellipsis);
2705 SETBUILTIN("NotImplemented", Py_NotImplemented);
2706 SETBUILTIN("False", Py_False);
2707 SETBUILTIN("True", Py_True);
2708 SETBUILTIN("bool", &PyBool_Type);
2709 SETBUILTIN("memoryview", &PyMemoryView_Type);
2710 SETBUILTIN("bytearray", &PyByteArray_Type);
2711 SETBUILTIN("bytes", &PyBytes_Type);
2712 SETBUILTIN("classmethod", &PyClassMethod_Type);
2713 SETBUILTIN("complex", &PyComplex_Type);
2714 SETBUILTIN("dict", &PyDict_Type);
2715 SETBUILTIN("enumerate", &PyEnum_Type);
2716 SETBUILTIN("filter", &PyFilter_Type);
2717 SETBUILTIN("float", &PyFloat_Type);
2718 SETBUILTIN("frozenset", &PyFrozenSet_Type);
2719 SETBUILTIN("property", &PyProperty_Type);
2720 SETBUILTIN("int", &PyLong_Type);
2721 SETBUILTIN("list", &PyList_Type);
2722 SETBUILTIN("map", &PyMap_Type);
2723 SETBUILTIN("object", &PyBaseObject_Type);
2724 SETBUILTIN("range", &PyRange_Type);
2725 SETBUILTIN("reversed", &PyReversed_Type);
2726 SETBUILTIN("set", &PySet_Type);
2727 SETBUILTIN("slice", &PySlice_Type);
2728 SETBUILTIN("staticmethod", &PyStaticMethod_Type);
2729 SETBUILTIN("str", &PyUnicode_Type);
2730 SETBUILTIN("super", &PySuper_Type);
2731 SETBUILTIN("tuple", &PyTuple_Type);
2732 SETBUILTIN("type", &PyType_Type);
2733 SETBUILTIN("zip", &PyZip_Type);
2734 debug = PyBool_FromLong(Py_OptimizeFlag == 0);
2735 if (PyDict_SetItemString(dict, "__debug__", debug) < 0) {
Serhiy Storchakacfdfbb42016-06-18 09:44:03 +03002736 Py_DECREF(debug);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002737 return NULL;
2738 }
Serhiy Storchakacfdfbb42016-06-18 09:44:03 +03002739 Py_DECREF(debug);
Barry Warsaw757af0e1997-08-29 22:13:51 +00002740
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002741 return mod;
Tim Peters7571a0f2003-03-23 17:52:28 +00002742#undef ADD_TO_ALL
Tim Peters4b7625e2001-09-13 21:37:17 +00002743#undef SETBUILTIN
Guido van Rossum3f5da241990-12-20 15:06:42 +00002744}