blob: 2269fe21657e61c64ae90ddf4eeb69ad3a00765b [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 }
Oren Milman5837d042017-09-27 17:04:37 +0300160 if (!PyMapping_Check(ns)) {
161 PyErr_Format(PyExc_TypeError,
162 "%.200s.__prepare__() must return a mapping, not %.200s",
163 isclass ? ((PyTypeObject *)meta)->tp_name : "<metaclass>",
164 Py_TYPE(ns)->tp_name);
165 goto error;
166 }
Nick Coghlan19d24672016-12-05 16:47:55 +1000167 cell = PyEval_EvalCodeEx(PyFunction_GET_CODE(func), PyFunction_GET_GLOBALS(func), ns,
Benjamin Petersone8e14592013-05-16 14:37:25 -0500168 NULL, 0, NULL, 0, NULL, 0, NULL,
169 PyFunction_GET_CLOSURE(func));
Nick Coghlan19d24672016-12-05 16:47:55 +1000170 if (cell != NULL) {
Victor Stinnerd1c2a8e2016-08-23 01:34:35 +0200171 PyObject *margs[3] = {name, bases, ns};
172 cls = _PyObject_FastCallDict(meta, margs, 3, mkw);
Nick Coghlan19d24672016-12-05 16:47:55 +1000173 if (cls != NULL && PyType_Check(cls) && PyCell_Check(cell)) {
174 PyObject *cell_cls = PyCell_GET(cell);
175 if (cell_cls != cls) {
176 /* TODO: In 3.7, DeprecationWarning will become RuntimeError.
177 * At that point, cell_error won't be needed.
178 */
179 int cell_error;
180 if (cell_cls == NULL) {
181 const char *msg =
182 "__class__ not set defining %.200R as %.200R. "
183 "Was __classcell__ propagated to type.__new__?";
184 cell_error = PyErr_WarnFormat(
185 PyExc_DeprecationWarning, 1, msg, name, cls);
186 } else {
187 const char *msg =
188 "__class__ set to %.200R defining %.200R as %.200R";
189 PyErr_Format(PyExc_TypeError, msg, cell_cls, name, cls);
190 cell_error = 1;
191 }
192 if (cell_error) {
193 Py_DECREF(cls);
194 cls = NULL;
195 goto error;
196 } else {
197 /* Fill in the cell, since type.__new__ didn't do it */
198 PyCell_Set(cell, cls);
199 }
200 }
201 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000202 }
Nick Coghlan19d24672016-12-05 16:47:55 +1000203error:
204 Py_XDECREF(cell);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000205 Py_DECREF(ns);
206 Py_DECREF(meta);
207 Py_XDECREF(mkw);
208 Py_DECREF(bases);
209 return cls;
Guido van Rossum52cc1d82007-03-18 15:41:51 +0000210}
211
212PyDoc_STRVAR(build_class_doc,
213"__build_class__(func, name, *bases, metaclass=None, **kwds) -> class\n\
214\n\
215Internal helper function used by the class statement.");
216
217static PyObject *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000218builtin___import__(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000219{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000220 static char *kwlist[] = {"name", "globals", "locals", "fromlist",
221 "level", 0};
Victor Stinnerfe93faf2011-03-14 15:54:52 -0400222 PyObject *name, *globals = NULL, *locals = NULL, *fromlist = NULL;
Brett Cannonfd074152012-04-14 14:10:13 -0400223 int level = 0;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000224
Victor Stinnerfe93faf2011-03-14 15:54:52 -0400225 if (!PyArg_ParseTupleAndKeywords(args, kwds, "U|OOOi:__import__",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000226 kwlist, &name, &globals, &locals, &fromlist, &level))
227 return NULL;
Victor Stinnerfe93faf2011-03-14 15:54:52 -0400228 return PyImport_ImportModuleLevelObject(name, globals, locals,
229 fromlist, level);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000230}
231
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000232PyDoc_STRVAR(import_doc,
Brett Cannoncb4996a2012-08-06 16:34:44 -0400233"__import__(name, globals=None, locals=None, fromlist=(), level=0) -> module\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000234\n\
Brett Cannon5305a992010-09-27 21:08:38 +0000235Import a module. Because this function is meant for use by the Python\n\
236interpreter and not for general use it is better to use\n\
237importlib.import_module() to programmatically import a module.\n\
238\n\
239The globals argument is only used to determine the context;\n\
240they are not modified. The locals argument is unused. The fromlist\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000241should be a list of names to emulate ``from name import ...'', or an\n\
242empty list to emulate ``import name''.\n\
243When importing a module from a package, note that __import__('A.B', ...)\n\
244returns package A when fromlist is empty, but its submodule B when\n\
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000245fromlist is not empty. Level is used to determine whether to perform \n\
Brett Cannon722d3ae2012-07-30 17:45:54 -0400246absolute or relative imports. 0 is absolute while a positive number\n\
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000247is the number of parent directories to search relative to the current module.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000248
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000249
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000250/*[clinic input]
251abs as builtin_abs
252
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300253 x: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000254 /
255
256Return the absolute value of the argument.
257[clinic start generated code]*/
258
Guido van Rossum79f25d91997-04-29 20:08:16 +0000259static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300260builtin_abs(PyObject *module, PyObject *x)
261/*[clinic end generated code: output=b1b433b9e51356f5 input=bed4ca14e29c20d1]*/
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000262{
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000263 return PyNumber_Absolute(x);
Guido van Rossum3f5da241990-12-20 15:06:42 +0000264}
265
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000266/*[clinic input]
267all as builtin_all
268
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300269 iterable: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000270 /
271
272Return True if bool(x) is True for all values x in the iterable.
273
274If the iterable is empty, return True.
275[clinic start generated code]*/
276
Raymond Hettinger96229b12005-03-11 06:49:40 +0000277static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300278builtin_all(PyObject *module, PyObject *iterable)
279/*[clinic end generated code: output=ca2a7127276f79b3 input=1a7c5d1bc3438a21]*/
Raymond Hettinger96229b12005-03-11 06:49:40 +0000280{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000281 PyObject *it, *item;
282 PyObject *(*iternext)(PyObject *);
283 int cmp;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000284
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000285 it = PyObject_GetIter(iterable);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000286 if (it == NULL)
287 return NULL;
288 iternext = *Py_TYPE(it)->tp_iternext;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000289
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000290 for (;;) {
291 item = iternext(it);
292 if (item == NULL)
293 break;
294 cmp = PyObject_IsTrue(item);
295 Py_DECREF(item);
296 if (cmp < 0) {
297 Py_DECREF(it);
298 return NULL;
299 }
300 if (cmp == 0) {
301 Py_DECREF(it);
302 Py_RETURN_FALSE;
303 }
304 }
305 Py_DECREF(it);
306 if (PyErr_Occurred()) {
307 if (PyErr_ExceptionMatches(PyExc_StopIteration))
308 PyErr_Clear();
309 else
310 return NULL;
311 }
312 Py_RETURN_TRUE;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000313}
314
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000315/*[clinic input]
316any as builtin_any
317
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300318 iterable: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000319 /
320
321Return True if bool(x) is True for any x in the iterable.
322
323If the iterable is empty, return False.
324[clinic start generated code]*/
325
Raymond Hettinger96229b12005-03-11 06:49:40 +0000326static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300327builtin_any(PyObject *module, PyObject *iterable)
328/*[clinic end generated code: output=fa65684748caa60e input=41d7451c23384f24]*/
Raymond Hettinger96229b12005-03-11 06:49:40 +0000329{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000330 PyObject *it, *item;
331 PyObject *(*iternext)(PyObject *);
332 int cmp;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000333
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000334 it = PyObject_GetIter(iterable);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000335 if (it == NULL)
336 return NULL;
337 iternext = *Py_TYPE(it)->tp_iternext;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000338
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000339 for (;;) {
340 item = iternext(it);
341 if (item == NULL)
342 break;
343 cmp = PyObject_IsTrue(item);
344 Py_DECREF(item);
345 if (cmp < 0) {
346 Py_DECREF(it);
347 return NULL;
348 }
Raymond Hettinger5098b582015-10-09 00:42:47 -0400349 if (cmp > 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000350 Py_DECREF(it);
351 Py_RETURN_TRUE;
352 }
353 }
354 Py_DECREF(it);
355 if (PyErr_Occurred()) {
356 if (PyErr_ExceptionMatches(PyExc_StopIteration))
357 PyErr_Clear();
358 else
359 return NULL;
360 }
361 Py_RETURN_FALSE;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000362}
363
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000364/*[clinic input]
365ascii as builtin_ascii
366
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300367 obj: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000368 /
369
370Return an ASCII-only representation of an object.
371
372As repr(), return a string containing a printable representation of an
373object, but escape the non-ASCII characters in the string returned by
374repr() using \\x, \\u or \\U escapes. This generates a string similar
375to that returned by repr() in Python 2.
376[clinic start generated code]*/
377
Georg Brandl559e5d72008-06-11 18:37:52 +0000378static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300379builtin_ascii(PyObject *module, PyObject *obj)
380/*[clinic end generated code: output=6d37b3f0984c7eb9 input=4c62732e1b3a3cc9]*/
Georg Brandl559e5d72008-06-11 18:37:52 +0000381{
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000382 return PyObject_ASCII(obj);
Georg Brandl559e5d72008-06-11 18:37:52 +0000383}
384
Georg Brandl559e5d72008-06-11 18:37:52 +0000385
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000386/*[clinic input]
387bin as builtin_bin
388
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300389 number: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000390 /
391
392Return the binary representation of an integer.
393
394 >>> bin(2796202)
395 '0b1010101010101010101010'
396[clinic start generated code]*/
397
Guido van Rossum79f25d91997-04-29 20:08:16 +0000398static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300399builtin_bin(PyObject *module, PyObject *number)
400/*[clinic end generated code: output=b6fc4ad5e649f4f7 input=53f8a0264bacaf90]*/
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000401{
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000402 return PyNumber_ToBase(number, 2);
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000403}
404
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000405
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000406/*[clinic input]
407callable as builtin_callable
408
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300409 obj: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000410 /
411
412Return whether the object is callable (i.e., some kind of function).
413
414Note that classes are callable, as are instances of classes with a
415__call__() method.
416[clinic start generated code]*/
417
Antoine Pitroue71362d2010-11-27 22:00:11 +0000418static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300419builtin_callable(PyObject *module, PyObject *obj)
420/*[clinic end generated code: output=2b095d59d934cb7e input=1423bab99cc41f58]*/
Antoine Pitroue71362d2010-11-27 22:00:11 +0000421{
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000422 return PyBool_FromLong((long)PyCallable_Check(obj));
Antoine Pitroue71362d2010-11-27 22:00:11 +0000423}
424
Antoine Pitroue71362d2010-11-27 22:00:11 +0000425
Raymond Hettinger17301e92008-03-13 00:19:26 +0000426typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000427 PyObject_HEAD
428 PyObject *func;
429 PyObject *it;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000430} filterobject;
431
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000432static PyObject *
Raymond Hettinger17301e92008-03-13 00:19:26 +0000433filter_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
Guido van Rossum12d12c51993-10-26 17:58:25 +0000434{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000435 PyObject *func, *seq;
436 PyObject *it;
437 filterobject *lz;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000438
Serhiy Storchaka6cca5c82017-06-08 14:41:19 +0300439 if (type == &PyFilter_Type && !_PyArg_NoKeywords("filter", kwds))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000440 return NULL;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000441
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000442 if (!PyArg_UnpackTuple(args, "filter", 2, 2, &func, &seq))
443 return NULL;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000444
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000445 /* Get iterator. */
446 it = PyObject_GetIter(seq);
447 if (it == NULL)
448 return NULL;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000449
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000450 /* create filterobject structure */
451 lz = (filterobject *)type->tp_alloc(type, 0);
452 if (lz == NULL) {
453 Py_DECREF(it);
454 return NULL;
455 }
456 Py_INCREF(func);
457 lz->func = func;
458 lz->it = it;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000459
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000460 return (PyObject *)lz;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000461}
462
463static void
464filter_dealloc(filterobject *lz)
465{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000466 PyObject_GC_UnTrack(lz);
467 Py_XDECREF(lz->func);
468 Py_XDECREF(lz->it);
469 Py_TYPE(lz)->tp_free(lz);
Raymond Hettinger17301e92008-03-13 00:19:26 +0000470}
471
472static int
473filter_traverse(filterobject *lz, visitproc visit, void *arg)
474{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000475 Py_VISIT(lz->it);
476 Py_VISIT(lz->func);
477 return 0;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000478}
479
480static PyObject *
481filter_next(filterobject *lz)
482{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000483 PyObject *item;
484 PyObject *it = lz->it;
485 long ok;
486 PyObject *(*iternext)(PyObject *);
Raymond Hettingerbd5f0e82015-10-09 01:34:08 -0400487 int checktrue = lz->func == Py_None || lz->func == (PyObject *)&PyBool_Type;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000488
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000489 iternext = *Py_TYPE(it)->tp_iternext;
490 for (;;) {
491 item = iternext(it);
492 if (item == NULL)
493 return NULL;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000494
Raymond Hettingerbd5f0e82015-10-09 01:34:08 -0400495 if (checktrue) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000496 ok = PyObject_IsTrue(item);
497 } else {
498 PyObject *good;
Victor Stinnerde4ae3d2016-12-04 22:59:09 +0100499 good = PyObject_CallFunctionObjArgs(lz->func, item, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000500 if (good == NULL) {
501 Py_DECREF(item);
502 return NULL;
503 }
504 ok = PyObject_IsTrue(good);
505 Py_DECREF(good);
506 }
Antoine Pitrou6f430e42012-08-15 23:18:25 +0200507 if (ok > 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000508 return item;
509 Py_DECREF(item);
Antoine Pitrou6f430e42012-08-15 23:18:25 +0200510 if (ok < 0)
511 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000512 }
Guido van Rossum12d12c51993-10-26 17:58:25 +0000513}
514
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +0000515static PyObject *
516filter_reduce(filterobject *lz)
517{
518 return Py_BuildValue("O(OO)", Py_TYPE(lz), lz->func, lz->it);
519}
520
521PyDoc_STRVAR(reduce_doc, "Return state information for pickling.");
522
523static PyMethodDef filter_methods[] = {
524 {"__reduce__", (PyCFunction)filter_reduce, METH_NOARGS, reduce_doc},
525 {NULL, NULL} /* sentinel */
526};
527
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000528PyDoc_STRVAR(filter_doc,
Georg Brandld11ae5d2008-05-16 13:27:32 +0000529"filter(function or None, iterable) --> filter object\n\
Guido van Rossumc1f779c2007-07-03 08:25:58 +0000530\n\
Georg Brandld11ae5d2008-05-16 13:27:32 +0000531Return an iterator yielding those items of iterable for which function(item)\n\
Raymond Hettinger17301e92008-03-13 00:19:26 +0000532is true. If function is None, return the items that are true.");
533
534PyTypeObject PyFilter_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000535 PyVarObject_HEAD_INIT(&PyType_Type, 0)
536 "filter", /* tp_name */
537 sizeof(filterobject), /* tp_basicsize */
538 0, /* tp_itemsize */
539 /* methods */
540 (destructor)filter_dealloc, /* tp_dealloc */
541 0, /* tp_print */
542 0, /* tp_getattr */
543 0, /* tp_setattr */
544 0, /* tp_reserved */
545 0, /* tp_repr */
546 0, /* tp_as_number */
547 0, /* tp_as_sequence */
548 0, /* tp_as_mapping */
549 0, /* tp_hash */
550 0, /* tp_call */
551 0, /* tp_str */
552 PyObject_GenericGetAttr, /* tp_getattro */
553 0, /* tp_setattro */
554 0, /* tp_as_buffer */
555 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
556 Py_TPFLAGS_BASETYPE, /* tp_flags */
557 filter_doc, /* tp_doc */
558 (traverseproc)filter_traverse, /* tp_traverse */
559 0, /* tp_clear */
560 0, /* tp_richcompare */
561 0, /* tp_weaklistoffset */
562 PyObject_SelfIter, /* tp_iter */
563 (iternextfunc)filter_next, /* tp_iternext */
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +0000564 filter_methods, /* tp_methods */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000565 0, /* tp_members */
566 0, /* tp_getset */
567 0, /* tp_base */
568 0, /* tp_dict */
569 0, /* tp_descr_get */
570 0, /* tp_descr_set */
571 0, /* tp_dictoffset */
572 0, /* tp_init */
573 PyType_GenericAlloc, /* tp_alloc */
574 filter_new, /* tp_new */
575 PyObject_GC_Del, /* tp_free */
Raymond Hettinger17301e92008-03-13 00:19:26 +0000576};
577
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000578
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000579/*[clinic input]
580format as builtin_format
581
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300582 value: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000583 format_spec: unicode(c_default="NULL") = ''
584 /
585
586Return value.__format__(format_spec)
587
Amit Kumar2e6bb442017-05-29 06:32:26 +0530588format_spec defaults to the empty string.
589See the Format Specification Mini-Language section of help('FORMATTING') for
590details.
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000591[clinic start generated code]*/
592
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000593static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300594builtin_format_impl(PyObject *module, PyObject *value, PyObject *format_spec)
Amit Kumar2e6bb442017-05-29 06:32:26 +0530595/*[clinic end generated code: output=2f40bdfa4954b077 input=88339c93ea522b33]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000596{
Eric Smith8fd3eba2008-02-17 19:48:00 +0000597 return PyObject_Format(value, format_spec);
Eric Smith8c663262007-08-25 02:26:07 +0000598}
599
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000600/*[clinic input]
601chr as builtin_chr
602
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300603 i: int
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000604 /
605
606Return a Unicode string of one character with ordinal i; 0 <= i <= 0x10ffff.
607[clinic start generated code]*/
608
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000609static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300610builtin_chr_impl(PyObject *module, int i)
611/*[clinic end generated code: output=c733afcd200afcb7 input=3f604ef45a70750d]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000612{
613 return PyUnicode_FromOrdinal(i);
614}
Guido van Rossum09095f32000-03-10 23:00:52 +0000615
616
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +0200617static const char *
Martin Pantereeb896c2015-11-07 02:32:21 +0000618source_as_string(PyObject *cmd, const char *funcname, const char *what, PyCompilerFlags *cf, PyObject **cmd_copy)
Guido van Rossumf15a29f2007-05-04 00:41:39 +0000619{
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +0200620 const char *str;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000621 Py_ssize_t size;
Martin Pantereeb896c2015-11-07 02:32:21 +0000622 Py_buffer view;
Guido van Rossumf15a29f2007-05-04 00:41:39 +0000623
Martin Pantereeb896c2015-11-07 02:32:21 +0000624 *cmd_copy = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000625 if (PyUnicode_Check(cmd)) {
626 cf->cf_flags |= PyCF_IGNORE_COOKIE;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200627 str = PyUnicode_AsUTF8AndSize(cmd, &size);
628 if (str == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000629 return NULL;
630 }
Martin Pantereeb896c2015-11-07 02:32:21 +0000631 else if (PyBytes_Check(cmd)) {
632 str = PyBytes_AS_STRING(cmd);
633 size = PyBytes_GET_SIZE(cmd);
634 }
635 else if (PyByteArray_Check(cmd)) {
636 str = PyByteArray_AS_STRING(cmd);
637 size = PyByteArray_GET_SIZE(cmd);
638 }
639 else if (PyObject_GetBuffer(cmd, &view, PyBUF_SIMPLE) == 0) {
640 /* Copy to NUL-terminated buffer. */
641 *cmd_copy = PyBytes_FromStringAndSize(
642 (const char *)view.buf, view.len);
643 PyBuffer_Release(&view);
644 if (*cmd_copy == NULL) {
645 return NULL;
646 }
647 str = PyBytes_AS_STRING(*cmd_copy);
648 size = PyBytes_GET_SIZE(*cmd_copy);
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +0200649 }
650 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000651 PyErr_Format(PyExc_TypeError,
652 "%s() arg 1 must be a %s object",
653 funcname, what);
654 return NULL;
655 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200656
Serhiy Storchaka3dd3e262015-02-03 01:25:42 +0200657 if (strlen(str) != (size_t)size) {
Serhiy Storchakad8a14472014-09-06 20:07:17 +0300658 PyErr_SetString(PyExc_ValueError,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000659 "source code string cannot contain null bytes");
Martin Pantereeb896c2015-11-07 02:32:21 +0000660 Py_CLEAR(*cmd_copy);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000661 return NULL;
662 }
663 return str;
Guido van Rossumf15a29f2007-05-04 00:41:39 +0000664}
665
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000666/*[clinic input]
667compile as builtin_compile
668
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300669 source: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000670 filename: object(converter="PyUnicode_FSDecoder")
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300671 mode: str
672 flags: int = 0
Serhiy Storchaka202fda52017-03-12 10:10:47 +0200673 dont_inherit: bool(accept={int}) = False
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300674 optimize: int = -1
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000675
676Compile source into a code object that can be executed by exec() or eval().
677
678The source code may represent a Python module, statement or expression.
679The filename will be used for run-time error messages.
680The mode must be 'exec' to compile a module, 'single' to compile a
681single (interactive) statement, or 'eval' to compile an expression.
682The flags argument, if present, controls which future statements influence
683the compilation of the code.
Serhiy Storchaka8b2e8b62015-05-30 11:30:39 +0300684The dont_inherit argument, if true, stops the compilation inheriting
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000685the effects of any future statements in effect in the code calling
Serhiy Storchaka8b2e8b62015-05-30 11:30:39 +0300686compile; if absent or false these statements do influence the compilation,
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000687in addition to any features explicitly specified.
688[clinic start generated code]*/
689
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000690static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300691builtin_compile_impl(PyObject *module, PyObject *source, PyObject *filename,
692 const char *mode, int flags, int dont_inherit,
693 int optimize)
Serhiy Storchaka202fda52017-03-12 10:10:47 +0200694/*[clinic end generated code: output=1fa176e33452bb63 input=0ff726f595eb9fcd]*/
Guido van Rossum5b722181993-03-30 17:46:03 +0000695{
Martin Panter61d6e4a2015-11-07 02:56:11 +0000696 PyObject *source_copy;
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +0200697 const char *str;
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000698 int compile_mode = -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000699 int is_ast;
700 PyCompilerFlags cf;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000701 int start[] = {Py_file_input, Py_eval_input, Py_single_input};
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000702 PyObject *result;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000703
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000704 cf.cf_flags = flags | PyCF_SOURCE_IS_UTF8;
Tim Peters6cd6a822001-08-17 22:11:27 +0000705
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000706 if (flags &
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000707 ~(PyCF_MASK | PyCF_MASK_OBSOLETE | PyCF_DONT_IMPLY_DEDENT | PyCF_ONLY_AST))
708 {
709 PyErr_SetString(PyExc_ValueError,
710 "compile(): unrecognised flags");
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000711 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000712 }
713 /* XXX Warn if (supplied_flags & PyCF_MASK_OBSOLETE) != 0? */
Tim Peters6cd6a822001-08-17 22:11:27 +0000714
Georg Brandl8334fd92010-12-04 10:26:46 +0000715 if (optimize < -1 || optimize > 2) {
716 PyErr_SetString(PyExc_ValueError,
717 "compile(): invalid optimize value");
718 goto error;
719 }
720
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000721 if (!dont_inherit) {
722 PyEval_MergeCompilerFlags(&cf);
723 }
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000724
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000725 if (strcmp(mode, "exec") == 0)
726 compile_mode = 0;
727 else if (strcmp(mode, "eval") == 0)
728 compile_mode = 1;
729 else if (strcmp(mode, "single") == 0)
730 compile_mode = 2;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000731 else {
732 PyErr_SetString(PyExc_ValueError,
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000733 "compile() mode must be 'exec', 'eval' or 'single'");
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000734 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000735 }
Neal Norwitzdb4115f2008-03-31 04:20:05 +0000736
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000737 is_ast = PyAST_Check(source);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000738 if (is_ast == -1)
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000739 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000740 if (is_ast) {
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000741 if (flags & PyCF_ONLY_AST) {
742 Py_INCREF(source);
743 result = source;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000744 }
745 else {
746 PyArena *arena;
747 mod_ty mod;
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000748
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000749 arena = PyArena_New();
Stefan Krah07795df2012-08-20 17:19:50 +0200750 if (arena == NULL)
751 goto error;
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000752 mod = PyAST_obj2mod(source, arena, compile_mode);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000753 if (mod == NULL) {
754 PyArena_Free(arena);
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000755 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000756 }
Benjamin Peterson832bfe22011-08-09 16:15:04 -0500757 if (!PyAST_Validate(mod)) {
758 PyArena_Free(arena);
759 goto error;
760 }
Victor Stinner14e461d2013-08-26 22:28:21 +0200761 result = (PyObject*)PyAST_CompileObject(mod, filename,
762 &cf, optimize, arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000763 PyArena_Free(arena);
764 }
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000765 goto finally;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000766 }
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000767
Martin Panter61d6e4a2015-11-07 02:56:11 +0000768 str = source_as_string(source, "compile", "string, bytes or AST", &cf, &source_copy);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000769 if (str == NULL)
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000770 goto error;
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000771
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000772 result = Py_CompileStringObject(str, filename, start[compile_mode], &cf, optimize);
Martin Panter61d6e4a2015-11-07 02:56:11 +0000773 Py_XDECREF(source_copy);
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000774 goto finally;
775
776error:
777 result = NULL;
778finally:
Victor Stinner14e461d2013-08-26 22:28:21 +0200779 Py_DECREF(filename);
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000780 return result;
Guido van Rossum5b722181993-03-30 17:46:03 +0000781}
782
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000783/* AC: cannot convert yet, as needs PEP 457 group support in inspect */
Guido van Rossum79f25d91997-04-29 20:08:16 +0000784static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000785builtin_dir(PyObject *self, PyObject *args)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000786{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000787 PyObject *arg = NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000788
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000789 if (!PyArg_UnpackTuple(args, "dir", 0, 1, &arg))
790 return NULL;
791 return PyObject_Dir(arg);
Guido van Rossum3f5da241990-12-20 15:06:42 +0000792}
793
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000794PyDoc_STRVAR(dir_doc,
Tim Peters5d2b77c2001-09-03 05:47:38 +0000795"dir([object]) -> list of strings\n"
796"\n"
Georg Brandle32b4222007-03-10 22:13:27 +0000797"If called without an argument, return the names in the current scope.\n"
798"Else, return an alphabetized list of names comprising (some of) the attributes\n"
799"of the given object, and of attributes reachable from it.\n"
800"If the object supplies a method named __dir__, it will be used; otherwise\n"
801"the default dir() logic is used and returns:\n"
802" for a module object: the module's attributes.\n"
803" for a class object: its attributes, and recursively the attributes\n"
804" of its bases.\n"
Guido van Rossumd8faa362007-04-27 19:54:29 +0000805" for any other object: its attributes, its class's attributes, and\n"
Georg Brandle32b4222007-03-10 22:13:27 +0000806" recursively the attributes of its class's base classes.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000807
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000808/*[clinic input]
809divmod as builtin_divmod
Guido van Rossum6a00cd81995-01-07 12:39:01 +0000810
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300811 x: object
812 y: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000813 /
814
Zachary Ware7f227d92016-04-28 14:39:50 -0500815Return the tuple (x//y, x%y). Invariant: div*y + mod == x.
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000816[clinic start generated code]*/
817
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000818static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300819builtin_divmod_impl(PyObject *module, PyObject *x, PyObject *y)
820/*[clinic end generated code: output=b06d8a5f6e0c745e input=175ad9c84ff41a85]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000821{
822 return PyNumber_Divmod(x, y);
823}
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000824
825
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000826/*[clinic input]
827eval as builtin_eval
828
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300829 source: object
830 globals: object = None
831 locals: object = None
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000832 /
833
834Evaluate the given source in the context of globals and locals.
835
836The source may be a string representing a Python expression
837or a code object as returned by compile().
838The globals must be a dictionary and locals can be any mapping,
839defaulting to the current globals and locals.
840If only globals is given, locals defaults to it.
841[clinic start generated code]*/
842
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000843static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300844builtin_eval_impl(PyObject *module, PyObject *source, PyObject *globals,
Larry Hastings89964c42015-04-14 18:07:59 -0400845 PyObject *locals)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300846/*[clinic end generated code: output=0a0824aa70093116 input=11ee718a8640e527]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000847{
Martin Panter61d6e4a2015-11-07 02:56:11 +0000848 PyObject *result, *source_copy;
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +0200849 const char *str;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000850 PyCompilerFlags cf;
Guido van Rossum590baa41993-11-30 13:40:46 +0000851
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000852 if (locals != Py_None && !PyMapping_Check(locals)) {
853 PyErr_SetString(PyExc_TypeError, "locals must be a mapping");
854 return NULL;
855 }
856 if (globals != Py_None && !PyDict_Check(globals)) {
857 PyErr_SetString(PyExc_TypeError, PyMapping_Check(globals) ?
858 "globals must be a real dict; try eval(expr, {}, mapping)"
859 : "globals must be a dict");
860 return NULL;
861 }
862 if (globals == Py_None) {
863 globals = PyEval_GetGlobals();
Victor Stinner41bb43a2013-10-29 01:19:37 +0100864 if (locals == Py_None) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000865 locals = PyEval_GetLocals();
Victor Stinner41bb43a2013-10-29 01:19:37 +0100866 if (locals == NULL)
867 return NULL;
868 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000869 }
870 else if (locals == Py_None)
871 locals = globals;
Tim Peters9fa96be2001-08-17 23:04:59 +0000872
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000873 if (globals == NULL || locals == NULL) {
874 PyErr_SetString(PyExc_TypeError,
875 "eval must be given globals and locals "
876 "when called without a frame");
877 return NULL;
878 }
Georg Brandl77c85e62005-09-15 10:46:13 +0000879
Victor Stinnerb44562b2013-11-06 19:03:11 +0100880 if (_PyDict_GetItemId(globals, &PyId___builtins__) == NULL) {
881 if (_PyDict_SetItemId(globals, &PyId___builtins__,
882 PyEval_GetBuiltins()) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000883 return NULL;
884 }
Tim Peters9fa96be2001-08-17 23:04:59 +0000885
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000886 if (PyCode_Check(source)) {
887 if (PyCode_GetNumFree((PyCodeObject *)source) > 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000888 PyErr_SetString(PyExc_TypeError,
889 "code object passed to eval() may not contain free variables");
890 return NULL;
891 }
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000892 return PyEval_EvalCode(source, globals, locals);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000893 }
Tim Peters9fa96be2001-08-17 23:04:59 +0000894
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000895 cf.cf_flags = PyCF_SOURCE_IS_UTF8;
Martin Panter61d6e4a2015-11-07 02:56:11 +0000896 str = source_as_string(source, "eval", "string, bytes or code", &cf, &source_copy);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000897 if (str == NULL)
898 return NULL;
Just van Rossum3aaf42c2003-02-10 08:21:10 +0000899
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000900 while (*str == ' ' || *str == '\t')
901 str++;
Tim Peters9fa96be2001-08-17 23:04:59 +0000902
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000903 (void)PyEval_MergeCompilerFlags(&cf);
904 result = PyRun_StringFlags(str, Py_eval_input, globals, locals, &cf);
Martin Panter61d6e4a2015-11-07 02:56:11 +0000905 Py_XDECREF(source_copy);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000906 return result;
Guido van Rossum3f5da241990-12-20 15:06:42 +0000907}
908
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000909/*[clinic input]
910exec as builtin_exec
911
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300912 source: object
913 globals: object = None
914 locals: object = None
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000915 /
916
917Execute the given source in the context of globals and locals.
918
919The source may be a string representing one or more Python statements
920or a code object as returned by compile().
921The globals must be a dictionary and locals can be any mapping,
922defaulting to the current globals and locals.
923If only globals is given, locals defaults to it.
924[clinic start generated code]*/
925
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000926static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300927builtin_exec_impl(PyObject *module, PyObject *source, PyObject *globals,
Larry Hastings89964c42015-04-14 18:07:59 -0400928 PyObject *locals)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300929/*[clinic end generated code: output=3c90efc6ab68ef5d input=01ca3e1c01692829]*/
Georg Brandl7cae87c2006-09-06 06:51:57 +0000930{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000931 PyObject *v;
Georg Brandl2cabc562008-08-28 07:57:16 +0000932
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000933 if (globals == Py_None) {
934 globals = PyEval_GetGlobals();
935 if (locals == Py_None) {
936 locals = PyEval_GetLocals();
Victor Stinner41bb43a2013-10-29 01:19:37 +0100937 if (locals == NULL)
938 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000939 }
940 if (!globals || !locals) {
941 PyErr_SetString(PyExc_SystemError,
942 "globals and locals cannot be NULL");
943 return NULL;
944 }
945 }
946 else if (locals == Py_None)
947 locals = globals;
Georg Brandl7cae87c2006-09-06 06:51:57 +0000948
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000949 if (!PyDict_Check(globals)) {
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000950 PyErr_Format(PyExc_TypeError, "exec() globals must be a dict, not %.100s",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000951 globals->ob_type->tp_name);
952 return NULL;
953 }
954 if (!PyMapping_Check(locals)) {
955 PyErr_Format(PyExc_TypeError,
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000956 "locals must be a mapping or None, not %.100s",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000957 locals->ob_type->tp_name);
958 return NULL;
959 }
Victor Stinnerb44562b2013-11-06 19:03:11 +0100960 if (_PyDict_GetItemId(globals, &PyId___builtins__) == NULL) {
961 if (_PyDict_SetItemId(globals, &PyId___builtins__,
962 PyEval_GetBuiltins()) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000963 return NULL;
964 }
965
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000966 if (PyCode_Check(source)) {
967 if (PyCode_GetNumFree((PyCodeObject *)source) > 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000968 PyErr_SetString(PyExc_TypeError,
969 "code object passed to exec() may not "
970 "contain free variables");
971 return NULL;
972 }
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000973 v = PyEval_EvalCode(source, globals, locals);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000974 }
975 else {
Martin Panter61d6e4a2015-11-07 02:56:11 +0000976 PyObject *source_copy;
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +0200977 const char *str;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000978 PyCompilerFlags cf;
979 cf.cf_flags = PyCF_SOURCE_IS_UTF8;
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000980 str = source_as_string(source, "exec",
Martin Panter61d6e4a2015-11-07 02:56:11 +0000981 "string, bytes or code", &cf,
982 &source_copy);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000983 if (str == NULL)
984 return NULL;
985 if (PyEval_MergeCompilerFlags(&cf))
986 v = PyRun_StringFlags(str, Py_file_input, globals,
987 locals, &cf);
988 else
989 v = PyRun_String(str, Py_file_input, globals, locals);
Martin Panter61d6e4a2015-11-07 02:56:11 +0000990 Py_XDECREF(source_copy);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000991 }
992 if (v == NULL)
993 return NULL;
994 Py_DECREF(v);
995 Py_RETURN_NONE;
Georg Brandl7cae87c2006-09-06 06:51:57 +0000996}
997
Georg Brandl7cae87c2006-09-06 06:51:57 +0000998
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000999/* AC: cannot convert yet, as needs PEP 457 group support in inspect */
Guido van Rossum79f25d91997-04-29 20:08:16 +00001000static PyObject *
Serhiy Storchaka6969eaf2017-07-03 21:20:15 +03001001builtin_getattr(PyObject *self, PyObject **args, Py_ssize_t nargs)
Guido van Rossum33894be1992-01-27 16:53:09 +00001002{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001003 PyObject *v, *result, *dflt = NULL;
1004 PyObject *name;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001005
Sylvain96c7c062017-06-15 17:05:23 +02001006 if (!_PyArg_UnpackStack(args, nargs, "getattr", 2, 3, &v, &name, &dflt))
1007 return NULL;
1008
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001009 if (!PyUnicode_Check(name)) {
1010 PyErr_SetString(PyExc_TypeError,
1011 "getattr(): attribute name must be string");
1012 return NULL;
1013 }
1014 result = PyObject_GetAttr(v, name);
1015 if (result == NULL && dflt != NULL &&
1016 PyErr_ExceptionMatches(PyExc_AttributeError))
1017 {
1018 PyErr_Clear();
1019 Py_INCREF(dflt);
1020 result = dflt;
1021 }
1022 return result;
Guido van Rossum9bfef441993-03-29 10:43:31 +00001023}
1024
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001025PyDoc_STRVAR(getattr_doc,
Guido van Rossum950ff291998-06-29 13:38:57 +00001026"getattr(object, name[, default]) -> value\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001027\n\
Guido van Rossum950ff291998-06-29 13:38:57 +00001028Get a named attribute from an object; getattr(x, 'y') is equivalent to x.y.\n\
1029When a default argument is given, it is returned when the attribute doesn't\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001030exist; without it, an exception is raised in that case.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001031
1032
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001033/*[clinic input]
1034globals as builtin_globals
1035
1036Return the dictionary containing the current scope's global variables.
1037
1038NOTE: Updates to this dictionary *will* affect name lookups in the current
1039global scope and vice-versa.
1040[clinic start generated code]*/
1041
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001042static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001043builtin_globals_impl(PyObject *module)
1044/*[clinic end generated code: output=e5dd1527067b94d2 input=9327576f92bb48ba]*/
Guido van Rossum872537c1995-07-07 22:43:42 +00001045{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001046 PyObject *d;
Guido van Rossum872537c1995-07-07 22:43:42 +00001047
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001048 d = PyEval_GetGlobals();
1049 Py_XINCREF(d);
1050 return d;
Guido van Rossum872537c1995-07-07 22:43:42 +00001051}
1052
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001053
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001054/*[clinic input]
1055hasattr as builtin_hasattr
1056
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001057 obj: object
1058 name: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001059 /
1060
1061Return whether the object has an attribute with the given name.
1062
1063This is done by calling getattr(obj, name) and catching AttributeError.
1064[clinic start generated code]*/
1065
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001066static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001067builtin_hasattr_impl(PyObject *module, PyObject *obj, PyObject *name)
1068/*[clinic end generated code: output=a7aff2090a4151e5 input=0faec9787d979542]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001069{
1070 PyObject *v;
1071
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001072 if (!PyUnicode_Check(name)) {
1073 PyErr_SetString(PyExc_TypeError,
1074 "hasattr(): attribute name must be string");
1075 return NULL;
1076 }
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001077 v = PyObject_GetAttr(obj, name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001078 if (v == NULL) {
Benjamin Peterson17689992010-08-24 03:26:23 +00001079 if (PyErr_ExceptionMatches(PyExc_AttributeError)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001080 PyErr_Clear();
Benjamin Peterson17689992010-08-24 03:26:23 +00001081 Py_RETURN_FALSE;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001082 }
Benjamin Peterson17689992010-08-24 03:26:23 +00001083 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001084 }
1085 Py_DECREF(v);
Benjamin Peterson17689992010-08-24 03:26:23 +00001086 Py_RETURN_TRUE;
Guido van Rossum33894be1992-01-27 16:53:09 +00001087}
1088
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001089
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001090/* AC: gdb's integration with CPython relies on builtin_id having
1091 * the *exact* parameter names of "self" and "v", so we ensure we
1092 * preserve those name rather than using the AC defaults.
1093 */
1094/*[clinic input]
1095id as builtin_id
1096
Serhiy Storchaka24182a32016-05-05 16:21:35 +03001097 self: self(type="PyModuleDef *")
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001098 obj as v: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001099 /
1100
1101Return the identity of an object.
1102
1103This is guaranteed to be unique among simultaneously existing objects.
1104(CPython uses the object's memory address.)
1105[clinic start generated code]*/
1106
Guido van Rossum79f25d91997-04-29 20:08:16 +00001107static PyObject *
Serhiy Storchaka24182a32016-05-05 16:21:35 +03001108builtin_id(PyModuleDef *self, PyObject *v)
1109/*[clinic end generated code: output=0aa640785f697f65 input=5a534136419631f4]*/
Guido van Rossum5b722181993-03-30 17:46:03 +00001110{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001111 return PyLong_FromVoidPtr(v);
Guido van Rossum5b722181993-03-30 17:46:03 +00001112}
1113
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001114
Raymond Hettingera6c60372008-03-13 01:26:19 +00001115/* map object ************************************************************/
1116
1117typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001118 PyObject_HEAD
1119 PyObject *iters;
1120 PyObject *func;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001121} mapobject;
1122
Guido van Rossum79f25d91997-04-29 20:08:16 +00001123static PyObject *
Raymond Hettingera6c60372008-03-13 01:26:19 +00001124map_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
Guido van Rossum12d12c51993-10-26 17:58:25 +00001125{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001126 PyObject *it, *iters, *func;
1127 mapobject *lz;
1128 Py_ssize_t numargs, i;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001129
Serhiy Storchaka6cca5c82017-06-08 14:41:19 +03001130 if (type == &PyMap_Type && !_PyArg_NoKeywords("map", kwds))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001131 return NULL;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001132
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001133 numargs = PyTuple_Size(args);
1134 if (numargs < 2) {
1135 PyErr_SetString(PyExc_TypeError,
1136 "map() must have at least two arguments.");
1137 return NULL;
1138 }
Raymond Hettingera6c60372008-03-13 01:26:19 +00001139
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001140 iters = PyTuple_New(numargs-1);
1141 if (iters == NULL)
1142 return NULL;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001143
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001144 for (i=1 ; i<numargs ; i++) {
1145 /* Get iterator. */
1146 it = PyObject_GetIter(PyTuple_GET_ITEM(args, i));
1147 if (it == NULL) {
1148 Py_DECREF(iters);
1149 return NULL;
1150 }
1151 PyTuple_SET_ITEM(iters, i-1, it);
1152 }
Raymond Hettingera6c60372008-03-13 01:26:19 +00001153
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001154 /* create mapobject structure */
1155 lz = (mapobject *)type->tp_alloc(type, 0);
1156 if (lz == NULL) {
1157 Py_DECREF(iters);
1158 return NULL;
1159 }
1160 lz->iters = iters;
1161 func = PyTuple_GET_ITEM(args, 0);
1162 Py_INCREF(func);
1163 lz->func = func;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001164
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001165 return (PyObject *)lz;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001166}
1167
1168static void
1169map_dealloc(mapobject *lz)
1170{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001171 PyObject_GC_UnTrack(lz);
1172 Py_XDECREF(lz->iters);
1173 Py_XDECREF(lz->func);
1174 Py_TYPE(lz)->tp_free(lz);
Raymond Hettingera6c60372008-03-13 01:26:19 +00001175}
1176
1177static int
1178map_traverse(mapobject *lz, visitproc visit, void *arg)
1179{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001180 Py_VISIT(lz->iters);
1181 Py_VISIT(lz->func);
1182 return 0;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001183}
1184
1185static PyObject *
1186map_next(mapobject *lz)
1187{
Victor Stinnerbc08ab42016-12-15 12:40:53 +01001188 PyObject *small_stack[_PY_FASTCALL_SMALL_STACK];
Victor Stinnercdb5cee2016-08-24 01:45:13 +02001189 PyObject **stack;
1190 Py_ssize_t niters, nargs, i;
1191 PyObject *result = NULL;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001192
Victor Stinnercdb5cee2016-08-24 01:45:13 +02001193 niters = PyTuple_GET_SIZE(lz->iters);
1194 if (niters <= (Py_ssize_t)Py_ARRAY_LENGTH(small_stack)) {
1195 stack = small_stack;
1196 }
1197 else {
1198 stack = PyMem_Malloc(niters * sizeof(stack[0]));
1199 if (stack == NULL) {
1200 PyErr_NoMemory();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001201 return NULL;
1202 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001203 }
Victor Stinnercdb5cee2016-08-24 01:45:13 +02001204
1205 nargs = 0;
1206 for (i=0; i < niters; i++) {
1207 PyObject *it = PyTuple_GET_ITEM(lz->iters, i);
1208 PyObject *val = Py_TYPE(it)->tp_iternext(it);
1209 if (val == NULL) {
1210 goto exit;
1211 }
1212 stack[i] = val;
1213 nargs++;
1214 }
1215
1216 result = _PyObject_FastCall(lz->func, stack, nargs);
1217
1218exit:
1219 for (i=0; i < nargs; i++) {
1220 Py_DECREF(stack[i]);
1221 }
1222 if (stack != small_stack) {
1223 PyMem_Free(stack);
1224 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001225 return result;
Guido van Rossum12d12c51993-10-26 17:58:25 +00001226}
1227
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001228static PyObject *
1229map_reduce(mapobject *lz)
1230{
1231 Py_ssize_t numargs = PyTuple_GET_SIZE(lz->iters);
1232 PyObject *args = PyTuple_New(numargs+1);
1233 Py_ssize_t i;
1234 if (args == NULL)
1235 return NULL;
1236 Py_INCREF(lz->func);
1237 PyTuple_SET_ITEM(args, 0, lz->func);
1238 for (i = 0; i<numargs; i++){
1239 PyObject *it = PyTuple_GET_ITEM(lz->iters, i);
1240 Py_INCREF(it);
1241 PyTuple_SET_ITEM(args, i+1, it);
1242 }
1243
1244 return Py_BuildValue("ON", Py_TYPE(lz), args);
1245}
1246
1247static PyMethodDef map_methods[] = {
1248 {"__reduce__", (PyCFunction)map_reduce, METH_NOARGS, reduce_doc},
1249 {NULL, NULL} /* sentinel */
1250};
1251
1252
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001253PyDoc_STRVAR(map_doc,
Raymond Hettingera6c60372008-03-13 01:26:19 +00001254"map(func, *iterables) --> map object\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001255\n\
Raymond Hettingera6c60372008-03-13 01:26:19 +00001256Make an iterator that computes the function using arguments from\n\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001257each of the iterables. Stops when the shortest iterable is exhausted.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001258
Raymond Hettingera6c60372008-03-13 01:26:19 +00001259PyTypeObject PyMap_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001260 PyVarObject_HEAD_INIT(&PyType_Type, 0)
1261 "map", /* tp_name */
1262 sizeof(mapobject), /* tp_basicsize */
1263 0, /* tp_itemsize */
1264 /* methods */
1265 (destructor)map_dealloc, /* tp_dealloc */
1266 0, /* tp_print */
1267 0, /* tp_getattr */
1268 0, /* tp_setattr */
1269 0, /* tp_reserved */
1270 0, /* tp_repr */
1271 0, /* tp_as_number */
1272 0, /* tp_as_sequence */
1273 0, /* tp_as_mapping */
1274 0, /* tp_hash */
1275 0, /* tp_call */
1276 0, /* tp_str */
1277 PyObject_GenericGetAttr, /* tp_getattro */
1278 0, /* tp_setattro */
1279 0, /* tp_as_buffer */
1280 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
1281 Py_TPFLAGS_BASETYPE, /* tp_flags */
1282 map_doc, /* tp_doc */
1283 (traverseproc)map_traverse, /* tp_traverse */
1284 0, /* tp_clear */
1285 0, /* tp_richcompare */
1286 0, /* tp_weaklistoffset */
1287 PyObject_SelfIter, /* tp_iter */
1288 (iternextfunc)map_next, /* tp_iternext */
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001289 map_methods, /* tp_methods */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001290 0, /* tp_members */
1291 0, /* tp_getset */
1292 0, /* tp_base */
1293 0, /* tp_dict */
1294 0, /* tp_descr_get */
1295 0, /* tp_descr_set */
1296 0, /* tp_dictoffset */
1297 0, /* tp_init */
1298 PyType_GenericAlloc, /* tp_alloc */
1299 map_new, /* tp_new */
1300 PyObject_GC_Del, /* tp_free */
Raymond Hettingera6c60372008-03-13 01:26:19 +00001301};
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001302
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001303
1304/* AC: cannot convert yet, as needs PEP 457 group support in inspect */
Guido van Rossum79f25d91997-04-29 20:08:16 +00001305static PyObject *
Serhiy Storchaka6969eaf2017-07-03 21:20:15 +03001306builtin_next(PyObject *self, PyObject **args, Py_ssize_t nargs)
Georg Brandla18af4e2007-04-21 15:47:16 +00001307{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001308 PyObject *it, *res;
1309 PyObject *def = NULL;
Georg Brandla18af4e2007-04-21 15:47:16 +00001310
Sylvain96c7c062017-06-15 17:05:23 +02001311 if (!_PyArg_UnpackStack(args, nargs, "next", 1, 2, &it, &def))
1312 return NULL;
1313
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001314 if (!PyIter_Check(it)) {
1315 PyErr_Format(PyExc_TypeError,
Philip Jenvey50add042011-11-06 16:37:52 -08001316 "'%.200s' object is not an iterator",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001317 it->ob_type->tp_name);
1318 return NULL;
1319 }
1320
1321 res = (*it->ob_type->tp_iternext)(it);
1322 if (res != NULL) {
1323 return res;
1324 } else if (def != NULL) {
1325 if (PyErr_Occurred()) {
1326 if(!PyErr_ExceptionMatches(PyExc_StopIteration))
1327 return NULL;
1328 PyErr_Clear();
1329 }
1330 Py_INCREF(def);
1331 return def;
1332 } else if (PyErr_Occurred()) {
1333 return NULL;
1334 } else {
1335 PyErr_SetNone(PyExc_StopIteration);
1336 return NULL;
1337 }
Georg Brandla18af4e2007-04-21 15:47:16 +00001338}
1339
1340PyDoc_STRVAR(next_doc,
1341"next(iterator[, default])\n\
1342\n\
1343Return the next item from the iterator. If default is given and the iterator\n\
1344is exhausted, it is returned instead of raising StopIteration.");
1345
1346
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001347/*[clinic input]
1348setattr as builtin_setattr
1349
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001350 obj: object
1351 name: object
1352 value: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001353 /
1354
1355Sets the named attribute on the given object to the specified value.
1356
1357setattr(x, 'y', v) is equivalent to ``x.y = v''
1358[clinic start generated code]*/
1359
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001360static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001361builtin_setattr_impl(PyObject *module, PyObject *obj, PyObject *name,
Larry Hastings89964c42015-04-14 18:07:59 -04001362 PyObject *value)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001363/*[clinic end generated code: output=dc2ce1d1add9acb4 input=bd2b7ca6875a1899]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001364{
1365 if (PyObject_SetAttr(obj, name, value) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001366 return NULL;
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02001367 Py_RETURN_NONE;
Guido van Rossum33894be1992-01-27 16:53:09 +00001368}
1369
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001370
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001371/*[clinic input]
1372delattr as builtin_delattr
1373
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001374 obj: object
1375 name: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001376 /
1377
1378Deletes the named attribute from the given object.
1379
1380delattr(x, 'y') is equivalent to ``del x.y''
1381[clinic start generated code]*/
1382
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001383static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001384builtin_delattr_impl(PyObject *module, PyObject *obj, PyObject *name)
1385/*[clinic end generated code: output=85134bc58dff79fa input=db16685d6b4b9410]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001386{
1387 if (PyObject_SetAttr(obj, name, (PyObject *)NULL) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001388 return NULL;
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02001389 Py_RETURN_NONE;
Guido van Rossum14144fc1994-08-29 12:53:40 +00001390}
1391
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001392
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001393/*[clinic input]
1394hash as builtin_hash
1395
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001396 obj: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001397 /
1398
1399Return the hash value for the given object.
1400
1401Two objects that compare equal must also have the same hash value, but the
1402reverse is not necessarily true.
1403[clinic start generated code]*/
1404
Guido van Rossum79f25d91997-04-29 20:08:16 +00001405static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001406builtin_hash(PyObject *module, PyObject *obj)
1407/*[clinic end generated code: output=237668e9d7688db7 input=58c48be822bf9c54]*/
Guido van Rossum9bfef441993-03-29 10:43:31 +00001408{
Benjamin Peterson8f67d082010-10-17 20:54:53 +00001409 Py_hash_t x;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001410
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001411 x = PyObject_Hash(obj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001412 if (x == -1)
1413 return NULL;
Benjamin Peterson8f67d082010-10-17 20:54:53 +00001414 return PyLong_FromSsize_t(x);
Guido van Rossum9bfef441993-03-29 10:43:31 +00001415}
1416
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001417
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001418/*[clinic input]
1419hex as builtin_hex
1420
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001421 number: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001422 /
1423
1424Return the hexadecimal representation of an integer.
1425
1426 >>> hex(12648430)
1427 '0xc0ffee'
1428[clinic start generated code]*/
1429
Guido van Rossum79f25d91997-04-29 20:08:16 +00001430static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001431builtin_hex(PyObject *module, PyObject *number)
1432/*[clinic end generated code: output=e46b612169099408 input=e645aff5fc7d540e]*/
Guido van Rossum006bcd41991-10-24 14:54:44 +00001433{
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001434 return PyNumber_ToBase(number, 16);
Guido van Rossum006bcd41991-10-24 14:54:44 +00001435}
1436
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001437
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001438/* AC: cannot convert yet, as needs PEP 457 group support in inspect */
Guido van Rossum79f25d91997-04-29 20:08:16 +00001439static PyObject *
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001440builtin_iter(PyObject *self, PyObject *args)
1441{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001442 PyObject *v, *w = NULL;
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001443
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001444 if (!PyArg_UnpackTuple(args, "iter", 1, 2, &v, &w))
1445 return NULL;
1446 if (w == NULL)
1447 return PyObject_GetIter(v);
1448 if (!PyCallable_Check(v)) {
1449 PyErr_SetString(PyExc_TypeError,
1450 "iter(v, w): v must be callable");
1451 return NULL;
1452 }
1453 return PyCallIter_New(v, w);
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001454}
1455
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001456PyDoc_STRVAR(iter_doc,
Georg Brandld11ae5d2008-05-16 13:27:32 +00001457"iter(iterable) -> iterator\n\
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001458iter(callable, sentinel) -> iterator\n\
1459\n\
1460Get an iterator from an object. In the first form, the argument must\n\
1461supply its own iterator, or be a sequence.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001462In the second form, the callable is called until it returns the sentinel.");
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001463
1464
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001465/*[clinic input]
1466len as builtin_len
1467
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001468 obj: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001469 /
1470
1471Return the number of items in a container.
1472[clinic start generated code]*/
1473
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001474static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001475builtin_len(PyObject *module, PyObject *obj)
1476/*[clinic end generated code: output=fa7a270d314dfb6c input=bc55598da9e9c9b5]*/
Guido van Rossum3f5da241990-12-20 15:06:42 +00001477{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001478 Py_ssize_t res;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001479
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001480 res = PyObject_Size(obj);
Serhiy Storchaka813f9432017-04-16 09:21:44 +03001481 if (res < 0) {
1482 assert(PyErr_Occurred());
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001483 return NULL;
Serhiy Storchaka813f9432017-04-16 09:21:44 +03001484 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001485 return PyLong_FromSsize_t(res);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001486}
1487
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001488
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001489/*[clinic input]
1490locals as builtin_locals
1491
1492Return a dictionary containing the current scope's local variables.
1493
1494NOTE: Whether or not updates to this dictionary will affect name lookups in
1495the local scope and vice-versa is *implementation dependent* and not
1496covered by any backwards compatibility guarantees.
1497[clinic start generated code]*/
1498
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001499static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001500builtin_locals_impl(PyObject *module)
1501/*[clinic end generated code: output=b46c94015ce11448 input=7874018d478d5c4b]*/
Guido van Rossum872537c1995-07-07 22:43:42 +00001502{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001503 PyObject *d;
Guido van Rossum872537c1995-07-07 22:43:42 +00001504
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001505 d = PyEval_GetLocals();
1506 Py_XINCREF(d);
1507 return d;
Guido van Rossum872537c1995-07-07 22:43:42 +00001508}
1509
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001510
Guido van Rossum79f25d91997-04-29 20:08:16 +00001511static PyObject *
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001512min_max(PyObject *args, PyObject *kwds, int op)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001513{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001514 PyObject *v, *it, *item, *val, *maxitem, *maxval, *keyfunc=NULL;
Raymond Hettinger4d6018f2013-06-24 22:43:02 -07001515 PyObject *emptytuple, *defaultval = NULL;
1516 static char *kwlist[] = {"key", "default", NULL};
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001517 const char *name = op == Py_LT ? "min" : "max";
Raymond Hettinger4d6018f2013-06-24 22:43:02 -07001518 const int positional = PyTuple_Size(args) > 1;
1519 int ret;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001520
Raymond Hettinger4d6018f2013-06-24 22:43:02 -07001521 if (positional)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001522 v = args;
Serhiy Storchakac6792272013-10-19 21:03:34 +03001523 else if (!PyArg_UnpackTuple(args, name, 1, 1, &v))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001524 return NULL;
Tim Peters67d687a2002-04-29 21:27:32 +00001525
Raymond Hettinger4d6018f2013-06-24 22:43:02 -07001526 emptytuple = PyTuple_New(0);
1527 if (emptytuple == NULL)
1528 return NULL;
Oren Milman58cf7482017-08-21 20:19:07 +03001529 ret = PyArg_ParseTupleAndKeywords(emptytuple, kwds,
1530 (op == Py_LT) ? "|$OO:min" : "|$OO:max",
1531 kwlist, &keyfunc, &defaultval);
Raymond Hettinger4d6018f2013-06-24 22:43:02 -07001532 Py_DECREF(emptytuple);
1533 if (!ret)
1534 return NULL;
1535
1536 if (positional && defaultval != NULL) {
1537 PyErr_Format(PyExc_TypeError,
1538 "Cannot specify a default for %s() with multiple "
1539 "positional arguments", name);
1540 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001541 }
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001542
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001543 it = PyObject_GetIter(v);
1544 if (it == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001545 return NULL;
1546 }
Tim Petersc3074532001-05-03 07:00:32 +00001547
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001548 maxitem = NULL; /* the result */
1549 maxval = NULL; /* the value associated with the result */
1550 while (( item = PyIter_Next(it) )) {
1551 /* get the value from the key function */
1552 if (keyfunc != NULL) {
Victor Stinnerde4ae3d2016-12-04 22:59:09 +01001553 val = PyObject_CallFunctionObjArgs(keyfunc, item, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001554 if (val == NULL)
1555 goto Fail_it_item;
1556 }
1557 /* no key function; the value is the item */
1558 else {
1559 val = item;
1560 Py_INCREF(val);
1561 }
Tim Petersc3074532001-05-03 07:00:32 +00001562
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001563 /* maximum value and item are unset; set them */
1564 if (maxval == NULL) {
1565 maxitem = item;
1566 maxval = val;
1567 }
1568 /* maximum value and item are set; update them as necessary */
1569 else {
1570 int cmp = PyObject_RichCompareBool(val, maxval, op);
1571 if (cmp < 0)
1572 goto Fail_it_item_and_val;
1573 else if (cmp > 0) {
1574 Py_DECREF(maxval);
1575 Py_DECREF(maxitem);
1576 maxval = val;
1577 maxitem = item;
1578 }
1579 else {
1580 Py_DECREF(item);
1581 Py_DECREF(val);
1582 }
1583 }
1584 }
1585 if (PyErr_Occurred())
1586 goto Fail_it;
1587 if (maxval == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001588 assert(maxitem == NULL);
Raymond Hettinger4d6018f2013-06-24 22:43:02 -07001589 if (defaultval != NULL) {
1590 Py_INCREF(defaultval);
1591 maxitem = defaultval;
1592 } else {
1593 PyErr_Format(PyExc_ValueError,
1594 "%s() arg is an empty sequence", name);
1595 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001596 }
1597 else
1598 Py_DECREF(maxval);
1599 Py_DECREF(it);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001600 return maxitem;
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001601
1602Fail_it_item_and_val:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001603 Py_DECREF(val);
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001604Fail_it_item:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001605 Py_DECREF(item);
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001606Fail_it:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001607 Py_XDECREF(maxval);
1608 Py_XDECREF(maxitem);
1609 Py_DECREF(it);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001610 return NULL;
Guido van Rossum3f5da241990-12-20 15:06:42 +00001611}
1612
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001613/* AC: cannot convert yet, waiting for *args support */
Guido van Rossum79f25d91997-04-29 20:08:16 +00001614static PyObject *
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001615builtin_min(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001616{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001617 return min_max(args, kwds, Py_LT);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001618}
1619
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001620PyDoc_STRVAR(min_doc,
Raymond Hettinger2a545822014-05-19 22:20:52 +01001621"min(iterable, *[, default=obj, key=func]) -> value\n\
1622min(arg1, arg2, *args, *[, key=func]) -> value\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001623\n\
Raymond Hettinger2a545822014-05-19 22:20:52 +01001624With a single iterable argument, return its smallest item. The\n\
1625default keyword-only argument specifies an object to return if\n\
1626the provided iterable is empty.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001627With two or more arguments, return the smallest argument.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001628
1629
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001630/* AC: cannot convert yet, waiting for *args support */
Guido van Rossum79f25d91997-04-29 20:08:16 +00001631static PyObject *
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001632builtin_max(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001633{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001634 return min_max(args, kwds, Py_GT);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001635}
1636
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001637PyDoc_STRVAR(max_doc,
Raymond Hettinger2a545822014-05-19 22:20:52 +01001638"max(iterable, *[, default=obj, key=func]) -> value\n\
1639max(arg1, arg2, *args, *[, key=func]) -> value\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001640\n\
Raymond Hettinger2a545822014-05-19 22:20:52 +01001641With a single iterable argument, return its biggest item. The\n\
1642default keyword-only argument specifies an object to return if\n\
1643the provided iterable is empty.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001644With two or more arguments, return the largest argument.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001645
1646
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001647/*[clinic input]
1648oct as builtin_oct
1649
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001650 number: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001651 /
1652
1653Return the octal representation of an integer.
1654
1655 >>> oct(342391)
1656 '0o1234567'
1657[clinic start generated code]*/
1658
Guido van Rossum79f25d91997-04-29 20:08:16 +00001659static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001660builtin_oct(PyObject *module, PyObject *number)
1661/*[clinic end generated code: output=40a34656b6875352 input=ad6b274af4016c72]*/
Guido van Rossum006bcd41991-10-24 14:54:44 +00001662{
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001663 return PyNumber_ToBase(number, 8);
Guido van Rossum006bcd41991-10-24 14:54:44 +00001664}
1665
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001666
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001667/*[clinic input]
1668ord as builtin_ord
1669
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001670 c: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001671 /
1672
1673Return the Unicode code point for a one-character string.
1674[clinic start generated code]*/
1675
Guido van Rossum79f25d91997-04-29 20:08:16 +00001676static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001677builtin_ord(PyObject *module, PyObject *c)
1678/*[clinic end generated code: output=4fa5e87a323bae71 input=3064e5d6203ad012]*/
Guido van Rossum3f5da241990-12-20 15:06:42 +00001679{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001680 long ord;
1681 Py_ssize_t size;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001682
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001683 if (PyBytes_Check(c)) {
1684 size = PyBytes_GET_SIZE(c);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001685 if (size == 1) {
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001686 ord = (long)((unsigned char)*PyBytes_AS_STRING(c));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001687 return PyLong_FromLong(ord);
1688 }
1689 }
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001690 else if (PyUnicode_Check(c)) {
1691 if (PyUnicode_READY(c) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001692 return NULL;
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001693 size = PyUnicode_GET_LENGTH(c);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001694 if (size == 1) {
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001695 ord = (long)PyUnicode_READ_CHAR(c, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001696 return PyLong_FromLong(ord);
1697 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001698 }
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001699 else if (PyByteArray_Check(c)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001700 /* XXX Hopefully this is temporary */
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001701 size = PyByteArray_GET_SIZE(c);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001702 if (size == 1) {
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001703 ord = (long)((unsigned char)*PyByteArray_AS_STRING(c));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001704 return PyLong_FromLong(ord);
1705 }
1706 }
1707 else {
1708 PyErr_Format(PyExc_TypeError,
1709 "ord() expected string of length 1, but " \
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001710 "%.200s found", c->ob_type->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001711 return NULL;
1712 }
Guido van Rossum09095f32000-03-10 23:00:52 +00001713
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001714 PyErr_Format(PyExc_TypeError,
1715 "ord() expected a character, "
1716 "but string of length %zd found",
1717 size);
1718 return NULL;
Guido van Rossum3f5da241990-12-20 15:06:42 +00001719}
1720
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001721
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001722/*[clinic input]
1723pow as builtin_pow
1724
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001725 x: object
1726 y: object
1727 z: object = None
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001728 /
1729
1730Equivalent to x**y (with two arguments) or x**y % z (with three arguments)
1731
1732Some types, such as ints, are able to use a more efficient algorithm when
1733invoked using the three argument form.
1734[clinic start generated code]*/
1735
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001736static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001737builtin_pow_impl(PyObject *module, PyObject *x, PyObject *y, PyObject *z)
1738/*[clinic end generated code: output=50a14d5d130d404b input=653d57d38d41fc07]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001739{
1740 return PyNumber_Power(x, y, z);
1741}
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001742
1743
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001744/* AC: cannot convert yet, waiting for *args support */
Guido van Rossum34343512006-11-30 22:13:52 +00001745static PyObject *
INADA Naokibd584f12017-01-19 12:50:34 +01001746builtin_print(PyObject *self, PyObject **args, Py_ssize_t nargs, PyObject *kwnames)
Guido van Rossum34343512006-11-30 22:13:52 +00001747{
INADA Naokibd584f12017-01-19 12:50:34 +01001748 static const char * const _keywords[] = {"sep", "end", "file", "flush", 0};
1749 static struct _PyArg_Parser _parser = {"|OOOO:print", _keywords, 0};
Georg Brandlbc3b6822012-01-13 19:41:25 +01001750 PyObject *sep = NULL, *end = NULL, *file = NULL, *flush = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001751 int i, err;
Guido van Rossum34343512006-11-30 22:13:52 +00001752
INADA Naokibd584f12017-01-19 12:50:34 +01001753 if (kwnames != NULL &&
1754 !_PyArg_ParseStackAndKeywords(args + nargs, 0, kwnames, &_parser,
1755 &sep, &end, &file, &flush)) {
Georg Brandlbc3b6822012-01-13 19:41:25 +01001756 return NULL;
INADA Naokibd584f12017-01-19 12:50:34 +01001757 }
1758
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001759 if (file == NULL || file == Py_None) {
Victor Stinnerbd303c12013-11-07 23:07:29 +01001760 file = _PySys_GetObjectId(&PyId_stdout);
Victor Stinner1e53bba2013-07-16 22:26:05 +02001761 if (file == NULL) {
1762 PyErr_SetString(PyExc_RuntimeError, "lost sys.stdout");
1763 return NULL;
1764 }
1765
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001766 /* sys.stdout may be None when FILE* stdout isn't connected */
1767 if (file == Py_None)
1768 Py_RETURN_NONE;
1769 }
Guido van Rossum34343512006-11-30 22:13:52 +00001770
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001771 if (sep == Py_None) {
1772 sep = NULL;
1773 }
1774 else if (sep && !PyUnicode_Check(sep)) {
1775 PyErr_Format(PyExc_TypeError,
1776 "sep must be None or a string, not %.200s",
1777 sep->ob_type->tp_name);
1778 return NULL;
1779 }
1780 if (end == Py_None) {
1781 end = NULL;
1782 }
1783 else if (end && !PyUnicode_Check(end)) {
1784 PyErr_Format(PyExc_TypeError,
1785 "end must be None or a string, not %.200s",
1786 end->ob_type->tp_name);
1787 return NULL;
1788 }
Guido van Rossum34343512006-11-30 22:13:52 +00001789
INADA Naokibd584f12017-01-19 12:50:34 +01001790 for (i = 0; i < nargs; i++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001791 if (i > 0) {
1792 if (sep == NULL)
1793 err = PyFile_WriteString(" ", file);
1794 else
1795 err = PyFile_WriteObject(sep, file,
1796 Py_PRINT_RAW);
1797 if (err)
1798 return NULL;
1799 }
INADA Naokibd584f12017-01-19 12:50:34 +01001800 err = PyFile_WriteObject(args[i], file, Py_PRINT_RAW);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001801 if (err)
1802 return NULL;
1803 }
Guido van Rossum34343512006-11-30 22:13:52 +00001804
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001805 if (end == NULL)
1806 err = PyFile_WriteString("\n", file);
1807 else
1808 err = PyFile_WriteObject(end, file, Py_PRINT_RAW);
1809 if (err)
1810 return NULL;
Guido van Rossum34343512006-11-30 22:13:52 +00001811
Georg Brandlbc3b6822012-01-13 19:41:25 +01001812 if (flush != NULL) {
1813 PyObject *tmp;
1814 int do_flush = PyObject_IsTrue(flush);
1815 if (do_flush == -1)
1816 return NULL;
1817 else if (do_flush) {
Victor Stinner3466bde2016-09-05 18:16:01 -07001818 tmp = _PyObject_CallMethodId(file, &PyId_flush, NULL);
Georg Brandlbc3b6822012-01-13 19:41:25 +01001819 if (tmp == NULL)
1820 return NULL;
1821 else
1822 Py_DECREF(tmp);
1823 }
1824 }
1825
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001826 Py_RETURN_NONE;
Guido van Rossum34343512006-11-30 22:13:52 +00001827}
1828
1829PyDoc_STRVAR(print_doc,
Senthil Kumarane9175bd2012-08-10 13:53:45 -07001830"print(value, ..., sep=' ', end='\\n', file=sys.stdout, flush=False)\n\
Guido van Rossum34343512006-11-30 22:13:52 +00001831\n\
1832Prints the values to a stream, or to sys.stdout by default.\n\
1833Optional keyword arguments:\n\
Senthil Kumarane9175bd2012-08-10 13:53:45 -07001834file: a file-like object (stream); defaults to the current sys.stdout.\n\
1835sep: string inserted between values, default a space.\n\
1836end: string appended after the last value, default a newline.\n\
1837flush: whether to forcibly flush the stream.");
Guido van Rossum34343512006-11-30 22:13:52 +00001838
1839
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001840/*[clinic input]
1841input as builtin_input
1842
1843 prompt: object(c_default="NULL") = None
1844 /
1845
1846Read a string from standard input. The trailing newline is stripped.
1847
1848The prompt string, if given, is printed to standard output without a
1849trailing newline before reading input.
1850
1851If the user hits EOF (*nix: Ctrl-D, Windows: Ctrl-Z+Return), raise EOFError.
1852On *nix systems, readline is used if available.
1853[clinic start generated code]*/
1854
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001855static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001856builtin_input_impl(PyObject *module, PyObject *prompt)
1857/*[clinic end generated code: output=83db5a191e7a0d60 input=5e8bb70c2908fe3c]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001858{
Victor Stinnerbd303c12013-11-07 23:07:29 +01001859 PyObject *fin = _PySys_GetObjectId(&PyId_stdin);
1860 PyObject *fout = _PySys_GetObjectId(&PyId_stdout);
1861 PyObject *ferr = _PySys_GetObjectId(&PyId_stderr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001862 PyObject *tmp;
1863 long fd;
1864 int tty;
Guido van Rossuma88a0332007-02-26 16:59:55 +00001865
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001866 /* Check that stdin/out/err are intact */
1867 if (fin == NULL || fin == Py_None) {
1868 PyErr_SetString(PyExc_RuntimeError,
1869 "input(): lost sys.stdin");
1870 return NULL;
1871 }
1872 if (fout == NULL || fout == Py_None) {
1873 PyErr_SetString(PyExc_RuntimeError,
1874 "input(): lost sys.stdout");
1875 return NULL;
1876 }
1877 if (ferr == NULL || ferr == Py_None) {
1878 PyErr_SetString(PyExc_RuntimeError,
1879 "input(): lost sys.stderr");
1880 return NULL;
1881 }
Guido van Rossumeba76962007-05-27 09:13:28 +00001882
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001883 /* First of all, flush stderr */
Victor Stinner3466bde2016-09-05 18:16:01 -07001884 tmp = _PyObject_CallMethodId(ferr, &PyId_flush, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001885 if (tmp == NULL)
1886 PyErr_Clear();
1887 else
1888 Py_DECREF(tmp);
Guido van Rossumeba76962007-05-27 09:13:28 +00001889
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001890 /* We should only use (GNU) readline if Python's sys.stdin and
1891 sys.stdout are the same as C's stdin and stdout, because we
1892 need to pass it those. */
Victor Stinner3466bde2016-09-05 18:16:01 -07001893 tmp = _PyObject_CallMethodId(fin, &PyId_fileno, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001894 if (tmp == NULL) {
1895 PyErr_Clear();
1896 tty = 0;
1897 }
1898 else {
1899 fd = PyLong_AsLong(tmp);
1900 Py_DECREF(tmp);
1901 if (fd < 0 && PyErr_Occurred())
1902 return NULL;
1903 tty = fd == fileno(stdin) && isatty(fd);
1904 }
1905 if (tty) {
Victor Stinner3466bde2016-09-05 18:16:01 -07001906 tmp = _PyObject_CallMethodId(fout, &PyId_fileno, NULL);
Martin Panterc9a6ab52015-10-10 01:25:38 +00001907 if (tmp == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001908 PyErr_Clear();
Martin Panterc9a6ab52015-10-10 01:25:38 +00001909 tty = 0;
1910 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001911 else {
1912 fd = PyLong_AsLong(tmp);
1913 Py_DECREF(tmp);
1914 if (fd < 0 && PyErr_Occurred())
1915 return NULL;
1916 tty = fd == fileno(stdout) && isatty(fd);
1917 }
1918 }
Guido van Rossumeba76962007-05-27 09:13:28 +00001919
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001920 /* If we're interactive, use (GNU) readline */
1921 if (tty) {
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001922 PyObject *po = NULL;
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001923 char *promptstr;
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001924 char *s = NULL;
1925 PyObject *stdin_encoding = NULL, *stdin_errors = NULL;
1926 PyObject *stdout_encoding = NULL, *stdout_errors = NULL;
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +02001927 const char *stdin_encoding_str, *stdin_errors_str;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001928 PyObject *result;
Victor Stinnerc0f1a1a2011-02-23 12:07:37 +00001929 size_t len;
Martin v. Löwis4a7b5d52007-09-04 05:24:49 +00001930
Serhiy Storchakac2cf1282017-03-12 13:50:36 +02001931 /* stdin is a text stream, so it must have an encoding. */
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02001932 stdin_encoding = _PyObject_GetAttrId(fin, &PyId_encoding);
Antoine Pitrou5ee9d8a2011-11-06 00:38:45 +01001933 stdin_errors = _PyObject_GetAttrId(fin, &PyId_errors);
Serhiy Storchakac2cf1282017-03-12 13:50:36 +02001934 if (!stdin_encoding || !stdin_errors ||
1935 !PyUnicode_Check(stdin_encoding) ||
1936 !PyUnicode_Check(stdin_errors)) {
1937 tty = 0;
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001938 goto _readline_errors;
Serhiy Storchakac2cf1282017-03-12 13:50:36 +02001939 }
Serhiy Storchaka06515832016-11-20 09:13:07 +02001940 stdin_encoding_str = PyUnicode_AsUTF8(stdin_encoding);
1941 stdin_errors_str = PyUnicode_AsUTF8(stdin_errors);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001942 if (!stdin_encoding_str || !stdin_errors_str)
1943 goto _readline_errors;
Victor Stinner3466bde2016-09-05 18:16:01 -07001944 tmp = _PyObject_CallMethodId(fout, &PyId_flush, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001945 if (tmp == NULL)
1946 PyErr_Clear();
1947 else
1948 Py_DECREF(tmp);
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001949 if (prompt != NULL) {
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001950 /* We have a prompt, encode it as stdout would */
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +02001951 const char *stdout_encoding_str, *stdout_errors_str;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001952 PyObject *stringpo;
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02001953 stdout_encoding = _PyObject_GetAttrId(fout, &PyId_encoding);
Antoine Pitrou5ee9d8a2011-11-06 00:38:45 +01001954 stdout_errors = _PyObject_GetAttrId(fout, &PyId_errors);
Serhiy Storchakac2cf1282017-03-12 13:50:36 +02001955 if (!stdout_encoding || !stdout_errors ||
1956 !PyUnicode_Check(stdout_encoding) ||
1957 !PyUnicode_Check(stdout_errors)) {
1958 tty = 0;
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001959 goto _readline_errors;
Serhiy Storchakac2cf1282017-03-12 13:50:36 +02001960 }
Serhiy Storchaka06515832016-11-20 09:13:07 +02001961 stdout_encoding_str = PyUnicode_AsUTF8(stdout_encoding);
1962 stdout_errors_str = PyUnicode_AsUTF8(stdout_errors);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001963 if (!stdout_encoding_str || !stdout_errors_str)
1964 goto _readline_errors;
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001965 stringpo = PyObject_Str(prompt);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001966 if (stringpo == NULL)
1967 goto _readline_errors;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001968 po = PyUnicode_AsEncodedString(stringpo,
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001969 stdout_encoding_str, stdout_errors_str);
1970 Py_CLEAR(stdout_encoding);
1971 Py_CLEAR(stdout_errors);
1972 Py_CLEAR(stringpo);
1973 if (po == NULL)
1974 goto _readline_errors;
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03001975 assert(PyBytes_Check(po));
1976 promptstr = PyBytes_AS_STRING(po);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001977 }
1978 else {
1979 po = NULL;
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001980 promptstr = "";
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001981 }
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001982 s = PyOS_Readline(stdin, stdout, promptstr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001983 if (s == NULL) {
Richard Oudkerk614c5782013-04-03 13:44:50 +01001984 PyErr_CheckSignals();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001985 if (!PyErr_Occurred())
1986 PyErr_SetNone(PyExc_KeyboardInterrupt);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001987 goto _readline_errors;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001988 }
Victor Stinnerc0f1a1a2011-02-23 12:07:37 +00001989
1990 len = strlen(s);
1991 if (len == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001992 PyErr_SetNone(PyExc_EOFError);
1993 result = NULL;
1994 }
Victor Stinnerc0f1a1a2011-02-23 12:07:37 +00001995 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001996 if (len > PY_SSIZE_T_MAX) {
1997 PyErr_SetString(PyExc_OverflowError,
1998 "input: input too long");
1999 result = NULL;
2000 }
2001 else {
Victor Stinnerc0f1a1a2011-02-23 12:07:37 +00002002 len--; /* strip trailing '\n' */
2003 if (len != 0 && s[len-1] == '\r')
2004 len--; /* strip trailing '\r' */
Antoine Pitrou0d776b12011-11-06 00:34:26 +01002005 result = PyUnicode_Decode(s, len, stdin_encoding_str,
2006 stdin_errors_str);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002007 }
2008 }
2009 Py_DECREF(stdin_encoding);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01002010 Py_DECREF(stdin_errors);
2011 Py_XDECREF(po);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002012 PyMem_FREE(s);
2013 return result;
Serhiy Storchakac2cf1282017-03-12 13:50:36 +02002014
Antoine Pitrou0d776b12011-11-06 00:34:26 +01002015 _readline_errors:
2016 Py_XDECREF(stdin_encoding);
2017 Py_XDECREF(stdout_encoding);
2018 Py_XDECREF(stdin_errors);
2019 Py_XDECREF(stdout_errors);
2020 Py_XDECREF(po);
Serhiy Storchakac2cf1282017-03-12 13:50:36 +02002021 if (tty)
2022 return NULL;
2023
2024 PyErr_Clear();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002025 }
Guido van Rossumeba76962007-05-27 09:13:28 +00002026
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002027 /* Fallback if we're not interactive */
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002028 if (prompt != NULL) {
2029 if (PyFile_WriteObject(prompt, fout, Py_PRINT_RAW) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002030 return NULL;
2031 }
Victor Stinner3466bde2016-09-05 18:16:01 -07002032 tmp = _PyObject_CallMethodId(fout, &PyId_flush, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002033 if (tmp == NULL)
2034 PyErr_Clear();
2035 else
2036 Py_DECREF(tmp);
2037 return PyFile_GetLine(fin, -1);
Guido van Rossuma88a0332007-02-26 16:59:55 +00002038}
2039
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002040
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002041/*[clinic input]
2042repr as builtin_repr
2043
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03002044 obj: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002045 /
2046
2047Return the canonical string representation of the object.
2048
2049For many object types, including most builtins, eval(repr(obj)) == obj.
2050[clinic start generated code]*/
2051
Guido van Rossum79f25d91997-04-29 20:08:16 +00002052static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002053builtin_repr(PyObject *module, PyObject *obj)
2054/*[clinic end generated code: output=7ed3778c44fd0194 input=1c9e6d66d3e3be04]*/
Guido van Rossumc89705d1992-11-26 08:54:07 +00002055{
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002056 return PyObject_Repr(obj);
Guido van Rossumc89705d1992-11-26 08:54:07 +00002057}
2058
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002059
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002060/* AC: cannot convert yet, as needs PEP 457 group support in inspect
2061 * or a semantic change to accept None for "ndigits"
2062 */
Guido van Rossum79f25d91997-04-29 20:08:16 +00002063static PyObject *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002064builtin_round(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum9e51f9b1993-02-12 16:29:05 +00002065{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002066 PyObject *ndigits = NULL;
2067 static char *kwlist[] = {"number", "ndigits", 0};
Benjamin Peterson214a7d22013-04-13 17:19:01 -04002068 PyObject *number, *round, *result;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002069
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002070 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|O:round",
2071 kwlist, &number, &ndigits))
2072 return NULL;
Alex Martelliae211f92007-08-22 23:21:33 +00002073
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002074 if (Py_TYPE(number)->tp_dict == NULL) {
2075 if (PyType_Ready(Py_TYPE(number)) < 0)
2076 return NULL;
2077 }
Guido van Rossum15d3d042007-08-24 02:02:45 +00002078
Benjamin Peterson214a7d22013-04-13 17:19:01 -04002079 round = _PyObject_LookupSpecial(number, &PyId___round__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002080 if (round == NULL) {
Benjamin Peterson214a7d22013-04-13 17:19:01 -04002081 if (!PyErr_Occurred())
2082 PyErr_Format(PyExc_TypeError,
2083 "type %.100s doesn't define __round__ method",
2084 Py_TYPE(number)->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002085 return NULL;
2086 }
Alex Martelliae211f92007-08-22 23:21:33 +00002087
Raymond Hettingerf0f1c232016-09-03 01:55:11 -07002088 if (ndigits == NULL || ndigits == Py_None)
Victor Stinnerf17c3de2016-12-06 18:46:19 +01002089 result = _PyObject_CallNoArg(round);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002090 else
Victor Stinnerde4ae3d2016-12-04 22:59:09 +01002091 result = PyObject_CallFunctionObjArgs(round, ndigits, NULL);
Benjamin Peterson214a7d22013-04-13 17:19:01 -04002092 Py_DECREF(round);
2093 return result;
Guido van Rossum9e51f9b1993-02-12 16:29:05 +00002094}
2095
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002096PyDoc_STRVAR(round_doc,
Mark Dickinson1124e712009-01-28 21:25:58 +00002097"round(number[, ndigits]) -> number\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002098\n\
2099Round a number to a given precision in decimal digits (default 0 digits).\n\
Mark Dickinson0d748c22008-07-05 11:29:03 +00002100This returns an int when called with one argument, otherwise the\n\
Georg Brandl809ddaa2008-07-01 20:39:59 +00002101same type as the number. ndigits may be negative.");
Guido van Rossum2fa33db2007-08-23 22:07:24 +00002102
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002103
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002104/*AC: we need to keep the kwds dict intact to easily call into the
2105 * list.sort method, which isn't currently supported in AC. So we just use
2106 * the initially generated signature with a custom implementation.
2107 */
2108/* [disabled clinic input]
2109sorted as builtin_sorted
2110
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03002111 iterable as seq: object
2112 key as keyfunc: object = None
2113 reverse: object = False
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002114
2115Return a new list containing all items from the iterable in ascending order.
2116
Raymond Hettinger7ea386e2016-08-25 21:11:50 -07002117A custom key function can be supplied to customize the sort order, and the
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002118reverse flag can be set to request the result in descending order.
2119[end disabled clinic input]*/
2120
2121PyDoc_STRVAR(builtin_sorted__doc__,
Serhiy Storchaka3a104252017-01-23 12:29:47 +02002122"sorted($module, iterable, /, *, key=None, reverse=False)\n"
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002123"--\n"
2124"\n"
2125"Return a new list containing all items from the iterable in ascending order.\n"
2126"\n"
Raymond Hettinger7ea386e2016-08-25 21:11:50 -07002127"A custom key function can be supplied to customize the sort order, and the\n"
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002128"reverse flag can be set to request the result in descending order.");
2129
2130#define BUILTIN_SORTED_METHODDEF \
Serhiy Storchaka6969eaf2017-07-03 21:20:15 +03002131 {"sorted", (PyCFunction)builtin_sorted, METH_FASTCALL | METH_KEYWORDS, builtin_sorted__doc__},
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002132
Raymond Hettinger64958a12003-12-17 20:43:33 +00002133static PyObject *
Victor Stinner5a60eca2017-01-17 15:17:49 +01002134builtin_sorted(PyObject *self, PyObject **args, Py_ssize_t nargs, PyObject *kwnames)
Raymond Hettinger64958a12003-12-17 20:43:33 +00002135{
Serhiy Storchaka7cf8beb2017-01-21 23:05:00 +02002136 PyObject *newlist, *v, *seq, *callable;
Victor Stinner5a60eca2017-01-17 15:17:49 +01002137
Serhiy Storchaka7cf8beb2017-01-21 23:05:00 +02002138 /* Keyword arguments are passed through list.sort() which will check
2139 them. */
2140 if (!_PyArg_UnpackStack(args, nargs, "sorted", 1, 1, &seq))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002141 return NULL;
Raymond Hettinger64958a12003-12-17 20:43:33 +00002142
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002143 newlist = PySequence_List(seq);
2144 if (newlist == NULL)
2145 return NULL;
Raymond Hettinger64958a12003-12-17 20:43:33 +00002146
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02002147 callable = _PyObject_GetAttrId(newlist, &PyId_sort);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002148 if (callable == NULL) {
2149 Py_DECREF(newlist);
2150 return NULL;
2151 }
Georg Brandl99d7e4e2005-08-31 22:21:15 +00002152
Serhiy Storchaka299dc232017-01-20 08:35:18 +02002153 assert(nargs >= 1);
Victor Stinner5a60eca2017-01-17 15:17:49 +01002154 v = _PyObject_FastCallKeywords(callable, args + 1, nargs - 1, kwnames);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002155 Py_DECREF(callable);
2156 if (v == NULL) {
2157 Py_DECREF(newlist);
2158 return NULL;
2159 }
2160 Py_DECREF(v);
2161 return newlist;
Raymond Hettinger64958a12003-12-17 20:43:33 +00002162}
2163
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002164
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002165/* AC: cannot convert yet, as needs PEP 457 group support in inspect */
Guido van Rossum79f25d91997-04-29 20:08:16 +00002166static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002167builtin_vars(PyObject *self, PyObject *args)
Guido van Rossum2d951851994-08-29 12:52:16 +00002168{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002169 PyObject *v = NULL;
2170 PyObject *d;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002171
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002172 if (!PyArg_UnpackTuple(args, "vars", 0, 1, &v))
2173 return NULL;
2174 if (v == NULL) {
2175 d = PyEval_GetLocals();
Victor Stinner41bb43a2013-10-29 01:19:37 +01002176 if (d == NULL)
2177 return NULL;
2178 Py_INCREF(d);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002179 }
2180 else {
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02002181 d = _PyObject_GetAttrId(v, &PyId___dict__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002182 if (d == NULL) {
2183 PyErr_SetString(PyExc_TypeError,
2184 "vars() argument must have __dict__ attribute");
2185 return NULL;
2186 }
2187 }
2188 return d;
Guido van Rossum2d951851994-08-29 12:52:16 +00002189}
2190
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002191PyDoc_STRVAR(vars_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002192"vars([object]) -> dictionary\n\
2193\n\
2194Without arguments, equivalent to locals().\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002195With an argument, equivalent to object.__dict__.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002196
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002197
2198/*[clinic input]
2199sum as builtin_sum
2200
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03002201 iterable: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002202 start: object(c_default="NULL") = 0
2203 /
2204
2205Return the sum of a 'start' value (default: 0) plus an iterable of numbers
2206
2207When the iterable is empty, return the start value.
2208This function is intended specifically for use with numeric values and may
2209reject non-numeric types.
2210[clinic start generated code]*/
2211
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002212static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002213builtin_sum_impl(PyObject *module, PyObject *iterable, PyObject *start)
2214/*[clinic end generated code: output=df758cec7d1d302f input=3b5b7a9d7611c73a]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002215{
2216 PyObject *result = start;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002217 PyObject *temp, *item, *iter;
Alex Martellia70b1912003-04-22 08:12:33 +00002218
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002219 iter = PyObject_GetIter(iterable);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002220 if (iter == NULL)
2221 return NULL;
Alex Martellia70b1912003-04-22 08:12:33 +00002222
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002223 if (result == NULL) {
2224 result = PyLong_FromLong(0);
2225 if (result == NULL) {
2226 Py_DECREF(iter);
2227 return NULL;
2228 }
2229 } else {
2230 /* reject string values for 'start' parameter */
2231 if (PyUnicode_Check(result)) {
2232 PyErr_SetString(PyExc_TypeError,
2233 "sum() can't sum strings [use ''.join(seq) instead]");
2234 Py_DECREF(iter);
2235 return NULL;
2236 }
Benjamin Petersonce071ca2011-07-29 14:23:47 -05002237 if (PyBytes_Check(result)) {
2238 PyErr_SetString(PyExc_TypeError,
2239 "sum() can't sum bytes [use b''.join(seq) instead]");
Benjamin Peterson405f32c2011-07-29 22:43:45 -05002240 Py_DECREF(iter);
Benjamin Petersonce071ca2011-07-29 14:23:47 -05002241 return NULL;
2242 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002243 if (PyByteArray_Check(result)) {
2244 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson4f921c22011-07-29 14:24:29 -05002245 "sum() can't sum bytearray [use b''.join(seq) instead]");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002246 Py_DECREF(iter);
2247 return NULL;
2248 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002249 Py_INCREF(result);
2250 }
Alex Martellia70b1912003-04-22 08:12:33 +00002251
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002252#ifndef SLOW_SUM
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002253 /* Fast addition by keeping temporary sums in C instead of new Python objects.
2254 Assumes all inputs are the same type. If the assumption fails, default
2255 to the more general routine.
2256 */
2257 if (PyLong_CheckExact(result)) {
2258 int overflow;
2259 long i_result = PyLong_AsLongAndOverflow(result, &overflow);
2260 /* If this already overflowed, don't even enter the loop. */
2261 if (overflow == 0) {
2262 Py_DECREF(result);
2263 result = NULL;
2264 }
2265 while(result == NULL) {
2266 item = PyIter_Next(iter);
2267 if (item == NULL) {
2268 Py_DECREF(iter);
2269 if (PyErr_Occurred())
2270 return NULL;
2271 return PyLong_FromLong(i_result);
2272 }
2273 if (PyLong_CheckExact(item)) {
2274 long b = PyLong_AsLongAndOverflow(item, &overflow);
2275 long x = i_result + b;
2276 if (overflow == 0 && ((x^i_result) >= 0 || (x^b) >= 0)) {
2277 i_result = x;
2278 Py_DECREF(item);
2279 continue;
2280 }
2281 }
2282 /* Either overflowed or is not an int. Restore real objects and process normally */
2283 result = PyLong_FromLong(i_result);
Christian Heimes704e2d32013-07-26 22:49:26 +02002284 if (result == NULL) {
2285 Py_DECREF(item);
2286 Py_DECREF(iter);
2287 return NULL;
2288 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002289 temp = PyNumber_Add(result, item);
2290 Py_DECREF(result);
2291 Py_DECREF(item);
2292 result = temp;
2293 if (result == NULL) {
2294 Py_DECREF(iter);
2295 return NULL;
2296 }
2297 }
2298 }
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002299
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002300 if (PyFloat_CheckExact(result)) {
2301 double f_result = PyFloat_AS_DOUBLE(result);
2302 Py_DECREF(result);
2303 result = NULL;
2304 while(result == NULL) {
2305 item = PyIter_Next(iter);
2306 if (item == NULL) {
2307 Py_DECREF(iter);
2308 if (PyErr_Occurred())
2309 return NULL;
2310 return PyFloat_FromDouble(f_result);
2311 }
2312 if (PyFloat_CheckExact(item)) {
2313 PyFPE_START_PROTECT("add", Py_DECREF(item); Py_DECREF(iter); return 0)
2314 f_result += PyFloat_AS_DOUBLE(item);
2315 PyFPE_END_PROTECT(f_result)
2316 Py_DECREF(item);
2317 continue;
2318 }
2319 if (PyLong_CheckExact(item)) {
2320 long value;
2321 int overflow;
2322 value = PyLong_AsLongAndOverflow(item, &overflow);
2323 if (!overflow) {
2324 PyFPE_START_PROTECT("add", Py_DECREF(item); Py_DECREF(iter); return 0)
2325 f_result += (double)value;
2326 PyFPE_END_PROTECT(f_result)
2327 Py_DECREF(item);
2328 continue;
2329 }
2330 }
2331 result = PyFloat_FromDouble(f_result);
2332 temp = PyNumber_Add(result, item);
2333 Py_DECREF(result);
2334 Py_DECREF(item);
2335 result = temp;
2336 if (result == NULL) {
2337 Py_DECREF(iter);
2338 return NULL;
2339 }
2340 }
2341 }
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002342#endif
2343
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002344 for(;;) {
2345 item = PyIter_Next(iter);
2346 if (item == NULL) {
2347 /* error, or end-of-sequence */
2348 if (PyErr_Occurred()) {
2349 Py_DECREF(result);
2350 result = NULL;
2351 }
2352 break;
2353 }
2354 /* It's tempting to use PyNumber_InPlaceAdd instead of
2355 PyNumber_Add here, to avoid quadratic running time
2356 when doing 'sum(list_of_lists, [])'. However, this
2357 would produce a change in behaviour: a snippet like
Mark Dickinson9acadc52009-10-26 14:19:42 +00002358
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002359 empty = []
2360 sum([[x] for x in range(10)], empty)
Mark Dickinson9acadc52009-10-26 14:19:42 +00002361
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002362 would change the value of empty. */
2363 temp = PyNumber_Add(result, item);
2364 Py_DECREF(result);
2365 Py_DECREF(item);
2366 result = temp;
2367 if (result == NULL)
2368 break;
2369 }
2370 Py_DECREF(iter);
2371 return result;
Alex Martellia70b1912003-04-22 08:12:33 +00002372}
2373
Alex Martellia70b1912003-04-22 08:12:33 +00002374
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002375/*[clinic input]
2376isinstance as builtin_isinstance
2377
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03002378 obj: object
2379 class_or_tuple: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002380 /
2381
2382Return whether an object is an instance of a class or of a subclass thereof.
2383
2384A tuple, as in ``isinstance(x, (A, B, ...))``, may be given as the target to
2385check against. This is equivalent to ``isinstance(x, A) or isinstance(x, B)
2386or ...`` etc.
2387[clinic start generated code]*/
2388
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002389static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002390builtin_isinstance_impl(PyObject *module, PyObject *obj,
Larry Hastings89964c42015-04-14 18:07:59 -04002391 PyObject *class_or_tuple)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002392/*[clinic end generated code: output=6faf01472c13b003 input=ffa743db1daf7549]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002393{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002394 int retval;
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002395
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002396 retval = PyObject_IsInstance(obj, class_or_tuple);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002397 if (retval < 0)
2398 return NULL;
2399 return PyBool_FromLong(retval);
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002400}
2401
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002402
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002403/*[clinic input]
2404issubclass as builtin_issubclass
2405
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03002406 cls: object
2407 class_or_tuple: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002408 /
2409
2410Return whether 'cls' is a derived from another class or is the same class.
2411
2412A tuple, as in ``issubclass(x, (A, B, ...))``, may be given as the target to
2413check against. This is equivalent to ``issubclass(x, A) or issubclass(x, B)
2414or ...`` etc.
2415[clinic start generated code]*/
2416
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002417static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002418builtin_issubclass_impl(PyObject *module, PyObject *cls,
Larry Hastings89964c42015-04-14 18:07:59 -04002419 PyObject *class_or_tuple)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002420/*[clinic end generated code: output=358412410cd7a250 input=af5f35e9ceaddaf6]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002421{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002422 int retval;
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002423
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002424 retval = PyObject_IsSubclass(cls, class_or_tuple);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002425 if (retval < 0)
2426 return NULL;
2427 return PyBool_FromLong(retval);
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002428}
2429
2430
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002431typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002432 PyObject_HEAD
2433 Py_ssize_t tuplesize;
2434 PyObject *ittuple; /* tuple of iterators */
2435 PyObject *result;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002436} zipobject;
2437
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002438static PyObject *
2439zip_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
Barry Warsawbd599b52000-08-03 15:45:29 +00002440{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002441 zipobject *lz;
2442 Py_ssize_t i;
2443 PyObject *ittuple; /* tuple of iterators */
2444 PyObject *result;
Serhiy Storchakabf623ae2017-04-19 20:03:52 +03002445 Py_ssize_t tuplesize;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002446
Serhiy Storchaka6cca5c82017-06-08 14:41:19 +03002447 if (type == &PyZip_Type && !_PyArg_NoKeywords("zip", kwds))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002448 return NULL;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002449
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002450 /* args must be a tuple */
2451 assert(PyTuple_Check(args));
Serhiy Storchakabf623ae2017-04-19 20:03:52 +03002452 tuplesize = PyTuple_GET_SIZE(args);
Barry Warsawbd599b52000-08-03 15:45:29 +00002453
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002454 /* obtain iterators */
2455 ittuple = PyTuple_New(tuplesize);
2456 if (ittuple == NULL)
2457 return NULL;
2458 for (i=0; i < tuplesize; ++i) {
2459 PyObject *item = PyTuple_GET_ITEM(args, i);
2460 PyObject *it = PyObject_GetIter(item);
2461 if (it == NULL) {
2462 if (PyErr_ExceptionMatches(PyExc_TypeError))
2463 PyErr_Format(PyExc_TypeError,
2464 "zip argument #%zd must support iteration",
2465 i+1);
2466 Py_DECREF(ittuple);
2467 return NULL;
2468 }
2469 PyTuple_SET_ITEM(ittuple, i, it);
2470 }
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002471
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002472 /* create a result holder */
2473 result = PyTuple_New(tuplesize);
2474 if (result == NULL) {
2475 Py_DECREF(ittuple);
2476 return NULL;
2477 }
2478 for (i=0 ; i < tuplesize ; i++) {
2479 Py_INCREF(Py_None);
2480 PyTuple_SET_ITEM(result, i, Py_None);
2481 }
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002482
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002483 /* create zipobject structure */
2484 lz = (zipobject *)type->tp_alloc(type, 0);
2485 if (lz == NULL) {
2486 Py_DECREF(ittuple);
2487 Py_DECREF(result);
2488 return NULL;
2489 }
2490 lz->ittuple = ittuple;
2491 lz->tuplesize = tuplesize;
2492 lz->result = result;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002493
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002494 return (PyObject *)lz;
Barry Warsawbd599b52000-08-03 15:45:29 +00002495}
2496
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002497static void
2498zip_dealloc(zipobject *lz)
2499{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002500 PyObject_GC_UnTrack(lz);
2501 Py_XDECREF(lz->ittuple);
2502 Py_XDECREF(lz->result);
2503 Py_TYPE(lz)->tp_free(lz);
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002504}
2505
2506static int
2507zip_traverse(zipobject *lz, visitproc visit, void *arg)
2508{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002509 Py_VISIT(lz->ittuple);
2510 Py_VISIT(lz->result);
2511 return 0;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002512}
2513
2514static PyObject *
2515zip_next(zipobject *lz)
2516{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002517 Py_ssize_t i;
2518 Py_ssize_t tuplesize = lz->tuplesize;
2519 PyObject *result = lz->result;
2520 PyObject *it;
2521 PyObject *item;
2522 PyObject *olditem;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002523
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002524 if (tuplesize == 0)
2525 return NULL;
2526 if (Py_REFCNT(result) == 1) {
2527 Py_INCREF(result);
2528 for (i=0 ; i < tuplesize ; i++) {
2529 it = PyTuple_GET_ITEM(lz->ittuple, i);
2530 item = (*Py_TYPE(it)->tp_iternext)(it);
Serhiy Storchaka278d03b2013-04-06 22:52:34 +03002531 if (item == NULL) {
2532 Py_DECREF(result);
2533 return NULL;
2534 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002535 olditem = PyTuple_GET_ITEM(result, i);
2536 PyTuple_SET_ITEM(result, i, item);
2537 Py_DECREF(olditem);
2538 }
2539 } else {
2540 result = PyTuple_New(tuplesize);
2541 if (result == NULL)
Serhiy Storchaka278d03b2013-04-06 22:52:34 +03002542 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002543 for (i=0 ; i < tuplesize ; i++) {
2544 it = PyTuple_GET_ITEM(lz->ittuple, i);
2545 item = (*Py_TYPE(it)->tp_iternext)(it);
Serhiy Storchaka278d03b2013-04-06 22:52:34 +03002546 if (item == NULL) {
2547 Py_DECREF(result);
2548 return NULL;
2549 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002550 PyTuple_SET_ITEM(result, i, item);
2551 }
2552 }
2553 return result;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002554}
Barry Warsawbd599b52000-08-03 15:45:29 +00002555
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002556static PyObject *
2557zip_reduce(zipobject *lz)
2558{
2559 /* Just recreate the zip with the internal iterator tuple */
2560 return Py_BuildValue("OO", Py_TYPE(lz), lz->ittuple);
2561}
2562
2563static PyMethodDef zip_methods[] = {
2564 {"__reduce__", (PyCFunction)zip_reduce, METH_NOARGS, reduce_doc},
2565 {NULL, NULL} /* sentinel */
2566};
2567
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002568PyDoc_STRVAR(zip_doc,
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002569"zip(iter1 [,iter2 [...]]) --> zip object\n\
Barry Warsawbd599b52000-08-03 15:45:29 +00002570\n\
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002571Return a zip object whose .__next__() method returns a tuple where\n\
2572the i-th element comes from the i-th iterable argument. The .__next__()\n\
2573method continues until the shortest iterable in the argument sequence\n\
Georg Brandlced51db2008-12-04 18:28:38 +00002574is exhausted and then it raises StopIteration.");
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002575
2576PyTypeObject PyZip_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002577 PyVarObject_HEAD_INIT(&PyType_Type, 0)
2578 "zip", /* tp_name */
2579 sizeof(zipobject), /* tp_basicsize */
2580 0, /* tp_itemsize */
2581 /* methods */
2582 (destructor)zip_dealloc, /* tp_dealloc */
2583 0, /* tp_print */
2584 0, /* tp_getattr */
2585 0, /* tp_setattr */
2586 0, /* tp_reserved */
2587 0, /* tp_repr */
2588 0, /* tp_as_number */
2589 0, /* tp_as_sequence */
2590 0, /* tp_as_mapping */
2591 0, /* tp_hash */
2592 0, /* tp_call */
2593 0, /* tp_str */
2594 PyObject_GenericGetAttr, /* tp_getattro */
2595 0, /* tp_setattro */
2596 0, /* tp_as_buffer */
2597 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
2598 Py_TPFLAGS_BASETYPE, /* tp_flags */
2599 zip_doc, /* tp_doc */
2600 (traverseproc)zip_traverse, /* tp_traverse */
2601 0, /* tp_clear */
2602 0, /* tp_richcompare */
2603 0, /* tp_weaklistoffset */
2604 PyObject_SelfIter, /* tp_iter */
2605 (iternextfunc)zip_next, /* tp_iternext */
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002606 zip_methods, /* tp_methods */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002607 0, /* tp_members */
2608 0, /* tp_getset */
2609 0, /* tp_base */
2610 0, /* tp_dict */
2611 0, /* tp_descr_get */
2612 0, /* tp_descr_set */
2613 0, /* tp_dictoffset */
2614 0, /* tp_init */
2615 PyType_GenericAlloc, /* tp_alloc */
2616 zip_new, /* tp_new */
2617 PyObject_GC_Del, /* tp_free */
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002618};
Barry Warsawbd599b52000-08-03 15:45:29 +00002619
2620
Guido van Rossum79f25d91997-04-29 20:08:16 +00002621static PyMethodDef builtin_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002622 {"__build_class__", (PyCFunction)builtin___build_class__,
Serhiy Storchaka6969eaf2017-07-03 21:20:15 +03002623 METH_FASTCALL | METH_KEYWORDS, build_class_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002624 {"__import__", (PyCFunction)builtin___import__, METH_VARARGS | METH_KEYWORDS, import_doc},
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002625 BUILTIN_ABS_METHODDEF
2626 BUILTIN_ALL_METHODDEF
2627 BUILTIN_ANY_METHODDEF
2628 BUILTIN_ASCII_METHODDEF
2629 BUILTIN_BIN_METHODDEF
2630 BUILTIN_CALLABLE_METHODDEF
2631 BUILTIN_CHR_METHODDEF
2632 BUILTIN_COMPILE_METHODDEF
2633 BUILTIN_DELATTR_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002634 {"dir", builtin_dir, METH_VARARGS, dir_doc},
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002635 BUILTIN_DIVMOD_METHODDEF
2636 BUILTIN_EVAL_METHODDEF
2637 BUILTIN_EXEC_METHODDEF
2638 BUILTIN_FORMAT_METHODDEF
Victor Stinner84b388b2017-01-17 03:52:27 +01002639 {"getattr", (PyCFunction)builtin_getattr, METH_FASTCALL, getattr_doc},
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002640 BUILTIN_GLOBALS_METHODDEF
2641 BUILTIN_HASATTR_METHODDEF
2642 BUILTIN_HASH_METHODDEF
2643 BUILTIN_HEX_METHODDEF
2644 BUILTIN_ID_METHODDEF
2645 BUILTIN_INPUT_METHODDEF
2646 BUILTIN_ISINSTANCE_METHODDEF
2647 BUILTIN_ISSUBCLASS_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002648 {"iter", builtin_iter, METH_VARARGS, iter_doc},
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002649 BUILTIN_LEN_METHODDEF
2650 BUILTIN_LOCALS_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002651 {"max", (PyCFunction)builtin_max, METH_VARARGS | METH_KEYWORDS, max_doc},
2652 {"min", (PyCFunction)builtin_min, METH_VARARGS | METH_KEYWORDS, min_doc},
Victor Stinnerfda6d0a2017-01-17 04:09:14 +01002653 {"next", (PyCFunction)builtin_next, METH_FASTCALL, next_doc},
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002654 BUILTIN_OCT_METHODDEF
2655 BUILTIN_ORD_METHODDEF
2656 BUILTIN_POW_METHODDEF
Serhiy Storchaka6969eaf2017-07-03 21:20:15 +03002657 {"print", (PyCFunction)builtin_print, METH_FASTCALL | METH_KEYWORDS, print_doc},
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002658 BUILTIN_REPR_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002659 {"round", (PyCFunction)builtin_round, METH_VARARGS | METH_KEYWORDS, round_doc},
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002660 BUILTIN_SETATTR_METHODDEF
2661 BUILTIN_SORTED_METHODDEF
2662 BUILTIN_SUM_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002663 {"vars", builtin_vars, METH_VARARGS, vars_doc},
2664 {NULL, NULL},
Guido van Rossum3f5da241990-12-20 15:06:42 +00002665};
2666
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002667PyDoc_STRVAR(builtin_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002668"Built-in functions, exceptions, and other objects.\n\
2669\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002670Noteworthy: None is the `nil' object; Ellipsis represents `...' in slices.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002671
Martin v. Löwis1a214512008-06-11 05:26:20 +00002672static struct PyModuleDef builtinsmodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002673 PyModuleDef_HEAD_INIT,
2674 "builtins",
2675 builtin_doc,
2676 -1, /* multiple "initialization" just copies the module dict. */
2677 builtin_methods,
2678 NULL,
2679 NULL,
2680 NULL,
2681 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00002682};
2683
2684
Guido van Rossum25ce5661997-08-02 03:10:38 +00002685PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002686_PyBuiltin_Init(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +00002687{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002688 PyObject *mod, *dict, *debug;
Benjamin Peterson42124a72012-10-30 23:41:54 -04002689
2690 if (PyType_Ready(&PyFilter_Type) < 0 ||
2691 PyType_Ready(&PyMap_Type) < 0 ||
2692 PyType_Ready(&PyZip_Type) < 0)
2693 return NULL;
2694
Eric Snowd393c1b2017-09-14 12:18:12 -06002695 mod = _PyModule_CreateInitialized(&builtinsmodule, PYTHON_API_VERSION);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002696 if (mod == NULL)
2697 return NULL;
2698 dict = PyModule_GetDict(mod);
Tim Peters4b7625e2001-09-13 21:37:17 +00002699
Tim Peters7571a0f2003-03-23 17:52:28 +00002700#ifdef Py_TRACE_REFS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002701 /* "builtins" exposes a number of statically allocated objects
2702 * that, before this code was added in 2.3, never showed up in
2703 * the list of "all objects" maintained by Py_TRACE_REFS. As a
2704 * result, programs leaking references to None and False (etc)
2705 * couldn't be diagnosed by examining sys.getobjects(0).
2706 */
Tim Peters7571a0f2003-03-23 17:52:28 +00002707#define ADD_TO_ALL(OBJECT) _Py_AddToAllObjects((PyObject *)(OBJECT), 0)
2708#else
2709#define ADD_TO_ALL(OBJECT) (void)0
2710#endif
2711
Tim Peters4b7625e2001-09-13 21:37:17 +00002712#define SETBUILTIN(NAME, OBJECT) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002713 if (PyDict_SetItemString(dict, NAME, (PyObject *)OBJECT) < 0) \
2714 return NULL; \
2715 ADD_TO_ALL(OBJECT)
Tim Peters4b7625e2001-09-13 21:37:17 +00002716
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002717 SETBUILTIN("None", Py_None);
2718 SETBUILTIN("Ellipsis", Py_Ellipsis);
2719 SETBUILTIN("NotImplemented", Py_NotImplemented);
2720 SETBUILTIN("False", Py_False);
2721 SETBUILTIN("True", Py_True);
2722 SETBUILTIN("bool", &PyBool_Type);
2723 SETBUILTIN("memoryview", &PyMemoryView_Type);
2724 SETBUILTIN("bytearray", &PyByteArray_Type);
2725 SETBUILTIN("bytes", &PyBytes_Type);
2726 SETBUILTIN("classmethod", &PyClassMethod_Type);
2727 SETBUILTIN("complex", &PyComplex_Type);
2728 SETBUILTIN("dict", &PyDict_Type);
2729 SETBUILTIN("enumerate", &PyEnum_Type);
2730 SETBUILTIN("filter", &PyFilter_Type);
2731 SETBUILTIN("float", &PyFloat_Type);
2732 SETBUILTIN("frozenset", &PyFrozenSet_Type);
2733 SETBUILTIN("property", &PyProperty_Type);
2734 SETBUILTIN("int", &PyLong_Type);
2735 SETBUILTIN("list", &PyList_Type);
2736 SETBUILTIN("map", &PyMap_Type);
2737 SETBUILTIN("object", &PyBaseObject_Type);
2738 SETBUILTIN("range", &PyRange_Type);
2739 SETBUILTIN("reversed", &PyReversed_Type);
2740 SETBUILTIN("set", &PySet_Type);
2741 SETBUILTIN("slice", &PySlice_Type);
2742 SETBUILTIN("staticmethod", &PyStaticMethod_Type);
2743 SETBUILTIN("str", &PyUnicode_Type);
2744 SETBUILTIN("super", &PySuper_Type);
2745 SETBUILTIN("tuple", &PyTuple_Type);
2746 SETBUILTIN("type", &PyType_Type);
2747 SETBUILTIN("zip", &PyZip_Type);
2748 debug = PyBool_FromLong(Py_OptimizeFlag == 0);
2749 if (PyDict_SetItemString(dict, "__debug__", debug) < 0) {
Serhiy Storchakacfdfbb42016-06-18 09:44:03 +03002750 Py_DECREF(debug);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002751 return NULL;
2752 }
Serhiy Storchakacfdfbb42016-06-18 09:44:03 +03002753 Py_DECREF(debug);
Barry Warsaw757af0e1997-08-29 22:13:51 +00002754
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002755 return mod;
Tim Peters7571a0f2003-03-23 17:52:28 +00002756#undef ADD_TO_ALL
Tim Peters4b7625e2001-09-13 21:37:17 +00002757#undef SETBUILTIN
Guido van Rossum3f5da241990-12-20 15:06:42 +00002758}