blob: c363cfe8cea26bd8b715da45eef49cd216aa1f54 [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
Serhiy Storchaka6cca5c82017-06-08 14:41:19 +0300432 if (type == &PyFilter_Type && !_PyArg_NoKeywords("filter", kwds))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000433 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
Amit Kumar2e6bb442017-05-29 06:32:26 +0530581format_spec defaults to the empty string.
582See the Format Specification Mini-Language section of help('FORMATTING') for
583details.
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000584[clinic start generated code]*/
585
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000586static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300587builtin_format_impl(PyObject *module, PyObject *value, PyObject *format_spec)
Amit Kumar2e6bb442017-05-29 06:32:26 +0530588/*[clinic end generated code: output=2f40bdfa4954b077 input=88339c93ea522b33]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000589{
Eric Smith8fd3eba2008-02-17 19:48:00 +0000590 return PyObject_Format(value, format_spec);
Eric Smith8c663262007-08-25 02:26:07 +0000591}
592
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000593/*[clinic input]
594chr as builtin_chr
595
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300596 i: int
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000597 /
598
599Return a Unicode string of one character with ordinal i; 0 <= i <= 0x10ffff.
600[clinic start generated code]*/
601
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000602static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300603builtin_chr_impl(PyObject *module, int i)
604/*[clinic end generated code: output=c733afcd200afcb7 input=3f604ef45a70750d]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000605{
606 return PyUnicode_FromOrdinal(i);
607}
Guido van Rossum09095f32000-03-10 23:00:52 +0000608
609
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +0200610static const char *
Martin Pantereeb896c2015-11-07 02:32:21 +0000611source_as_string(PyObject *cmd, const char *funcname, const char *what, PyCompilerFlags *cf, PyObject **cmd_copy)
Guido van Rossumf15a29f2007-05-04 00:41:39 +0000612{
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +0200613 const char *str;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000614 Py_ssize_t size;
Martin Pantereeb896c2015-11-07 02:32:21 +0000615 Py_buffer view;
Guido van Rossumf15a29f2007-05-04 00:41:39 +0000616
Martin Pantereeb896c2015-11-07 02:32:21 +0000617 *cmd_copy = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000618 if (PyUnicode_Check(cmd)) {
619 cf->cf_flags |= PyCF_IGNORE_COOKIE;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200620 str = PyUnicode_AsUTF8AndSize(cmd, &size);
621 if (str == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000622 return NULL;
623 }
Martin Pantereeb896c2015-11-07 02:32:21 +0000624 else if (PyBytes_Check(cmd)) {
625 str = PyBytes_AS_STRING(cmd);
626 size = PyBytes_GET_SIZE(cmd);
627 }
628 else if (PyByteArray_Check(cmd)) {
629 str = PyByteArray_AS_STRING(cmd);
630 size = PyByteArray_GET_SIZE(cmd);
631 }
632 else if (PyObject_GetBuffer(cmd, &view, PyBUF_SIMPLE) == 0) {
633 /* Copy to NUL-terminated buffer. */
634 *cmd_copy = PyBytes_FromStringAndSize(
635 (const char *)view.buf, view.len);
636 PyBuffer_Release(&view);
637 if (*cmd_copy == NULL) {
638 return NULL;
639 }
640 str = PyBytes_AS_STRING(*cmd_copy);
641 size = PyBytes_GET_SIZE(*cmd_copy);
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +0200642 }
643 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000644 PyErr_Format(PyExc_TypeError,
645 "%s() arg 1 must be a %s object",
646 funcname, what);
647 return NULL;
648 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200649
Serhiy Storchaka3dd3e262015-02-03 01:25:42 +0200650 if (strlen(str) != (size_t)size) {
Serhiy Storchakad8a14472014-09-06 20:07:17 +0300651 PyErr_SetString(PyExc_ValueError,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000652 "source code string cannot contain null bytes");
Martin Pantereeb896c2015-11-07 02:32:21 +0000653 Py_CLEAR(*cmd_copy);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000654 return NULL;
655 }
656 return str;
Guido van Rossumf15a29f2007-05-04 00:41:39 +0000657}
658
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000659/*[clinic input]
660compile as builtin_compile
661
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300662 source: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000663 filename: object(converter="PyUnicode_FSDecoder")
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300664 mode: str
665 flags: int = 0
Serhiy Storchaka202fda52017-03-12 10:10:47 +0200666 dont_inherit: bool(accept={int}) = False
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300667 optimize: int = -1
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000668
669Compile source into a code object that can be executed by exec() or eval().
670
671The source code may represent a Python module, statement or expression.
672The filename will be used for run-time error messages.
673The mode must be 'exec' to compile a module, 'single' to compile a
674single (interactive) statement, or 'eval' to compile an expression.
675The flags argument, if present, controls which future statements influence
676the compilation of the code.
Serhiy Storchaka8b2e8b62015-05-30 11:30:39 +0300677The dont_inherit argument, if true, stops the compilation inheriting
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000678the effects of any future statements in effect in the code calling
Serhiy Storchaka8b2e8b62015-05-30 11:30:39 +0300679compile; if absent or false these statements do influence the compilation,
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000680in addition to any features explicitly specified.
681[clinic start generated code]*/
682
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000683static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300684builtin_compile_impl(PyObject *module, PyObject *source, PyObject *filename,
685 const char *mode, int flags, int dont_inherit,
686 int optimize)
Serhiy Storchaka202fda52017-03-12 10:10:47 +0200687/*[clinic end generated code: output=1fa176e33452bb63 input=0ff726f595eb9fcd]*/
Guido van Rossum5b722181993-03-30 17:46:03 +0000688{
Martin Panter61d6e4a2015-11-07 02:56:11 +0000689 PyObject *source_copy;
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +0200690 const char *str;
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000691 int compile_mode = -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000692 int is_ast;
693 PyCompilerFlags cf;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000694 int start[] = {Py_file_input, Py_eval_input, Py_single_input};
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000695 PyObject *result;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000696
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000697 cf.cf_flags = flags | PyCF_SOURCE_IS_UTF8;
Tim Peters6cd6a822001-08-17 22:11:27 +0000698
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000699 if (flags &
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000700 ~(PyCF_MASK | PyCF_MASK_OBSOLETE | PyCF_DONT_IMPLY_DEDENT | PyCF_ONLY_AST))
701 {
702 PyErr_SetString(PyExc_ValueError,
703 "compile(): unrecognised flags");
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000704 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000705 }
706 /* XXX Warn if (supplied_flags & PyCF_MASK_OBSOLETE) != 0? */
Tim Peters6cd6a822001-08-17 22:11:27 +0000707
Georg Brandl8334fd92010-12-04 10:26:46 +0000708 if (optimize < -1 || optimize > 2) {
709 PyErr_SetString(PyExc_ValueError,
710 "compile(): invalid optimize value");
711 goto error;
712 }
713
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000714 if (!dont_inherit) {
715 PyEval_MergeCompilerFlags(&cf);
716 }
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000717
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000718 if (strcmp(mode, "exec") == 0)
719 compile_mode = 0;
720 else if (strcmp(mode, "eval") == 0)
721 compile_mode = 1;
722 else if (strcmp(mode, "single") == 0)
723 compile_mode = 2;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000724 else {
725 PyErr_SetString(PyExc_ValueError,
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000726 "compile() mode must be 'exec', 'eval' or 'single'");
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000727 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000728 }
Neal Norwitzdb4115f2008-03-31 04:20:05 +0000729
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000730 is_ast = PyAST_Check(source);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000731 if (is_ast == -1)
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000732 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000733 if (is_ast) {
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000734 if (flags & PyCF_ONLY_AST) {
735 Py_INCREF(source);
736 result = source;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000737 }
738 else {
739 PyArena *arena;
740 mod_ty mod;
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000741
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000742 arena = PyArena_New();
Stefan Krah07795df2012-08-20 17:19:50 +0200743 if (arena == NULL)
744 goto error;
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000745 mod = PyAST_obj2mod(source, arena, compile_mode);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000746 if (mod == NULL) {
747 PyArena_Free(arena);
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000748 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000749 }
Benjamin Peterson832bfe22011-08-09 16:15:04 -0500750 if (!PyAST_Validate(mod)) {
751 PyArena_Free(arena);
752 goto error;
753 }
Victor Stinner14e461d2013-08-26 22:28:21 +0200754 result = (PyObject*)PyAST_CompileObject(mod, filename,
755 &cf, optimize, arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000756 PyArena_Free(arena);
757 }
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000758 goto finally;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000759 }
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000760
Martin Panter61d6e4a2015-11-07 02:56:11 +0000761 str = source_as_string(source, "compile", "string, bytes or AST", &cf, &source_copy);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000762 if (str == NULL)
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000763 goto error;
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000764
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000765 result = Py_CompileStringObject(str, filename, start[compile_mode], &cf, optimize);
Martin Panter61d6e4a2015-11-07 02:56:11 +0000766 Py_XDECREF(source_copy);
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000767 goto finally;
768
769error:
770 result = NULL;
771finally:
Victor Stinner14e461d2013-08-26 22:28:21 +0200772 Py_DECREF(filename);
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000773 return result;
Guido van Rossum5b722181993-03-30 17:46:03 +0000774}
775
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000776/* AC: cannot convert yet, as needs PEP 457 group support in inspect */
Guido van Rossum79f25d91997-04-29 20:08:16 +0000777static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000778builtin_dir(PyObject *self, PyObject *args)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000779{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000780 PyObject *arg = NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000781
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000782 if (!PyArg_UnpackTuple(args, "dir", 0, 1, &arg))
783 return NULL;
784 return PyObject_Dir(arg);
Guido van Rossum3f5da241990-12-20 15:06:42 +0000785}
786
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000787PyDoc_STRVAR(dir_doc,
Tim Peters5d2b77c2001-09-03 05:47:38 +0000788"dir([object]) -> list of strings\n"
789"\n"
Georg Brandle32b4222007-03-10 22:13:27 +0000790"If called without an argument, return the names in the current scope.\n"
791"Else, return an alphabetized list of names comprising (some of) the attributes\n"
792"of the given object, and of attributes reachable from it.\n"
793"If the object supplies a method named __dir__, it will be used; otherwise\n"
794"the default dir() logic is used and returns:\n"
795" for a module object: the module's attributes.\n"
796" for a class object: its attributes, and recursively the attributes\n"
797" of its bases.\n"
Guido van Rossumd8faa362007-04-27 19:54:29 +0000798" for any other object: its attributes, its class's attributes, and\n"
Georg Brandle32b4222007-03-10 22:13:27 +0000799" recursively the attributes of its class's base classes.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000800
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000801/*[clinic input]
802divmod as builtin_divmod
Guido van Rossum6a00cd81995-01-07 12:39:01 +0000803
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300804 x: object
805 y: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000806 /
807
Zachary Ware7f227d92016-04-28 14:39:50 -0500808Return the tuple (x//y, x%y). Invariant: div*y + mod == x.
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000809[clinic start generated code]*/
810
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000811static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300812builtin_divmod_impl(PyObject *module, PyObject *x, PyObject *y)
813/*[clinic end generated code: output=b06d8a5f6e0c745e input=175ad9c84ff41a85]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000814{
815 return PyNumber_Divmod(x, y);
816}
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000817
818
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000819/*[clinic input]
820eval as builtin_eval
821
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300822 source: object
823 globals: object = None
824 locals: object = None
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000825 /
826
827Evaluate the given source in the context of globals and locals.
828
829The source may be a string representing a Python expression
830or a code object as returned by compile().
831The globals must be a dictionary and locals can be any mapping,
832defaulting to the current globals and locals.
833If only globals is given, locals defaults to it.
834[clinic start generated code]*/
835
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000836static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300837builtin_eval_impl(PyObject *module, PyObject *source, PyObject *globals,
Larry Hastings89964c42015-04-14 18:07:59 -0400838 PyObject *locals)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300839/*[clinic end generated code: output=0a0824aa70093116 input=11ee718a8640e527]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000840{
Martin Panter61d6e4a2015-11-07 02:56:11 +0000841 PyObject *result, *source_copy;
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +0200842 const char *str;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000843 PyCompilerFlags cf;
Guido van Rossum590baa41993-11-30 13:40:46 +0000844
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000845 if (locals != Py_None && !PyMapping_Check(locals)) {
846 PyErr_SetString(PyExc_TypeError, "locals must be a mapping");
847 return NULL;
848 }
849 if (globals != Py_None && !PyDict_Check(globals)) {
850 PyErr_SetString(PyExc_TypeError, PyMapping_Check(globals) ?
851 "globals must be a real dict; try eval(expr, {}, mapping)"
852 : "globals must be a dict");
853 return NULL;
854 }
855 if (globals == Py_None) {
856 globals = PyEval_GetGlobals();
Victor Stinner41bb43a2013-10-29 01:19:37 +0100857 if (locals == Py_None) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000858 locals = PyEval_GetLocals();
Victor Stinner41bb43a2013-10-29 01:19:37 +0100859 if (locals == NULL)
860 return NULL;
861 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000862 }
863 else if (locals == Py_None)
864 locals = globals;
Tim Peters9fa96be2001-08-17 23:04:59 +0000865
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000866 if (globals == NULL || locals == NULL) {
867 PyErr_SetString(PyExc_TypeError,
868 "eval must be given globals and locals "
869 "when called without a frame");
870 return NULL;
871 }
Georg Brandl77c85e62005-09-15 10:46:13 +0000872
Victor Stinnerb44562b2013-11-06 19:03:11 +0100873 if (_PyDict_GetItemId(globals, &PyId___builtins__) == NULL) {
874 if (_PyDict_SetItemId(globals, &PyId___builtins__,
875 PyEval_GetBuiltins()) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000876 return NULL;
877 }
Tim Peters9fa96be2001-08-17 23:04:59 +0000878
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000879 if (PyCode_Check(source)) {
880 if (PyCode_GetNumFree((PyCodeObject *)source) > 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000881 PyErr_SetString(PyExc_TypeError,
882 "code object passed to eval() may not contain free variables");
883 return NULL;
884 }
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000885 return PyEval_EvalCode(source, globals, locals);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000886 }
Tim Peters9fa96be2001-08-17 23:04:59 +0000887
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000888 cf.cf_flags = PyCF_SOURCE_IS_UTF8;
Martin Panter61d6e4a2015-11-07 02:56:11 +0000889 str = source_as_string(source, "eval", "string, bytes or code", &cf, &source_copy);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000890 if (str == NULL)
891 return NULL;
Just van Rossum3aaf42c2003-02-10 08:21:10 +0000892
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000893 while (*str == ' ' || *str == '\t')
894 str++;
Tim Peters9fa96be2001-08-17 23:04:59 +0000895
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000896 (void)PyEval_MergeCompilerFlags(&cf);
897 result = PyRun_StringFlags(str, Py_eval_input, globals, locals, &cf);
Martin Panter61d6e4a2015-11-07 02:56:11 +0000898 Py_XDECREF(source_copy);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000899 return result;
Guido van Rossum3f5da241990-12-20 15:06:42 +0000900}
901
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000902/*[clinic input]
903exec as builtin_exec
904
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300905 source: object
906 globals: object = None
907 locals: object = None
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000908 /
909
910Execute the given source in the context of globals and locals.
911
912The source may be a string representing one or more Python statements
913or a code object as returned by compile().
914The globals must be a dictionary and locals can be any mapping,
915defaulting to the current globals and locals.
916If only globals is given, locals defaults to it.
917[clinic start generated code]*/
918
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000919static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300920builtin_exec_impl(PyObject *module, PyObject *source, PyObject *globals,
Larry Hastings89964c42015-04-14 18:07:59 -0400921 PyObject *locals)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300922/*[clinic end generated code: output=3c90efc6ab68ef5d input=01ca3e1c01692829]*/
Georg Brandl7cae87c2006-09-06 06:51:57 +0000923{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000924 PyObject *v;
Georg Brandl2cabc562008-08-28 07:57:16 +0000925
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000926 if (globals == Py_None) {
927 globals = PyEval_GetGlobals();
928 if (locals == Py_None) {
929 locals = PyEval_GetLocals();
Victor Stinner41bb43a2013-10-29 01:19:37 +0100930 if (locals == NULL)
931 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000932 }
933 if (!globals || !locals) {
934 PyErr_SetString(PyExc_SystemError,
935 "globals and locals cannot be NULL");
936 return NULL;
937 }
938 }
939 else if (locals == Py_None)
940 locals = globals;
Georg Brandl7cae87c2006-09-06 06:51:57 +0000941
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000942 if (!PyDict_Check(globals)) {
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000943 PyErr_Format(PyExc_TypeError, "exec() globals must be a dict, not %.100s",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000944 globals->ob_type->tp_name);
945 return NULL;
946 }
947 if (!PyMapping_Check(locals)) {
948 PyErr_Format(PyExc_TypeError,
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000949 "locals must be a mapping or None, not %.100s",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000950 locals->ob_type->tp_name);
951 return NULL;
952 }
Victor Stinnerb44562b2013-11-06 19:03:11 +0100953 if (_PyDict_GetItemId(globals, &PyId___builtins__) == NULL) {
954 if (_PyDict_SetItemId(globals, &PyId___builtins__,
955 PyEval_GetBuiltins()) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000956 return NULL;
957 }
958
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000959 if (PyCode_Check(source)) {
960 if (PyCode_GetNumFree((PyCodeObject *)source) > 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000961 PyErr_SetString(PyExc_TypeError,
962 "code object passed to exec() may not "
963 "contain free variables");
964 return NULL;
965 }
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000966 v = PyEval_EvalCode(source, globals, locals);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000967 }
968 else {
Martin Panter61d6e4a2015-11-07 02:56:11 +0000969 PyObject *source_copy;
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +0200970 const char *str;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000971 PyCompilerFlags cf;
972 cf.cf_flags = PyCF_SOURCE_IS_UTF8;
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000973 str = source_as_string(source, "exec",
Martin Panter61d6e4a2015-11-07 02:56:11 +0000974 "string, bytes or code", &cf,
975 &source_copy);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000976 if (str == NULL)
977 return NULL;
978 if (PyEval_MergeCompilerFlags(&cf))
979 v = PyRun_StringFlags(str, Py_file_input, globals,
980 locals, &cf);
981 else
982 v = PyRun_String(str, Py_file_input, globals, locals);
Martin Panter61d6e4a2015-11-07 02:56:11 +0000983 Py_XDECREF(source_copy);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000984 }
985 if (v == NULL)
986 return NULL;
987 Py_DECREF(v);
988 Py_RETURN_NONE;
Georg Brandl7cae87c2006-09-06 06:51:57 +0000989}
990
Georg Brandl7cae87c2006-09-06 06:51:57 +0000991
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000992/* AC: cannot convert yet, as needs PEP 457 group support in inspect */
Guido van Rossum79f25d91997-04-29 20:08:16 +0000993static PyObject *
Serhiy Storchaka6969eaf2017-07-03 21:20:15 +0300994builtin_getattr(PyObject *self, PyObject **args, Py_ssize_t nargs)
Guido van Rossum33894be1992-01-27 16:53:09 +0000995{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000996 PyObject *v, *result, *dflt = NULL;
997 PyObject *name;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000998
Sylvain96c7c062017-06-15 17:05:23 +0200999 if (!_PyArg_UnpackStack(args, nargs, "getattr", 2, 3, &v, &name, &dflt))
1000 return NULL;
1001
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001002 if (!PyUnicode_Check(name)) {
1003 PyErr_SetString(PyExc_TypeError,
1004 "getattr(): attribute name must be string");
1005 return NULL;
1006 }
1007 result = PyObject_GetAttr(v, name);
1008 if (result == NULL && dflt != NULL &&
1009 PyErr_ExceptionMatches(PyExc_AttributeError))
1010 {
1011 PyErr_Clear();
1012 Py_INCREF(dflt);
1013 result = dflt;
1014 }
1015 return result;
Guido van Rossum9bfef441993-03-29 10:43:31 +00001016}
1017
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001018PyDoc_STRVAR(getattr_doc,
Guido van Rossum950ff291998-06-29 13:38:57 +00001019"getattr(object, name[, default]) -> value\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001020\n\
Guido van Rossum950ff291998-06-29 13:38:57 +00001021Get a named attribute from an object; getattr(x, 'y') is equivalent to x.y.\n\
1022When a default argument is given, it is returned when the attribute doesn't\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001023exist; without it, an exception is raised in that case.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001024
1025
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001026/*[clinic input]
1027globals as builtin_globals
1028
1029Return the dictionary containing the current scope's global variables.
1030
1031NOTE: Updates to this dictionary *will* affect name lookups in the current
1032global scope and vice-versa.
1033[clinic start generated code]*/
1034
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001035static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001036builtin_globals_impl(PyObject *module)
1037/*[clinic end generated code: output=e5dd1527067b94d2 input=9327576f92bb48ba]*/
Guido van Rossum872537c1995-07-07 22:43:42 +00001038{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001039 PyObject *d;
Guido van Rossum872537c1995-07-07 22:43:42 +00001040
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001041 d = PyEval_GetGlobals();
1042 Py_XINCREF(d);
1043 return d;
Guido van Rossum872537c1995-07-07 22:43:42 +00001044}
1045
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001046
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001047/*[clinic input]
1048hasattr as builtin_hasattr
1049
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001050 obj: object
1051 name: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001052 /
1053
1054Return whether the object has an attribute with the given name.
1055
1056This is done by calling getattr(obj, name) and catching AttributeError.
1057[clinic start generated code]*/
1058
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001059static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001060builtin_hasattr_impl(PyObject *module, PyObject *obj, PyObject *name)
1061/*[clinic end generated code: output=a7aff2090a4151e5 input=0faec9787d979542]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001062{
1063 PyObject *v;
1064
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001065 if (!PyUnicode_Check(name)) {
1066 PyErr_SetString(PyExc_TypeError,
1067 "hasattr(): attribute name must be string");
1068 return NULL;
1069 }
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001070 v = PyObject_GetAttr(obj, name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001071 if (v == NULL) {
Benjamin Peterson17689992010-08-24 03:26:23 +00001072 if (PyErr_ExceptionMatches(PyExc_AttributeError)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001073 PyErr_Clear();
Benjamin Peterson17689992010-08-24 03:26:23 +00001074 Py_RETURN_FALSE;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001075 }
Benjamin Peterson17689992010-08-24 03:26:23 +00001076 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001077 }
1078 Py_DECREF(v);
Benjamin Peterson17689992010-08-24 03:26:23 +00001079 Py_RETURN_TRUE;
Guido van Rossum33894be1992-01-27 16:53:09 +00001080}
1081
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001082
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001083/* AC: gdb's integration with CPython relies on builtin_id having
1084 * the *exact* parameter names of "self" and "v", so we ensure we
1085 * preserve those name rather than using the AC defaults.
1086 */
1087/*[clinic input]
1088id as builtin_id
1089
Serhiy Storchaka24182a32016-05-05 16:21:35 +03001090 self: self(type="PyModuleDef *")
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001091 obj as v: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001092 /
1093
1094Return the identity of an object.
1095
1096This is guaranteed to be unique among simultaneously existing objects.
1097(CPython uses the object's memory address.)
1098[clinic start generated code]*/
1099
Guido van Rossum79f25d91997-04-29 20:08:16 +00001100static PyObject *
Serhiy Storchaka24182a32016-05-05 16:21:35 +03001101builtin_id(PyModuleDef *self, PyObject *v)
1102/*[clinic end generated code: output=0aa640785f697f65 input=5a534136419631f4]*/
Guido van Rossum5b722181993-03-30 17:46:03 +00001103{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001104 return PyLong_FromVoidPtr(v);
Guido van Rossum5b722181993-03-30 17:46:03 +00001105}
1106
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001107
Raymond Hettingera6c60372008-03-13 01:26:19 +00001108/* map object ************************************************************/
1109
1110typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001111 PyObject_HEAD
1112 PyObject *iters;
1113 PyObject *func;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001114} mapobject;
1115
Guido van Rossum79f25d91997-04-29 20:08:16 +00001116static PyObject *
Raymond Hettingera6c60372008-03-13 01:26:19 +00001117map_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
Guido van Rossum12d12c51993-10-26 17:58:25 +00001118{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001119 PyObject *it, *iters, *func;
1120 mapobject *lz;
1121 Py_ssize_t numargs, i;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001122
Serhiy Storchaka6cca5c82017-06-08 14:41:19 +03001123 if (type == &PyMap_Type && !_PyArg_NoKeywords("map", kwds))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001124 return NULL;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001125
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001126 numargs = PyTuple_Size(args);
1127 if (numargs < 2) {
1128 PyErr_SetString(PyExc_TypeError,
1129 "map() must have at least two arguments.");
1130 return NULL;
1131 }
Raymond Hettingera6c60372008-03-13 01:26:19 +00001132
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001133 iters = PyTuple_New(numargs-1);
1134 if (iters == NULL)
1135 return NULL;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001136
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001137 for (i=1 ; i<numargs ; i++) {
1138 /* Get iterator. */
1139 it = PyObject_GetIter(PyTuple_GET_ITEM(args, i));
1140 if (it == NULL) {
1141 Py_DECREF(iters);
1142 return NULL;
1143 }
1144 PyTuple_SET_ITEM(iters, i-1, it);
1145 }
Raymond Hettingera6c60372008-03-13 01:26:19 +00001146
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001147 /* create mapobject structure */
1148 lz = (mapobject *)type->tp_alloc(type, 0);
1149 if (lz == NULL) {
1150 Py_DECREF(iters);
1151 return NULL;
1152 }
1153 lz->iters = iters;
1154 func = PyTuple_GET_ITEM(args, 0);
1155 Py_INCREF(func);
1156 lz->func = func;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001157
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001158 return (PyObject *)lz;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001159}
1160
1161static void
1162map_dealloc(mapobject *lz)
1163{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001164 PyObject_GC_UnTrack(lz);
1165 Py_XDECREF(lz->iters);
1166 Py_XDECREF(lz->func);
1167 Py_TYPE(lz)->tp_free(lz);
Raymond Hettingera6c60372008-03-13 01:26:19 +00001168}
1169
1170static int
1171map_traverse(mapobject *lz, visitproc visit, void *arg)
1172{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001173 Py_VISIT(lz->iters);
1174 Py_VISIT(lz->func);
1175 return 0;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001176}
1177
1178static PyObject *
1179map_next(mapobject *lz)
1180{
Victor Stinnerbc08ab42016-12-15 12:40:53 +01001181 PyObject *small_stack[_PY_FASTCALL_SMALL_STACK];
Victor Stinnercdb5cee2016-08-24 01:45:13 +02001182 PyObject **stack;
1183 Py_ssize_t niters, nargs, i;
1184 PyObject *result = NULL;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001185
Victor Stinnercdb5cee2016-08-24 01:45:13 +02001186 niters = PyTuple_GET_SIZE(lz->iters);
1187 if (niters <= (Py_ssize_t)Py_ARRAY_LENGTH(small_stack)) {
1188 stack = small_stack;
1189 }
1190 else {
1191 stack = PyMem_Malloc(niters * sizeof(stack[0]));
1192 if (stack == NULL) {
1193 PyErr_NoMemory();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001194 return NULL;
1195 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001196 }
Victor Stinnercdb5cee2016-08-24 01:45:13 +02001197
1198 nargs = 0;
1199 for (i=0; i < niters; i++) {
1200 PyObject *it = PyTuple_GET_ITEM(lz->iters, i);
1201 PyObject *val = Py_TYPE(it)->tp_iternext(it);
1202 if (val == NULL) {
1203 goto exit;
1204 }
1205 stack[i] = val;
1206 nargs++;
1207 }
1208
1209 result = _PyObject_FastCall(lz->func, stack, nargs);
1210
1211exit:
1212 for (i=0; i < nargs; i++) {
1213 Py_DECREF(stack[i]);
1214 }
1215 if (stack != small_stack) {
1216 PyMem_Free(stack);
1217 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001218 return result;
Guido van Rossum12d12c51993-10-26 17:58:25 +00001219}
1220
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001221static PyObject *
1222map_reduce(mapobject *lz)
1223{
1224 Py_ssize_t numargs = PyTuple_GET_SIZE(lz->iters);
1225 PyObject *args = PyTuple_New(numargs+1);
1226 Py_ssize_t i;
1227 if (args == NULL)
1228 return NULL;
1229 Py_INCREF(lz->func);
1230 PyTuple_SET_ITEM(args, 0, lz->func);
1231 for (i = 0; i<numargs; i++){
1232 PyObject *it = PyTuple_GET_ITEM(lz->iters, i);
1233 Py_INCREF(it);
1234 PyTuple_SET_ITEM(args, i+1, it);
1235 }
1236
1237 return Py_BuildValue("ON", Py_TYPE(lz), args);
1238}
1239
1240static PyMethodDef map_methods[] = {
1241 {"__reduce__", (PyCFunction)map_reduce, METH_NOARGS, reduce_doc},
1242 {NULL, NULL} /* sentinel */
1243};
1244
1245
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001246PyDoc_STRVAR(map_doc,
Raymond Hettingera6c60372008-03-13 01:26:19 +00001247"map(func, *iterables) --> map object\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001248\n\
Raymond Hettingera6c60372008-03-13 01:26:19 +00001249Make an iterator that computes the function using arguments from\n\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001250each of the iterables. Stops when the shortest iterable is exhausted.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001251
Raymond Hettingera6c60372008-03-13 01:26:19 +00001252PyTypeObject PyMap_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001253 PyVarObject_HEAD_INIT(&PyType_Type, 0)
1254 "map", /* tp_name */
1255 sizeof(mapobject), /* tp_basicsize */
1256 0, /* tp_itemsize */
1257 /* methods */
1258 (destructor)map_dealloc, /* tp_dealloc */
1259 0, /* tp_print */
1260 0, /* tp_getattr */
1261 0, /* tp_setattr */
1262 0, /* tp_reserved */
1263 0, /* tp_repr */
1264 0, /* tp_as_number */
1265 0, /* tp_as_sequence */
1266 0, /* tp_as_mapping */
1267 0, /* tp_hash */
1268 0, /* tp_call */
1269 0, /* tp_str */
1270 PyObject_GenericGetAttr, /* tp_getattro */
1271 0, /* tp_setattro */
1272 0, /* tp_as_buffer */
1273 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
1274 Py_TPFLAGS_BASETYPE, /* tp_flags */
1275 map_doc, /* tp_doc */
1276 (traverseproc)map_traverse, /* tp_traverse */
1277 0, /* tp_clear */
1278 0, /* tp_richcompare */
1279 0, /* tp_weaklistoffset */
1280 PyObject_SelfIter, /* tp_iter */
1281 (iternextfunc)map_next, /* tp_iternext */
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001282 map_methods, /* tp_methods */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001283 0, /* tp_members */
1284 0, /* tp_getset */
1285 0, /* tp_base */
1286 0, /* tp_dict */
1287 0, /* tp_descr_get */
1288 0, /* tp_descr_set */
1289 0, /* tp_dictoffset */
1290 0, /* tp_init */
1291 PyType_GenericAlloc, /* tp_alloc */
1292 map_new, /* tp_new */
1293 PyObject_GC_Del, /* tp_free */
Raymond Hettingera6c60372008-03-13 01:26:19 +00001294};
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001295
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001296
1297/* AC: cannot convert yet, as needs PEP 457 group support in inspect */
Guido van Rossum79f25d91997-04-29 20:08:16 +00001298static PyObject *
Serhiy Storchaka6969eaf2017-07-03 21:20:15 +03001299builtin_next(PyObject *self, PyObject **args, Py_ssize_t nargs)
Georg Brandla18af4e2007-04-21 15:47:16 +00001300{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001301 PyObject *it, *res;
1302 PyObject *def = NULL;
Georg Brandla18af4e2007-04-21 15:47:16 +00001303
Sylvain96c7c062017-06-15 17:05:23 +02001304 if (!_PyArg_UnpackStack(args, nargs, "next", 1, 2, &it, &def))
1305 return NULL;
1306
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001307 if (!PyIter_Check(it)) {
1308 PyErr_Format(PyExc_TypeError,
Philip Jenvey50add042011-11-06 16:37:52 -08001309 "'%.200s' object is not an iterator",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001310 it->ob_type->tp_name);
1311 return NULL;
1312 }
1313
1314 res = (*it->ob_type->tp_iternext)(it);
1315 if (res != NULL) {
1316 return res;
1317 } else if (def != NULL) {
1318 if (PyErr_Occurred()) {
1319 if(!PyErr_ExceptionMatches(PyExc_StopIteration))
1320 return NULL;
1321 PyErr_Clear();
1322 }
1323 Py_INCREF(def);
1324 return def;
1325 } else if (PyErr_Occurred()) {
1326 return NULL;
1327 } else {
1328 PyErr_SetNone(PyExc_StopIteration);
1329 return NULL;
1330 }
Georg Brandla18af4e2007-04-21 15:47:16 +00001331}
1332
1333PyDoc_STRVAR(next_doc,
1334"next(iterator[, default])\n\
1335\n\
1336Return the next item from the iterator. If default is given and the iterator\n\
1337is exhausted, it is returned instead of raising StopIteration.");
1338
1339
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001340/*[clinic input]
1341setattr as builtin_setattr
1342
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001343 obj: object
1344 name: object
1345 value: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001346 /
1347
1348Sets the named attribute on the given object to the specified value.
1349
1350setattr(x, 'y', v) is equivalent to ``x.y = v''
1351[clinic start generated code]*/
1352
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001353static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001354builtin_setattr_impl(PyObject *module, PyObject *obj, PyObject *name,
Larry Hastings89964c42015-04-14 18:07:59 -04001355 PyObject *value)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001356/*[clinic end generated code: output=dc2ce1d1add9acb4 input=bd2b7ca6875a1899]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001357{
1358 if (PyObject_SetAttr(obj, name, value) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001359 return NULL;
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02001360 Py_RETURN_NONE;
Guido van Rossum33894be1992-01-27 16:53:09 +00001361}
1362
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001363
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001364/*[clinic input]
1365delattr as builtin_delattr
1366
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001367 obj: object
1368 name: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001369 /
1370
1371Deletes the named attribute from the given object.
1372
1373delattr(x, 'y') is equivalent to ``del x.y''
1374[clinic start generated code]*/
1375
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001376static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001377builtin_delattr_impl(PyObject *module, PyObject *obj, PyObject *name)
1378/*[clinic end generated code: output=85134bc58dff79fa input=db16685d6b4b9410]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001379{
1380 if (PyObject_SetAttr(obj, name, (PyObject *)NULL) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001381 return NULL;
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02001382 Py_RETURN_NONE;
Guido van Rossum14144fc1994-08-29 12:53:40 +00001383}
1384
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001385
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001386/*[clinic input]
1387hash as builtin_hash
1388
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001389 obj: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001390 /
1391
1392Return the hash value for the given object.
1393
1394Two objects that compare equal must also have the same hash value, but the
1395reverse is not necessarily true.
1396[clinic start generated code]*/
1397
Guido van Rossum79f25d91997-04-29 20:08:16 +00001398static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001399builtin_hash(PyObject *module, PyObject *obj)
1400/*[clinic end generated code: output=237668e9d7688db7 input=58c48be822bf9c54]*/
Guido van Rossum9bfef441993-03-29 10:43:31 +00001401{
Benjamin Peterson8f67d082010-10-17 20:54:53 +00001402 Py_hash_t x;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001403
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001404 x = PyObject_Hash(obj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001405 if (x == -1)
1406 return NULL;
Benjamin Peterson8f67d082010-10-17 20:54:53 +00001407 return PyLong_FromSsize_t(x);
Guido van Rossum9bfef441993-03-29 10:43:31 +00001408}
1409
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001410
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001411/*[clinic input]
1412hex as builtin_hex
1413
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001414 number: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001415 /
1416
1417Return the hexadecimal representation of an integer.
1418
1419 >>> hex(12648430)
1420 '0xc0ffee'
1421[clinic start generated code]*/
1422
Guido van Rossum79f25d91997-04-29 20:08:16 +00001423static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001424builtin_hex(PyObject *module, PyObject *number)
1425/*[clinic end generated code: output=e46b612169099408 input=e645aff5fc7d540e]*/
Guido van Rossum006bcd41991-10-24 14:54:44 +00001426{
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001427 return PyNumber_ToBase(number, 16);
Guido van Rossum006bcd41991-10-24 14:54:44 +00001428}
1429
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001430
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001431/* AC: cannot convert yet, as needs PEP 457 group support in inspect */
Guido van Rossum79f25d91997-04-29 20:08:16 +00001432static PyObject *
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001433builtin_iter(PyObject *self, PyObject *args)
1434{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001435 PyObject *v, *w = NULL;
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001436
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001437 if (!PyArg_UnpackTuple(args, "iter", 1, 2, &v, &w))
1438 return NULL;
1439 if (w == NULL)
1440 return PyObject_GetIter(v);
1441 if (!PyCallable_Check(v)) {
1442 PyErr_SetString(PyExc_TypeError,
1443 "iter(v, w): v must be callable");
1444 return NULL;
1445 }
1446 return PyCallIter_New(v, w);
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001447}
1448
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001449PyDoc_STRVAR(iter_doc,
Georg Brandld11ae5d2008-05-16 13:27:32 +00001450"iter(iterable) -> iterator\n\
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001451iter(callable, sentinel) -> iterator\n\
1452\n\
1453Get an iterator from an object. In the first form, the argument must\n\
1454supply its own iterator, or be a sequence.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001455In the second form, the callable is called until it returns the sentinel.");
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001456
1457
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001458/*[clinic input]
1459len as builtin_len
1460
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001461 obj: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001462 /
1463
1464Return the number of items in a container.
1465[clinic start generated code]*/
1466
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001467static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001468builtin_len(PyObject *module, PyObject *obj)
1469/*[clinic end generated code: output=fa7a270d314dfb6c input=bc55598da9e9c9b5]*/
Guido van Rossum3f5da241990-12-20 15:06:42 +00001470{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001471 Py_ssize_t res;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001472
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001473 res = PyObject_Size(obj);
Serhiy Storchaka813f9432017-04-16 09:21:44 +03001474 if (res < 0) {
1475 assert(PyErr_Occurred());
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001476 return NULL;
Serhiy Storchaka813f9432017-04-16 09:21:44 +03001477 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001478 return PyLong_FromSsize_t(res);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001479}
1480
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001481
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001482/*[clinic input]
1483locals as builtin_locals
1484
1485Return a dictionary containing the current scope's local variables.
1486
1487NOTE: Whether or not updates to this dictionary will affect name lookups in
1488the local scope and vice-versa is *implementation dependent* and not
1489covered by any backwards compatibility guarantees.
1490[clinic start generated code]*/
1491
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001492static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001493builtin_locals_impl(PyObject *module)
1494/*[clinic end generated code: output=b46c94015ce11448 input=7874018d478d5c4b]*/
Guido van Rossum872537c1995-07-07 22:43:42 +00001495{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001496 PyObject *d;
Guido van Rossum872537c1995-07-07 22:43:42 +00001497
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001498 d = PyEval_GetLocals();
1499 Py_XINCREF(d);
1500 return d;
Guido van Rossum872537c1995-07-07 22:43:42 +00001501}
1502
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001503
Guido van Rossum79f25d91997-04-29 20:08:16 +00001504static PyObject *
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001505min_max(PyObject *args, PyObject *kwds, int op)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001506{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001507 PyObject *v, *it, *item, *val, *maxitem, *maxval, *keyfunc=NULL;
Raymond Hettinger4d6018f2013-06-24 22:43:02 -07001508 PyObject *emptytuple, *defaultval = NULL;
1509 static char *kwlist[] = {"key", "default", NULL};
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001510 const char *name = op == Py_LT ? "min" : "max";
Raymond Hettinger4d6018f2013-06-24 22:43:02 -07001511 const int positional = PyTuple_Size(args) > 1;
1512 int ret;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001513
Raymond Hettinger4d6018f2013-06-24 22:43:02 -07001514 if (positional)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001515 v = args;
Serhiy Storchakac6792272013-10-19 21:03:34 +03001516 else if (!PyArg_UnpackTuple(args, name, 1, 1, &v))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001517 return NULL;
Tim Peters67d687a2002-04-29 21:27:32 +00001518
Raymond Hettinger4d6018f2013-06-24 22:43:02 -07001519 emptytuple = PyTuple_New(0);
1520 if (emptytuple == NULL)
1521 return NULL;
Oren Milman58cf7482017-08-21 20:19:07 +03001522 ret = PyArg_ParseTupleAndKeywords(emptytuple, kwds,
1523 (op == Py_LT) ? "|$OO:min" : "|$OO:max",
1524 kwlist, &keyfunc, &defaultval);
Raymond Hettinger4d6018f2013-06-24 22:43:02 -07001525 Py_DECREF(emptytuple);
1526 if (!ret)
1527 return NULL;
1528
1529 if (positional && defaultval != NULL) {
1530 PyErr_Format(PyExc_TypeError,
1531 "Cannot specify a default for %s() with multiple "
1532 "positional arguments", name);
1533 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001534 }
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001535
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001536 it = PyObject_GetIter(v);
1537 if (it == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001538 return NULL;
1539 }
Tim Petersc3074532001-05-03 07:00:32 +00001540
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001541 maxitem = NULL; /* the result */
1542 maxval = NULL; /* the value associated with the result */
1543 while (( item = PyIter_Next(it) )) {
1544 /* get the value from the key function */
1545 if (keyfunc != NULL) {
Victor Stinnerde4ae3d2016-12-04 22:59:09 +01001546 val = PyObject_CallFunctionObjArgs(keyfunc, item, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001547 if (val == NULL)
1548 goto Fail_it_item;
1549 }
1550 /* no key function; the value is the item */
1551 else {
1552 val = item;
1553 Py_INCREF(val);
1554 }
Tim Petersc3074532001-05-03 07:00:32 +00001555
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001556 /* maximum value and item are unset; set them */
1557 if (maxval == NULL) {
1558 maxitem = item;
1559 maxval = val;
1560 }
1561 /* maximum value and item are set; update them as necessary */
1562 else {
1563 int cmp = PyObject_RichCompareBool(val, maxval, op);
1564 if (cmp < 0)
1565 goto Fail_it_item_and_val;
1566 else if (cmp > 0) {
1567 Py_DECREF(maxval);
1568 Py_DECREF(maxitem);
1569 maxval = val;
1570 maxitem = item;
1571 }
1572 else {
1573 Py_DECREF(item);
1574 Py_DECREF(val);
1575 }
1576 }
1577 }
1578 if (PyErr_Occurred())
1579 goto Fail_it;
1580 if (maxval == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001581 assert(maxitem == NULL);
Raymond Hettinger4d6018f2013-06-24 22:43:02 -07001582 if (defaultval != NULL) {
1583 Py_INCREF(defaultval);
1584 maxitem = defaultval;
1585 } else {
1586 PyErr_Format(PyExc_ValueError,
1587 "%s() arg is an empty sequence", name);
1588 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001589 }
1590 else
1591 Py_DECREF(maxval);
1592 Py_DECREF(it);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001593 return maxitem;
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001594
1595Fail_it_item_and_val:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001596 Py_DECREF(val);
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001597Fail_it_item:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001598 Py_DECREF(item);
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001599Fail_it:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001600 Py_XDECREF(maxval);
1601 Py_XDECREF(maxitem);
1602 Py_DECREF(it);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001603 return NULL;
Guido van Rossum3f5da241990-12-20 15:06:42 +00001604}
1605
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001606/* AC: cannot convert yet, waiting for *args support */
Guido van Rossum79f25d91997-04-29 20:08:16 +00001607static PyObject *
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001608builtin_min(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001609{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001610 return min_max(args, kwds, Py_LT);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001611}
1612
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001613PyDoc_STRVAR(min_doc,
Raymond Hettinger2a545822014-05-19 22:20:52 +01001614"min(iterable, *[, default=obj, key=func]) -> value\n\
1615min(arg1, arg2, *args, *[, key=func]) -> value\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001616\n\
Raymond Hettinger2a545822014-05-19 22:20:52 +01001617With a single iterable argument, return its smallest item. The\n\
1618default keyword-only argument specifies an object to return if\n\
1619the provided iterable is empty.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001620With two or more arguments, return the smallest argument.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001621
1622
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001623/* AC: cannot convert yet, waiting for *args support */
Guido van Rossum79f25d91997-04-29 20:08:16 +00001624static PyObject *
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001625builtin_max(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001626{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001627 return min_max(args, kwds, Py_GT);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001628}
1629
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001630PyDoc_STRVAR(max_doc,
Raymond Hettinger2a545822014-05-19 22:20:52 +01001631"max(iterable, *[, default=obj, key=func]) -> value\n\
1632max(arg1, arg2, *args, *[, key=func]) -> value\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001633\n\
Raymond Hettinger2a545822014-05-19 22:20:52 +01001634With a single iterable argument, return its biggest item. The\n\
1635default keyword-only argument specifies an object to return if\n\
1636the provided iterable is empty.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001637With two or more arguments, return the largest argument.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001638
1639
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001640/*[clinic input]
1641oct as builtin_oct
1642
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001643 number: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001644 /
1645
1646Return the octal representation of an integer.
1647
1648 >>> oct(342391)
1649 '0o1234567'
1650[clinic start generated code]*/
1651
Guido van Rossum79f25d91997-04-29 20:08:16 +00001652static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001653builtin_oct(PyObject *module, PyObject *number)
1654/*[clinic end generated code: output=40a34656b6875352 input=ad6b274af4016c72]*/
Guido van Rossum006bcd41991-10-24 14:54:44 +00001655{
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001656 return PyNumber_ToBase(number, 8);
Guido van Rossum006bcd41991-10-24 14:54:44 +00001657}
1658
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001659
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001660/*[clinic input]
1661ord as builtin_ord
1662
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001663 c: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001664 /
1665
1666Return the Unicode code point for a one-character string.
1667[clinic start generated code]*/
1668
Guido van Rossum79f25d91997-04-29 20:08:16 +00001669static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001670builtin_ord(PyObject *module, PyObject *c)
1671/*[clinic end generated code: output=4fa5e87a323bae71 input=3064e5d6203ad012]*/
Guido van Rossum3f5da241990-12-20 15:06:42 +00001672{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001673 long ord;
1674 Py_ssize_t size;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001675
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001676 if (PyBytes_Check(c)) {
1677 size = PyBytes_GET_SIZE(c);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001678 if (size == 1) {
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001679 ord = (long)((unsigned char)*PyBytes_AS_STRING(c));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001680 return PyLong_FromLong(ord);
1681 }
1682 }
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001683 else if (PyUnicode_Check(c)) {
1684 if (PyUnicode_READY(c) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001685 return NULL;
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001686 size = PyUnicode_GET_LENGTH(c);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001687 if (size == 1) {
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001688 ord = (long)PyUnicode_READ_CHAR(c, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001689 return PyLong_FromLong(ord);
1690 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001691 }
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001692 else if (PyByteArray_Check(c)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001693 /* XXX Hopefully this is temporary */
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001694 size = PyByteArray_GET_SIZE(c);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001695 if (size == 1) {
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001696 ord = (long)((unsigned char)*PyByteArray_AS_STRING(c));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001697 return PyLong_FromLong(ord);
1698 }
1699 }
1700 else {
1701 PyErr_Format(PyExc_TypeError,
1702 "ord() expected string of length 1, but " \
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001703 "%.200s found", c->ob_type->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001704 return NULL;
1705 }
Guido van Rossum09095f32000-03-10 23:00:52 +00001706
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001707 PyErr_Format(PyExc_TypeError,
1708 "ord() expected a character, "
1709 "but string of length %zd found",
1710 size);
1711 return NULL;
Guido van Rossum3f5da241990-12-20 15:06:42 +00001712}
1713
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001714
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001715/*[clinic input]
1716pow as builtin_pow
1717
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001718 x: object
1719 y: object
1720 z: object = None
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001721 /
1722
1723Equivalent to x**y (with two arguments) or x**y % z (with three arguments)
1724
1725Some types, such as ints, are able to use a more efficient algorithm when
1726invoked using the three argument form.
1727[clinic start generated code]*/
1728
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001729static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001730builtin_pow_impl(PyObject *module, PyObject *x, PyObject *y, PyObject *z)
1731/*[clinic end generated code: output=50a14d5d130d404b input=653d57d38d41fc07]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001732{
1733 return PyNumber_Power(x, y, z);
1734}
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001735
1736
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001737/* AC: cannot convert yet, waiting for *args support */
Guido van Rossum34343512006-11-30 22:13:52 +00001738static PyObject *
INADA Naokibd584f12017-01-19 12:50:34 +01001739builtin_print(PyObject *self, PyObject **args, Py_ssize_t nargs, PyObject *kwnames)
Guido van Rossum34343512006-11-30 22:13:52 +00001740{
INADA Naokibd584f12017-01-19 12:50:34 +01001741 static const char * const _keywords[] = {"sep", "end", "file", "flush", 0};
1742 static struct _PyArg_Parser _parser = {"|OOOO:print", _keywords, 0};
Georg Brandlbc3b6822012-01-13 19:41:25 +01001743 PyObject *sep = NULL, *end = NULL, *file = NULL, *flush = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001744 int i, err;
Guido van Rossum34343512006-11-30 22:13:52 +00001745
INADA Naokibd584f12017-01-19 12:50:34 +01001746 if (kwnames != NULL &&
1747 !_PyArg_ParseStackAndKeywords(args + nargs, 0, kwnames, &_parser,
1748 &sep, &end, &file, &flush)) {
Georg Brandlbc3b6822012-01-13 19:41:25 +01001749 return NULL;
INADA Naokibd584f12017-01-19 12:50:34 +01001750 }
1751
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001752 if (file == NULL || file == Py_None) {
Victor Stinnerbd303c12013-11-07 23:07:29 +01001753 file = _PySys_GetObjectId(&PyId_stdout);
Victor Stinner1e53bba2013-07-16 22:26:05 +02001754 if (file == NULL) {
1755 PyErr_SetString(PyExc_RuntimeError, "lost sys.stdout");
1756 return NULL;
1757 }
1758
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001759 /* sys.stdout may be None when FILE* stdout isn't connected */
1760 if (file == Py_None)
1761 Py_RETURN_NONE;
1762 }
Guido van Rossum34343512006-11-30 22:13:52 +00001763
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001764 if (sep == Py_None) {
1765 sep = NULL;
1766 }
1767 else if (sep && !PyUnicode_Check(sep)) {
1768 PyErr_Format(PyExc_TypeError,
1769 "sep must be None or a string, not %.200s",
1770 sep->ob_type->tp_name);
1771 return NULL;
1772 }
1773 if (end == Py_None) {
1774 end = NULL;
1775 }
1776 else if (end && !PyUnicode_Check(end)) {
1777 PyErr_Format(PyExc_TypeError,
1778 "end must be None or a string, not %.200s",
1779 end->ob_type->tp_name);
1780 return NULL;
1781 }
Guido van Rossum34343512006-11-30 22:13:52 +00001782
INADA Naokibd584f12017-01-19 12:50:34 +01001783 for (i = 0; i < nargs; i++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001784 if (i > 0) {
1785 if (sep == NULL)
1786 err = PyFile_WriteString(" ", file);
1787 else
1788 err = PyFile_WriteObject(sep, file,
1789 Py_PRINT_RAW);
1790 if (err)
1791 return NULL;
1792 }
INADA Naokibd584f12017-01-19 12:50:34 +01001793 err = PyFile_WriteObject(args[i], file, Py_PRINT_RAW);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001794 if (err)
1795 return NULL;
1796 }
Guido van Rossum34343512006-11-30 22:13:52 +00001797
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001798 if (end == NULL)
1799 err = PyFile_WriteString("\n", file);
1800 else
1801 err = PyFile_WriteObject(end, file, Py_PRINT_RAW);
1802 if (err)
1803 return NULL;
Guido van Rossum34343512006-11-30 22:13:52 +00001804
Georg Brandlbc3b6822012-01-13 19:41:25 +01001805 if (flush != NULL) {
1806 PyObject *tmp;
1807 int do_flush = PyObject_IsTrue(flush);
1808 if (do_flush == -1)
1809 return NULL;
1810 else if (do_flush) {
Victor Stinner3466bde2016-09-05 18:16:01 -07001811 tmp = _PyObject_CallMethodId(file, &PyId_flush, NULL);
Georg Brandlbc3b6822012-01-13 19:41:25 +01001812 if (tmp == NULL)
1813 return NULL;
1814 else
1815 Py_DECREF(tmp);
1816 }
1817 }
1818
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001819 Py_RETURN_NONE;
Guido van Rossum34343512006-11-30 22:13:52 +00001820}
1821
1822PyDoc_STRVAR(print_doc,
Senthil Kumarane9175bd2012-08-10 13:53:45 -07001823"print(value, ..., sep=' ', end='\\n', file=sys.stdout, flush=False)\n\
Guido van Rossum34343512006-11-30 22:13:52 +00001824\n\
1825Prints the values to a stream, or to sys.stdout by default.\n\
1826Optional keyword arguments:\n\
Senthil Kumarane9175bd2012-08-10 13:53:45 -07001827file: a file-like object (stream); defaults to the current sys.stdout.\n\
1828sep: string inserted between values, default a space.\n\
1829end: string appended after the last value, default a newline.\n\
1830flush: whether to forcibly flush the stream.");
Guido van Rossum34343512006-11-30 22:13:52 +00001831
1832
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001833/*[clinic input]
1834input as builtin_input
1835
1836 prompt: object(c_default="NULL") = None
1837 /
1838
1839Read a string from standard input. The trailing newline is stripped.
1840
1841The prompt string, if given, is printed to standard output without a
1842trailing newline before reading input.
1843
1844If the user hits EOF (*nix: Ctrl-D, Windows: Ctrl-Z+Return), raise EOFError.
1845On *nix systems, readline is used if available.
1846[clinic start generated code]*/
1847
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001848static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001849builtin_input_impl(PyObject *module, PyObject *prompt)
1850/*[clinic end generated code: output=83db5a191e7a0d60 input=5e8bb70c2908fe3c]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001851{
Victor Stinnerbd303c12013-11-07 23:07:29 +01001852 PyObject *fin = _PySys_GetObjectId(&PyId_stdin);
1853 PyObject *fout = _PySys_GetObjectId(&PyId_stdout);
1854 PyObject *ferr = _PySys_GetObjectId(&PyId_stderr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001855 PyObject *tmp;
1856 long fd;
1857 int tty;
Guido van Rossuma88a0332007-02-26 16:59:55 +00001858
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001859 /* Check that stdin/out/err are intact */
1860 if (fin == NULL || fin == Py_None) {
1861 PyErr_SetString(PyExc_RuntimeError,
1862 "input(): lost sys.stdin");
1863 return NULL;
1864 }
1865 if (fout == NULL || fout == Py_None) {
1866 PyErr_SetString(PyExc_RuntimeError,
1867 "input(): lost sys.stdout");
1868 return NULL;
1869 }
1870 if (ferr == NULL || ferr == Py_None) {
1871 PyErr_SetString(PyExc_RuntimeError,
1872 "input(): lost sys.stderr");
1873 return NULL;
1874 }
Guido van Rossumeba76962007-05-27 09:13:28 +00001875
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001876 /* First of all, flush stderr */
Victor Stinner3466bde2016-09-05 18:16:01 -07001877 tmp = _PyObject_CallMethodId(ferr, &PyId_flush, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001878 if (tmp == NULL)
1879 PyErr_Clear();
1880 else
1881 Py_DECREF(tmp);
Guido van Rossumeba76962007-05-27 09:13:28 +00001882
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001883 /* We should only use (GNU) readline if Python's sys.stdin and
1884 sys.stdout are the same as C's stdin and stdout, because we
1885 need to pass it those. */
Victor Stinner3466bde2016-09-05 18:16:01 -07001886 tmp = _PyObject_CallMethodId(fin, &PyId_fileno, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001887 if (tmp == NULL) {
1888 PyErr_Clear();
1889 tty = 0;
1890 }
1891 else {
1892 fd = PyLong_AsLong(tmp);
1893 Py_DECREF(tmp);
1894 if (fd < 0 && PyErr_Occurred())
1895 return NULL;
1896 tty = fd == fileno(stdin) && isatty(fd);
1897 }
1898 if (tty) {
Victor Stinner3466bde2016-09-05 18:16:01 -07001899 tmp = _PyObject_CallMethodId(fout, &PyId_fileno, NULL);
Martin Panterc9a6ab52015-10-10 01:25:38 +00001900 if (tmp == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001901 PyErr_Clear();
Martin Panterc9a6ab52015-10-10 01:25:38 +00001902 tty = 0;
1903 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001904 else {
1905 fd = PyLong_AsLong(tmp);
1906 Py_DECREF(tmp);
1907 if (fd < 0 && PyErr_Occurred())
1908 return NULL;
1909 tty = fd == fileno(stdout) && isatty(fd);
1910 }
1911 }
Guido van Rossumeba76962007-05-27 09:13:28 +00001912
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001913 /* If we're interactive, use (GNU) readline */
1914 if (tty) {
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001915 PyObject *po = NULL;
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001916 char *promptstr;
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001917 char *s = NULL;
1918 PyObject *stdin_encoding = NULL, *stdin_errors = NULL;
1919 PyObject *stdout_encoding = NULL, *stdout_errors = NULL;
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +02001920 const char *stdin_encoding_str, *stdin_errors_str;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001921 PyObject *result;
Victor Stinnerc0f1a1a2011-02-23 12:07:37 +00001922 size_t len;
Martin v. Löwis4a7b5d52007-09-04 05:24:49 +00001923
Serhiy Storchakac2cf1282017-03-12 13:50:36 +02001924 /* stdin is a text stream, so it must have an encoding. */
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02001925 stdin_encoding = _PyObject_GetAttrId(fin, &PyId_encoding);
Antoine Pitrou5ee9d8a2011-11-06 00:38:45 +01001926 stdin_errors = _PyObject_GetAttrId(fin, &PyId_errors);
Serhiy Storchakac2cf1282017-03-12 13:50:36 +02001927 if (!stdin_encoding || !stdin_errors ||
1928 !PyUnicode_Check(stdin_encoding) ||
1929 !PyUnicode_Check(stdin_errors)) {
1930 tty = 0;
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001931 goto _readline_errors;
Serhiy Storchakac2cf1282017-03-12 13:50:36 +02001932 }
Serhiy Storchaka06515832016-11-20 09:13:07 +02001933 stdin_encoding_str = PyUnicode_AsUTF8(stdin_encoding);
1934 stdin_errors_str = PyUnicode_AsUTF8(stdin_errors);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001935 if (!stdin_encoding_str || !stdin_errors_str)
1936 goto _readline_errors;
Victor Stinner3466bde2016-09-05 18:16:01 -07001937 tmp = _PyObject_CallMethodId(fout, &PyId_flush, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001938 if (tmp == NULL)
1939 PyErr_Clear();
1940 else
1941 Py_DECREF(tmp);
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001942 if (prompt != NULL) {
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001943 /* We have a prompt, encode it as stdout would */
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +02001944 const char *stdout_encoding_str, *stdout_errors_str;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001945 PyObject *stringpo;
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02001946 stdout_encoding = _PyObject_GetAttrId(fout, &PyId_encoding);
Antoine Pitrou5ee9d8a2011-11-06 00:38:45 +01001947 stdout_errors = _PyObject_GetAttrId(fout, &PyId_errors);
Serhiy Storchakac2cf1282017-03-12 13:50:36 +02001948 if (!stdout_encoding || !stdout_errors ||
1949 !PyUnicode_Check(stdout_encoding) ||
1950 !PyUnicode_Check(stdout_errors)) {
1951 tty = 0;
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001952 goto _readline_errors;
Serhiy Storchakac2cf1282017-03-12 13:50:36 +02001953 }
Serhiy Storchaka06515832016-11-20 09:13:07 +02001954 stdout_encoding_str = PyUnicode_AsUTF8(stdout_encoding);
1955 stdout_errors_str = PyUnicode_AsUTF8(stdout_errors);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001956 if (!stdout_encoding_str || !stdout_errors_str)
1957 goto _readline_errors;
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001958 stringpo = PyObject_Str(prompt);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001959 if (stringpo == NULL)
1960 goto _readline_errors;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001961 po = PyUnicode_AsEncodedString(stringpo,
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001962 stdout_encoding_str, stdout_errors_str);
1963 Py_CLEAR(stdout_encoding);
1964 Py_CLEAR(stdout_errors);
1965 Py_CLEAR(stringpo);
1966 if (po == NULL)
1967 goto _readline_errors;
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03001968 assert(PyBytes_Check(po));
1969 promptstr = PyBytes_AS_STRING(po);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001970 }
1971 else {
1972 po = NULL;
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001973 promptstr = "";
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001974 }
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001975 s = PyOS_Readline(stdin, stdout, promptstr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001976 if (s == NULL) {
Richard Oudkerk614c5782013-04-03 13:44:50 +01001977 PyErr_CheckSignals();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001978 if (!PyErr_Occurred())
1979 PyErr_SetNone(PyExc_KeyboardInterrupt);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001980 goto _readline_errors;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001981 }
Victor Stinnerc0f1a1a2011-02-23 12:07:37 +00001982
1983 len = strlen(s);
1984 if (len == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001985 PyErr_SetNone(PyExc_EOFError);
1986 result = NULL;
1987 }
Victor Stinnerc0f1a1a2011-02-23 12:07:37 +00001988 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001989 if (len > PY_SSIZE_T_MAX) {
1990 PyErr_SetString(PyExc_OverflowError,
1991 "input: input too long");
1992 result = NULL;
1993 }
1994 else {
Victor Stinnerc0f1a1a2011-02-23 12:07:37 +00001995 len--; /* strip trailing '\n' */
1996 if (len != 0 && s[len-1] == '\r')
1997 len--; /* strip trailing '\r' */
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001998 result = PyUnicode_Decode(s, len, stdin_encoding_str,
1999 stdin_errors_str);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002000 }
2001 }
2002 Py_DECREF(stdin_encoding);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01002003 Py_DECREF(stdin_errors);
2004 Py_XDECREF(po);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002005 PyMem_FREE(s);
2006 return result;
Serhiy Storchakac2cf1282017-03-12 13:50:36 +02002007
Antoine Pitrou0d776b12011-11-06 00:34:26 +01002008 _readline_errors:
2009 Py_XDECREF(stdin_encoding);
2010 Py_XDECREF(stdout_encoding);
2011 Py_XDECREF(stdin_errors);
2012 Py_XDECREF(stdout_errors);
2013 Py_XDECREF(po);
Serhiy Storchakac2cf1282017-03-12 13:50:36 +02002014 if (tty)
2015 return NULL;
2016
2017 PyErr_Clear();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002018 }
Guido van Rossumeba76962007-05-27 09:13:28 +00002019
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002020 /* Fallback if we're not interactive */
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002021 if (prompt != NULL) {
2022 if (PyFile_WriteObject(prompt, fout, Py_PRINT_RAW) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002023 return NULL;
2024 }
Victor Stinner3466bde2016-09-05 18:16:01 -07002025 tmp = _PyObject_CallMethodId(fout, &PyId_flush, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002026 if (tmp == NULL)
2027 PyErr_Clear();
2028 else
2029 Py_DECREF(tmp);
2030 return PyFile_GetLine(fin, -1);
Guido van Rossuma88a0332007-02-26 16:59:55 +00002031}
2032
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002033
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002034/*[clinic input]
2035repr as builtin_repr
2036
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03002037 obj: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002038 /
2039
2040Return the canonical string representation of the object.
2041
2042For many object types, including most builtins, eval(repr(obj)) == obj.
2043[clinic start generated code]*/
2044
Guido van Rossum79f25d91997-04-29 20:08:16 +00002045static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002046builtin_repr(PyObject *module, PyObject *obj)
2047/*[clinic end generated code: output=7ed3778c44fd0194 input=1c9e6d66d3e3be04]*/
Guido van Rossumc89705d1992-11-26 08:54:07 +00002048{
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002049 return PyObject_Repr(obj);
Guido van Rossumc89705d1992-11-26 08:54:07 +00002050}
2051
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002052
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002053/* AC: cannot convert yet, as needs PEP 457 group support in inspect
2054 * or a semantic change to accept None for "ndigits"
2055 */
Guido van Rossum79f25d91997-04-29 20:08:16 +00002056static PyObject *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002057builtin_round(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum9e51f9b1993-02-12 16:29:05 +00002058{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002059 PyObject *ndigits = NULL;
2060 static char *kwlist[] = {"number", "ndigits", 0};
Benjamin Peterson214a7d22013-04-13 17:19:01 -04002061 PyObject *number, *round, *result;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002062
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002063 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|O:round",
2064 kwlist, &number, &ndigits))
2065 return NULL;
Alex Martelliae211f92007-08-22 23:21:33 +00002066
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002067 if (Py_TYPE(number)->tp_dict == NULL) {
2068 if (PyType_Ready(Py_TYPE(number)) < 0)
2069 return NULL;
2070 }
Guido van Rossum15d3d042007-08-24 02:02:45 +00002071
Benjamin Peterson214a7d22013-04-13 17:19:01 -04002072 round = _PyObject_LookupSpecial(number, &PyId___round__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002073 if (round == NULL) {
Benjamin Peterson214a7d22013-04-13 17:19:01 -04002074 if (!PyErr_Occurred())
2075 PyErr_Format(PyExc_TypeError,
2076 "type %.100s doesn't define __round__ method",
2077 Py_TYPE(number)->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002078 return NULL;
2079 }
Alex Martelliae211f92007-08-22 23:21:33 +00002080
Raymond Hettingerf0f1c232016-09-03 01:55:11 -07002081 if (ndigits == NULL || ndigits == Py_None)
Victor Stinnerf17c3de2016-12-06 18:46:19 +01002082 result = _PyObject_CallNoArg(round);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002083 else
Victor Stinnerde4ae3d2016-12-04 22:59:09 +01002084 result = PyObject_CallFunctionObjArgs(round, ndigits, NULL);
Benjamin Peterson214a7d22013-04-13 17:19:01 -04002085 Py_DECREF(round);
2086 return result;
Guido van Rossum9e51f9b1993-02-12 16:29:05 +00002087}
2088
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002089PyDoc_STRVAR(round_doc,
Mark Dickinson1124e712009-01-28 21:25:58 +00002090"round(number[, ndigits]) -> number\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002091\n\
2092Round a number to a given precision in decimal digits (default 0 digits).\n\
Mark Dickinson0d748c22008-07-05 11:29:03 +00002093This returns an int when called with one argument, otherwise the\n\
Georg Brandl809ddaa2008-07-01 20:39:59 +00002094same type as the number. ndigits may be negative.");
Guido van Rossum2fa33db2007-08-23 22:07:24 +00002095
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002096
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002097/*AC: we need to keep the kwds dict intact to easily call into the
2098 * list.sort method, which isn't currently supported in AC. So we just use
2099 * the initially generated signature with a custom implementation.
2100 */
2101/* [disabled clinic input]
2102sorted as builtin_sorted
2103
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03002104 iterable as seq: object
2105 key as keyfunc: object = None
2106 reverse: object = False
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002107
2108Return a new list containing all items from the iterable in ascending order.
2109
Raymond Hettinger7ea386e2016-08-25 21:11:50 -07002110A custom key function can be supplied to customize the sort order, and the
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002111reverse flag can be set to request the result in descending order.
2112[end disabled clinic input]*/
2113
2114PyDoc_STRVAR(builtin_sorted__doc__,
Serhiy Storchaka3a104252017-01-23 12:29:47 +02002115"sorted($module, iterable, /, *, key=None, reverse=False)\n"
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002116"--\n"
2117"\n"
2118"Return a new list containing all items from the iterable in ascending order.\n"
2119"\n"
Raymond Hettinger7ea386e2016-08-25 21:11:50 -07002120"A custom key function can be supplied to customize the sort order, and the\n"
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002121"reverse flag can be set to request the result in descending order.");
2122
2123#define BUILTIN_SORTED_METHODDEF \
Serhiy Storchaka6969eaf2017-07-03 21:20:15 +03002124 {"sorted", (PyCFunction)builtin_sorted, METH_FASTCALL | METH_KEYWORDS, builtin_sorted__doc__},
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002125
Raymond Hettinger64958a12003-12-17 20:43:33 +00002126static PyObject *
Victor Stinner5a60eca2017-01-17 15:17:49 +01002127builtin_sorted(PyObject *self, PyObject **args, Py_ssize_t nargs, PyObject *kwnames)
Raymond Hettinger64958a12003-12-17 20:43:33 +00002128{
Serhiy Storchaka7cf8beb2017-01-21 23:05:00 +02002129 PyObject *newlist, *v, *seq, *callable;
Victor Stinner5a60eca2017-01-17 15:17:49 +01002130
Serhiy Storchaka7cf8beb2017-01-21 23:05:00 +02002131 /* Keyword arguments are passed through list.sort() which will check
2132 them. */
2133 if (!_PyArg_UnpackStack(args, nargs, "sorted", 1, 1, &seq))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002134 return NULL;
Raymond Hettinger64958a12003-12-17 20:43:33 +00002135
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002136 newlist = PySequence_List(seq);
2137 if (newlist == NULL)
2138 return NULL;
Raymond Hettinger64958a12003-12-17 20:43:33 +00002139
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02002140 callable = _PyObject_GetAttrId(newlist, &PyId_sort);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002141 if (callable == NULL) {
2142 Py_DECREF(newlist);
2143 return NULL;
2144 }
Georg Brandl99d7e4e2005-08-31 22:21:15 +00002145
Serhiy Storchaka299dc232017-01-20 08:35:18 +02002146 assert(nargs >= 1);
Victor Stinner5a60eca2017-01-17 15:17:49 +01002147 v = _PyObject_FastCallKeywords(callable, args + 1, nargs - 1, kwnames);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002148 Py_DECREF(callable);
2149 if (v == NULL) {
2150 Py_DECREF(newlist);
2151 return NULL;
2152 }
2153 Py_DECREF(v);
2154 return newlist;
Raymond Hettinger64958a12003-12-17 20:43:33 +00002155}
2156
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002157
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002158/* AC: cannot convert yet, as needs PEP 457 group support in inspect */
Guido van Rossum79f25d91997-04-29 20:08:16 +00002159static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002160builtin_vars(PyObject *self, PyObject *args)
Guido van Rossum2d951851994-08-29 12:52:16 +00002161{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002162 PyObject *v = NULL;
2163 PyObject *d;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002164
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002165 if (!PyArg_UnpackTuple(args, "vars", 0, 1, &v))
2166 return NULL;
2167 if (v == NULL) {
2168 d = PyEval_GetLocals();
Victor Stinner41bb43a2013-10-29 01:19:37 +01002169 if (d == NULL)
2170 return NULL;
2171 Py_INCREF(d);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002172 }
2173 else {
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02002174 d = _PyObject_GetAttrId(v, &PyId___dict__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002175 if (d == NULL) {
2176 PyErr_SetString(PyExc_TypeError,
2177 "vars() argument must have __dict__ attribute");
2178 return NULL;
2179 }
2180 }
2181 return d;
Guido van Rossum2d951851994-08-29 12:52:16 +00002182}
2183
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002184PyDoc_STRVAR(vars_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002185"vars([object]) -> dictionary\n\
2186\n\
2187Without arguments, equivalent to locals().\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002188With an argument, equivalent to object.__dict__.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002189
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002190
2191/*[clinic input]
2192sum as builtin_sum
2193
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03002194 iterable: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002195 start: object(c_default="NULL") = 0
2196 /
2197
2198Return the sum of a 'start' value (default: 0) plus an iterable of numbers
2199
2200When the iterable is empty, return the start value.
2201This function is intended specifically for use with numeric values and may
2202reject non-numeric types.
2203[clinic start generated code]*/
2204
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002205static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002206builtin_sum_impl(PyObject *module, PyObject *iterable, PyObject *start)
2207/*[clinic end generated code: output=df758cec7d1d302f input=3b5b7a9d7611c73a]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002208{
2209 PyObject *result = start;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002210 PyObject *temp, *item, *iter;
Alex Martellia70b1912003-04-22 08:12:33 +00002211
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002212 iter = PyObject_GetIter(iterable);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002213 if (iter == NULL)
2214 return NULL;
Alex Martellia70b1912003-04-22 08:12:33 +00002215
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002216 if (result == NULL) {
2217 result = PyLong_FromLong(0);
2218 if (result == NULL) {
2219 Py_DECREF(iter);
2220 return NULL;
2221 }
2222 } else {
2223 /* reject string values for 'start' parameter */
2224 if (PyUnicode_Check(result)) {
2225 PyErr_SetString(PyExc_TypeError,
2226 "sum() can't sum strings [use ''.join(seq) instead]");
2227 Py_DECREF(iter);
2228 return NULL;
2229 }
Benjamin Petersonce071ca2011-07-29 14:23:47 -05002230 if (PyBytes_Check(result)) {
2231 PyErr_SetString(PyExc_TypeError,
2232 "sum() can't sum bytes [use b''.join(seq) instead]");
Benjamin Peterson405f32c2011-07-29 22:43:45 -05002233 Py_DECREF(iter);
Benjamin Petersonce071ca2011-07-29 14:23:47 -05002234 return NULL;
2235 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002236 if (PyByteArray_Check(result)) {
2237 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson4f921c22011-07-29 14:24:29 -05002238 "sum() can't sum bytearray [use b''.join(seq) instead]");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002239 Py_DECREF(iter);
2240 return NULL;
2241 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002242 Py_INCREF(result);
2243 }
Alex Martellia70b1912003-04-22 08:12:33 +00002244
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002245#ifndef SLOW_SUM
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002246 /* Fast addition by keeping temporary sums in C instead of new Python objects.
2247 Assumes all inputs are the same type. If the assumption fails, default
2248 to the more general routine.
2249 */
2250 if (PyLong_CheckExact(result)) {
2251 int overflow;
2252 long i_result = PyLong_AsLongAndOverflow(result, &overflow);
2253 /* If this already overflowed, don't even enter the loop. */
2254 if (overflow == 0) {
2255 Py_DECREF(result);
2256 result = NULL;
2257 }
2258 while(result == NULL) {
2259 item = PyIter_Next(iter);
2260 if (item == NULL) {
2261 Py_DECREF(iter);
2262 if (PyErr_Occurred())
2263 return NULL;
2264 return PyLong_FromLong(i_result);
2265 }
2266 if (PyLong_CheckExact(item)) {
2267 long b = PyLong_AsLongAndOverflow(item, &overflow);
2268 long x = i_result + b;
2269 if (overflow == 0 && ((x^i_result) >= 0 || (x^b) >= 0)) {
2270 i_result = x;
2271 Py_DECREF(item);
2272 continue;
2273 }
2274 }
2275 /* Either overflowed or is not an int. Restore real objects and process normally */
2276 result = PyLong_FromLong(i_result);
Christian Heimes704e2d32013-07-26 22:49:26 +02002277 if (result == NULL) {
2278 Py_DECREF(item);
2279 Py_DECREF(iter);
2280 return NULL;
2281 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002282 temp = PyNumber_Add(result, item);
2283 Py_DECREF(result);
2284 Py_DECREF(item);
2285 result = temp;
2286 if (result == NULL) {
2287 Py_DECREF(iter);
2288 return NULL;
2289 }
2290 }
2291 }
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002292
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002293 if (PyFloat_CheckExact(result)) {
2294 double f_result = PyFloat_AS_DOUBLE(result);
2295 Py_DECREF(result);
2296 result = NULL;
2297 while(result == NULL) {
2298 item = PyIter_Next(iter);
2299 if (item == NULL) {
2300 Py_DECREF(iter);
2301 if (PyErr_Occurred())
2302 return NULL;
2303 return PyFloat_FromDouble(f_result);
2304 }
2305 if (PyFloat_CheckExact(item)) {
2306 PyFPE_START_PROTECT("add", Py_DECREF(item); Py_DECREF(iter); return 0)
2307 f_result += PyFloat_AS_DOUBLE(item);
2308 PyFPE_END_PROTECT(f_result)
2309 Py_DECREF(item);
2310 continue;
2311 }
2312 if (PyLong_CheckExact(item)) {
2313 long value;
2314 int overflow;
2315 value = PyLong_AsLongAndOverflow(item, &overflow);
2316 if (!overflow) {
2317 PyFPE_START_PROTECT("add", Py_DECREF(item); Py_DECREF(iter); return 0)
2318 f_result += (double)value;
2319 PyFPE_END_PROTECT(f_result)
2320 Py_DECREF(item);
2321 continue;
2322 }
2323 }
2324 result = PyFloat_FromDouble(f_result);
2325 temp = PyNumber_Add(result, item);
2326 Py_DECREF(result);
2327 Py_DECREF(item);
2328 result = temp;
2329 if (result == NULL) {
2330 Py_DECREF(iter);
2331 return NULL;
2332 }
2333 }
2334 }
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002335#endif
2336
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002337 for(;;) {
2338 item = PyIter_Next(iter);
2339 if (item == NULL) {
2340 /* error, or end-of-sequence */
2341 if (PyErr_Occurred()) {
2342 Py_DECREF(result);
2343 result = NULL;
2344 }
2345 break;
2346 }
2347 /* It's tempting to use PyNumber_InPlaceAdd instead of
2348 PyNumber_Add here, to avoid quadratic running time
2349 when doing 'sum(list_of_lists, [])'. However, this
2350 would produce a change in behaviour: a snippet like
Mark Dickinson9acadc52009-10-26 14:19:42 +00002351
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002352 empty = []
2353 sum([[x] for x in range(10)], empty)
Mark Dickinson9acadc52009-10-26 14:19:42 +00002354
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002355 would change the value of empty. */
2356 temp = PyNumber_Add(result, item);
2357 Py_DECREF(result);
2358 Py_DECREF(item);
2359 result = temp;
2360 if (result == NULL)
2361 break;
2362 }
2363 Py_DECREF(iter);
2364 return result;
Alex Martellia70b1912003-04-22 08:12:33 +00002365}
2366
Alex Martellia70b1912003-04-22 08:12:33 +00002367
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002368/*[clinic input]
2369isinstance as builtin_isinstance
2370
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03002371 obj: object
2372 class_or_tuple: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002373 /
2374
2375Return whether an object is an instance of a class or of a subclass thereof.
2376
2377A tuple, as in ``isinstance(x, (A, B, ...))``, may be given as the target to
2378check against. This is equivalent to ``isinstance(x, A) or isinstance(x, B)
2379or ...`` etc.
2380[clinic start generated code]*/
2381
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002382static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002383builtin_isinstance_impl(PyObject *module, PyObject *obj,
Larry Hastings89964c42015-04-14 18:07:59 -04002384 PyObject *class_or_tuple)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002385/*[clinic end generated code: output=6faf01472c13b003 input=ffa743db1daf7549]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002386{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002387 int retval;
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002388
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002389 retval = PyObject_IsInstance(obj, class_or_tuple);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002390 if (retval < 0)
2391 return NULL;
2392 return PyBool_FromLong(retval);
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002393}
2394
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002395
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002396/*[clinic input]
2397issubclass as builtin_issubclass
2398
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03002399 cls: object
2400 class_or_tuple: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002401 /
2402
2403Return whether 'cls' is a derived from another class or is the same class.
2404
2405A tuple, as in ``issubclass(x, (A, B, ...))``, may be given as the target to
2406check against. This is equivalent to ``issubclass(x, A) or issubclass(x, B)
2407or ...`` etc.
2408[clinic start generated code]*/
2409
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002410static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002411builtin_issubclass_impl(PyObject *module, PyObject *cls,
Larry Hastings89964c42015-04-14 18:07:59 -04002412 PyObject *class_or_tuple)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002413/*[clinic end generated code: output=358412410cd7a250 input=af5f35e9ceaddaf6]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002414{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002415 int retval;
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002416
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002417 retval = PyObject_IsSubclass(cls, class_or_tuple);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002418 if (retval < 0)
2419 return NULL;
2420 return PyBool_FromLong(retval);
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002421}
2422
2423
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002424typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002425 PyObject_HEAD
2426 Py_ssize_t tuplesize;
2427 PyObject *ittuple; /* tuple of iterators */
2428 PyObject *result;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002429} zipobject;
2430
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002431static PyObject *
2432zip_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
Barry Warsawbd599b52000-08-03 15:45:29 +00002433{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002434 zipobject *lz;
2435 Py_ssize_t i;
2436 PyObject *ittuple; /* tuple of iterators */
2437 PyObject *result;
Serhiy Storchakabf623ae2017-04-19 20:03:52 +03002438 Py_ssize_t tuplesize;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002439
Serhiy Storchaka6cca5c82017-06-08 14:41:19 +03002440 if (type == &PyZip_Type && !_PyArg_NoKeywords("zip", kwds))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002441 return NULL;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002442
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002443 /* args must be a tuple */
2444 assert(PyTuple_Check(args));
Serhiy Storchakabf623ae2017-04-19 20:03:52 +03002445 tuplesize = PyTuple_GET_SIZE(args);
Barry Warsawbd599b52000-08-03 15:45:29 +00002446
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002447 /* obtain iterators */
2448 ittuple = PyTuple_New(tuplesize);
2449 if (ittuple == NULL)
2450 return NULL;
2451 for (i=0; i < tuplesize; ++i) {
2452 PyObject *item = PyTuple_GET_ITEM(args, i);
2453 PyObject *it = PyObject_GetIter(item);
2454 if (it == NULL) {
2455 if (PyErr_ExceptionMatches(PyExc_TypeError))
2456 PyErr_Format(PyExc_TypeError,
2457 "zip argument #%zd must support iteration",
2458 i+1);
2459 Py_DECREF(ittuple);
2460 return NULL;
2461 }
2462 PyTuple_SET_ITEM(ittuple, i, it);
2463 }
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002464
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002465 /* create a result holder */
2466 result = PyTuple_New(tuplesize);
2467 if (result == NULL) {
2468 Py_DECREF(ittuple);
2469 return NULL;
2470 }
2471 for (i=0 ; i < tuplesize ; i++) {
2472 Py_INCREF(Py_None);
2473 PyTuple_SET_ITEM(result, i, Py_None);
2474 }
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002475
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002476 /* create zipobject structure */
2477 lz = (zipobject *)type->tp_alloc(type, 0);
2478 if (lz == NULL) {
2479 Py_DECREF(ittuple);
2480 Py_DECREF(result);
2481 return NULL;
2482 }
2483 lz->ittuple = ittuple;
2484 lz->tuplesize = tuplesize;
2485 lz->result = result;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002486
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002487 return (PyObject *)lz;
Barry Warsawbd599b52000-08-03 15:45:29 +00002488}
2489
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002490static void
2491zip_dealloc(zipobject *lz)
2492{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002493 PyObject_GC_UnTrack(lz);
2494 Py_XDECREF(lz->ittuple);
2495 Py_XDECREF(lz->result);
2496 Py_TYPE(lz)->tp_free(lz);
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002497}
2498
2499static int
2500zip_traverse(zipobject *lz, visitproc visit, void *arg)
2501{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002502 Py_VISIT(lz->ittuple);
2503 Py_VISIT(lz->result);
2504 return 0;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002505}
2506
2507static PyObject *
2508zip_next(zipobject *lz)
2509{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002510 Py_ssize_t i;
2511 Py_ssize_t tuplesize = lz->tuplesize;
2512 PyObject *result = lz->result;
2513 PyObject *it;
2514 PyObject *item;
2515 PyObject *olditem;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002516
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002517 if (tuplesize == 0)
2518 return NULL;
2519 if (Py_REFCNT(result) == 1) {
2520 Py_INCREF(result);
2521 for (i=0 ; i < tuplesize ; i++) {
2522 it = PyTuple_GET_ITEM(lz->ittuple, i);
2523 item = (*Py_TYPE(it)->tp_iternext)(it);
Serhiy Storchaka278d03b2013-04-06 22:52:34 +03002524 if (item == NULL) {
2525 Py_DECREF(result);
2526 return NULL;
2527 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002528 olditem = PyTuple_GET_ITEM(result, i);
2529 PyTuple_SET_ITEM(result, i, item);
2530 Py_DECREF(olditem);
2531 }
2532 } else {
2533 result = PyTuple_New(tuplesize);
2534 if (result == NULL)
Serhiy Storchaka278d03b2013-04-06 22:52:34 +03002535 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002536 for (i=0 ; i < tuplesize ; i++) {
2537 it = PyTuple_GET_ITEM(lz->ittuple, i);
2538 item = (*Py_TYPE(it)->tp_iternext)(it);
Serhiy Storchaka278d03b2013-04-06 22:52:34 +03002539 if (item == NULL) {
2540 Py_DECREF(result);
2541 return NULL;
2542 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002543 PyTuple_SET_ITEM(result, i, item);
2544 }
2545 }
2546 return result;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002547}
Barry Warsawbd599b52000-08-03 15:45:29 +00002548
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002549static PyObject *
2550zip_reduce(zipobject *lz)
2551{
2552 /* Just recreate the zip with the internal iterator tuple */
2553 return Py_BuildValue("OO", Py_TYPE(lz), lz->ittuple);
2554}
2555
2556static PyMethodDef zip_methods[] = {
2557 {"__reduce__", (PyCFunction)zip_reduce, METH_NOARGS, reduce_doc},
2558 {NULL, NULL} /* sentinel */
2559};
2560
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002561PyDoc_STRVAR(zip_doc,
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002562"zip(iter1 [,iter2 [...]]) --> zip object\n\
Barry Warsawbd599b52000-08-03 15:45:29 +00002563\n\
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002564Return a zip object whose .__next__() method returns a tuple where\n\
2565the i-th element comes from the i-th iterable argument. The .__next__()\n\
2566method continues until the shortest iterable in the argument sequence\n\
Georg Brandlced51db2008-12-04 18:28:38 +00002567is exhausted and then it raises StopIteration.");
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002568
2569PyTypeObject PyZip_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002570 PyVarObject_HEAD_INIT(&PyType_Type, 0)
2571 "zip", /* tp_name */
2572 sizeof(zipobject), /* tp_basicsize */
2573 0, /* tp_itemsize */
2574 /* methods */
2575 (destructor)zip_dealloc, /* tp_dealloc */
2576 0, /* tp_print */
2577 0, /* tp_getattr */
2578 0, /* tp_setattr */
2579 0, /* tp_reserved */
2580 0, /* tp_repr */
2581 0, /* tp_as_number */
2582 0, /* tp_as_sequence */
2583 0, /* tp_as_mapping */
2584 0, /* tp_hash */
2585 0, /* tp_call */
2586 0, /* tp_str */
2587 PyObject_GenericGetAttr, /* tp_getattro */
2588 0, /* tp_setattro */
2589 0, /* tp_as_buffer */
2590 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
2591 Py_TPFLAGS_BASETYPE, /* tp_flags */
2592 zip_doc, /* tp_doc */
2593 (traverseproc)zip_traverse, /* tp_traverse */
2594 0, /* tp_clear */
2595 0, /* tp_richcompare */
2596 0, /* tp_weaklistoffset */
2597 PyObject_SelfIter, /* tp_iter */
2598 (iternextfunc)zip_next, /* tp_iternext */
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002599 zip_methods, /* tp_methods */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002600 0, /* tp_members */
2601 0, /* tp_getset */
2602 0, /* tp_base */
2603 0, /* tp_dict */
2604 0, /* tp_descr_get */
2605 0, /* tp_descr_set */
2606 0, /* tp_dictoffset */
2607 0, /* tp_init */
2608 PyType_GenericAlloc, /* tp_alloc */
2609 zip_new, /* tp_new */
2610 PyObject_GC_Del, /* tp_free */
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002611};
Barry Warsawbd599b52000-08-03 15:45:29 +00002612
2613
Guido van Rossum79f25d91997-04-29 20:08:16 +00002614static PyMethodDef builtin_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002615 {"__build_class__", (PyCFunction)builtin___build_class__,
Serhiy Storchaka6969eaf2017-07-03 21:20:15 +03002616 METH_FASTCALL | METH_KEYWORDS, build_class_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002617 {"__import__", (PyCFunction)builtin___import__, METH_VARARGS | METH_KEYWORDS, import_doc},
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002618 BUILTIN_ABS_METHODDEF
2619 BUILTIN_ALL_METHODDEF
2620 BUILTIN_ANY_METHODDEF
2621 BUILTIN_ASCII_METHODDEF
2622 BUILTIN_BIN_METHODDEF
2623 BUILTIN_CALLABLE_METHODDEF
2624 BUILTIN_CHR_METHODDEF
2625 BUILTIN_COMPILE_METHODDEF
2626 BUILTIN_DELATTR_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002627 {"dir", builtin_dir, METH_VARARGS, dir_doc},
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002628 BUILTIN_DIVMOD_METHODDEF
2629 BUILTIN_EVAL_METHODDEF
2630 BUILTIN_EXEC_METHODDEF
2631 BUILTIN_FORMAT_METHODDEF
Victor Stinner84b388b2017-01-17 03:52:27 +01002632 {"getattr", (PyCFunction)builtin_getattr, METH_FASTCALL, getattr_doc},
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002633 BUILTIN_GLOBALS_METHODDEF
2634 BUILTIN_HASATTR_METHODDEF
2635 BUILTIN_HASH_METHODDEF
2636 BUILTIN_HEX_METHODDEF
2637 BUILTIN_ID_METHODDEF
2638 BUILTIN_INPUT_METHODDEF
2639 BUILTIN_ISINSTANCE_METHODDEF
2640 BUILTIN_ISSUBCLASS_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002641 {"iter", builtin_iter, METH_VARARGS, iter_doc},
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002642 BUILTIN_LEN_METHODDEF
2643 BUILTIN_LOCALS_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002644 {"max", (PyCFunction)builtin_max, METH_VARARGS | METH_KEYWORDS, max_doc},
2645 {"min", (PyCFunction)builtin_min, METH_VARARGS | METH_KEYWORDS, min_doc},
Victor Stinnerfda6d0a2017-01-17 04:09:14 +01002646 {"next", (PyCFunction)builtin_next, METH_FASTCALL, next_doc},
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002647 BUILTIN_OCT_METHODDEF
2648 BUILTIN_ORD_METHODDEF
2649 BUILTIN_POW_METHODDEF
Serhiy Storchaka6969eaf2017-07-03 21:20:15 +03002650 {"print", (PyCFunction)builtin_print, METH_FASTCALL | METH_KEYWORDS, print_doc},
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002651 BUILTIN_REPR_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002652 {"round", (PyCFunction)builtin_round, METH_VARARGS | METH_KEYWORDS, round_doc},
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002653 BUILTIN_SETATTR_METHODDEF
2654 BUILTIN_SORTED_METHODDEF
2655 BUILTIN_SUM_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002656 {"vars", builtin_vars, METH_VARARGS, vars_doc},
2657 {NULL, NULL},
Guido van Rossum3f5da241990-12-20 15:06:42 +00002658};
2659
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002660PyDoc_STRVAR(builtin_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002661"Built-in functions, exceptions, and other objects.\n\
2662\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002663Noteworthy: None is the `nil' object; Ellipsis represents `...' in slices.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002664
Martin v. Löwis1a214512008-06-11 05:26:20 +00002665static struct PyModuleDef builtinsmodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002666 PyModuleDef_HEAD_INIT,
2667 "builtins",
2668 builtin_doc,
2669 -1, /* multiple "initialization" just copies the module dict. */
2670 builtin_methods,
2671 NULL,
2672 NULL,
2673 NULL,
2674 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00002675};
2676
2677
Guido van Rossum25ce5661997-08-02 03:10:38 +00002678PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002679_PyBuiltin_Init(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +00002680{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002681 PyObject *mod, *dict, *debug;
Benjamin Peterson42124a72012-10-30 23:41:54 -04002682
2683 if (PyType_Ready(&PyFilter_Type) < 0 ||
2684 PyType_Ready(&PyMap_Type) < 0 ||
2685 PyType_Ready(&PyZip_Type) < 0)
2686 return NULL;
2687
Eric Snowd393c1b2017-09-14 12:18:12 -06002688 mod = _PyModule_CreateInitialized(&builtinsmodule, PYTHON_API_VERSION);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002689 if (mod == NULL)
2690 return NULL;
2691 dict = PyModule_GetDict(mod);
Tim Peters4b7625e2001-09-13 21:37:17 +00002692
Tim Peters7571a0f2003-03-23 17:52:28 +00002693#ifdef Py_TRACE_REFS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002694 /* "builtins" exposes a number of statically allocated objects
2695 * that, before this code was added in 2.3, never showed up in
2696 * the list of "all objects" maintained by Py_TRACE_REFS. As a
2697 * result, programs leaking references to None and False (etc)
2698 * couldn't be diagnosed by examining sys.getobjects(0).
2699 */
Tim Peters7571a0f2003-03-23 17:52:28 +00002700#define ADD_TO_ALL(OBJECT) _Py_AddToAllObjects((PyObject *)(OBJECT), 0)
2701#else
2702#define ADD_TO_ALL(OBJECT) (void)0
2703#endif
2704
Tim Peters4b7625e2001-09-13 21:37:17 +00002705#define SETBUILTIN(NAME, OBJECT) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002706 if (PyDict_SetItemString(dict, NAME, (PyObject *)OBJECT) < 0) \
2707 return NULL; \
2708 ADD_TO_ALL(OBJECT)
Tim Peters4b7625e2001-09-13 21:37:17 +00002709
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002710 SETBUILTIN("None", Py_None);
2711 SETBUILTIN("Ellipsis", Py_Ellipsis);
2712 SETBUILTIN("NotImplemented", Py_NotImplemented);
2713 SETBUILTIN("False", Py_False);
2714 SETBUILTIN("True", Py_True);
2715 SETBUILTIN("bool", &PyBool_Type);
2716 SETBUILTIN("memoryview", &PyMemoryView_Type);
2717 SETBUILTIN("bytearray", &PyByteArray_Type);
2718 SETBUILTIN("bytes", &PyBytes_Type);
2719 SETBUILTIN("classmethod", &PyClassMethod_Type);
2720 SETBUILTIN("complex", &PyComplex_Type);
2721 SETBUILTIN("dict", &PyDict_Type);
2722 SETBUILTIN("enumerate", &PyEnum_Type);
2723 SETBUILTIN("filter", &PyFilter_Type);
2724 SETBUILTIN("float", &PyFloat_Type);
2725 SETBUILTIN("frozenset", &PyFrozenSet_Type);
2726 SETBUILTIN("property", &PyProperty_Type);
2727 SETBUILTIN("int", &PyLong_Type);
2728 SETBUILTIN("list", &PyList_Type);
2729 SETBUILTIN("map", &PyMap_Type);
2730 SETBUILTIN("object", &PyBaseObject_Type);
2731 SETBUILTIN("range", &PyRange_Type);
2732 SETBUILTIN("reversed", &PyReversed_Type);
2733 SETBUILTIN("set", &PySet_Type);
2734 SETBUILTIN("slice", &PySlice_Type);
2735 SETBUILTIN("staticmethod", &PyStaticMethod_Type);
2736 SETBUILTIN("str", &PyUnicode_Type);
2737 SETBUILTIN("super", &PySuper_Type);
2738 SETBUILTIN("tuple", &PyTuple_Type);
2739 SETBUILTIN("type", &PyType_Type);
2740 SETBUILTIN("zip", &PyZip_Type);
2741 debug = PyBool_FromLong(Py_OptimizeFlag == 0);
2742 if (PyDict_SetItemString(dict, "__debug__", debug) < 0) {
Serhiy Storchakacfdfbb42016-06-18 09:44:03 +03002743 Py_DECREF(debug);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002744 return NULL;
2745 }
Serhiy Storchakacfdfbb42016-06-18 09:44:03 +03002746 Py_DECREF(debug);
Barry Warsaw757af0e1997-08-29 22:13:51 +00002747
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002748 return mod;
Tim Peters7571a0f2003-03-23 17:52:28 +00002749#undef ADD_TO_ALL
Tim Peters4b7625e2001-09-13 21:37:17 +00002750#undef SETBUILTIN
Guido van Rossum3f5da241990-12-20 15:06:42 +00002751}