blob: 763c2a2bb8e3b54211070cf1d55c2c8ab6db471b [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
Victor Stinnerb744ba12010-05-15 12:27:16 +000014#ifdef HAVE_LANGINFO_H
15#include <langinfo.h> /* CODESET */
16#endif
17
Mark Hammond26cffde42001-05-14 12:17:34 +000018/* The default encoding used by the platform file system APIs
19 Can remain NULL for all platforms that don't have such a concept
Guido van Rossum00bc0e02007-10-15 02:52:41 +000020
21 Don't forget to modify PyUnicode_DecodeFSDefault() if you touch any of the
22 values for Py_FileSystemDefaultEncoding!
Mark Hammond26cffde42001-05-14 12:17:34 +000023*/
Steve Dowercc16be82016-09-08 10:35:16 -070024#if defined(__APPLE__)
25const char *Py_FileSystemDefaultEncoding = "utf-8";
Martin v. Löwis04dc25c2008-10-03 16:09:28 +000026int Py_HasFileSystemDefaultEncoding = 1;
Steve Dowercc16be82016-09-08 10:35:16 -070027#elif defined(MS_WINDOWS)
28/* may be changed by initfsencoding(), but should never be free()d */
Just van Rossumb9b8e9c2003-02-10 09:22:01 +000029const char *Py_FileSystemDefaultEncoding = "utf-8";
Martin v. Löwis04dc25c2008-10-03 16:09:28 +000030int Py_HasFileSystemDefaultEncoding = 1;
Victor Stinnerd64e8a72011-07-04 13:48:30 +020031#else
Victor Stinnerb744ba12010-05-15 12:27:16 +000032const char *Py_FileSystemDefaultEncoding = NULL; /* set by initfsencoding() */
Martin v. Löwis04dc25c2008-10-03 16:09:28 +000033int Py_HasFileSystemDefaultEncoding = 0;
Mark Hammond26cffde42001-05-14 12:17:34 +000034#endif
Steve Dowercc16be82016-09-08 10:35:16 -070035const char *Py_FileSystemDefaultEncodeErrors = "surrogateescape";
Mark Hammondef8b6542001-05-13 08:04:26 +000036
Victor Stinnerbd303c12013-11-07 23:07:29 +010037_Py_IDENTIFIER(__builtins__);
38_Py_IDENTIFIER(__dict__);
39_Py_IDENTIFIER(__prepare__);
40_Py_IDENTIFIER(__round__);
41_Py_IDENTIFIER(encoding);
42_Py_IDENTIFIER(errors);
Martin v. Löwisbd928fe2011-10-14 10:20:37 +020043_Py_IDENTIFIER(fileno);
44_Py_IDENTIFIER(flush);
Victor Stinnerbd303c12013-11-07 23:07:29 +010045_Py_IDENTIFIER(metaclass);
46_Py_IDENTIFIER(sort);
47_Py_IDENTIFIER(stdin);
48_Py_IDENTIFIER(stdout);
49_Py_IDENTIFIER(stderr);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +020050
Serhiy Storchaka1009bf12015-04-03 23:53:51 +030051#include "clinic/bltinmodule.c.h"
52
Nick Coghlanf9e227e2014-08-17 14:01:19 +100053/* AC: cannot convert yet, waiting for *args support */
Guido van Rossum79f25d91997-04-29 20:08:16 +000054static PyObject *
Victor Stinner773dc6d2017-01-16 23:46:26 +010055builtin___build_class__(PyObject *self, PyObject **args, Py_ssize_t nargs,
56 PyObject *kwnames)
Guido van Rossum52cc1d82007-03-18 15:41:51 +000057{
Nick Coghlan19d24672016-12-05 16:47:55 +100058 PyObject *func, *name, *bases, *mkw, *meta, *winner, *prep, *ns;
59 PyObject *cls = NULL, *cell = NULL;
Victor Stinner0c39b1b2015-03-18 15:02:06 +010060 int isclass = 0; /* initialize to prevent gcc warning */
Guido van Rossum52cc1d82007-03-18 15:41:51 +000061
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000062 if (nargs < 2) {
63 PyErr_SetString(PyExc_TypeError,
64 "__build_class__: not enough arguments");
65 return NULL;
66 }
Victor Stinner773dc6d2017-01-16 23:46:26 +010067 func = args[0]; /* Better be callable */
Benjamin Petersone8e14592013-05-16 14:37:25 -050068 if (!PyFunction_Check(func)) {
69 PyErr_SetString(PyExc_TypeError,
Zachary Ware9b338722014-08-05 14:01:10 -050070 "__build_class__: func must be a function");
Benjamin Petersone8e14592013-05-16 14:37:25 -050071 return NULL;
72 }
Victor Stinner773dc6d2017-01-16 23:46:26 +010073 name = args[1];
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000074 if (!PyUnicode_Check(name)) {
75 PyErr_SetString(PyExc_TypeError,
76 "__build_class__: name is not a string");
77 return NULL;
78 }
Victor Stinner773dc6d2017-01-16 23:46:26 +010079 bases = _PyStack_AsTupleSlice(args, nargs, 2, nargs);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000080 if (bases == NULL)
81 return NULL;
Guido van Rossum52cc1d82007-03-18 15:41:51 +000082
Victor Stinner773dc6d2017-01-16 23:46:26 +010083 if (kwnames == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000084 meta = NULL;
85 mkw = NULL;
86 }
87 else {
Victor Stinner773dc6d2017-01-16 23:46:26 +010088 mkw = _PyStack_AsDict(args + nargs, kwnames);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000089 if (mkw == NULL) {
90 Py_DECREF(bases);
91 return NULL;
Guido van Rossum52cc1d82007-03-18 15:41:51 +000092 }
Victor Stinner773dc6d2017-01-16 23:46:26 +010093
Victor Stinnerae9f1612013-11-06 22:46:51 +010094 meta = _PyDict_GetItemId(mkw, &PyId_metaclass);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000095 if (meta != NULL) {
96 Py_INCREF(meta);
Victor Stinnerae9f1612013-11-06 22:46:51 +010097 if (_PyDict_DelItemId(mkw, &PyId_metaclass) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000098 Py_DECREF(meta);
99 Py_DECREF(mkw);
100 Py_DECREF(bases);
101 return NULL;
102 }
Nick Coghlande31b192011-10-23 22:04:16 +1000103 /* metaclass is explicitly given, check if it's indeed a class */
104 isclass = PyType_Check(meta);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000105 }
106 }
107 if (meta == NULL) {
Nick Coghlande31b192011-10-23 22:04:16 +1000108 /* if there are no bases, use type: */
109 if (PyTuple_GET_SIZE(bases) == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000110 meta = (PyObject *) (&PyType_Type);
Nick Coghlande31b192011-10-23 22:04:16 +1000111 }
112 /* else get the type of the first base */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000113 else {
114 PyObject *base0 = PyTuple_GET_ITEM(bases, 0);
115 meta = (PyObject *) (base0->ob_type);
116 }
117 Py_INCREF(meta);
Nick Coghlande31b192011-10-23 22:04:16 +1000118 isclass = 1; /* meta is really a class */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000119 }
Nick Coghlan9715d262011-10-23 22:36:42 +1000120
Nick Coghlande31b192011-10-23 22:04:16 +1000121 if (isclass) {
122 /* meta is really a class, so check for a more derived
123 metaclass, or possible metaclass conflicts: */
124 winner = (PyObject *)_PyType_CalculateMetaclass((PyTypeObject *)meta,
125 bases);
126 if (winner == NULL) {
127 Py_DECREF(meta);
128 Py_XDECREF(mkw);
129 Py_DECREF(bases);
130 return NULL;
131 }
132 if (winner != meta) {
133 Py_DECREF(meta);
134 meta = winner;
135 Py_INCREF(meta);
136 }
137 }
138 /* else: meta is not a class, so we cannot do the metaclass
139 calculation, so we will use the explicitly given object as it is */
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +0200140 prep = _PyObject_GetAttrId(meta, &PyId___prepare__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000141 if (prep == NULL) {
142 if (PyErr_ExceptionMatches(PyExc_AttributeError)) {
143 PyErr_Clear();
Eric Snow4f29e752016-09-08 15:11:11 -0700144 ns = PyDict_New();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000145 }
146 else {
147 Py_DECREF(meta);
148 Py_XDECREF(mkw);
149 Py_DECREF(bases);
150 return NULL;
151 }
152 }
153 else {
Victor Stinner463b86a2016-08-22 23:33:13 +0200154 PyObject *pargs[2] = {name, bases};
155 ns = _PyObject_FastCallDict(prep, pargs, 2, mkw);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000156 Py_DECREF(prep);
157 }
158 if (ns == NULL) {
159 Py_DECREF(meta);
160 Py_XDECREF(mkw);
161 Py_DECREF(bases);
162 return NULL;
163 }
Nick Coghlan19d24672016-12-05 16:47:55 +1000164 cell = PyEval_EvalCodeEx(PyFunction_GET_CODE(func), PyFunction_GET_GLOBALS(func), ns,
Benjamin Petersone8e14592013-05-16 14:37:25 -0500165 NULL, 0, NULL, 0, NULL, 0, NULL,
166 PyFunction_GET_CLOSURE(func));
Nick Coghlan19d24672016-12-05 16:47:55 +1000167 if (cell != NULL) {
Victor Stinnerd1c2a8e2016-08-23 01:34:35 +0200168 PyObject *margs[3] = {name, bases, ns};
169 cls = _PyObject_FastCallDict(meta, margs, 3, mkw);
Nick Coghlan19d24672016-12-05 16:47:55 +1000170 if (cls != NULL && PyType_Check(cls) && PyCell_Check(cell)) {
171 PyObject *cell_cls = PyCell_GET(cell);
172 if (cell_cls != cls) {
173 /* TODO: In 3.7, DeprecationWarning will become RuntimeError.
174 * At that point, cell_error won't be needed.
175 */
176 int cell_error;
177 if (cell_cls == NULL) {
178 const char *msg =
179 "__class__ not set defining %.200R as %.200R. "
180 "Was __classcell__ propagated to type.__new__?";
181 cell_error = PyErr_WarnFormat(
182 PyExc_DeprecationWarning, 1, msg, name, cls);
183 } else {
184 const char *msg =
185 "__class__ set to %.200R defining %.200R as %.200R";
186 PyErr_Format(PyExc_TypeError, msg, cell_cls, name, cls);
187 cell_error = 1;
188 }
189 if (cell_error) {
190 Py_DECREF(cls);
191 cls = NULL;
192 goto error;
193 } else {
194 /* Fill in the cell, since type.__new__ didn't do it */
195 PyCell_Set(cell, cls);
196 }
197 }
198 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000199 }
Nick Coghlan19d24672016-12-05 16:47:55 +1000200error:
201 Py_XDECREF(cell);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000202 Py_DECREF(ns);
203 Py_DECREF(meta);
204 Py_XDECREF(mkw);
205 Py_DECREF(bases);
206 return cls;
Guido van Rossum52cc1d82007-03-18 15:41:51 +0000207}
208
209PyDoc_STRVAR(build_class_doc,
210"__build_class__(func, name, *bases, metaclass=None, **kwds) -> class\n\
211\n\
212Internal helper function used by the class statement.");
213
214static PyObject *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000215builtin___import__(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000216{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000217 static char *kwlist[] = {"name", "globals", "locals", "fromlist",
218 "level", 0};
Victor Stinnerfe93faf2011-03-14 15:54:52 -0400219 PyObject *name, *globals = NULL, *locals = NULL, *fromlist = NULL;
Brett Cannonfd074152012-04-14 14:10:13 -0400220 int level = 0;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000221
Victor Stinnerfe93faf2011-03-14 15:54:52 -0400222 if (!PyArg_ParseTupleAndKeywords(args, kwds, "U|OOOi:__import__",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000223 kwlist, &name, &globals, &locals, &fromlist, &level))
224 return NULL;
Victor Stinnerfe93faf2011-03-14 15:54:52 -0400225 return PyImport_ImportModuleLevelObject(name, globals, locals,
226 fromlist, level);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000227}
228
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000229PyDoc_STRVAR(import_doc,
Brett Cannoncb4996a2012-08-06 16:34:44 -0400230"__import__(name, globals=None, locals=None, fromlist=(), level=0) -> module\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000231\n\
Brett Cannon5305a992010-09-27 21:08:38 +0000232Import a module. Because this function is meant for use by the Python\n\
233interpreter and not for general use it is better to use\n\
234importlib.import_module() to programmatically import a module.\n\
235\n\
236The globals argument is only used to determine the context;\n\
237they are not modified. The locals argument is unused. The fromlist\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000238should be a list of names to emulate ``from name import ...'', or an\n\
239empty list to emulate ``import name''.\n\
240When importing a module from a package, note that __import__('A.B', ...)\n\
241returns package A when fromlist is empty, but its submodule B when\n\
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000242fromlist is not empty. Level is used to determine whether to perform \n\
Brett Cannon722d3ae2012-07-30 17:45:54 -0400243absolute or relative imports. 0 is absolute while a positive number\n\
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000244is the number of parent directories to search relative to the current module.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000245
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000246
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000247/*[clinic input]
248abs as builtin_abs
249
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300250 x: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000251 /
252
253Return the absolute value of the argument.
254[clinic start generated code]*/
255
Guido van Rossum79f25d91997-04-29 20:08:16 +0000256static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300257builtin_abs(PyObject *module, PyObject *x)
258/*[clinic end generated code: output=b1b433b9e51356f5 input=bed4ca14e29c20d1]*/
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000259{
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000260 return PyNumber_Absolute(x);
Guido van Rossum3f5da241990-12-20 15:06:42 +0000261}
262
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000263/*[clinic input]
264all as builtin_all
265
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300266 iterable: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000267 /
268
269Return True if bool(x) is True for all values x in the iterable.
270
271If the iterable is empty, return True.
272[clinic start generated code]*/
273
Raymond Hettinger96229b12005-03-11 06:49:40 +0000274static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300275builtin_all(PyObject *module, PyObject *iterable)
276/*[clinic end generated code: output=ca2a7127276f79b3 input=1a7c5d1bc3438a21]*/
Raymond Hettinger96229b12005-03-11 06:49:40 +0000277{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000278 PyObject *it, *item;
279 PyObject *(*iternext)(PyObject *);
280 int cmp;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000281
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000282 it = PyObject_GetIter(iterable);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000283 if (it == NULL)
284 return NULL;
285 iternext = *Py_TYPE(it)->tp_iternext;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000286
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000287 for (;;) {
288 item = iternext(it);
289 if (item == NULL)
290 break;
291 cmp = PyObject_IsTrue(item);
292 Py_DECREF(item);
293 if (cmp < 0) {
294 Py_DECREF(it);
295 return NULL;
296 }
297 if (cmp == 0) {
298 Py_DECREF(it);
299 Py_RETURN_FALSE;
300 }
301 }
302 Py_DECREF(it);
303 if (PyErr_Occurred()) {
304 if (PyErr_ExceptionMatches(PyExc_StopIteration))
305 PyErr_Clear();
306 else
307 return NULL;
308 }
309 Py_RETURN_TRUE;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000310}
311
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000312/*[clinic input]
313any as builtin_any
314
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300315 iterable: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000316 /
317
318Return True if bool(x) is True for any x in the iterable.
319
320If the iterable is empty, return False.
321[clinic start generated code]*/
322
Raymond Hettinger96229b12005-03-11 06:49:40 +0000323static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300324builtin_any(PyObject *module, PyObject *iterable)
325/*[clinic end generated code: output=fa65684748caa60e input=41d7451c23384f24]*/
Raymond Hettinger96229b12005-03-11 06:49:40 +0000326{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000327 PyObject *it, *item;
328 PyObject *(*iternext)(PyObject *);
329 int cmp;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000330
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000331 it = PyObject_GetIter(iterable);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000332 if (it == NULL)
333 return NULL;
334 iternext = *Py_TYPE(it)->tp_iternext;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000335
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000336 for (;;) {
337 item = iternext(it);
338 if (item == NULL)
339 break;
340 cmp = PyObject_IsTrue(item);
341 Py_DECREF(item);
342 if (cmp < 0) {
343 Py_DECREF(it);
344 return NULL;
345 }
Raymond Hettinger5098b582015-10-09 00:42:47 -0400346 if (cmp > 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000347 Py_DECREF(it);
348 Py_RETURN_TRUE;
349 }
350 }
351 Py_DECREF(it);
352 if (PyErr_Occurred()) {
353 if (PyErr_ExceptionMatches(PyExc_StopIteration))
354 PyErr_Clear();
355 else
356 return NULL;
357 }
358 Py_RETURN_FALSE;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000359}
360
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000361/*[clinic input]
362ascii as builtin_ascii
363
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300364 obj: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000365 /
366
367Return an ASCII-only representation of an object.
368
369As repr(), return a string containing a printable representation of an
370object, but escape the non-ASCII characters in the string returned by
371repr() using \\x, \\u or \\U escapes. This generates a string similar
372to that returned by repr() in Python 2.
373[clinic start generated code]*/
374
Georg Brandl559e5d72008-06-11 18:37:52 +0000375static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300376builtin_ascii(PyObject *module, PyObject *obj)
377/*[clinic end generated code: output=6d37b3f0984c7eb9 input=4c62732e1b3a3cc9]*/
Georg Brandl559e5d72008-06-11 18:37:52 +0000378{
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000379 return PyObject_ASCII(obj);
Georg Brandl559e5d72008-06-11 18:37:52 +0000380}
381
Georg Brandl559e5d72008-06-11 18:37:52 +0000382
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000383/*[clinic input]
384bin as builtin_bin
385
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300386 number: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000387 /
388
389Return the binary representation of an integer.
390
391 >>> bin(2796202)
392 '0b1010101010101010101010'
393[clinic start generated code]*/
394
Guido van Rossum79f25d91997-04-29 20:08:16 +0000395static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300396builtin_bin(PyObject *module, PyObject *number)
397/*[clinic end generated code: output=b6fc4ad5e649f4f7 input=53f8a0264bacaf90]*/
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000398{
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000399 return PyNumber_ToBase(number, 2);
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000400}
401
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000402
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000403/*[clinic input]
404callable as builtin_callable
405
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300406 obj: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000407 /
408
409Return whether the object is callable (i.e., some kind of function).
410
411Note that classes are callable, as are instances of classes with a
412__call__() method.
413[clinic start generated code]*/
414
Antoine Pitroue71362d2010-11-27 22:00:11 +0000415static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300416builtin_callable(PyObject *module, PyObject *obj)
417/*[clinic end generated code: output=2b095d59d934cb7e input=1423bab99cc41f58]*/
Antoine Pitroue71362d2010-11-27 22:00:11 +0000418{
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000419 return PyBool_FromLong((long)PyCallable_Check(obj));
Antoine Pitroue71362d2010-11-27 22:00:11 +0000420}
421
Antoine Pitroue71362d2010-11-27 22:00:11 +0000422
Raymond Hettinger17301e92008-03-13 00:19:26 +0000423typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000424 PyObject_HEAD
425 PyObject *func;
426 PyObject *it;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000427} filterobject;
428
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000429static PyObject *
Raymond Hettinger17301e92008-03-13 00:19:26 +0000430filter_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
Guido van Rossum12d12c51993-10-26 17:58:25 +0000431{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000432 PyObject *func, *seq;
433 PyObject *it;
434 filterobject *lz;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000435
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000436 if (type == &PyFilter_Type && !_PyArg_NoKeywords("filter()", kwds))
437 return NULL;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000438
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000439 if (!PyArg_UnpackTuple(args, "filter", 2, 2, &func, &seq))
440 return NULL;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000441
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000442 /* Get iterator. */
443 it = PyObject_GetIter(seq);
444 if (it == NULL)
445 return NULL;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000446
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000447 /* create filterobject structure */
448 lz = (filterobject *)type->tp_alloc(type, 0);
449 if (lz == NULL) {
450 Py_DECREF(it);
451 return NULL;
452 }
453 Py_INCREF(func);
454 lz->func = func;
455 lz->it = it;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000456
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000457 return (PyObject *)lz;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000458}
459
460static void
461filter_dealloc(filterobject *lz)
462{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000463 PyObject_GC_UnTrack(lz);
464 Py_XDECREF(lz->func);
465 Py_XDECREF(lz->it);
466 Py_TYPE(lz)->tp_free(lz);
Raymond Hettinger17301e92008-03-13 00:19:26 +0000467}
468
469static int
470filter_traverse(filterobject *lz, visitproc visit, void *arg)
471{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000472 Py_VISIT(lz->it);
473 Py_VISIT(lz->func);
474 return 0;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000475}
476
477static PyObject *
478filter_next(filterobject *lz)
479{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000480 PyObject *item;
481 PyObject *it = lz->it;
482 long ok;
483 PyObject *(*iternext)(PyObject *);
Raymond Hettingerbd5f0e82015-10-09 01:34:08 -0400484 int checktrue = lz->func == Py_None || lz->func == (PyObject *)&PyBool_Type;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000485
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000486 iternext = *Py_TYPE(it)->tp_iternext;
487 for (;;) {
488 item = iternext(it);
489 if (item == NULL)
490 return NULL;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000491
Raymond Hettingerbd5f0e82015-10-09 01:34:08 -0400492 if (checktrue) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000493 ok = PyObject_IsTrue(item);
494 } else {
495 PyObject *good;
Victor Stinnerde4ae3d2016-12-04 22:59:09 +0100496 good = PyObject_CallFunctionObjArgs(lz->func, item, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000497 if (good == NULL) {
498 Py_DECREF(item);
499 return NULL;
500 }
501 ok = PyObject_IsTrue(good);
502 Py_DECREF(good);
503 }
Antoine Pitrou6f430e42012-08-15 23:18:25 +0200504 if (ok > 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000505 return item;
506 Py_DECREF(item);
Antoine Pitrou6f430e42012-08-15 23:18:25 +0200507 if (ok < 0)
508 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000509 }
Guido van Rossum12d12c51993-10-26 17:58:25 +0000510}
511
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +0000512static PyObject *
513filter_reduce(filterobject *lz)
514{
515 return Py_BuildValue("O(OO)", Py_TYPE(lz), lz->func, lz->it);
516}
517
518PyDoc_STRVAR(reduce_doc, "Return state information for pickling.");
519
520static PyMethodDef filter_methods[] = {
521 {"__reduce__", (PyCFunction)filter_reduce, METH_NOARGS, reduce_doc},
522 {NULL, NULL} /* sentinel */
523};
524
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000525PyDoc_STRVAR(filter_doc,
Georg Brandld11ae5d2008-05-16 13:27:32 +0000526"filter(function or None, iterable) --> filter object\n\
Guido van Rossumc1f779c2007-07-03 08:25:58 +0000527\n\
Georg Brandld11ae5d2008-05-16 13:27:32 +0000528Return an iterator yielding those items of iterable for which function(item)\n\
Raymond Hettinger17301e92008-03-13 00:19:26 +0000529is true. If function is None, return the items that are true.");
530
531PyTypeObject PyFilter_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000532 PyVarObject_HEAD_INIT(&PyType_Type, 0)
533 "filter", /* tp_name */
534 sizeof(filterobject), /* tp_basicsize */
535 0, /* tp_itemsize */
536 /* methods */
537 (destructor)filter_dealloc, /* tp_dealloc */
538 0, /* tp_print */
539 0, /* tp_getattr */
540 0, /* tp_setattr */
541 0, /* tp_reserved */
542 0, /* tp_repr */
543 0, /* tp_as_number */
544 0, /* tp_as_sequence */
545 0, /* tp_as_mapping */
546 0, /* tp_hash */
547 0, /* tp_call */
548 0, /* tp_str */
549 PyObject_GenericGetAttr, /* tp_getattro */
550 0, /* tp_setattro */
551 0, /* tp_as_buffer */
552 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
553 Py_TPFLAGS_BASETYPE, /* tp_flags */
554 filter_doc, /* tp_doc */
555 (traverseproc)filter_traverse, /* tp_traverse */
556 0, /* tp_clear */
557 0, /* tp_richcompare */
558 0, /* tp_weaklistoffset */
559 PyObject_SelfIter, /* tp_iter */
560 (iternextfunc)filter_next, /* tp_iternext */
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +0000561 filter_methods, /* tp_methods */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000562 0, /* tp_members */
563 0, /* tp_getset */
564 0, /* tp_base */
565 0, /* tp_dict */
566 0, /* tp_descr_get */
567 0, /* tp_descr_set */
568 0, /* tp_dictoffset */
569 0, /* tp_init */
570 PyType_GenericAlloc, /* tp_alloc */
571 filter_new, /* tp_new */
572 PyObject_GC_Del, /* tp_free */
Raymond Hettinger17301e92008-03-13 00:19:26 +0000573};
574
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000575
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000576/*[clinic input]
577format as builtin_format
578
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300579 value: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000580 format_spec: unicode(c_default="NULL") = ''
581 /
582
583Return value.__format__(format_spec)
584
585format_spec defaults to the empty string
586[clinic start generated code]*/
587
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000588static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300589builtin_format_impl(PyObject *module, PyObject *value, PyObject *format_spec)
590/*[clinic end generated code: output=2f40bdfa4954b077 input=6325e751a1b29b86]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000591{
Eric Smith8fd3eba2008-02-17 19:48:00 +0000592 return PyObject_Format(value, format_spec);
Eric Smith8c663262007-08-25 02:26:07 +0000593}
594
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000595/*[clinic input]
596chr as builtin_chr
597
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300598 i: int
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000599 /
600
601Return a Unicode string of one character with ordinal i; 0 <= i <= 0x10ffff.
602[clinic start generated code]*/
603
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000604static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300605builtin_chr_impl(PyObject *module, int i)
606/*[clinic end generated code: output=c733afcd200afcb7 input=3f604ef45a70750d]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000607{
608 return PyUnicode_FromOrdinal(i);
609}
Guido van Rossum09095f32000-03-10 23:00:52 +0000610
611
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +0200612static const char *
Martin Pantereeb896c2015-11-07 02:32:21 +0000613source_as_string(PyObject *cmd, const char *funcname, const char *what, PyCompilerFlags *cf, PyObject **cmd_copy)
Guido van Rossumf15a29f2007-05-04 00:41:39 +0000614{
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +0200615 const char *str;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000616 Py_ssize_t size;
Martin Pantereeb896c2015-11-07 02:32:21 +0000617 Py_buffer view;
Guido van Rossumf15a29f2007-05-04 00:41:39 +0000618
Martin Pantereeb896c2015-11-07 02:32:21 +0000619 *cmd_copy = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000620 if (PyUnicode_Check(cmd)) {
621 cf->cf_flags |= PyCF_IGNORE_COOKIE;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200622 str = PyUnicode_AsUTF8AndSize(cmd, &size);
623 if (str == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000624 return NULL;
625 }
Martin Pantereeb896c2015-11-07 02:32:21 +0000626 else if (PyBytes_Check(cmd)) {
627 str = PyBytes_AS_STRING(cmd);
628 size = PyBytes_GET_SIZE(cmd);
629 }
630 else if (PyByteArray_Check(cmd)) {
631 str = PyByteArray_AS_STRING(cmd);
632 size = PyByteArray_GET_SIZE(cmd);
633 }
634 else if (PyObject_GetBuffer(cmd, &view, PyBUF_SIMPLE) == 0) {
635 /* Copy to NUL-terminated buffer. */
636 *cmd_copy = PyBytes_FromStringAndSize(
637 (const char *)view.buf, view.len);
638 PyBuffer_Release(&view);
639 if (*cmd_copy == NULL) {
640 return NULL;
641 }
642 str = PyBytes_AS_STRING(*cmd_copy);
643 size = PyBytes_GET_SIZE(*cmd_copy);
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +0200644 }
645 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000646 PyErr_Format(PyExc_TypeError,
647 "%s() arg 1 must be a %s object",
648 funcname, what);
649 return NULL;
650 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200651
Serhiy Storchaka3dd3e262015-02-03 01:25:42 +0200652 if (strlen(str) != (size_t)size) {
Serhiy Storchakad8a14472014-09-06 20:07:17 +0300653 PyErr_SetString(PyExc_ValueError,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000654 "source code string cannot contain null bytes");
Martin Pantereeb896c2015-11-07 02:32:21 +0000655 Py_CLEAR(*cmd_copy);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000656 return NULL;
657 }
658 return str;
Guido van Rossumf15a29f2007-05-04 00:41:39 +0000659}
660
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000661/*[clinic input]
662compile as builtin_compile
663
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300664 source: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000665 filename: object(converter="PyUnicode_FSDecoder")
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300666 mode: str
667 flags: int = 0
Serhiy Storchaka8b2e8b62015-05-30 11:30:39 +0300668 dont_inherit: int(c_default="0") = False
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300669 optimize: int = -1
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000670
671Compile source into a code object that can be executed by exec() or eval().
672
673The source code may represent a Python module, statement or expression.
674The filename will be used for run-time error messages.
675The mode must be 'exec' to compile a module, 'single' to compile a
676single (interactive) statement, or 'eval' to compile an expression.
677The flags argument, if present, controls which future statements influence
678the compilation of the code.
Serhiy Storchaka8b2e8b62015-05-30 11:30:39 +0300679The dont_inherit argument, if true, stops the compilation inheriting
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000680the effects of any future statements in effect in the code calling
Serhiy Storchaka8b2e8b62015-05-30 11:30:39 +0300681compile; if absent or false these statements do influence the compilation,
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000682in addition to any features explicitly specified.
683[clinic start generated code]*/
684
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000685static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300686builtin_compile_impl(PyObject *module, PyObject *source, PyObject *filename,
687 const char *mode, int flags, int dont_inherit,
688 int optimize)
689/*[clinic end generated code: output=1fa176e33452bb63 input=9d53e8cfb3c86414]*/
Guido van Rossum5b722181993-03-30 17:46:03 +0000690{
Martin Panter61d6e4a2015-11-07 02:56:11 +0000691 PyObject *source_copy;
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +0200692 const char *str;
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000693 int compile_mode = -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000694 int is_ast;
695 PyCompilerFlags cf;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000696 int start[] = {Py_file_input, Py_eval_input, Py_single_input};
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000697 PyObject *result;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000698
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000699 cf.cf_flags = flags | PyCF_SOURCE_IS_UTF8;
Tim Peters6cd6a822001-08-17 22:11:27 +0000700
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000701 if (flags &
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000702 ~(PyCF_MASK | PyCF_MASK_OBSOLETE | PyCF_DONT_IMPLY_DEDENT | PyCF_ONLY_AST))
703 {
704 PyErr_SetString(PyExc_ValueError,
705 "compile(): unrecognised flags");
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000706 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000707 }
708 /* XXX Warn if (supplied_flags & PyCF_MASK_OBSOLETE) != 0? */
Tim Peters6cd6a822001-08-17 22:11:27 +0000709
Georg Brandl8334fd92010-12-04 10:26:46 +0000710 if (optimize < -1 || optimize > 2) {
711 PyErr_SetString(PyExc_ValueError,
712 "compile(): invalid optimize value");
713 goto error;
714 }
715
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000716 if (!dont_inherit) {
717 PyEval_MergeCompilerFlags(&cf);
718 }
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000719
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000720 if (strcmp(mode, "exec") == 0)
721 compile_mode = 0;
722 else if (strcmp(mode, "eval") == 0)
723 compile_mode = 1;
724 else if (strcmp(mode, "single") == 0)
725 compile_mode = 2;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000726 else {
727 PyErr_SetString(PyExc_ValueError,
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000728 "compile() mode must be 'exec', 'eval' or 'single'");
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000729 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000730 }
Neal Norwitzdb4115f2008-03-31 04:20:05 +0000731
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000732 is_ast = PyAST_Check(source);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000733 if (is_ast == -1)
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000734 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000735 if (is_ast) {
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000736 if (flags & PyCF_ONLY_AST) {
737 Py_INCREF(source);
738 result = source;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000739 }
740 else {
741 PyArena *arena;
742 mod_ty mod;
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000743
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000744 arena = PyArena_New();
Stefan Krah07795df2012-08-20 17:19:50 +0200745 if (arena == NULL)
746 goto error;
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000747 mod = PyAST_obj2mod(source, arena, compile_mode);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000748 if (mod == NULL) {
749 PyArena_Free(arena);
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000750 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000751 }
Benjamin Peterson832bfe22011-08-09 16:15:04 -0500752 if (!PyAST_Validate(mod)) {
753 PyArena_Free(arena);
754 goto error;
755 }
Victor Stinner14e461d2013-08-26 22:28:21 +0200756 result = (PyObject*)PyAST_CompileObject(mod, filename,
757 &cf, optimize, arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000758 PyArena_Free(arena);
759 }
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000760 goto finally;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000761 }
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000762
Martin Panter61d6e4a2015-11-07 02:56:11 +0000763 str = source_as_string(source, "compile", "string, bytes or AST", &cf, &source_copy);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000764 if (str == NULL)
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000765 goto error;
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000766
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000767 result = Py_CompileStringObject(str, filename, start[compile_mode], &cf, optimize);
Martin Panter61d6e4a2015-11-07 02:56:11 +0000768 Py_XDECREF(source_copy);
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000769 goto finally;
770
771error:
772 result = NULL;
773finally:
Victor Stinner14e461d2013-08-26 22:28:21 +0200774 Py_DECREF(filename);
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000775 return result;
Guido van Rossum5b722181993-03-30 17:46:03 +0000776}
777
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000778/* AC: cannot convert yet, as needs PEP 457 group support in inspect */
Guido van Rossum79f25d91997-04-29 20:08:16 +0000779static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000780builtin_dir(PyObject *self, PyObject *args)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000781{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000782 PyObject *arg = NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000783
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000784 if (!PyArg_UnpackTuple(args, "dir", 0, 1, &arg))
785 return NULL;
786 return PyObject_Dir(arg);
Guido van Rossum3f5da241990-12-20 15:06:42 +0000787}
788
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000789PyDoc_STRVAR(dir_doc,
Tim Peters5d2b77c2001-09-03 05:47:38 +0000790"dir([object]) -> list of strings\n"
791"\n"
Georg Brandle32b4222007-03-10 22:13:27 +0000792"If called without an argument, return the names in the current scope.\n"
793"Else, return an alphabetized list of names comprising (some of) the attributes\n"
794"of the given object, and of attributes reachable from it.\n"
795"If the object supplies a method named __dir__, it will be used; otherwise\n"
796"the default dir() logic is used and returns:\n"
797" for a module object: the module's attributes.\n"
798" for a class object: its attributes, and recursively the attributes\n"
799" of its bases.\n"
Guido van Rossumd8faa362007-04-27 19:54:29 +0000800" for any other object: its attributes, its class's attributes, and\n"
Georg Brandle32b4222007-03-10 22:13:27 +0000801" recursively the attributes of its class's base classes.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000802
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000803/*[clinic input]
804divmod as builtin_divmod
Guido van Rossum6a00cd81995-01-07 12:39:01 +0000805
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300806 x: object
807 y: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000808 /
809
Zachary Ware7f227d92016-04-28 14:39:50 -0500810Return the tuple (x//y, x%y). Invariant: div*y + mod == x.
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000811[clinic start generated code]*/
812
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000813static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300814builtin_divmod_impl(PyObject *module, PyObject *x, PyObject *y)
815/*[clinic end generated code: output=b06d8a5f6e0c745e input=175ad9c84ff41a85]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000816{
817 return PyNumber_Divmod(x, y);
818}
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000819
820
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000821/*[clinic input]
822eval as builtin_eval
823
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300824 source: object
825 globals: object = None
826 locals: object = None
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000827 /
828
829Evaluate the given source in the context of globals and locals.
830
831The source may be a string representing a Python expression
832or a code object as returned by compile().
833The globals must be a dictionary and locals can be any mapping,
834defaulting to the current globals and locals.
835If only globals is given, locals defaults to it.
836[clinic start generated code]*/
837
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000838static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300839builtin_eval_impl(PyObject *module, PyObject *source, PyObject *globals,
Larry Hastings89964c42015-04-14 18:07:59 -0400840 PyObject *locals)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300841/*[clinic end generated code: output=0a0824aa70093116 input=11ee718a8640e527]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000842{
Martin Panter61d6e4a2015-11-07 02:56:11 +0000843 PyObject *result, *source_copy;
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +0200844 const char *str;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000845 PyCompilerFlags cf;
Guido van Rossum590baa41993-11-30 13:40:46 +0000846
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000847 if (locals != Py_None && !PyMapping_Check(locals)) {
848 PyErr_SetString(PyExc_TypeError, "locals must be a mapping");
849 return NULL;
850 }
851 if (globals != Py_None && !PyDict_Check(globals)) {
852 PyErr_SetString(PyExc_TypeError, PyMapping_Check(globals) ?
853 "globals must be a real dict; try eval(expr, {}, mapping)"
854 : "globals must be a dict");
855 return NULL;
856 }
857 if (globals == Py_None) {
858 globals = PyEval_GetGlobals();
Victor Stinner41bb43a2013-10-29 01:19:37 +0100859 if (locals == Py_None) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000860 locals = PyEval_GetLocals();
Victor Stinner41bb43a2013-10-29 01:19:37 +0100861 if (locals == NULL)
862 return NULL;
863 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000864 }
865 else if (locals == Py_None)
866 locals = globals;
Tim Peters9fa96be2001-08-17 23:04:59 +0000867
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000868 if (globals == NULL || locals == NULL) {
869 PyErr_SetString(PyExc_TypeError,
870 "eval must be given globals and locals "
871 "when called without a frame");
872 return NULL;
873 }
Georg Brandl77c85e62005-09-15 10:46:13 +0000874
Victor Stinnerb44562b2013-11-06 19:03:11 +0100875 if (_PyDict_GetItemId(globals, &PyId___builtins__) == NULL) {
876 if (_PyDict_SetItemId(globals, &PyId___builtins__,
877 PyEval_GetBuiltins()) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000878 return NULL;
879 }
Tim Peters9fa96be2001-08-17 23:04:59 +0000880
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000881 if (PyCode_Check(source)) {
882 if (PyCode_GetNumFree((PyCodeObject *)source) > 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000883 PyErr_SetString(PyExc_TypeError,
884 "code object passed to eval() may not contain free variables");
885 return NULL;
886 }
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000887 return PyEval_EvalCode(source, globals, locals);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000888 }
Tim Peters9fa96be2001-08-17 23:04:59 +0000889
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000890 cf.cf_flags = PyCF_SOURCE_IS_UTF8;
Martin Panter61d6e4a2015-11-07 02:56:11 +0000891 str = source_as_string(source, "eval", "string, bytes or code", &cf, &source_copy);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000892 if (str == NULL)
893 return NULL;
Just van Rossum3aaf42c2003-02-10 08:21:10 +0000894
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000895 while (*str == ' ' || *str == '\t')
896 str++;
Tim Peters9fa96be2001-08-17 23:04:59 +0000897
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000898 (void)PyEval_MergeCompilerFlags(&cf);
899 result = PyRun_StringFlags(str, Py_eval_input, globals, locals, &cf);
Martin Panter61d6e4a2015-11-07 02:56:11 +0000900 Py_XDECREF(source_copy);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000901 return result;
Guido van Rossum3f5da241990-12-20 15:06:42 +0000902}
903
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000904/*[clinic input]
905exec as builtin_exec
906
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300907 source: object
908 globals: object = None
909 locals: object = None
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000910 /
911
912Execute the given source in the context of globals and locals.
913
914The source may be a string representing one or more Python statements
915or a code object as returned by compile().
916The globals must be a dictionary and locals can be any mapping,
917defaulting to the current globals and locals.
918If only globals is given, locals defaults to it.
919[clinic start generated code]*/
920
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000921static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300922builtin_exec_impl(PyObject *module, PyObject *source, PyObject *globals,
Larry Hastings89964c42015-04-14 18:07:59 -0400923 PyObject *locals)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300924/*[clinic end generated code: output=3c90efc6ab68ef5d input=01ca3e1c01692829]*/
Georg Brandl7cae87c2006-09-06 06:51:57 +0000925{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000926 PyObject *v;
Georg Brandl2cabc562008-08-28 07:57:16 +0000927
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000928 if (globals == Py_None) {
929 globals = PyEval_GetGlobals();
930 if (locals == Py_None) {
931 locals = PyEval_GetLocals();
Victor Stinner41bb43a2013-10-29 01:19:37 +0100932 if (locals == NULL)
933 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000934 }
935 if (!globals || !locals) {
936 PyErr_SetString(PyExc_SystemError,
937 "globals and locals cannot be NULL");
938 return NULL;
939 }
940 }
941 else if (locals == Py_None)
942 locals = globals;
Georg Brandl7cae87c2006-09-06 06:51:57 +0000943
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000944 if (!PyDict_Check(globals)) {
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000945 PyErr_Format(PyExc_TypeError, "exec() globals must be a dict, not %.100s",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000946 globals->ob_type->tp_name);
947 return NULL;
948 }
949 if (!PyMapping_Check(locals)) {
950 PyErr_Format(PyExc_TypeError,
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000951 "locals must be a mapping or None, not %.100s",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000952 locals->ob_type->tp_name);
953 return NULL;
954 }
Victor Stinnerb44562b2013-11-06 19:03:11 +0100955 if (_PyDict_GetItemId(globals, &PyId___builtins__) == NULL) {
956 if (_PyDict_SetItemId(globals, &PyId___builtins__,
957 PyEval_GetBuiltins()) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000958 return NULL;
959 }
960
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000961 if (PyCode_Check(source)) {
962 if (PyCode_GetNumFree((PyCodeObject *)source) > 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000963 PyErr_SetString(PyExc_TypeError,
964 "code object passed to exec() may not "
965 "contain free variables");
966 return NULL;
967 }
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000968 v = PyEval_EvalCode(source, globals, locals);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000969 }
970 else {
Martin Panter61d6e4a2015-11-07 02:56:11 +0000971 PyObject *source_copy;
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +0200972 const char *str;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000973 PyCompilerFlags cf;
974 cf.cf_flags = PyCF_SOURCE_IS_UTF8;
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000975 str = source_as_string(source, "exec",
Martin Panter61d6e4a2015-11-07 02:56:11 +0000976 "string, bytes or code", &cf,
977 &source_copy);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000978 if (str == NULL)
979 return NULL;
980 if (PyEval_MergeCompilerFlags(&cf))
981 v = PyRun_StringFlags(str, Py_file_input, globals,
982 locals, &cf);
983 else
984 v = PyRun_String(str, Py_file_input, globals, locals);
Martin Panter61d6e4a2015-11-07 02:56:11 +0000985 Py_XDECREF(source_copy);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000986 }
987 if (v == NULL)
988 return NULL;
989 Py_DECREF(v);
990 Py_RETURN_NONE;
Georg Brandl7cae87c2006-09-06 06:51:57 +0000991}
992
Georg Brandl7cae87c2006-09-06 06:51:57 +0000993
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000994/* AC: cannot convert yet, as needs PEP 457 group support in inspect */
Guido van Rossum79f25d91997-04-29 20:08:16 +0000995static PyObject *
Victor Stinner84b388b2017-01-17 03:52:27 +0100996builtin_getattr(PyObject *self, PyObject **args, Py_ssize_t nargs,
997 PyObject *kwnames)
Guido van Rossum33894be1992-01-27 16:53:09 +0000998{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000999 PyObject *v, *result, *dflt = NULL;
1000 PyObject *name;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001001
Victor Stinner84b388b2017-01-17 03:52:27 +01001002 if (!_PyArg_UnpackStack(args, nargs, "getattr", 2, 3, &v, &name, &dflt))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001003 return NULL;
Martin v. Löwis5b222132007-06-10 09:51:05 +00001004
Victor Stinner84b388b2017-01-17 03:52:27 +01001005 if (!_PyArg_NoStackKeywords("getattr", kwnames)) {
1006 return NULL;
1007 }
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
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001130 if (type == &PyMap_Type && !_PyArg_NoKeywords("map()", kwds))
1131 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 *
Victor Stinnerfda6d0a2017-01-17 04:09:14 +01001306builtin_next(PyObject *self, PyObject **args, Py_ssize_t nargs,
1307 PyObject *kwnames)
Georg Brandla18af4e2007-04-21 15:47:16 +00001308{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001309 PyObject *it, *res;
1310 PyObject *def = NULL;
Georg Brandla18af4e2007-04-21 15:47:16 +00001311
Victor Stinnerfda6d0a2017-01-17 04:09:14 +01001312 if (!_PyArg_UnpackStack(args, nargs, "next", 1, 2, &it, &def))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001313 return NULL;
Victor Stinnerfda6d0a2017-01-17 04:09:14 +01001314
1315 if (!_PyArg_NoStackKeywords("next", kwnames)) {
1316 return NULL;
1317 }
1318
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001319 if (!PyIter_Check(it)) {
1320 PyErr_Format(PyExc_TypeError,
Philip Jenvey50add042011-11-06 16:37:52 -08001321 "'%.200s' object is not an iterator",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001322 it->ob_type->tp_name);
1323 return NULL;
1324 }
1325
1326 res = (*it->ob_type->tp_iternext)(it);
1327 if (res != NULL) {
1328 return res;
1329 } else if (def != NULL) {
1330 if (PyErr_Occurred()) {
1331 if(!PyErr_ExceptionMatches(PyExc_StopIteration))
1332 return NULL;
1333 PyErr_Clear();
1334 }
1335 Py_INCREF(def);
1336 return def;
1337 } else if (PyErr_Occurred()) {
1338 return NULL;
1339 } else {
1340 PyErr_SetNone(PyExc_StopIteration);
1341 return NULL;
1342 }
Georg Brandla18af4e2007-04-21 15:47:16 +00001343}
1344
1345PyDoc_STRVAR(next_doc,
1346"next(iterator[, default])\n\
1347\n\
1348Return the next item from the iterator. If default is given and the iterator\n\
1349is exhausted, it is returned instead of raising StopIteration.");
1350
1351
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001352/*[clinic input]
1353setattr as builtin_setattr
1354
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001355 obj: object
1356 name: object
1357 value: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001358 /
1359
1360Sets the named attribute on the given object to the specified value.
1361
1362setattr(x, 'y', v) is equivalent to ``x.y = v''
1363[clinic start generated code]*/
1364
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001365static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001366builtin_setattr_impl(PyObject *module, PyObject *obj, PyObject *name,
Larry Hastings89964c42015-04-14 18:07:59 -04001367 PyObject *value)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001368/*[clinic end generated code: output=dc2ce1d1add9acb4 input=bd2b7ca6875a1899]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001369{
1370 if (PyObject_SetAttr(obj, name, value) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001371 return NULL;
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02001372 Py_RETURN_NONE;
Guido van Rossum33894be1992-01-27 16:53:09 +00001373}
1374
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001375
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001376/*[clinic input]
1377delattr as builtin_delattr
1378
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001379 obj: object
1380 name: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001381 /
1382
1383Deletes the named attribute from the given object.
1384
1385delattr(x, 'y') is equivalent to ``del x.y''
1386[clinic start generated code]*/
1387
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001388static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001389builtin_delattr_impl(PyObject *module, PyObject *obj, PyObject *name)
1390/*[clinic end generated code: output=85134bc58dff79fa input=db16685d6b4b9410]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001391{
1392 if (PyObject_SetAttr(obj, name, (PyObject *)NULL) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001393 return NULL;
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02001394 Py_RETURN_NONE;
Guido van Rossum14144fc1994-08-29 12:53:40 +00001395}
1396
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001397
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001398/*[clinic input]
1399hash as builtin_hash
1400
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001401 obj: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001402 /
1403
1404Return the hash value for the given object.
1405
1406Two objects that compare equal must also have the same hash value, but the
1407reverse is not necessarily true.
1408[clinic start generated code]*/
1409
Guido van Rossum79f25d91997-04-29 20:08:16 +00001410static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001411builtin_hash(PyObject *module, PyObject *obj)
1412/*[clinic end generated code: output=237668e9d7688db7 input=58c48be822bf9c54]*/
Guido van Rossum9bfef441993-03-29 10:43:31 +00001413{
Benjamin Peterson8f67d082010-10-17 20:54:53 +00001414 Py_hash_t x;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001415
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001416 x = PyObject_Hash(obj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001417 if (x == -1)
1418 return NULL;
Benjamin Peterson8f67d082010-10-17 20:54:53 +00001419 return PyLong_FromSsize_t(x);
Guido van Rossum9bfef441993-03-29 10:43:31 +00001420}
1421
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001422
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001423/*[clinic input]
1424hex as builtin_hex
1425
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001426 number: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001427 /
1428
1429Return the hexadecimal representation of an integer.
1430
1431 >>> hex(12648430)
1432 '0xc0ffee'
1433[clinic start generated code]*/
1434
Guido van Rossum79f25d91997-04-29 20:08:16 +00001435static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001436builtin_hex(PyObject *module, PyObject *number)
1437/*[clinic end generated code: output=e46b612169099408 input=e645aff5fc7d540e]*/
Guido van Rossum006bcd41991-10-24 14:54:44 +00001438{
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001439 return PyNumber_ToBase(number, 16);
Guido van Rossum006bcd41991-10-24 14:54:44 +00001440}
1441
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001442
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001443/* AC: cannot convert yet, as needs PEP 457 group support in inspect */
Guido van Rossum79f25d91997-04-29 20:08:16 +00001444static PyObject *
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001445builtin_iter(PyObject *self, PyObject *args)
1446{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001447 PyObject *v, *w = NULL;
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001448
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001449 if (!PyArg_UnpackTuple(args, "iter", 1, 2, &v, &w))
1450 return NULL;
1451 if (w == NULL)
1452 return PyObject_GetIter(v);
1453 if (!PyCallable_Check(v)) {
1454 PyErr_SetString(PyExc_TypeError,
1455 "iter(v, w): v must be callable");
1456 return NULL;
1457 }
1458 return PyCallIter_New(v, w);
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001459}
1460
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001461PyDoc_STRVAR(iter_doc,
Georg Brandld11ae5d2008-05-16 13:27:32 +00001462"iter(iterable) -> iterator\n\
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001463iter(callable, sentinel) -> iterator\n\
1464\n\
1465Get an iterator from an object. In the first form, the argument must\n\
1466supply its own iterator, or be a sequence.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001467In the second form, the callable is called until it returns the sentinel.");
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001468
1469
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001470/*[clinic input]
1471len as builtin_len
1472
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001473 obj: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001474 /
1475
1476Return the number of items in a container.
1477[clinic start generated code]*/
1478
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001479static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001480builtin_len(PyObject *module, PyObject *obj)
1481/*[clinic end generated code: output=fa7a270d314dfb6c input=bc55598da9e9c9b5]*/
Guido van Rossum3f5da241990-12-20 15:06:42 +00001482{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001483 Py_ssize_t res;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001484
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001485 res = PyObject_Size(obj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001486 if (res < 0 && PyErr_Occurred())
1487 return NULL;
1488 return PyLong_FromSsize_t(res);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001489}
1490
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001491
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001492/*[clinic input]
1493locals as builtin_locals
1494
1495Return a dictionary containing the current scope's local variables.
1496
1497NOTE: Whether or not updates to this dictionary will affect name lookups in
1498the local scope and vice-versa is *implementation dependent* and not
1499covered by any backwards compatibility guarantees.
1500[clinic start generated code]*/
1501
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001502static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001503builtin_locals_impl(PyObject *module)
1504/*[clinic end generated code: output=b46c94015ce11448 input=7874018d478d5c4b]*/
Guido van Rossum872537c1995-07-07 22:43:42 +00001505{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001506 PyObject *d;
Guido van Rossum872537c1995-07-07 22:43:42 +00001507
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001508 d = PyEval_GetLocals();
1509 Py_XINCREF(d);
1510 return d;
Guido van Rossum872537c1995-07-07 22:43:42 +00001511}
1512
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001513
Guido van Rossum79f25d91997-04-29 20:08:16 +00001514static PyObject *
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001515min_max(PyObject *args, PyObject *kwds, int op)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001516{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001517 PyObject *v, *it, *item, *val, *maxitem, *maxval, *keyfunc=NULL;
Raymond Hettinger4d6018f2013-06-24 22:43:02 -07001518 PyObject *emptytuple, *defaultval = NULL;
1519 static char *kwlist[] = {"key", "default", NULL};
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001520 const char *name = op == Py_LT ? "min" : "max";
Raymond Hettinger4d6018f2013-06-24 22:43:02 -07001521 const int positional = PyTuple_Size(args) > 1;
1522 int ret;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001523
Raymond Hettinger4d6018f2013-06-24 22:43:02 -07001524 if (positional)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001525 v = args;
Serhiy Storchakac6792272013-10-19 21:03:34 +03001526 else if (!PyArg_UnpackTuple(args, name, 1, 1, &v))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001527 return NULL;
Tim Peters67d687a2002-04-29 21:27:32 +00001528
Raymond Hettinger4d6018f2013-06-24 22:43:02 -07001529 emptytuple = PyTuple_New(0);
1530 if (emptytuple == NULL)
1531 return NULL;
1532 ret = PyArg_ParseTupleAndKeywords(emptytuple, kwds, "|$OO", kwlist,
1533 &keyfunc, &defaultval);
1534 Py_DECREF(emptytuple);
1535 if (!ret)
1536 return NULL;
1537
1538 if (positional && defaultval != NULL) {
1539 PyErr_Format(PyExc_TypeError,
1540 "Cannot specify a default for %s() with multiple "
1541 "positional arguments", name);
1542 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001543 }
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001544
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001545 it = PyObject_GetIter(v);
1546 if (it == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001547 return NULL;
1548 }
Tim Petersc3074532001-05-03 07:00:32 +00001549
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001550 maxitem = NULL; /* the result */
1551 maxval = NULL; /* the value associated with the result */
1552 while (( item = PyIter_Next(it) )) {
1553 /* get the value from the key function */
1554 if (keyfunc != NULL) {
Victor Stinnerde4ae3d2016-12-04 22:59:09 +01001555 val = PyObject_CallFunctionObjArgs(keyfunc, item, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001556 if (val == NULL)
1557 goto Fail_it_item;
1558 }
1559 /* no key function; the value is the item */
1560 else {
1561 val = item;
1562 Py_INCREF(val);
1563 }
Tim Petersc3074532001-05-03 07:00:32 +00001564
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001565 /* maximum value and item are unset; set them */
1566 if (maxval == NULL) {
1567 maxitem = item;
1568 maxval = val;
1569 }
1570 /* maximum value and item are set; update them as necessary */
1571 else {
1572 int cmp = PyObject_RichCompareBool(val, maxval, op);
1573 if (cmp < 0)
1574 goto Fail_it_item_and_val;
1575 else if (cmp > 0) {
1576 Py_DECREF(maxval);
1577 Py_DECREF(maxitem);
1578 maxval = val;
1579 maxitem = item;
1580 }
1581 else {
1582 Py_DECREF(item);
1583 Py_DECREF(val);
1584 }
1585 }
1586 }
1587 if (PyErr_Occurred())
1588 goto Fail_it;
1589 if (maxval == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001590 assert(maxitem == NULL);
Raymond Hettinger4d6018f2013-06-24 22:43:02 -07001591 if (defaultval != NULL) {
1592 Py_INCREF(defaultval);
1593 maxitem = defaultval;
1594 } else {
1595 PyErr_Format(PyExc_ValueError,
1596 "%s() arg is an empty sequence", name);
1597 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001598 }
1599 else
1600 Py_DECREF(maxval);
1601 Py_DECREF(it);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001602 return maxitem;
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001603
1604Fail_it_item_and_val:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001605 Py_DECREF(val);
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001606Fail_it_item:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001607 Py_DECREF(item);
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001608Fail_it:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001609 Py_XDECREF(maxval);
1610 Py_XDECREF(maxitem);
1611 Py_DECREF(it);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001612 return NULL;
Guido van Rossum3f5da241990-12-20 15:06:42 +00001613}
1614
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001615/* AC: cannot convert yet, waiting for *args support */
Guido van Rossum79f25d91997-04-29 20:08:16 +00001616static PyObject *
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001617builtin_min(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001618{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001619 return min_max(args, kwds, Py_LT);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001620}
1621
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001622PyDoc_STRVAR(min_doc,
Raymond Hettinger2a545822014-05-19 22:20:52 +01001623"min(iterable, *[, default=obj, key=func]) -> value\n\
1624min(arg1, arg2, *args, *[, key=func]) -> value\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001625\n\
Raymond Hettinger2a545822014-05-19 22:20:52 +01001626With a single iterable argument, return its smallest item. The\n\
1627default keyword-only argument specifies an object to return if\n\
1628the provided iterable is empty.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001629With two or more arguments, return the smallest argument.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001630
1631
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001632/* AC: cannot convert yet, waiting for *args support */
Guido van Rossum79f25d91997-04-29 20:08:16 +00001633static PyObject *
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001634builtin_max(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001635{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001636 return min_max(args, kwds, Py_GT);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001637}
1638
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001639PyDoc_STRVAR(max_doc,
Raymond Hettinger2a545822014-05-19 22:20:52 +01001640"max(iterable, *[, default=obj, key=func]) -> value\n\
1641max(arg1, arg2, *args, *[, key=func]) -> value\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001642\n\
Raymond Hettinger2a545822014-05-19 22:20:52 +01001643With a single iterable argument, return its biggest item. The\n\
1644default keyword-only argument specifies an object to return if\n\
1645the provided iterable is empty.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001646With two or more arguments, return the largest argument.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001647
1648
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001649/*[clinic input]
1650oct as builtin_oct
1651
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001652 number: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001653 /
1654
1655Return the octal representation of an integer.
1656
1657 >>> oct(342391)
1658 '0o1234567'
1659[clinic start generated code]*/
1660
Guido van Rossum79f25d91997-04-29 20:08:16 +00001661static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001662builtin_oct(PyObject *module, PyObject *number)
1663/*[clinic end generated code: output=40a34656b6875352 input=ad6b274af4016c72]*/
Guido van Rossum006bcd41991-10-24 14:54:44 +00001664{
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001665 return PyNumber_ToBase(number, 8);
Guido van Rossum006bcd41991-10-24 14:54:44 +00001666}
1667
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001668
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001669/*[clinic input]
1670ord as builtin_ord
1671
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001672 c: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001673 /
1674
1675Return the Unicode code point for a one-character string.
1676[clinic start generated code]*/
1677
Guido van Rossum79f25d91997-04-29 20:08:16 +00001678static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001679builtin_ord(PyObject *module, PyObject *c)
1680/*[clinic end generated code: output=4fa5e87a323bae71 input=3064e5d6203ad012]*/
Guido van Rossum3f5da241990-12-20 15:06:42 +00001681{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001682 long ord;
1683 Py_ssize_t size;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001684
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001685 if (PyBytes_Check(c)) {
1686 size = PyBytes_GET_SIZE(c);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001687 if (size == 1) {
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001688 ord = (long)((unsigned char)*PyBytes_AS_STRING(c));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001689 return PyLong_FromLong(ord);
1690 }
1691 }
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001692 else if (PyUnicode_Check(c)) {
1693 if (PyUnicode_READY(c) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001694 return NULL;
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001695 size = PyUnicode_GET_LENGTH(c);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001696 if (size == 1) {
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001697 ord = (long)PyUnicode_READ_CHAR(c, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001698 return PyLong_FromLong(ord);
1699 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001700 }
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001701 else if (PyByteArray_Check(c)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001702 /* XXX Hopefully this is temporary */
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001703 size = PyByteArray_GET_SIZE(c);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001704 if (size == 1) {
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001705 ord = (long)((unsigned char)*PyByteArray_AS_STRING(c));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001706 return PyLong_FromLong(ord);
1707 }
1708 }
1709 else {
1710 PyErr_Format(PyExc_TypeError,
1711 "ord() expected string of length 1, but " \
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001712 "%.200s found", c->ob_type->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001713 return NULL;
1714 }
Guido van Rossum09095f32000-03-10 23:00:52 +00001715
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001716 PyErr_Format(PyExc_TypeError,
1717 "ord() expected a character, "
1718 "but string of length %zd found",
1719 size);
1720 return NULL;
Guido van Rossum3f5da241990-12-20 15:06:42 +00001721}
1722
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001723
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001724/*[clinic input]
1725pow as builtin_pow
1726
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001727 x: object
1728 y: object
1729 z: object = None
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001730 /
1731
1732Equivalent to x**y (with two arguments) or x**y % z (with three arguments)
1733
1734Some types, such as ints, are able to use a more efficient algorithm when
1735invoked using the three argument form.
1736[clinic start generated code]*/
1737
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001738static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001739builtin_pow_impl(PyObject *module, PyObject *x, PyObject *y, PyObject *z)
1740/*[clinic end generated code: output=50a14d5d130d404b input=653d57d38d41fc07]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001741{
1742 return PyNumber_Power(x, y, z);
1743}
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001744
1745
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001746/* AC: cannot convert yet, waiting for *args support */
Guido van Rossum34343512006-11-30 22:13:52 +00001747static PyObject *
INADA Naokibd584f12017-01-19 12:50:34 +01001748builtin_print(PyObject *self, PyObject **args, Py_ssize_t nargs, PyObject *kwnames)
Guido van Rossum34343512006-11-30 22:13:52 +00001749{
INADA Naokibd584f12017-01-19 12:50:34 +01001750 static const char * const _keywords[] = {"sep", "end", "file", "flush", 0};
1751 static struct _PyArg_Parser _parser = {"|OOOO:print", _keywords, 0};
Georg Brandlbc3b6822012-01-13 19:41:25 +01001752 PyObject *sep = NULL, *end = NULL, *file = NULL, *flush = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001753 int i, err;
Guido van Rossum34343512006-11-30 22:13:52 +00001754
INADA Naokibd584f12017-01-19 12:50:34 +01001755 if (kwnames != NULL &&
1756 !_PyArg_ParseStackAndKeywords(args + nargs, 0, kwnames, &_parser,
1757 &sep, &end, &file, &flush)) {
Georg Brandlbc3b6822012-01-13 19:41:25 +01001758 return NULL;
INADA Naokibd584f12017-01-19 12:50:34 +01001759 }
1760
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001761 if (file == NULL || file == Py_None) {
Victor Stinnerbd303c12013-11-07 23:07:29 +01001762 file = _PySys_GetObjectId(&PyId_stdout);
Victor Stinner1e53bba2013-07-16 22:26:05 +02001763 if (file == NULL) {
1764 PyErr_SetString(PyExc_RuntimeError, "lost sys.stdout");
1765 return NULL;
1766 }
1767
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001768 /* sys.stdout may be None when FILE* stdout isn't connected */
1769 if (file == Py_None)
1770 Py_RETURN_NONE;
1771 }
Guido van Rossum34343512006-11-30 22:13:52 +00001772
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001773 if (sep == Py_None) {
1774 sep = NULL;
1775 }
1776 else if (sep && !PyUnicode_Check(sep)) {
1777 PyErr_Format(PyExc_TypeError,
1778 "sep must be None or a string, not %.200s",
1779 sep->ob_type->tp_name);
1780 return NULL;
1781 }
1782 if (end == Py_None) {
1783 end = NULL;
1784 }
1785 else if (end && !PyUnicode_Check(end)) {
1786 PyErr_Format(PyExc_TypeError,
1787 "end must be None or a string, not %.200s",
1788 end->ob_type->tp_name);
1789 return NULL;
1790 }
Guido van Rossum34343512006-11-30 22:13:52 +00001791
INADA Naokibd584f12017-01-19 12:50:34 +01001792 for (i = 0; i < nargs; i++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001793 if (i > 0) {
1794 if (sep == NULL)
1795 err = PyFile_WriteString(" ", file);
1796 else
1797 err = PyFile_WriteObject(sep, file,
1798 Py_PRINT_RAW);
1799 if (err)
1800 return NULL;
1801 }
INADA Naokibd584f12017-01-19 12:50:34 +01001802 err = PyFile_WriteObject(args[i], file, Py_PRINT_RAW);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001803 if (err)
1804 return NULL;
1805 }
Guido van Rossum34343512006-11-30 22:13:52 +00001806
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001807 if (end == NULL)
1808 err = PyFile_WriteString("\n", file);
1809 else
1810 err = PyFile_WriteObject(end, file, Py_PRINT_RAW);
1811 if (err)
1812 return NULL;
Guido van Rossum34343512006-11-30 22:13:52 +00001813
Georg Brandlbc3b6822012-01-13 19:41:25 +01001814 if (flush != NULL) {
1815 PyObject *tmp;
1816 int do_flush = PyObject_IsTrue(flush);
1817 if (do_flush == -1)
1818 return NULL;
1819 else if (do_flush) {
Victor Stinner3466bde2016-09-05 18:16:01 -07001820 tmp = _PyObject_CallMethodId(file, &PyId_flush, NULL);
Georg Brandlbc3b6822012-01-13 19:41:25 +01001821 if (tmp == NULL)
1822 return NULL;
1823 else
1824 Py_DECREF(tmp);
1825 }
1826 }
1827
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001828 Py_RETURN_NONE;
Guido van Rossum34343512006-11-30 22:13:52 +00001829}
1830
1831PyDoc_STRVAR(print_doc,
Senthil Kumarane9175bd2012-08-10 13:53:45 -07001832"print(value, ..., sep=' ', end='\\n', file=sys.stdout, flush=False)\n\
Guido van Rossum34343512006-11-30 22:13:52 +00001833\n\
1834Prints the values to a stream, or to sys.stdout by default.\n\
1835Optional keyword arguments:\n\
Senthil Kumarane9175bd2012-08-10 13:53:45 -07001836file: a file-like object (stream); defaults to the current sys.stdout.\n\
1837sep: string inserted between values, default a space.\n\
1838end: string appended after the last value, default a newline.\n\
1839flush: whether to forcibly flush the stream.");
Guido van Rossum34343512006-11-30 22:13:52 +00001840
1841
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001842/*[clinic input]
1843input as builtin_input
1844
1845 prompt: object(c_default="NULL") = None
1846 /
1847
1848Read a string from standard input. The trailing newline is stripped.
1849
1850The prompt string, if given, is printed to standard output without a
1851trailing newline before reading input.
1852
1853If the user hits EOF (*nix: Ctrl-D, Windows: Ctrl-Z+Return), raise EOFError.
1854On *nix systems, readline is used if available.
1855[clinic start generated code]*/
1856
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001857static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001858builtin_input_impl(PyObject *module, PyObject *prompt)
1859/*[clinic end generated code: output=83db5a191e7a0d60 input=5e8bb70c2908fe3c]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001860{
Victor Stinnerbd303c12013-11-07 23:07:29 +01001861 PyObject *fin = _PySys_GetObjectId(&PyId_stdin);
1862 PyObject *fout = _PySys_GetObjectId(&PyId_stdout);
1863 PyObject *ferr = _PySys_GetObjectId(&PyId_stderr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001864 PyObject *tmp;
1865 long fd;
1866 int tty;
Guido van Rossuma88a0332007-02-26 16:59:55 +00001867
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001868 /* Check that stdin/out/err are intact */
1869 if (fin == NULL || fin == Py_None) {
1870 PyErr_SetString(PyExc_RuntimeError,
1871 "input(): lost sys.stdin");
1872 return NULL;
1873 }
1874 if (fout == NULL || fout == Py_None) {
1875 PyErr_SetString(PyExc_RuntimeError,
1876 "input(): lost sys.stdout");
1877 return NULL;
1878 }
1879 if (ferr == NULL || ferr == Py_None) {
1880 PyErr_SetString(PyExc_RuntimeError,
1881 "input(): lost sys.stderr");
1882 return NULL;
1883 }
Guido van Rossumeba76962007-05-27 09:13:28 +00001884
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001885 /* First of all, flush stderr */
Victor Stinner3466bde2016-09-05 18:16:01 -07001886 tmp = _PyObject_CallMethodId(ferr, &PyId_flush, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001887 if (tmp == NULL)
1888 PyErr_Clear();
1889 else
1890 Py_DECREF(tmp);
Guido van Rossumeba76962007-05-27 09:13:28 +00001891
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001892 /* We should only use (GNU) readline if Python's sys.stdin and
1893 sys.stdout are the same as C's stdin and stdout, because we
1894 need to pass it those. */
Victor Stinner3466bde2016-09-05 18:16:01 -07001895 tmp = _PyObject_CallMethodId(fin, &PyId_fileno, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001896 if (tmp == NULL) {
1897 PyErr_Clear();
1898 tty = 0;
1899 }
1900 else {
1901 fd = PyLong_AsLong(tmp);
1902 Py_DECREF(tmp);
1903 if (fd < 0 && PyErr_Occurred())
1904 return NULL;
1905 tty = fd == fileno(stdin) && isatty(fd);
1906 }
1907 if (tty) {
Victor Stinner3466bde2016-09-05 18:16:01 -07001908 tmp = _PyObject_CallMethodId(fout, &PyId_fileno, NULL);
Martin Panterc9a6ab52015-10-10 01:25:38 +00001909 if (tmp == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001910 PyErr_Clear();
Martin Panterc9a6ab52015-10-10 01:25:38 +00001911 tty = 0;
1912 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001913 else {
1914 fd = PyLong_AsLong(tmp);
1915 Py_DECREF(tmp);
1916 if (fd < 0 && PyErr_Occurred())
1917 return NULL;
1918 tty = fd == fileno(stdout) && isatty(fd);
1919 }
1920 }
Guido van Rossumeba76962007-05-27 09:13:28 +00001921
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001922 /* If we're interactive, use (GNU) readline */
1923 if (tty) {
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001924 PyObject *po = NULL;
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001925 char *promptstr;
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001926 char *s = NULL;
1927 PyObject *stdin_encoding = NULL, *stdin_errors = NULL;
1928 PyObject *stdout_encoding = NULL, *stdout_errors = NULL;
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +02001929 const char *stdin_encoding_str, *stdin_errors_str;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001930 PyObject *result;
Victor Stinnerc0f1a1a2011-02-23 12:07:37 +00001931 size_t len;
Martin v. Löwis4a7b5d52007-09-04 05:24:49 +00001932
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02001933 stdin_encoding = _PyObject_GetAttrId(fin, &PyId_encoding);
Antoine Pitrou5ee9d8a2011-11-06 00:38:45 +01001934 stdin_errors = _PyObject_GetAttrId(fin, &PyId_errors);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001935 if (!stdin_encoding || !stdin_errors)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001936 /* stdin is a text stream, so it must have an
1937 encoding. */
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001938 goto _readline_errors;
Serhiy Storchaka06515832016-11-20 09:13:07 +02001939 stdin_encoding_str = PyUnicode_AsUTF8(stdin_encoding);
1940 stdin_errors_str = PyUnicode_AsUTF8(stdin_errors);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001941 if (!stdin_encoding_str || !stdin_errors_str)
1942 goto _readline_errors;
Victor Stinner3466bde2016-09-05 18:16:01 -07001943 tmp = _PyObject_CallMethodId(fout, &PyId_flush, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001944 if (tmp == NULL)
1945 PyErr_Clear();
1946 else
1947 Py_DECREF(tmp);
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001948 if (prompt != NULL) {
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001949 /* We have a prompt, encode it as stdout would */
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +02001950 const char *stdout_encoding_str, *stdout_errors_str;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001951 PyObject *stringpo;
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02001952 stdout_encoding = _PyObject_GetAttrId(fout, &PyId_encoding);
Antoine Pitrou5ee9d8a2011-11-06 00:38:45 +01001953 stdout_errors = _PyObject_GetAttrId(fout, &PyId_errors);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001954 if (!stdout_encoding || !stdout_errors)
1955 goto _readline_errors;
Serhiy Storchaka06515832016-11-20 09:13:07 +02001956 stdout_encoding_str = PyUnicode_AsUTF8(stdout_encoding);
1957 stdout_errors_str = PyUnicode_AsUTF8(stdout_errors);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001958 if (!stdout_encoding_str || !stdout_errors_str)
1959 goto _readline_errors;
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001960 stringpo = PyObject_Str(prompt);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001961 if (stringpo == NULL)
1962 goto _readline_errors;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001963 po = PyUnicode_AsEncodedString(stringpo,
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001964 stdout_encoding_str, stdout_errors_str);
1965 Py_CLEAR(stdout_encoding);
1966 Py_CLEAR(stdout_errors);
1967 Py_CLEAR(stringpo);
1968 if (po == NULL)
1969 goto _readline_errors;
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03001970 assert(PyBytes_Check(po));
1971 promptstr = PyBytes_AS_STRING(po);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001972 }
1973 else {
1974 po = NULL;
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001975 promptstr = "";
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001976 }
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001977 s = PyOS_Readline(stdin, stdout, promptstr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001978 if (s == NULL) {
Richard Oudkerk614c5782013-04-03 13:44:50 +01001979 PyErr_CheckSignals();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001980 if (!PyErr_Occurred())
1981 PyErr_SetNone(PyExc_KeyboardInterrupt);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001982 goto _readline_errors;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001983 }
Victor Stinnerc0f1a1a2011-02-23 12:07:37 +00001984
1985 len = strlen(s);
1986 if (len == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001987 PyErr_SetNone(PyExc_EOFError);
1988 result = NULL;
1989 }
Victor Stinnerc0f1a1a2011-02-23 12:07:37 +00001990 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001991 if (len > PY_SSIZE_T_MAX) {
1992 PyErr_SetString(PyExc_OverflowError,
1993 "input: input too long");
1994 result = NULL;
1995 }
1996 else {
Victor Stinnerc0f1a1a2011-02-23 12:07:37 +00001997 len--; /* strip trailing '\n' */
1998 if (len != 0 && s[len-1] == '\r')
1999 len--; /* strip trailing '\r' */
Antoine Pitrou0d776b12011-11-06 00:34:26 +01002000 result = PyUnicode_Decode(s, len, stdin_encoding_str,
2001 stdin_errors_str);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002002 }
2003 }
2004 Py_DECREF(stdin_encoding);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01002005 Py_DECREF(stdin_errors);
2006 Py_XDECREF(po);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002007 PyMem_FREE(s);
2008 return result;
Antoine Pitrou0d776b12011-11-06 00:34:26 +01002009 _readline_errors:
2010 Py_XDECREF(stdin_encoding);
2011 Py_XDECREF(stdout_encoding);
2012 Py_XDECREF(stdin_errors);
2013 Py_XDECREF(stdout_errors);
2014 Py_XDECREF(po);
2015 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002016 }
Guido van Rossumeba76962007-05-27 09:13:28 +00002017
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002018 /* Fallback if we're not interactive */
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002019 if (prompt != NULL) {
2020 if (PyFile_WriteObject(prompt, fout, Py_PRINT_RAW) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002021 return NULL;
2022 }
Victor Stinner3466bde2016-09-05 18:16:01 -07002023 tmp = _PyObject_CallMethodId(fout, &PyId_flush, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002024 if (tmp == NULL)
2025 PyErr_Clear();
2026 else
2027 Py_DECREF(tmp);
2028 return PyFile_GetLine(fin, -1);
Guido van Rossuma88a0332007-02-26 16:59:55 +00002029}
2030
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002031
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002032/*[clinic input]
2033repr as builtin_repr
2034
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03002035 obj: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002036 /
2037
2038Return the canonical string representation of the object.
2039
2040For many object types, including most builtins, eval(repr(obj)) == obj.
2041[clinic start generated code]*/
2042
Guido van Rossum79f25d91997-04-29 20:08:16 +00002043static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002044builtin_repr(PyObject *module, PyObject *obj)
2045/*[clinic end generated code: output=7ed3778c44fd0194 input=1c9e6d66d3e3be04]*/
Guido van Rossumc89705d1992-11-26 08:54:07 +00002046{
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002047 return PyObject_Repr(obj);
Guido van Rossumc89705d1992-11-26 08:54:07 +00002048}
2049
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002050
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002051/* AC: cannot convert yet, as needs PEP 457 group support in inspect
2052 * or a semantic change to accept None for "ndigits"
2053 */
Guido van Rossum79f25d91997-04-29 20:08:16 +00002054static PyObject *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002055builtin_round(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum9e51f9b1993-02-12 16:29:05 +00002056{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002057 PyObject *ndigits = NULL;
2058 static char *kwlist[] = {"number", "ndigits", 0};
Benjamin Peterson214a7d22013-04-13 17:19:01 -04002059 PyObject *number, *round, *result;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002060
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002061 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|O:round",
2062 kwlist, &number, &ndigits))
2063 return NULL;
Alex Martelliae211f92007-08-22 23:21:33 +00002064
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002065 if (Py_TYPE(number)->tp_dict == NULL) {
2066 if (PyType_Ready(Py_TYPE(number)) < 0)
2067 return NULL;
2068 }
Guido van Rossum15d3d042007-08-24 02:02:45 +00002069
Benjamin Peterson214a7d22013-04-13 17:19:01 -04002070 round = _PyObject_LookupSpecial(number, &PyId___round__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002071 if (round == NULL) {
Benjamin Peterson214a7d22013-04-13 17:19:01 -04002072 if (!PyErr_Occurred())
2073 PyErr_Format(PyExc_TypeError,
2074 "type %.100s doesn't define __round__ method",
2075 Py_TYPE(number)->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002076 return NULL;
2077 }
Alex Martelliae211f92007-08-22 23:21:33 +00002078
Raymond Hettingerf0f1c232016-09-03 01:55:11 -07002079 if (ndigits == NULL || ndigits == Py_None)
Victor Stinnerf17c3de2016-12-06 18:46:19 +01002080 result = _PyObject_CallNoArg(round);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002081 else
Victor Stinnerde4ae3d2016-12-04 22:59:09 +01002082 result = PyObject_CallFunctionObjArgs(round, ndigits, NULL);
Benjamin Peterson214a7d22013-04-13 17:19:01 -04002083 Py_DECREF(round);
2084 return result;
Guido van Rossum9e51f9b1993-02-12 16:29:05 +00002085}
2086
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002087PyDoc_STRVAR(round_doc,
Mark Dickinson1124e712009-01-28 21:25:58 +00002088"round(number[, ndigits]) -> number\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002089\n\
2090Round a number to a given precision in decimal digits (default 0 digits).\n\
Mark Dickinson0d748c22008-07-05 11:29:03 +00002091This returns an int when called with one argument, otherwise the\n\
Georg Brandl809ddaa2008-07-01 20:39:59 +00002092same type as the number. ndigits may be negative.");
Guido van Rossum2fa33db2007-08-23 22:07:24 +00002093
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002094
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002095/*AC: we need to keep the kwds dict intact to easily call into the
2096 * list.sort method, which isn't currently supported in AC. So we just use
2097 * the initially generated signature with a custom implementation.
2098 */
2099/* [disabled clinic input]
2100sorted as builtin_sorted
2101
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03002102 iterable as seq: object
2103 key as keyfunc: object = None
2104 reverse: object = False
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002105
2106Return a new list containing all items from the iterable in ascending order.
2107
Raymond Hettinger7ea386e2016-08-25 21:11:50 -07002108A custom key function can be supplied to customize the sort order, and the
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002109reverse flag can be set to request the result in descending order.
2110[end disabled clinic input]*/
2111
2112PyDoc_STRVAR(builtin_sorted__doc__,
Serhiy Storchaka3a104252017-01-23 12:29:47 +02002113"sorted($module, iterable, /, *, key=None, reverse=False)\n"
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002114"--\n"
2115"\n"
2116"Return a new list containing all items from the iterable in ascending order.\n"
2117"\n"
Raymond Hettinger7ea386e2016-08-25 21:11:50 -07002118"A custom key function can be supplied to customize the sort order, and the\n"
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002119"reverse flag can be set to request the result in descending order.");
2120
2121#define BUILTIN_SORTED_METHODDEF \
Victor Stinner5a60eca2017-01-17 15:17:49 +01002122 {"sorted", (PyCFunction)builtin_sorted, METH_FASTCALL, builtin_sorted__doc__},
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002123
Raymond Hettinger64958a12003-12-17 20:43:33 +00002124static PyObject *
Victor Stinner5a60eca2017-01-17 15:17:49 +01002125builtin_sorted(PyObject *self, PyObject **args, Py_ssize_t nargs, PyObject *kwnames)
Raymond Hettinger64958a12003-12-17 20:43:33 +00002126{
Serhiy Storchaka7cf8beb2017-01-21 23:05:00 +02002127 PyObject *newlist, *v, *seq, *callable;
Victor Stinner5a60eca2017-01-17 15:17:49 +01002128
Serhiy Storchaka7cf8beb2017-01-21 23:05:00 +02002129 /* Keyword arguments are passed through list.sort() which will check
2130 them. */
2131 if (!_PyArg_UnpackStack(args, nargs, "sorted", 1, 1, &seq))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002132 return NULL;
Raymond Hettinger64958a12003-12-17 20:43:33 +00002133
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002134 newlist = PySequence_List(seq);
2135 if (newlist == NULL)
2136 return NULL;
Raymond Hettinger64958a12003-12-17 20:43:33 +00002137
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02002138 callable = _PyObject_GetAttrId(newlist, &PyId_sort);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002139 if (callable == NULL) {
2140 Py_DECREF(newlist);
2141 return NULL;
2142 }
Georg Brandl99d7e4e2005-08-31 22:21:15 +00002143
Serhiy Storchaka299dc232017-01-20 08:35:18 +02002144 assert(nargs >= 1);
Victor Stinner5a60eca2017-01-17 15:17:49 +01002145 v = _PyObject_FastCallKeywords(callable, args + 1, nargs - 1, kwnames);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002146 Py_DECREF(callable);
2147 if (v == NULL) {
2148 Py_DECREF(newlist);
2149 return NULL;
2150 }
2151 Py_DECREF(v);
2152 return newlist;
Raymond Hettinger64958a12003-12-17 20:43:33 +00002153}
2154
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002155
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002156/* AC: cannot convert yet, as needs PEP 457 group support in inspect */
Guido van Rossum79f25d91997-04-29 20:08:16 +00002157static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002158builtin_vars(PyObject *self, PyObject *args)
Guido van Rossum2d951851994-08-29 12:52:16 +00002159{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002160 PyObject *v = NULL;
2161 PyObject *d;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002162
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002163 if (!PyArg_UnpackTuple(args, "vars", 0, 1, &v))
2164 return NULL;
2165 if (v == NULL) {
2166 d = PyEval_GetLocals();
Victor Stinner41bb43a2013-10-29 01:19:37 +01002167 if (d == NULL)
2168 return NULL;
2169 Py_INCREF(d);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002170 }
2171 else {
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02002172 d = _PyObject_GetAttrId(v, &PyId___dict__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002173 if (d == NULL) {
2174 PyErr_SetString(PyExc_TypeError,
2175 "vars() argument must have __dict__ attribute");
2176 return NULL;
2177 }
2178 }
2179 return d;
Guido van Rossum2d951851994-08-29 12:52:16 +00002180}
2181
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002182PyDoc_STRVAR(vars_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002183"vars([object]) -> dictionary\n\
2184\n\
2185Without arguments, equivalent to locals().\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002186With an argument, equivalent to object.__dict__.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002187
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002188
2189/*[clinic input]
2190sum as builtin_sum
2191
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03002192 iterable: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002193 start: object(c_default="NULL") = 0
2194 /
2195
2196Return the sum of a 'start' value (default: 0) plus an iterable of numbers
2197
2198When the iterable is empty, return the start value.
2199This function is intended specifically for use with numeric values and may
2200reject non-numeric types.
2201[clinic start generated code]*/
2202
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002203static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002204builtin_sum_impl(PyObject *module, PyObject *iterable, PyObject *start)
2205/*[clinic end generated code: output=df758cec7d1d302f input=3b5b7a9d7611c73a]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002206{
2207 PyObject *result = start;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002208 PyObject *temp, *item, *iter;
Alex Martellia70b1912003-04-22 08:12:33 +00002209
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002210 iter = PyObject_GetIter(iterable);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002211 if (iter == NULL)
2212 return NULL;
Alex Martellia70b1912003-04-22 08:12:33 +00002213
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002214 if (result == NULL) {
2215 result = PyLong_FromLong(0);
2216 if (result == NULL) {
2217 Py_DECREF(iter);
2218 return NULL;
2219 }
2220 } else {
2221 /* reject string values for 'start' parameter */
2222 if (PyUnicode_Check(result)) {
2223 PyErr_SetString(PyExc_TypeError,
2224 "sum() can't sum strings [use ''.join(seq) instead]");
2225 Py_DECREF(iter);
2226 return NULL;
2227 }
Benjamin Petersonce071ca2011-07-29 14:23:47 -05002228 if (PyBytes_Check(result)) {
2229 PyErr_SetString(PyExc_TypeError,
2230 "sum() can't sum bytes [use b''.join(seq) instead]");
Benjamin Peterson405f32c2011-07-29 22:43:45 -05002231 Py_DECREF(iter);
Benjamin Petersonce071ca2011-07-29 14:23:47 -05002232 return NULL;
2233 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002234 if (PyByteArray_Check(result)) {
2235 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson4f921c22011-07-29 14:24:29 -05002236 "sum() can't sum bytearray [use b''.join(seq) instead]");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002237 Py_DECREF(iter);
2238 return NULL;
2239 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002240 Py_INCREF(result);
2241 }
Alex Martellia70b1912003-04-22 08:12:33 +00002242
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002243#ifndef SLOW_SUM
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002244 /* Fast addition by keeping temporary sums in C instead of new Python objects.
2245 Assumes all inputs are the same type. If the assumption fails, default
2246 to the more general routine.
2247 */
2248 if (PyLong_CheckExact(result)) {
2249 int overflow;
2250 long i_result = PyLong_AsLongAndOverflow(result, &overflow);
2251 /* If this already overflowed, don't even enter the loop. */
2252 if (overflow == 0) {
2253 Py_DECREF(result);
2254 result = NULL;
2255 }
2256 while(result == NULL) {
2257 item = PyIter_Next(iter);
2258 if (item == NULL) {
2259 Py_DECREF(iter);
2260 if (PyErr_Occurred())
2261 return NULL;
2262 return PyLong_FromLong(i_result);
2263 }
2264 if (PyLong_CheckExact(item)) {
2265 long b = PyLong_AsLongAndOverflow(item, &overflow);
2266 long x = i_result + b;
2267 if (overflow == 0 && ((x^i_result) >= 0 || (x^b) >= 0)) {
2268 i_result = x;
2269 Py_DECREF(item);
2270 continue;
2271 }
2272 }
2273 /* Either overflowed or is not an int. Restore real objects and process normally */
2274 result = PyLong_FromLong(i_result);
Christian Heimes704e2d32013-07-26 22:49:26 +02002275 if (result == NULL) {
2276 Py_DECREF(item);
2277 Py_DECREF(iter);
2278 return NULL;
2279 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002280 temp = PyNumber_Add(result, item);
2281 Py_DECREF(result);
2282 Py_DECREF(item);
2283 result = temp;
2284 if (result == NULL) {
2285 Py_DECREF(iter);
2286 return NULL;
2287 }
2288 }
2289 }
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002290
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002291 if (PyFloat_CheckExact(result)) {
2292 double f_result = PyFloat_AS_DOUBLE(result);
2293 Py_DECREF(result);
2294 result = NULL;
2295 while(result == NULL) {
2296 item = PyIter_Next(iter);
2297 if (item == NULL) {
2298 Py_DECREF(iter);
2299 if (PyErr_Occurred())
2300 return NULL;
2301 return PyFloat_FromDouble(f_result);
2302 }
2303 if (PyFloat_CheckExact(item)) {
2304 PyFPE_START_PROTECT("add", Py_DECREF(item); Py_DECREF(iter); return 0)
2305 f_result += PyFloat_AS_DOUBLE(item);
2306 PyFPE_END_PROTECT(f_result)
2307 Py_DECREF(item);
2308 continue;
2309 }
2310 if (PyLong_CheckExact(item)) {
2311 long value;
2312 int overflow;
2313 value = PyLong_AsLongAndOverflow(item, &overflow);
2314 if (!overflow) {
2315 PyFPE_START_PROTECT("add", Py_DECREF(item); Py_DECREF(iter); return 0)
2316 f_result += (double)value;
2317 PyFPE_END_PROTECT(f_result)
2318 Py_DECREF(item);
2319 continue;
2320 }
2321 }
2322 result = PyFloat_FromDouble(f_result);
2323 temp = PyNumber_Add(result, item);
2324 Py_DECREF(result);
2325 Py_DECREF(item);
2326 result = temp;
2327 if (result == NULL) {
2328 Py_DECREF(iter);
2329 return NULL;
2330 }
2331 }
2332 }
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002333#endif
2334
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002335 for(;;) {
2336 item = PyIter_Next(iter);
2337 if (item == NULL) {
2338 /* error, or end-of-sequence */
2339 if (PyErr_Occurred()) {
2340 Py_DECREF(result);
2341 result = NULL;
2342 }
2343 break;
2344 }
2345 /* It's tempting to use PyNumber_InPlaceAdd instead of
2346 PyNumber_Add here, to avoid quadratic running time
2347 when doing 'sum(list_of_lists, [])'. However, this
2348 would produce a change in behaviour: a snippet like
Mark Dickinson9acadc52009-10-26 14:19:42 +00002349
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002350 empty = []
2351 sum([[x] for x in range(10)], empty)
Mark Dickinson9acadc52009-10-26 14:19:42 +00002352
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002353 would change the value of empty. */
2354 temp = PyNumber_Add(result, item);
2355 Py_DECREF(result);
2356 Py_DECREF(item);
2357 result = temp;
2358 if (result == NULL)
2359 break;
2360 }
2361 Py_DECREF(iter);
2362 return result;
Alex Martellia70b1912003-04-22 08:12:33 +00002363}
2364
Alex Martellia70b1912003-04-22 08:12:33 +00002365
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002366/*[clinic input]
2367isinstance as builtin_isinstance
2368
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03002369 obj: object
2370 class_or_tuple: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002371 /
2372
2373Return whether an object is an instance of a class or of a subclass thereof.
2374
2375A tuple, as in ``isinstance(x, (A, B, ...))``, may be given as the target to
2376check against. This is equivalent to ``isinstance(x, A) or isinstance(x, B)
2377or ...`` etc.
2378[clinic start generated code]*/
2379
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002380static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002381builtin_isinstance_impl(PyObject *module, PyObject *obj,
Larry Hastings89964c42015-04-14 18:07:59 -04002382 PyObject *class_or_tuple)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002383/*[clinic end generated code: output=6faf01472c13b003 input=ffa743db1daf7549]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002384{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002385 int retval;
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002386
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002387 retval = PyObject_IsInstance(obj, class_or_tuple);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002388 if (retval < 0)
2389 return NULL;
2390 return PyBool_FromLong(retval);
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002391}
2392
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002393
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002394/*[clinic input]
2395issubclass as builtin_issubclass
2396
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03002397 cls: object
2398 class_or_tuple: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002399 /
2400
2401Return whether 'cls' is a derived from another class or is the same class.
2402
2403A tuple, as in ``issubclass(x, (A, B, ...))``, may be given as the target to
2404check against. This is equivalent to ``issubclass(x, A) or issubclass(x, B)
2405or ...`` etc.
2406[clinic start generated code]*/
2407
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002408static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002409builtin_issubclass_impl(PyObject *module, PyObject *cls,
Larry Hastings89964c42015-04-14 18:07:59 -04002410 PyObject *class_or_tuple)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002411/*[clinic end generated code: output=358412410cd7a250 input=af5f35e9ceaddaf6]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002412{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002413 int retval;
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002414
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002415 retval = PyObject_IsSubclass(cls, class_or_tuple);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002416 if (retval < 0)
2417 return NULL;
2418 return PyBool_FromLong(retval);
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002419}
2420
2421
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002422typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002423 PyObject_HEAD
2424 Py_ssize_t tuplesize;
2425 PyObject *ittuple; /* tuple of iterators */
2426 PyObject *result;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002427} zipobject;
2428
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002429static PyObject *
2430zip_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
Barry Warsawbd599b52000-08-03 15:45:29 +00002431{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002432 zipobject *lz;
2433 Py_ssize_t i;
2434 PyObject *ittuple; /* tuple of iterators */
2435 PyObject *result;
2436 Py_ssize_t tuplesize = PySequence_Length(args);
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002437
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002438 if (type == &PyZip_Type && !_PyArg_NoKeywords("zip()", kwds))
2439 return NULL;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002440
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002441 /* args must be a tuple */
2442 assert(PyTuple_Check(args));
Barry Warsawbd599b52000-08-03 15:45:29 +00002443
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002444 /* obtain iterators */
2445 ittuple = PyTuple_New(tuplesize);
2446 if (ittuple == NULL)
2447 return NULL;
2448 for (i=0; i < tuplesize; ++i) {
2449 PyObject *item = PyTuple_GET_ITEM(args, i);
2450 PyObject *it = PyObject_GetIter(item);
2451 if (it == NULL) {
2452 if (PyErr_ExceptionMatches(PyExc_TypeError))
2453 PyErr_Format(PyExc_TypeError,
2454 "zip argument #%zd must support iteration",
2455 i+1);
2456 Py_DECREF(ittuple);
2457 return NULL;
2458 }
2459 PyTuple_SET_ITEM(ittuple, i, it);
2460 }
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002461
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002462 /* create a result holder */
2463 result = PyTuple_New(tuplesize);
2464 if (result == NULL) {
2465 Py_DECREF(ittuple);
2466 return NULL;
2467 }
2468 for (i=0 ; i < tuplesize ; i++) {
2469 Py_INCREF(Py_None);
2470 PyTuple_SET_ITEM(result, i, Py_None);
2471 }
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002472
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002473 /* create zipobject structure */
2474 lz = (zipobject *)type->tp_alloc(type, 0);
2475 if (lz == NULL) {
2476 Py_DECREF(ittuple);
2477 Py_DECREF(result);
2478 return NULL;
2479 }
2480 lz->ittuple = ittuple;
2481 lz->tuplesize = tuplesize;
2482 lz->result = result;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002483
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002484 return (PyObject *)lz;
Barry Warsawbd599b52000-08-03 15:45:29 +00002485}
2486
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002487static void
2488zip_dealloc(zipobject *lz)
2489{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002490 PyObject_GC_UnTrack(lz);
2491 Py_XDECREF(lz->ittuple);
2492 Py_XDECREF(lz->result);
2493 Py_TYPE(lz)->tp_free(lz);
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002494}
2495
2496static int
2497zip_traverse(zipobject *lz, visitproc visit, void *arg)
2498{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002499 Py_VISIT(lz->ittuple);
2500 Py_VISIT(lz->result);
2501 return 0;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002502}
2503
2504static PyObject *
2505zip_next(zipobject *lz)
2506{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002507 Py_ssize_t i;
2508 Py_ssize_t tuplesize = lz->tuplesize;
2509 PyObject *result = lz->result;
2510 PyObject *it;
2511 PyObject *item;
2512 PyObject *olditem;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002513
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002514 if (tuplesize == 0)
2515 return NULL;
2516 if (Py_REFCNT(result) == 1) {
2517 Py_INCREF(result);
2518 for (i=0 ; i < tuplesize ; i++) {
2519 it = PyTuple_GET_ITEM(lz->ittuple, i);
2520 item = (*Py_TYPE(it)->tp_iternext)(it);
Serhiy Storchaka278d03b2013-04-06 22:52:34 +03002521 if (item == NULL) {
2522 Py_DECREF(result);
2523 return NULL;
2524 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002525 olditem = PyTuple_GET_ITEM(result, i);
2526 PyTuple_SET_ITEM(result, i, item);
2527 Py_DECREF(olditem);
2528 }
2529 } else {
2530 result = PyTuple_New(tuplesize);
2531 if (result == NULL)
Serhiy Storchaka278d03b2013-04-06 22:52:34 +03002532 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002533 for (i=0 ; i < tuplesize ; i++) {
2534 it = PyTuple_GET_ITEM(lz->ittuple, i);
2535 item = (*Py_TYPE(it)->tp_iternext)(it);
Serhiy Storchaka278d03b2013-04-06 22:52:34 +03002536 if (item == NULL) {
2537 Py_DECREF(result);
2538 return NULL;
2539 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002540 PyTuple_SET_ITEM(result, i, item);
2541 }
2542 }
2543 return result;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002544}
Barry Warsawbd599b52000-08-03 15:45:29 +00002545
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002546static PyObject *
2547zip_reduce(zipobject *lz)
2548{
2549 /* Just recreate the zip with the internal iterator tuple */
2550 return Py_BuildValue("OO", Py_TYPE(lz), lz->ittuple);
2551}
2552
2553static PyMethodDef zip_methods[] = {
2554 {"__reduce__", (PyCFunction)zip_reduce, METH_NOARGS, reduce_doc},
2555 {NULL, NULL} /* sentinel */
2556};
2557
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002558PyDoc_STRVAR(zip_doc,
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002559"zip(iter1 [,iter2 [...]]) --> zip object\n\
Barry Warsawbd599b52000-08-03 15:45:29 +00002560\n\
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002561Return a zip object whose .__next__() method returns a tuple where\n\
2562the i-th element comes from the i-th iterable argument. The .__next__()\n\
2563method continues until the shortest iterable in the argument sequence\n\
Georg Brandlced51db2008-12-04 18:28:38 +00002564is exhausted and then it raises StopIteration.");
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002565
2566PyTypeObject PyZip_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002567 PyVarObject_HEAD_INIT(&PyType_Type, 0)
2568 "zip", /* tp_name */
2569 sizeof(zipobject), /* tp_basicsize */
2570 0, /* tp_itemsize */
2571 /* methods */
2572 (destructor)zip_dealloc, /* tp_dealloc */
2573 0, /* tp_print */
2574 0, /* tp_getattr */
2575 0, /* tp_setattr */
2576 0, /* tp_reserved */
2577 0, /* tp_repr */
2578 0, /* tp_as_number */
2579 0, /* tp_as_sequence */
2580 0, /* tp_as_mapping */
2581 0, /* tp_hash */
2582 0, /* tp_call */
2583 0, /* tp_str */
2584 PyObject_GenericGetAttr, /* tp_getattro */
2585 0, /* tp_setattro */
2586 0, /* tp_as_buffer */
2587 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
2588 Py_TPFLAGS_BASETYPE, /* tp_flags */
2589 zip_doc, /* tp_doc */
2590 (traverseproc)zip_traverse, /* tp_traverse */
2591 0, /* tp_clear */
2592 0, /* tp_richcompare */
2593 0, /* tp_weaklistoffset */
2594 PyObject_SelfIter, /* tp_iter */
2595 (iternextfunc)zip_next, /* tp_iternext */
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002596 zip_methods, /* tp_methods */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002597 0, /* tp_members */
2598 0, /* tp_getset */
2599 0, /* tp_base */
2600 0, /* tp_dict */
2601 0, /* tp_descr_get */
2602 0, /* tp_descr_set */
2603 0, /* tp_dictoffset */
2604 0, /* tp_init */
2605 PyType_GenericAlloc, /* tp_alloc */
2606 zip_new, /* tp_new */
2607 PyObject_GC_Del, /* tp_free */
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002608};
Barry Warsawbd599b52000-08-03 15:45:29 +00002609
2610
Guido van Rossum79f25d91997-04-29 20:08:16 +00002611static PyMethodDef builtin_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002612 {"__build_class__", (PyCFunction)builtin___build_class__,
Victor Stinner773dc6d2017-01-16 23:46:26 +01002613 METH_FASTCALL, build_class_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002614 {"__import__", (PyCFunction)builtin___import__, METH_VARARGS | METH_KEYWORDS, import_doc},
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002615 BUILTIN_ABS_METHODDEF
2616 BUILTIN_ALL_METHODDEF
2617 BUILTIN_ANY_METHODDEF
2618 BUILTIN_ASCII_METHODDEF
2619 BUILTIN_BIN_METHODDEF
2620 BUILTIN_CALLABLE_METHODDEF
2621 BUILTIN_CHR_METHODDEF
2622 BUILTIN_COMPILE_METHODDEF
2623 BUILTIN_DELATTR_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002624 {"dir", builtin_dir, METH_VARARGS, dir_doc},
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002625 BUILTIN_DIVMOD_METHODDEF
2626 BUILTIN_EVAL_METHODDEF
2627 BUILTIN_EXEC_METHODDEF
2628 BUILTIN_FORMAT_METHODDEF
Victor Stinner84b388b2017-01-17 03:52:27 +01002629 {"getattr", (PyCFunction)builtin_getattr, METH_FASTCALL, getattr_doc},
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002630 BUILTIN_GLOBALS_METHODDEF
2631 BUILTIN_HASATTR_METHODDEF
2632 BUILTIN_HASH_METHODDEF
2633 BUILTIN_HEX_METHODDEF
2634 BUILTIN_ID_METHODDEF
2635 BUILTIN_INPUT_METHODDEF
2636 BUILTIN_ISINSTANCE_METHODDEF
2637 BUILTIN_ISSUBCLASS_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002638 {"iter", builtin_iter, METH_VARARGS, iter_doc},
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002639 BUILTIN_LEN_METHODDEF
2640 BUILTIN_LOCALS_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002641 {"max", (PyCFunction)builtin_max, METH_VARARGS | METH_KEYWORDS, max_doc},
2642 {"min", (PyCFunction)builtin_min, METH_VARARGS | METH_KEYWORDS, min_doc},
Victor Stinnerfda6d0a2017-01-17 04:09:14 +01002643 {"next", (PyCFunction)builtin_next, METH_FASTCALL, next_doc},
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002644 BUILTIN_OCT_METHODDEF
2645 BUILTIN_ORD_METHODDEF
2646 BUILTIN_POW_METHODDEF
INADA Naokibd584f12017-01-19 12:50:34 +01002647 {"print", (PyCFunction)builtin_print, METH_FASTCALL, print_doc},
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002648 BUILTIN_REPR_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002649 {"round", (PyCFunction)builtin_round, METH_VARARGS | METH_KEYWORDS, round_doc},
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002650 BUILTIN_SETATTR_METHODDEF
2651 BUILTIN_SORTED_METHODDEF
2652 BUILTIN_SUM_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002653 {"vars", builtin_vars, METH_VARARGS, vars_doc},
2654 {NULL, NULL},
Guido van Rossum3f5da241990-12-20 15:06:42 +00002655};
2656
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002657PyDoc_STRVAR(builtin_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002658"Built-in functions, exceptions, and other objects.\n\
2659\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002660Noteworthy: None is the `nil' object; Ellipsis represents `...' in slices.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002661
Martin v. Löwis1a214512008-06-11 05:26:20 +00002662static struct PyModuleDef builtinsmodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002663 PyModuleDef_HEAD_INIT,
2664 "builtins",
2665 builtin_doc,
2666 -1, /* multiple "initialization" just copies the module dict. */
2667 builtin_methods,
2668 NULL,
2669 NULL,
2670 NULL,
2671 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00002672};
2673
2674
Guido van Rossum25ce5661997-08-02 03:10:38 +00002675PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002676_PyBuiltin_Init(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +00002677{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002678 PyObject *mod, *dict, *debug;
Benjamin Peterson42124a72012-10-30 23:41:54 -04002679
2680 if (PyType_Ready(&PyFilter_Type) < 0 ||
2681 PyType_Ready(&PyMap_Type) < 0 ||
2682 PyType_Ready(&PyZip_Type) < 0)
2683 return NULL;
2684
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002685 mod = PyModule_Create(&builtinsmodule);
2686 if (mod == NULL)
2687 return NULL;
2688 dict = PyModule_GetDict(mod);
Tim Peters4b7625e2001-09-13 21:37:17 +00002689
Tim Peters7571a0f2003-03-23 17:52:28 +00002690#ifdef Py_TRACE_REFS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002691 /* "builtins" exposes a number of statically allocated objects
2692 * that, before this code was added in 2.3, never showed up in
2693 * the list of "all objects" maintained by Py_TRACE_REFS. As a
2694 * result, programs leaking references to None and False (etc)
2695 * couldn't be diagnosed by examining sys.getobjects(0).
2696 */
Tim Peters7571a0f2003-03-23 17:52:28 +00002697#define ADD_TO_ALL(OBJECT) _Py_AddToAllObjects((PyObject *)(OBJECT), 0)
2698#else
2699#define ADD_TO_ALL(OBJECT) (void)0
2700#endif
2701
Tim Peters4b7625e2001-09-13 21:37:17 +00002702#define SETBUILTIN(NAME, OBJECT) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002703 if (PyDict_SetItemString(dict, NAME, (PyObject *)OBJECT) < 0) \
2704 return NULL; \
2705 ADD_TO_ALL(OBJECT)
Tim Peters4b7625e2001-09-13 21:37:17 +00002706
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002707 SETBUILTIN("None", Py_None);
2708 SETBUILTIN("Ellipsis", Py_Ellipsis);
2709 SETBUILTIN("NotImplemented", Py_NotImplemented);
2710 SETBUILTIN("False", Py_False);
2711 SETBUILTIN("True", Py_True);
2712 SETBUILTIN("bool", &PyBool_Type);
2713 SETBUILTIN("memoryview", &PyMemoryView_Type);
2714 SETBUILTIN("bytearray", &PyByteArray_Type);
2715 SETBUILTIN("bytes", &PyBytes_Type);
2716 SETBUILTIN("classmethod", &PyClassMethod_Type);
2717 SETBUILTIN("complex", &PyComplex_Type);
2718 SETBUILTIN("dict", &PyDict_Type);
2719 SETBUILTIN("enumerate", &PyEnum_Type);
2720 SETBUILTIN("filter", &PyFilter_Type);
2721 SETBUILTIN("float", &PyFloat_Type);
2722 SETBUILTIN("frozenset", &PyFrozenSet_Type);
2723 SETBUILTIN("property", &PyProperty_Type);
2724 SETBUILTIN("int", &PyLong_Type);
2725 SETBUILTIN("list", &PyList_Type);
2726 SETBUILTIN("map", &PyMap_Type);
2727 SETBUILTIN("object", &PyBaseObject_Type);
2728 SETBUILTIN("range", &PyRange_Type);
2729 SETBUILTIN("reversed", &PyReversed_Type);
2730 SETBUILTIN("set", &PySet_Type);
2731 SETBUILTIN("slice", &PySlice_Type);
2732 SETBUILTIN("staticmethod", &PyStaticMethod_Type);
2733 SETBUILTIN("str", &PyUnicode_Type);
2734 SETBUILTIN("super", &PySuper_Type);
2735 SETBUILTIN("tuple", &PyTuple_Type);
2736 SETBUILTIN("type", &PyType_Type);
2737 SETBUILTIN("zip", &PyZip_Type);
2738 debug = PyBool_FromLong(Py_OptimizeFlag == 0);
2739 if (PyDict_SetItemString(dict, "__debug__", debug) < 0) {
Serhiy Storchakacfdfbb42016-06-18 09:44:03 +03002740 Py_DECREF(debug);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002741 return NULL;
2742 }
Serhiy Storchakacfdfbb42016-06-18 09:44:03 +03002743 Py_DECREF(debug);
Barry Warsaw757af0e1997-08-29 22:13:51 +00002744
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002745 return mod;
Tim Peters7571a0f2003-03-23 17:52:28 +00002746#undef ADD_TO_ALL
Tim Peters4b7625e2001-09-13 21:37:17 +00002747#undef SETBUILTIN
Guido van Rossum3f5da241990-12-20 15:06:42 +00002748}