blob: ef5a34cae900b648dd68655b045a4066ac06f690 [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 *
Guido van Rossum52cc1d82007-03-18 15:41:51 +000055builtin___build_class__(PyObject *self, PyObject *args, PyObject *kwds)
56{
Nick Coghlan19d24672016-12-05 16:47:55 +100057 PyObject *func, *name, *bases, *mkw, *meta, *winner, *prep, *ns;
58 PyObject *cls = NULL, *cell = NULL;
Florent Xicluna4d46c2a2011-10-28 15:00:50 +020059 Py_ssize_t nargs;
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 assert(args != NULL);
63 if (!PyTuple_Check(args)) {
64 PyErr_SetString(PyExc_TypeError,
65 "__build_class__: args is not a tuple");
66 return NULL;
67 }
68 nargs = PyTuple_GET_SIZE(args);
69 if (nargs < 2) {
70 PyErr_SetString(PyExc_TypeError,
71 "__build_class__: not enough arguments");
72 return NULL;
73 }
74 func = PyTuple_GET_ITEM(args, 0); /* Better be callable */
Benjamin Petersone8e14592013-05-16 14:37:25 -050075 if (!PyFunction_Check(func)) {
76 PyErr_SetString(PyExc_TypeError,
Zachary Ware9b338722014-08-05 14:01:10 -050077 "__build_class__: func must be a function");
Benjamin Petersone8e14592013-05-16 14:37:25 -050078 return NULL;
79 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000080 name = PyTuple_GET_ITEM(args, 1);
81 if (!PyUnicode_Check(name)) {
82 PyErr_SetString(PyExc_TypeError,
83 "__build_class__: name is not a string");
84 return NULL;
85 }
86 bases = PyTuple_GetSlice(args, 2, nargs);
87 if (bases == NULL)
88 return NULL;
Guido van Rossum52cc1d82007-03-18 15:41:51 +000089
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000090 if (kwds == NULL) {
91 meta = NULL;
92 mkw = NULL;
93 }
94 else {
95 mkw = PyDict_Copy(kwds); /* Don't modify kwds passed in! */
96 if (mkw == NULL) {
97 Py_DECREF(bases);
98 return NULL;
Guido van Rossum52cc1d82007-03-18 15:41:51 +000099 }
Victor Stinnerae9f1612013-11-06 22:46:51 +0100100 meta = _PyDict_GetItemId(mkw, &PyId_metaclass);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000101 if (meta != NULL) {
102 Py_INCREF(meta);
Victor Stinnerae9f1612013-11-06 22:46:51 +0100103 if (_PyDict_DelItemId(mkw, &PyId_metaclass) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000104 Py_DECREF(meta);
105 Py_DECREF(mkw);
106 Py_DECREF(bases);
107 return NULL;
108 }
Nick Coghlande31b192011-10-23 22:04:16 +1000109 /* metaclass is explicitly given, check if it's indeed a class */
110 isclass = PyType_Check(meta);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000111 }
112 }
113 if (meta == NULL) {
Nick Coghlande31b192011-10-23 22:04:16 +1000114 /* if there are no bases, use type: */
115 if (PyTuple_GET_SIZE(bases) == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000116 meta = (PyObject *) (&PyType_Type);
Nick Coghlande31b192011-10-23 22:04:16 +1000117 }
118 /* else get the type of the first base */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000119 else {
120 PyObject *base0 = PyTuple_GET_ITEM(bases, 0);
121 meta = (PyObject *) (base0->ob_type);
122 }
123 Py_INCREF(meta);
Nick Coghlande31b192011-10-23 22:04:16 +1000124 isclass = 1; /* meta is really a class */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000125 }
Nick Coghlan9715d262011-10-23 22:36:42 +1000126
Nick Coghlande31b192011-10-23 22:04:16 +1000127 if (isclass) {
128 /* meta is really a class, so check for a more derived
129 metaclass, or possible metaclass conflicts: */
130 winner = (PyObject *)_PyType_CalculateMetaclass((PyTypeObject *)meta,
131 bases);
132 if (winner == NULL) {
133 Py_DECREF(meta);
134 Py_XDECREF(mkw);
135 Py_DECREF(bases);
136 return NULL;
137 }
138 if (winner != meta) {
139 Py_DECREF(meta);
140 meta = winner;
141 Py_INCREF(meta);
142 }
143 }
144 /* else: meta is not a class, so we cannot do the metaclass
145 calculation, so we will use the explicitly given object as it is */
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +0200146 prep = _PyObject_GetAttrId(meta, &PyId___prepare__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000147 if (prep == NULL) {
148 if (PyErr_ExceptionMatches(PyExc_AttributeError)) {
149 PyErr_Clear();
Eric Snow4f29e752016-09-08 15:11:11 -0700150 ns = PyDict_New();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000151 }
152 else {
153 Py_DECREF(meta);
154 Py_XDECREF(mkw);
155 Py_DECREF(bases);
156 return NULL;
157 }
158 }
159 else {
Victor Stinner463b86a2016-08-22 23:33:13 +0200160 PyObject *pargs[2] = {name, bases};
161 ns = _PyObject_FastCallDict(prep, pargs, 2, mkw);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000162 Py_DECREF(prep);
163 }
164 if (ns == NULL) {
165 Py_DECREF(meta);
166 Py_XDECREF(mkw);
167 Py_DECREF(bases);
168 return NULL;
169 }
Nick Coghlan19d24672016-12-05 16:47:55 +1000170 cell = PyEval_EvalCodeEx(PyFunction_GET_CODE(func), PyFunction_GET_GLOBALS(func), ns,
Benjamin Petersone8e14592013-05-16 14:37:25 -0500171 NULL, 0, NULL, 0, NULL, 0, NULL,
172 PyFunction_GET_CLOSURE(func));
Nick Coghlan19d24672016-12-05 16:47:55 +1000173 if (cell != NULL) {
Victor Stinnerd1c2a8e2016-08-23 01:34:35 +0200174 PyObject *margs[3] = {name, bases, ns};
175 cls = _PyObject_FastCallDict(meta, margs, 3, mkw);
Nick Coghlan19d24672016-12-05 16:47:55 +1000176 if (cls != NULL && PyType_Check(cls) && PyCell_Check(cell)) {
177 PyObject *cell_cls = PyCell_GET(cell);
178 if (cell_cls != cls) {
179 /* TODO: In 3.7, DeprecationWarning will become RuntimeError.
180 * At that point, cell_error won't be needed.
181 */
182 int cell_error;
183 if (cell_cls == NULL) {
184 const char *msg =
185 "__class__ not set defining %.200R as %.200R. "
186 "Was __classcell__ propagated to type.__new__?";
187 cell_error = PyErr_WarnFormat(
188 PyExc_DeprecationWarning, 1, msg, name, cls);
189 } else {
190 const char *msg =
191 "__class__ set to %.200R defining %.200R as %.200R";
192 PyErr_Format(PyExc_TypeError, msg, cell_cls, name, cls);
193 cell_error = 1;
194 }
195 if (cell_error) {
196 Py_DECREF(cls);
197 cls = NULL;
198 goto error;
199 } else {
200 /* Fill in the cell, since type.__new__ didn't do it */
201 PyCell_Set(cell, cls);
202 }
203 }
204 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000205 }
Nick Coghlan19d24672016-12-05 16:47:55 +1000206error:
207 Py_XDECREF(cell);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000208 Py_DECREF(ns);
209 Py_DECREF(meta);
210 Py_XDECREF(mkw);
211 Py_DECREF(bases);
212 return cls;
Guido van Rossum52cc1d82007-03-18 15:41:51 +0000213}
214
215PyDoc_STRVAR(build_class_doc,
216"__build_class__(func, name, *bases, metaclass=None, **kwds) -> class\n\
217\n\
218Internal helper function used by the class statement.");
219
220static PyObject *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000221builtin___import__(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000222{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000223 static char *kwlist[] = {"name", "globals", "locals", "fromlist",
224 "level", 0};
Victor Stinnerfe93faf2011-03-14 15:54:52 -0400225 PyObject *name, *globals = NULL, *locals = NULL, *fromlist = NULL;
Brett Cannonfd074152012-04-14 14:10:13 -0400226 int level = 0;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000227
Victor Stinnerfe93faf2011-03-14 15:54:52 -0400228 if (!PyArg_ParseTupleAndKeywords(args, kwds, "U|OOOi:__import__",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000229 kwlist, &name, &globals, &locals, &fromlist, &level))
230 return NULL;
Victor Stinnerfe93faf2011-03-14 15:54:52 -0400231 return PyImport_ImportModuleLevelObject(name, globals, locals,
232 fromlist, level);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000233}
234
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000235PyDoc_STRVAR(import_doc,
Brett Cannoncb4996a2012-08-06 16:34:44 -0400236"__import__(name, globals=None, locals=None, fromlist=(), level=0) -> module\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000237\n\
Brett Cannon5305a992010-09-27 21:08:38 +0000238Import a module. Because this function is meant for use by the Python\n\
239interpreter and not for general use it is better to use\n\
240importlib.import_module() to programmatically import a module.\n\
241\n\
242The globals argument is only used to determine the context;\n\
243they are not modified. The locals argument is unused. The fromlist\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000244should be a list of names to emulate ``from name import ...'', or an\n\
245empty list to emulate ``import name''.\n\
246When importing a module from a package, note that __import__('A.B', ...)\n\
247returns package A when fromlist is empty, but its submodule B when\n\
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000248fromlist is not empty. Level is used to determine whether to perform \n\
Brett Cannon722d3ae2012-07-30 17:45:54 -0400249absolute or relative imports. 0 is absolute while a positive number\n\
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000250is the number of parent directories to search relative to the current module.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000251
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000252
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000253/*[clinic input]
254abs as builtin_abs
255
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300256 x: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000257 /
258
259Return the absolute value of the argument.
260[clinic start generated code]*/
261
Guido van Rossum79f25d91997-04-29 20:08:16 +0000262static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300263builtin_abs(PyObject *module, PyObject *x)
264/*[clinic end generated code: output=b1b433b9e51356f5 input=bed4ca14e29c20d1]*/
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000265{
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000266 return PyNumber_Absolute(x);
Guido van Rossum3f5da241990-12-20 15:06:42 +0000267}
268
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000269/*[clinic input]
270all as builtin_all
271
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300272 iterable: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000273 /
274
275Return True if bool(x) is True for all values x in the iterable.
276
277If the iterable is empty, return True.
278[clinic start generated code]*/
279
Raymond Hettinger96229b12005-03-11 06:49:40 +0000280static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300281builtin_all(PyObject *module, PyObject *iterable)
282/*[clinic end generated code: output=ca2a7127276f79b3 input=1a7c5d1bc3438a21]*/
Raymond Hettinger96229b12005-03-11 06:49:40 +0000283{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000284 PyObject *it, *item;
285 PyObject *(*iternext)(PyObject *);
286 int cmp;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000287
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000288 it = PyObject_GetIter(iterable);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000289 if (it == NULL)
290 return NULL;
291 iternext = *Py_TYPE(it)->tp_iternext;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000292
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000293 for (;;) {
294 item = iternext(it);
295 if (item == NULL)
296 break;
297 cmp = PyObject_IsTrue(item);
298 Py_DECREF(item);
299 if (cmp < 0) {
300 Py_DECREF(it);
301 return NULL;
302 }
303 if (cmp == 0) {
304 Py_DECREF(it);
305 Py_RETURN_FALSE;
306 }
307 }
308 Py_DECREF(it);
309 if (PyErr_Occurred()) {
310 if (PyErr_ExceptionMatches(PyExc_StopIteration))
311 PyErr_Clear();
312 else
313 return NULL;
314 }
315 Py_RETURN_TRUE;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000316}
317
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000318/*[clinic input]
319any as builtin_any
320
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300321 iterable: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000322 /
323
324Return True if bool(x) is True for any x in the iterable.
325
326If the iterable is empty, return False.
327[clinic start generated code]*/
328
Raymond Hettinger96229b12005-03-11 06:49:40 +0000329static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300330builtin_any(PyObject *module, PyObject *iterable)
331/*[clinic end generated code: output=fa65684748caa60e input=41d7451c23384f24]*/
Raymond Hettinger96229b12005-03-11 06:49:40 +0000332{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000333 PyObject *it, *item;
334 PyObject *(*iternext)(PyObject *);
335 int cmp;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000336
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000337 it = PyObject_GetIter(iterable);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000338 if (it == NULL)
339 return NULL;
340 iternext = *Py_TYPE(it)->tp_iternext;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000341
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000342 for (;;) {
343 item = iternext(it);
344 if (item == NULL)
345 break;
346 cmp = PyObject_IsTrue(item);
347 Py_DECREF(item);
348 if (cmp < 0) {
349 Py_DECREF(it);
350 return NULL;
351 }
Raymond Hettinger5098b582015-10-09 00:42:47 -0400352 if (cmp > 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000353 Py_DECREF(it);
354 Py_RETURN_TRUE;
355 }
356 }
357 Py_DECREF(it);
358 if (PyErr_Occurred()) {
359 if (PyErr_ExceptionMatches(PyExc_StopIteration))
360 PyErr_Clear();
361 else
362 return NULL;
363 }
364 Py_RETURN_FALSE;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000365}
366
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000367/*[clinic input]
368ascii as builtin_ascii
369
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300370 obj: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000371 /
372
373Return an ASCII-only representation of an object.
374
375As repr(), return a string containing a printable representation of an
376object, but escape the non-ASCII characters in the string returned by
377repr() using \\x, \\u or \\U escapes. This generates a string similar
378to that returned by repr() in Python 2.
379[clinic start generated code]*/
380
Georg Brandl559e5d72008-06-11 18:37:52 +0000381static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300382builtin_ascii(PyObject *module, PyObject *obj)
383/*[clinic end generated code: output=6d37b3f0984c7eb9 input=4c62732e1b3a3cc9]*/
Georg Brandl559e5d72008-06-11 18:37:52 +0000384{
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000385 return PyObject_ASCII(obj);
Georg Brandl559e5d72008-06-11 18:37:52 +0000386}
387
Georg Brandl559e5d72008-06-11 18:37:52 +0000388
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000389/*[clinic input]
390bin as builtin_bin
391
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300392 number: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000393 /
394
395Return the binary representation of an integer.
396
397 >>> bin(2796202)
398 '0b1010101010101010101010'
399[clinic start generated code]*/
400
Guido van Rossum79f25d91997-04-29 20:08:16 +0000401static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300402builtin_bin(PyObject *module, PyObject *number)
403/*[clinic end generated code: output=b6fc4ad5e649f4f7 input=53f8a0264bacaf90]*/
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000404{
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000405 return PyNumber_ToBase(number, 2);
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000406}
407
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000408
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000409/*[clinic input]
410callable as builtin_callable
411
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300412 obj: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000413 /
414
415Return whether the object is callable (i.e., some kind of function).
416
417Note that classes are callable, as are instances of classes with a
418__call__() method.
419[clinic start generated code]*/
420
Antoine Pitroue71362d2010-11-27 22:00:11 +0000421static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300422builtin_callable(PyObject *module, PyObject *obj)
423/*[clinic end generated code: output=2b095d59d934cb7e input=1423bab99cc41f58]*/
Antoine Pitroue71362d2010-11-27 22:00:11 +0000424{
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000425 return PyBool_FromLong((long)PyCallable_Check(obj));
Antoine Pitroue71362d2010-11-27 22:00:11 +0000426}
427
Antoine Pitroue71362d2010-11-27 22:00:11 +0000428
Raymond Hettinger17301e92008-03-13 00:19:26 +0000429typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000430 PyObject_HEAD
431 PyObject *func;
432 PyObject *it;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000433} filterobject;
434
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000435static PyObject *
Raymond Hettinger17301e92008-03-13 00:19:26 +0000436filter_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
Guido van Rossum12d12c51993-10-26 17:58:25 +0000437{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000438 PyObject *func, *seq;
439 PyObject *it;
440 filterobject *lz;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000441
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000442 if (type == &PyFilter_Type && !_PyArg_NoKeywords("filter()", kwds))
443 return NULL;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000444
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000445 if (!PyArg_UnpackTuple(args, "filter", 2, 2, &func, &seq))
446 return NULL;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000447
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000448 /* Get iterator. */
449 it = PyObject_GetIter(seq);
450 if (it == NULL)
451 return NULL;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000452
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000453 /* create filterobject structure */
454 lz = (filterobject *)type->tp_alloc(type, 0);
455 if (lz == NULL) {
456 Py_DECREF(it);
457 return NULL;
458 }
459 Py_INCREF(func);
460 lz->func = func;
461 lz->it = it;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000462
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000463 return (PyObject *)lz;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000464}
465
466static void
467filter_dealloc(filterobject *lz)
468{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000469 PyObject_GC_UnTrack(lz);
470 Py_XDECREF(lz->func);
471 Py_XDECREF(lz->it);
472 Py_TYPE(lz)->tp_free(lz);
Raymond Hettinger17301e92008-03-13 00:19:26 +0000473}
474
475static int
476filter_traverse(filterobject *lz, visitproc visit, void *arg)
477{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000478 Py_VISIT(lz->it);
479 Py_VISIT(lz->func);
480 return 0;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000481}
482
483static PyObject *
484filter_next(filterobject *lz)
485{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000486 PyObject *item;
487 PyObject *it = lz->it;
488 long ok;
489 PyObject *(*iternext)(PyObject *);
Raymond Hettingerbd5f0e82015-10-09 01:34:08 -0400490 int checktrue = lz->func == Py_None || lz->func == (PyObject *)&PyBool_Type;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000491
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000492 iternext = *Py_TYPE(it)->tp_iternext;
493 for (;;) {
494 item = iternext(it);
495 if (item == NULL)
496 return NULL;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000497
Raymond Hettingerbd5f0e82015-10-09 01:34:08 -0400498 if (checktrue) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000499 ok = PyObject_IsTrue(item);
500 } else {
501 PyObject *good;
Raymond Hettingerbd5f0e82015-10-09 01:34:08 -0400502 good = PyObject_CallFunctionObjArgs(lz->func, item, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000503 if (good == NULL) {
504 Py_DECREF(item);
505 return NULL;
506 }
507 ok = PyObject_IsTrue(good);
508 Py_DECREF(good);
509 }
Antoine Pitrou6f430e42012-08-15 23:18:25 +0200510 if (ok > 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000511 return item;
512 Py_DECREF(item);
Antoine Pitrou6f430e42012-08-15 23:18:25 +0200513 if (ok < 0)
514 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000515 }
Guido van Rossum12d12c51993-10-26 17:58:25 +0000516}
517
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +0000518static PyObject *
519filter_reduce(filterobject *lz)
520{
521 return Py_BuildValue("O(OO)", Py_TYPE(lz), lz->func, lz->it);
522}
523
524PyDoc_STRVAR(reduce_doc, "Return state information for pickling.");
525
526static PyMethodDef filter_methods[] = {
527 {"__reduce__", (PyCFunction)filter_reduce, METH_NOARGS, reduce_doc},
528 {NULL, NULL} /* sentinel */
529};
530
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000531PyDoc_STRVAR(filter_doc,
Georg Brandld11ae5d2008-05-16 13:27:32 +0000532"filter(function or None, iterable) --> filter object\n\
Guido van Rossumc1f779c2007-07-03 08:25:58 +0000533\n\
Georg Brandld11ae5d2008-05-16 13:27:32 +0000534Return an iterator yielding those items of iterable for which function(item)\n\
Raymond Hettinger17301e92008-03-13 00:19:26 +0000535is true. If function is None, return the items that are true.");
536
537PyTypeObject PyFilter_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000538 PyVarObject_HEAD_INIT(&PyType_Type, 0)
539 "filter", /* tp_name */
540 sizeof(filterobject), /* tp_basicsize */
541 0, /* tp_itemsize */
542 /* methods */
543 (destructor)filter_dealloc, /* tp_dealloc */
544 0, /* tp_print */
545 0, /* tp_getattr */
546 0, /* tp_setattr */
547 0, /* tp_reserved */
548 0, /* tp_repr */
549 0, /* tp_as_number */
550 0, /* tp_as_sequence */
551 0, /* tp_as_mapping */
552 0, /* tp_hash */
553 0, /* tp_call */
554 0, /* tp_str */
555 PyObject_GenericGetAttr, /* tp_getattro */
556 0, /* tp_setattro */
557 0, /* tp_as_buffer */
558 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
559 Py_TPFLAGS_BASETYPE, /* tp_flags */
560 filter_doc, /* tp_doc */
561 (traverseproc)filter_traverse, /* tp_traverse */
562 0, /* tp_clear */
563 0, /* tp_richcompare */
564 0, /* tp_weaklistoffset */
565 PyObject_SelfIter, /* tp_iter */
566 (iternextfunc)filter_next, /* tp_iternext */
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +0000567 filter_methods, /* tp_methods */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000568 0, /* tp_members */
569 0, /* tp_getset */
570 0, /* tp_base */
571 0, /* tp_dict */
572 0, /* tp_descr_get */
573 0, /* tp_descr_set */
574 0, /* tp_dictoffset */
575 0, /* tp_init */
576 PyType_GenericAlloc, /* tp_alloc */
577 filter_new, /* tp_new */
578 PyObject_GC_Del, /* tp_free */
Raymond Hettinger17301e92008-03-13 00:19:26 +0000579};
580
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000581
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000582/*[clinic input]
583format as builtin_format
584
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300585 value: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000586 format_spec: unicode(c_default="NULL") = ''
587 /
588
589Return value.__format__(format_spec)
590
591format_spec defaults to the empty string
592[clinic start generated code]*/
593
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000594static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300595builtin_format_impl(PyObject *module, PyObject *value, PyObject *format_spec)
596/*[clinic end generated code: output=2f40bdfa4954b077 input=6325e751a1b29b86]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000597{
Eric Smith8fd3eba2008-02-17 19:48:00 +0000598 return PyObject_Format(value, format_spec);
Eric Smith8c663262007-08-25 02:26:07 +0000599}
600
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000601/*[clinic input]
602chr as builtin_chr
603
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300604 i: int
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000605 /
606
607Return a Unicode string of one character with ordinal i; 0 <= i <= 0x10ffff.
608[clinic start generated code]*/
609
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000610static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300611builtin_chr_impl(PyObject *module, int i)
612/*[clinic end generated code: output=c733afcd200afcb7 input=3f604ef45a70750d]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000613{
614 return PyUnicode_FromOrdinal(i);
615}
Guido van Rossum09095f32000-03-10 23:00:52 +0000616
617
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +0200618static const char *
Martin Pantereeb896c2015-11-07 02:32:21 +0000619source_as_string(PyObject *cmd, const char *funcname, const char *what, PyCompilerFlags *cf, PyObject **cmd_copy)
Guido van Rossumf15a29f2007-05-04 00:41:39 +0000620{
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +0200621 const char *str;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000622 Py_ssize_t size;
Martin Pantereeb896c2015-11-07 02:32:21 +0000623 Py_buffer view;
Guido van Rossumf15a29f2007-05-04 00:41:39 +0000624
Martin Pantereeb896c2015-11-07 02:32:21 +0000625 *cmd_copy = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000626 if (PyUnicode_Check(cmd)) {
627 cf->cf_flags |= PyCF_IGNORE_COOKIE;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200628 str = PyUnicode_AsUTF8AndSize(cmd, &size);
629 if (str == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000630 return NULL;
631 }
Martin Pantereeb896c2015-11-07 02:32:21 +0000632 else if (PyBytes_Check(cmd)) {
633 str = PyBytes_AS_STRING(cmd);
634 size = PyBytes_GET_SIZE(cmd);
635 }
636 else if (PyByteArray_Check(cmd)) {
637 str = PyByteArray_AS_STRING(cmd);
638 size = PyByteArray_GET_SIZE(cmd);
639 }
640 else if (PyObject_GetBuffer(cmd, &view, PyBUF_SIMPLE) == 0) {
641 /* Copy to NUL-terminated buffer. */
642 *cmd_copy = PyBytes_FromStringAndSize(
643 (const char *)view.buf, view.len);
644 PyBuffer_Release(&view);
645 if (*cmd_copy == NULL) {
646 return NULL;
647 }
648 str = PyBytes_AS_STRING(*cmd_copy);
649 size = PyBytes_GET_SIZE(*cmd_copy);
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +0200650 }
651 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000652 PyErr_Format(PyExc_TypeError,
653 "%s() arg 1 must be a %s object",
654 funcname, what);
655 return NULL;
656 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200657
Serhiy Storchaka3dd3e262015-02-03 01:25:42 +0200658 if (strlen(str) != (size_t)size) {
Serhiy Storchakad8a14472014-09-06 20:07:17 +0300659 PyErr_SetString(PyExc_ValueError,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000660 "source code string cannot contain null bytes");
Martin Pantereeb896c2015-11-07 02:32:21 +0000661 Py_CLEAR(*cmd_copy);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000662 return NULL;
663 }
664 return str;
Guido van Rossumf15a29f2007-05-04 00:41:39 +0000665}
666
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000667/*[clinic input]
668compile as builtin_compile
669
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300670 source: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000671 filename: object(converter="PyUnicode_FSDecoder")
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300672 mode: str
673 flags: int = 0
Serhiy Storchaka8b2e8b62015-05-30 11:30:39 +0300674 dont_inherit: int(c_default="0") = False
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300675 optimize: int = -1
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000676
677Compile source into a code object that can be executed by exec() or eval().
678
679The source code may represent a Python module, statement or expression.
680The filename will be used for run-time error messages.
681The mode must be 'exec' to compile a module, 'single' to compile a
682single (interactive) statement, or 'eval' to compile an expression.
683The flags argument, if present, controls which future statements influence
684the compilation of the code.
Serhiy Storchaka8b2e8b62015-05-30 11:30:39 +0300685The dont_inherit argument, if true, stops the compilation inheriting
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000686the effects of any future statements in effect in the code calling
Serhiy Storchaka8b2e8b62015-05-30 11:30:39 +0300687compile; if absent or false these statements do influence the compilation,
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000688in addition to any features explicitly specified.
689[clinic start generated code]*/
690
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000691static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300692builtin_compile_impl(PyObject *module, PyObject *source, PyObject *filename,
693 const char *mode, int flags, int dont_inherit,
694 int optimize)
695/*[clinic end generated code: output=1fa176e33452bb63 input=9d53e8cfb3c86414]*/
Guido van Rossum5b722181993-03-30 17:46:03 +0000696{
Martin Panter61d6e4a2015-11-07 02:56:11 +0000697 PyObject *source_copy;
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +0200698 const char *str;
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000699 int compile_mode = -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000700 int is_ast;
701 PyCompilerFlags cf;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000702 int start[] = {Py_file_input, Py_eval_input, Py_single_input};
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000703 PyObject *result;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000704
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000705 cf.cf_flags = flags | PyCF_SOURCE_IS_UTF8;
Tim Peters6cd6a822001-08-17 22:11:27 +0000706
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000707 if (flags &
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000708 ~(PyCF_MASK | PyCF_MASK_OBSOLETE | PyCF_DONT_IMPLY_DEDENT | PyCF_ONLY_AST))
709 {
710 PyErr_SetString(PyExc_ValueError,
711 "compile(): unrecognised flags");
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000712 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000713 }
714 /* XXX Warn if (supplied_flags & PyCF_MASK_OBSOLETE) != 0? */
Tim Peters6cd6a822001-08-17 22:11:27 +0000715
Georg Brandl8334fd92010-12-04 10:26:46 +0000716 if (optimize < -1 || optimize > 2) {
717 PyErr_SetString(PyExc_ValueError,
718 "compile(): invalid optimize value");
719 goto error;
720 }
721
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000722 if (!dont_inherit) {
723 PyEval_MergeCompilerFlags(&cf);
724 }
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000725
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000726 if (strcmp(mode, "exec") == 0)
727 compile_mode = 0;
728 else if (strcmp(mode, "eval") == 0)
729 compile_mode = 1;
730 else if (strcmp(mode, "single") == 0)
731 compile_mode = 2;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000732 else {
733 PyErr_SetString(PyExc_ValueError,
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000734 "compile() mode must be 'exec', 'eval' or 'single'");
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000735 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000736 }
Neal Norwitzdb4115f2008-03-31 04:20:05 +0000737
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000738 is_ast = PyAST_Check(source);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000739 if (is_ast == -1)
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000740 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000741 if (is_ast) {
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000742 if (flags & PyCF_ONLY_AST) {
743 Py_INCREF(source);
744 result = source;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000745 }
746 else {
747 PyArena *arena;
748 mod_ty mod;
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000749
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000750 arena = PyArena_New();
Stefan Krah07795df2012-08-20 17:19:50 +0200751 if (arena == NULL)
752 goto error;
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000753 mod = PyAST_obj2mod(source, arena, compile_mode);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000754 if (mod == NULL) {
755 PyArena_Free(arena);
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000756 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000757 }
Benjamin Peterson832bfe22011-08-09 16:15:04 -0500758 if (!PyAST_Validate(mod)) {
759 PyArena_Free(arena);
760 goto error;
761 }
Victor Stinner14e461d2013-08-26 22:28:21 +0200762 result = (PyObject*)PyAST_CompileObject(mod, filename,
763 &cf, optimize, arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000764 PyArena_Free(arena);
765 }
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000766 goto finally;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000767 }
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000768
Martin Panter61d6e4a2015-11-07 02:56:11 +0000769 str = source_as_string(source, "compile", "string, bytes or AST", &cf, &source_copy);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000770 if (str == NULL)
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000771 goto error;
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000772
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000773 result = Py_CompileStringObject(str, filename, start[compile_mode], &cf, optimize);
Martin Panter61d6e4a2015-11-07 02:56:11 +0000774 Py_XDECREF(source_copy);
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000775 goto finally;
776
777error:
778 result = NULL;
779finally:
Victor Stinner14e461d2013-08-26 22:28:21 +0200780 Py_DECREF(filename);
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000781 return result;
Guido van Rossum5b722181993-03-30 17:46:03 +0000782}
783
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000784/* AC: cannot convert yet, as needs PEP 457 group support in inspect */
Guido van Rossum79f25d91997-04-29 20:08:16 +0000785static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000786builtin_dir(PyObject *self, PyObject *args)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000787{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000788 PyObject *arg = NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000789
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000790 if (!PyArg_UnpackTuple(args, "dir", 0, 1, &arg))
791 return NULL;
792 return PyObject_Dir(arg);
Guido van Rossum3f5da241990-12-20 15:06:42 +0000793}
794
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000795PyDoc_STRVAR(dir_doc,
Tim Peters5d2b77c2001-09-03 05:47:38 +0000796"dir([object]) -> list of strings\n"
797"\n"
Georg Brandle32b4222007-03-10 22:13:27 +0000798"If called without an argument, return the names in the current scope.\n"
799"Else, return an alphabetized list of names comprising (some of) the attributes\n"
800"of the given object, and of attributes reachable from it.\n"
801"If the object supplies a method named __dir__, it will be used; otherwise\n"
802"the default dir() logic is used and returns:\n"
803" for a module object: the module's attributes.\n"
804" for a class object: its attributes, and recursively the attributes\n"
805" of its bases.\n"
Guido van Rossumd8faa362007-04-27 19:54:29 +0000806" for any other object: its attributes, its class's attributes, and\n"
Georg Brandle32b4222007-03-10 22:13:27 +0000807" recursively the attributes of its class's base classes.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000808
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000809/*[clinic input]
810divmod as builtin_divmod
Guido van Rossum6a00cd81995-01-07 12:39:01 +0000811
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300812 x: object
813 y: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000814 /
815
Zachary Ware7f227d92016-04-28 14:39:50 -0500816Return the tuple (x//y, x%y). Invariant: div*y + mod == x.
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000817[clinic start generated code]*/
818
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000819static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300820builtin_divmod_impl(PyObject *module, PyObject *x, PyObject *y)
821/*[clinic end generated code: output=b06d8a5f6e0c745e input=175ad9c84ff41a85]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000822{
823 return PyNumber_Divmod(x, y);
824}
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000825
826
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000827/*[clinic input]
828eval as builtin_eval
829
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300830 source: object
831 globals: object = None
832 locals: object = None
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000833 /
834
835Evaluate the given source in the context of globals and locals.
836
837The source may be a string representing a Python expression
838or a code object as returned by compile().
839The globals must be a dictionary and locals can be any mapping,
840defaulting to the current globals and locals.
841If only globals is given, locals defaults to it.
842[clinic start generated code]*/
843
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000844static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300845builtin_eval_impl(PyObject *module, PyObject *source, PyObject *globals,
Larry Hastings89964c42015-04-14 18:07:59 -0400846 PyObject *locals)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300847/*[clinic end generated code: output=0a0824aa70093116 input=11ee718a8640e527]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000848{
Martin Panter61d6e4a2015-11-07 02:56:11 +0000849 PyObject *result, *source_copy;
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +0200850 const char *str;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000851 PyCompilerFlags cf;
Guido van Rossum590baa41993-11-30 13:40:46 +0000852
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000853 if (locals != Py_None && !PyMapping_Check(locals)) {
854 PyErr_SetString(PyExc_TypeError, "locals must be a mapping");
855 return NULL;
856 }
857 if (globals != Py_None && !PyDict_Check(globals)) {
858 PyErr_SetString(PyExc_TypeError, PyMapping_Check(globals) ?
859 "globals must be a real dict; try eval(expr, {}, mapping)"
860 : "globals must be a dict");
861 return NULL;
862 }
863 if (globals == Py_None) {
864 globals = PyEval_GetGlobals();
Victor Stinner41bb43a2013-10-29 01:19:37 +0100865 if (locals == Py_None) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000866 locals = PyEval_GetLocals();
Victor Stinner41bb43a2013-10-29 01:19:37 +0100867 if (locals == NULL)
868 return NULL;
869 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000870 }
871 else if (locals == Py_None)
872 locals = globals;
Tim Peters9fa96be2001-08-17 23:04:59 +0000873
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000874 if (globals == NULL || locals == NULL) {
875 PyErr_SetString(PyExc_TypeError,
876 "eval must be given globals and locals "
877 "when called without a frame");
878 return NULL;
879 }
Georg Brandl77c85e62005-09-15 10:46:13 +0000880
Victor Stinnerb44562b2013-11-06 19:03:11 +0100881 if (_PyDict_GetItemId(globals, &PyId___builtins__) == NULL) {
882 if (_PyDict_SetItemId(globals, &PyId___builtins__,
883 PyEval_GetBuiltins()) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000884 return NULL;
885 }
Tim Peters9fa96be2001-08-17 23:04:59 +0000886
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000887 if (PyCode_Check(source)) {
888 if (PyCode_GetNumFree((PyCodeObject *)source) > 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000889 PyErr_SetString(PyExc_TypeError,
890 "code object passed to eval() may not contain free variables");
891 return NULL;
892 }
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000893 return PyEval_EvalCode(source, globals, locals);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000894 }
Tim Peters9fa96be2001-08-17 23:04:59 +0000895
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000896 cf.cf_flags = PyCF_SOURCE_IS_UTF8;
Martin Panter61d6e4a2015-11-07 02:56:11 +0000897 str = source_as_string(source, "eval", "string, bytes or code", &cf, &source_copy);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000898 if (str == NULL)
899 return NULL;
Just van Rossum3aaf42c2003-02-10 08:21:10 +0000900
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000901 while (*str == ' ' || *str == '\t')
902 str++;
Tim Peters9fa96be2001-08-17 23:04:59 +0000903
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000904 (void)PyEval_MergeCompilerFlags(&cf);
905 result = PyRun_StringFlags(str, Py_eval_input, globals, locals, &cf);
Martin Panter61d6e4a2015-11-07 02:56:11 +0000906 Py_XDECREF(source_copy);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000907 return result;
Guido van Rossum3f5da241990-12-20 15:06:42 +0000908}
909
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000910/*[clinic input]
911exec as builtin_exec
912
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300913 source: object
914 globals: object = None
915 locals: object = None
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000916 /
917
918Execute the given source in the context of globals and locals.
919
920The source may be a string representing one or more Python statements
921or a code object as returned by compile().
922The globals must be a dictionary and locals can be any mapping,
923defaulting to the current globals and locals.
924If only globals is given, locals defaults to it.
925[clinic start generated code]*/
926
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000927static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300928builtin_exec_impl(PyObject *module, PyObject *source, PyObject *globals,
Larry Hastings89964c42015-04-14 18:07:59 -0400929 PyObject *locals)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300930/*[clinic end generated code: output=3c90efc6ab68ef5d input=01ca3e1c01692829]*/
Georg Brandl7cae87c2006-09-06 06:51:57 +0000931{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000932 PyObject *v;
Georg Brandl2cabc562008-08-28 07:57:16 +0000933
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000934 if (globals == Py_None) {
935 globals = PyEval_GetGlobals();
936 if (locals == Py_None) {
937 locals = PyEval_GetLocals();
Victor Stinner41bb43a2013-10-29 01:19:37 +0100938 if (locals == NULL)
939 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000940 }
941 if (!globals || !locals) {
942 PyErr_SetString(PyExc_SystemError,
943 "globals and locals cannot be NULL");
944 return NULL;
945 }
946 }
947 else if (locals == Py_None)
948 locals = globals;
Georg Brandl7cae87c2006-09-06 06:51:57 +0000949
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000950 if (!PyDict_Check(globals)) {
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000951 PyErr_Format(PyExc_TypeError, "exec() globals must be a dict, not %.100s",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000952 globals->ob_type->tp_name);
953 return NULL;
954 }
955 if (!PyMapping_Check(locals)) {
956 PyErr_Format(PyExc_TypeError,
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000957 "locals must be a mapping or None, not %.100s",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000958 locals->ob_type->tp_name);
959 return NULL;
960 }
Victor Stinnerb44562b2013-11-06 19:03:11 +0100961 if (_PyDict_GetItemId(globals, &PyId___builtins__) == NULL) {
962 if (_PyDict_SetItemId(globals, &PyId___builtins__,
963 PyEval_GetBuiltins()) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000964 return NULL;
965 }
966
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000967 if (PyCode_Check(source)) {
968 if (PyCode_GetNumFree((PyCodeObject *)source) > 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000969 PyErr_SetString(PyExc_TypeError,
970 "code object passed to exec() may not "
971 "contain free variables");
972 return NULL;
973 }
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000974 v = PyEval_EvalCode(source, globals, locals);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000975 }
976 else {
Martin Panter61d6e4a2015-11-07 02:56:11 +0000977 PyObject *source_copy;
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +0200978 const char *str;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000979 PyCompilerFlags cf;
980 cf.cf_flags = PyCF_SOURCE_IS_UTF8;
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000981 str = source_as_string(source, "exec",
Martin Panter61d6e4a2015-11-07 02:56:11 +0000982 "string, bytes or code", &cf,
983 &source_copy);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000984 if (str == NULL)
985 return NULL;
986 if (PyEval_MergeCompilerFlags(&cf))
987 v = PyRun_StringFlags(str, Py_file_input, globals,
988 locals, &cf);
989 else
990 v = PyRun_String(str, Py_file_input, globals, locals);
Martin Panter61d6e4a2015-11-07 02:56:11 +0000991 Py_XDECREF(source_copy);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000992 }
993 if (v == NULL)
994 return NULL;
995 Py_DECREF(v);
996 Py_RETURN_NONE;
Georg Brandl7cae87c2006-09-06 06:51:57 +0000997}
998
Georg Brandl7cae87c2006-09-06 06:51:57 +0000999
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001000/* AC: cannot convert yet, as needs PEP 457 group support in inspect */
Guido van Rossum79f25d91997-04-29 20:08:16 +00001001static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001002builtin_getattr(PyObject *self, PyObject *args)
Guido van Rossum33894be1992-01-27 16:53:09 +00001003{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001004 PyObject *v, *result, *dflt = NULL;
1005 PyObject *name;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001006
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001007 if (!PyArg_UnpackTuple(args, "getattr", 2, 3, &v, &name, &dflt))
1008 return NULL;
Martin v. Löwis5b222132007-06-10 09:51:05 +00001009
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001010 if (!PyUnicode_Check(name)) {
1011 PyErr_SetString(PyExc_TypeError,
1012 "getattr(): attribute name must be string");
1013 return NULL;
1014 }
1015 result = PyObject_GetAttr(v, name);
1016 if (result == NULL && dflt != NULL &&
1017 PyErr_ExceptionMatches(PyExc_AttributeError))
1018 {
1019 PyErr_Clear();
1020 Py_INCREF(dflt);
1021 result = dflt;
1022 }
1023 return result;
Guido van Rossum9bfef441993-03-29 10:43:31 +00001024}
1025
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001026PyDoc_STRVAR(getattr_doc,
Guido van Rossum950ff291998-06-29 13:38:57 +00001027"getattr(object, name[, default]) -> value\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001028\n\
Guido van Rossum950ff291998-06-29 13:38:57 +00001029Get a named attribute from an object; getattr(x, 'y') is equivalent to x.y.\n\
1030When a default argument is given, it is returned when the attribute doesn't\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001031exist; without it, an exception is raised in that case.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001032
1033
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001034/*[clinic input]
1035globals as builtin_globals
1036
1037Return the dictionary containing the current scope's global variables.
1038
1039NOTE: Updates to this dictionary *will* affect name lookups in the current
1040global scope and vice-versa.
1041[clinic start generated code]*/
1042
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001043static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001044builtin_globals_impl(PyObject *module)
1045/*[clinic end generated code: output=e5dd1527067b94d2 input=9327576f92bb48ba]*/
Guido van Rossum872537c1995-07-07 22:43:42 +00001046{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001047 PyObject *d;
Guido van Rossum872537c1995-07-07 22:43:42 +00001048
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001049 d = PyEval_GetGlobals();
1050 Py_XINCREF(d);
1051 return d;
Guido van Rossum872537c1995-07-07 22:43:42 +00001052}
1053
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001054
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001055/*[clinic input]
1056hasattr as builtin_hasattr
1057
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001058 obj: object
1059 name: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001060 /
1061
1062Return whether the object has an attribute with the given name.
1063
1064This is done by calling getattr(obj, name) and catching AttributeError.
1065[clinic start generated code]*/
1066
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001067static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001068builtin_hasattr_impl(PyObject *module, PyObject *obj, PyObject *name)
1069/*[clinic end generated code: output=a7aff2090a4151e5 input=0faec9787d979542]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001070{
1071 PyObject *v;
1072
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001073 if (!PyUnicode_Check(name)) {
1074 PyErr_SetString(PyExc_TypeError,
1075 "hasattr(): attribute name must be string");
1076 return NULL;
1077 }
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001078 v = PyObject_GetAttr(obj, name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001079 if (v == NULL) {
Benjamin Peterson17689992010-08-24 03:26:23 +00001080 if (PyErr_ExceptionMatches(PyExc_AttributeError)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001081 PyErr_Clear();
Benjamin Peterson17689992010-08-24 03:26:23 +00001082 Py_RETURN_FALSE;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001083 }
Benjamin Peterson17689992010-08-24 03:26:23 +00001084 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001085 }
1086 Py_DECREF(v);
Benjamin Peterson17689992010-08-24 03:26:23 +00001087 Py_RETURN_TRUE;
Guido van Rossum33894be1992-01-27 16:53:09 +00001088}
1089
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001090
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001091/* AC: gdb's integration with CPython relies on builtin_id having
1092 * the *exact* parameter names of "self" and "v", so we ensure we
1093 * preserve those name rather than using the AC defaults.
1094 */
1095/*[clinic input]
1096id as builtin_id
1097
Serhiy Storchaka24182a32016-05-05 16:21:35 +03001098 self: self(type="PyModuleDef *")
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001099 obj as v: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001100 /
1101
1102Return the identity of an object.
1103
1104This is guaranteed to be unique among simultaneously existing objects.
1105(CPython uses the object's memory address.)
1106[clinic start generated code]*/
1107
Guido van Rossum79f25d91997-04-29 20:08:16 +00001108static PyObject *
Serhiy Storchaka24182a32016-05-05 16:21:35 +03001109builtin_id(PyModuleDef *self, PyObject *v)
1110/*[clinic end generated code: output=0aa640785f697f65 input=5a534136419631f4]*/
Guido van Rossum5b722181993-03-30 17:46:03 +00001111{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001112 return PyLong_FromVoidPtr(v);
Guido van Rossum5b722181993-03-30 17:46:03 +00001113}
1114
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001115
Raymond Hettingera6c60372008-03-13 01:26:19 +00001116/* map object ************************************************************/
1117
1118typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001119 PyObject_HEAD
1120 PyObject *iters;
1121 PyObject *func;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001122} mapobject;
1123
Guido van Rossum79f25d91997-04-29 20:08:16 +00001124static PyObject *
Raymond Hettingera6c60372008-03-13 01:26:19 +00001125map_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
Guido van Rossum12d12c51993-10-26 17:58:25 +00001126{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001127 PyObject *it, *iters, *func;
1128 mapobject *lz;
1129 Py_ssize_t numargs, i;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001130
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001131 if (type == &PyMap_Type && !_PyArg_NoKeywords("map()", kwds))
1132 return NULL;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001133
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001134 numargs = PyTuple_Size(args);
1135 if (numargs < 2) {
1136 PyErr_SetString(PyExc_TypeError,
1137 "map() must have at least two arguments.");
1138 return NULL;
1139 }
Raymond Hettingera6c60372008-03-13 01:26:19 +00001140
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001141 iters = PyTuple_New(numargs-1);
1142 if (iters == NULL)
1143 return NULL;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001144
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001145 for (i=1 ; i<numargs ; i++) {
1146 /* Get iterator. */
1147 it = PyObject_GetIter(PyTuple_GET_ITEM(args, i));
1148 if (it == NULL) {
1149 Py_DECREF(iters);
1150 return NULL;
1151 }
1152 PyTuple_SET_ITEM(iters, i-1, it);
1153 }
Raymond Hettingera6c60372008-03-13 01:26:19 +00001154
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001155 /* create mapobject structure */
1156 lz = (mapobject *)type->tp_alloc(type, 0);
1157 if (lz == NULL) {
1158 Py_DECREF(iters);
1159 return NULL;
1160 }
1161 lz->iters = iters;
1162 func = PyTuple_GET_ITEM(args, 0);
1163 Py_INCREF(func);
1164 lz->func = func;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001165
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001166 return (PyObject *)lz;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001167}
1168
1169static void
1170map_dealloc(mapobject *lz)
1171{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001172 PyObject_GC_UnTrack(lz);
1173 Py_XDECREF(lz->iters);
1174 Py_XDECREF(lz->func);
1175 Py_TYPE(lz)->tp_free(lz);
Raymond Hettingera6c60372008-03-13 01:26:19 +00001176}
1177
1178static int
1179map_traverse(mapobject *lz, visitproc visit, void *arg)
1180{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001181 Py_VISIT(lz->iters);
1182 Py_VISIT(lz->func);
1183 return 0;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001184}
1185
1186static PyObject *
1187map_next(mapobject *lz)
1188{
Victor Stinnercdb5cee2016-08-24 01:45:13 +02001189 PyObject *small_stack[5];
1190 PyObject **stack;
1191 Py_ssize_t niters, nargs, i;
1192 PyObject *result = NULL;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001193
Victor Stinnercdb5cee2016-08-24 01:45:13 +02001194 niters = PyTuple_GET_SIZE(lz->iters);
1195 if (niters <= (Py_ssize_t)Py_ARRAY_LENGTH(small_stack)) {
1196 stack = small_stack;
1197 }
1198 else {
1199 stack = PyMem_Malloc(niters * sizeof(stack[0]));
1200 if (stack == NULL) {
1201 PyErr_NoMemory();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001202 return NULL;
1203 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001204 }
Victor Stinnercdb5cee2016-08-24 01:45:13 +02001205
1206 nargs = 0;
1207 for (i=0; i < niters; i++) {
1208 PyObject *it = PyTuple_GET_ITEM(lz->iters, i);
1209 PyObject *val = Py_TYPE(it)->tp_iternext(it);
1210 if (val == NULL) {
1211 goto exit;
1212 }
1213 stack[i] = val;
1214 nargs++;
1215 }
1216
1217 result = _PyObject_FastCall(lz->func, stack, nargs);
1218
1219exit:
1220 for (i=0; i < nargs; i++) {
1221 Py_DECREF(stack[i]);
1222 }
1223 if (stack != small_stack) {
1224 PyMem_Free(stack);
1225 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001226 return result;
Guido van Rossum12d12c51993-10-26 17:58:25 +00001227}
1228
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001229static PyObject *
1230map_reduce(mapobject *lz)
1231{
1232 Py_ssize_t numargs = PyTuple_GET_SIZE(lz->iters);
1233 PyObject *args = PyTuple_New(numargs+1);
1234 Py_ssize_t i;
1235 if (args == NULL)
1236 return NULL;
1237 Py_INCREF(lz->func);
1238 PyTuple_SET_ITEM(args, 0, lz->func);
1239 for (i = 0; i<numargs; i++){
1240 PyObject *it = PyTuple_GET_ITEM(lz->iters, i);
1241 Py_INCREF(it);
1242 PyTuple_SET_ITEM(args, i+1, it);
1243 }
1244
1245 return Py_BuildValue("ON", Py_TYPE(lz), args);
1246}
1247
1248static PyMethodDef map_methods[] = {
1249 {"__reduce__", (PyCFunction)map_reduce, METH_NOARGS, reduce_doc},
1250 {NULL, NULL} /* sentinel */
1251};
1252
1253
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001254PyDoc_STRVAR(map_doc,
Raymond Hettingera6c60372008-03-13 01:26:19 +00001255"map(func, *iterables) --> map object\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001256\n\
Raymond Hettingera6c60372008-03-13 01:26:19 +00001257Make an iterator that computes the function using arguments from\n\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001258each of the iterables. Stops when the shortest iterable is exhausted.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001259
Raymond Hettingera6c60372008-03-13 01:26:19 +00001260PyTypeObject PyMap_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001261 PyVarObject_HEAD_INIT(&PyType_Type, 0)
1262 "map", /* tp_name */
1263 sizeof(mapobject), /* tp_basicsize */
1264 0, /* tp_itemsize */
1265 /* methods */
1266 (destructor)map_dealloc, /* tp_dealloc */
1267 0, /* tp_print */
1268 0, /* tp_getattr */
1269 0, /* tp_setattr */
1270 0, /* tp_reserved */
1271 0, /* tp_repr */
1272 0, /* tp_as_number */
1273 0, /* tp_as_sequence */
1274 0, /* tp_as_mapping */
1275 0, /* tp_hash */
1276 0, /* tp_call */
1277 0, /* tp_str */
1278 PyObject_GenericGetAttr, /* tp_getattro */
1279 0, /* tp_setattro */
1280 0, /* tp_as_buffer */
1281 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
1282 Py_TPFLAGS_BASETYPE, /* tp_flags */
1283 map_doc, /* tp_doc */
1284 (traverseproc)map_traverse, /* tp_traverse */
1285 0, /* tp_clear */
1286 0, /* tp_richcompare */
1287 0, /* tp_weaklistoffset */
1288 PyObject_SelfIter, /* tp_iter */
1289 (iternextfunc)map_next, /* tp_iternext */
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001290 map_methods, /* tp_methods */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001291 0, /* tp_members */
1292 0, /* tp_getset */
1293 0, /* tp_base */
1294 0, /* tp_dict */
1295 0, /* tp_descr_get */
1296 0, /* tp_descr_set */
1297 0, /* tp_dictoffset */
1298 0, /* tp_init */
1299 PyType_GenericAlloc, /* tp_alloc */
1300 map_new, /* tp_new */
1301 PyObject_GC_Del, /* tp_free */
Raymond Hettingera6c60372008-03-13 01:26:19 +00001302};
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001303
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001304
1305/* AC: cannot convert yet, as needs PEP 457 group support in inspect */
Guido van Rossum79f25d91997-04-29 20:08:16 +00001306static PyObject *
Georg Brandla18af4e2007-04-21 15:47:16 +00001307builtin_next(PyObject *self, PyObject *args)
1308{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001309 PyObject *it, *res;
1310 PyObject *def = NULL;
Georg Brandla18af4e2007-04-21 15:47:16 +00001311
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001312 if (!PyArg_UnpackTuple(args, "next", 1, 2, &it, &def))
1313 return NULL;
1314 if (!PyIter_Check(it)) {
1315 PyErr_Format(PyExc_TypeError,
Philip Jenvey50add042011-11-06 16:37:52 -08001316 "'%.200s' object is not an iterator",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001317 it->ob_type->tp_name);
1318 return NULL;
1319 }
1320
1321 res = (*it->ob_type->tp_iternext)(it);
1322 if (res != NULL) {
1323 return res;
1324 } else if (def != NULL) {
1325 if (PyErr_Occurred()) {
1326 if(!PyErr_ExceptionMatches(PyExc_StopIteration))
1327 return NULL;
1328 PyErr_Clear();
1329 }
1330 Py_INCREF(def);
1331 return def;
1332 } else if (PyErr_Occurred()) {
1333 return NULL;
1334 } else {
1335 PyErr_SetNone(PyExc_StopIteration);
1336 return NULL;
1337 }
Georg Brandla18af4e2007-04-21 15:47:16 +00001338}
1339
1340PyDoc_STRVAR(next_doc,
1341"next(iterator[, default])\n\
1342\n\
1343Return the next item from the iterator. If default is given and the iterator\n\
1344is exhausted, it is returned instead of raising StopIteration.");
1345
1346
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001347/*[clinic input]
1348setattr as builtin_setattr
1349
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001350 obj: object
1351 name: object
1352 value: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001353 /
1354
1355Sets the named attribute on the given object to the specified value.
1356
1357setattr(x, 'y', v) is equivalent to ``x.y = v''
1358[clinic start generated code]*/
1359
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001360static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001361builtin_setattr_impl(PyObject *module, PyObject *obj, PyObject *name,
Larry Hastings89964c42015-04-14 18:07:59 -04001362 PyObject *value)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001363/*[clinic end generated code: output=dc2ce1d1add9acb4 input=bd2b7ca6875a1899]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001364{
1365 if (PyObject_SetAttr(obj, name, value) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001366 return NULL;
1367 Py_INCREF(Py_None);
1368 return Py_None;
Guido van Rossum33894be1992-01-27 16:53:09 +00001369}
1370
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001371
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001372/*[clinic input]
1373delattr as builtin_delattr
1374
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001375 obj: object
1376 name: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001377 /
1378
1379Deletes the named attribute from the given object.
1380
1381delattr(x, 'y') is equivalent to ``del x.y''
1382[clinic start generated code]*/
1383
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001384static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001385builtin_delattr_impl(PyObject *module, PyObject *obj, PyObject *name)
1386/*[clinic end generated code: output=85134bc58dff79fa input=db16685d6b4b9410]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001387{
1388 if (PyObject_SetAttr(obj, name, (PyObject *)NULL) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001389 return NULL;
1390 Py_INCREF(Py_None);
1391 return Py_None;
Guido van Rossum14144fc1994-08-29 12:53:40 +00001392}
1393
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001394
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001395/*[clinic input]
1396hash as builtin_hash
1397
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001398 obj: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001399 /
1400
1401Return the hash value for the given object.
1402
1403Two objects that compare equal must also have the same hash value, but the
1404reverse is not necessarily true.
1405[clinic start generated code]*/
1406
Guido van Rossum79f25d91997-04-29 20:08:16 +00001407static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001408builtin_hash(PyObject *module, PyObject *obj)
1409/*[clinic end generated code: output=237668e9d7688db7 input=58c48be822bf9c54]*/
Guido van Rossum9bfef441993-03-29 10:43:31 +00001410{
Benjamin Peterson8f67d082010-10-17 20:54:53 +00001411 Py_hash_t x;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001412
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001413 x = PyObject_Hash(obj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001414 if (x == -1)
1415 return NULL;
Benjamin Peterson8f67d082010-10-17 20:54:53 +00001416 return PyLong_FromSsize_t(x);
Guido van Rossum9bfef441993-03-29 10:43:31 +00001417}
1418
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001419
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001420/*[clinic input]
1421hex as builtin_hex
1422
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001423 number: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001424 /
1425
1426Return the hexadecimal representation of an integer.
1427
1428 >>> hex(12648430)
1429 '0xc0ffee'
1430[clinic start generated code]*/
1431
Guido van Rossum79f25d91997-04-29 20:08:16 +00001432static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001433builtin_hex(PyObject *module, PyObject *number)
1434/*[clinic end generated code: output=e46b612169099408 input=e645aff5fc7d540e]*/
Guido van Rossum006bcd41991-10-24 14:54:44 +00001435{
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001436 return PyNumber_ToBase(number, 16);
Guido van Rossum006bcd41991-10-24 14:54:44 +00001437}
1438
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001439
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001440/* AC: cannot convert yet, as needs PEP 457 group support in inspect */
Guido van Rossum79f25d91997-04-29 20:08:16 +00001441static PyObject *
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001442builtin_iter(PyObject *self, PyObject *args)
1443{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001444 PyObject *v, *w = NULL;
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001445
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001446 if (!PyArg_UnpackTuple(args, "iter", 1, 2, &v, &w))
1447 return NULL;
1448 if (w == NULL)
1449 return PyObject_GetIter(v);
1450 if (!PyCallable_Check(v)) {
1451 PyErr_SetString(PyExc_TypeError,
1452 "iter(v, w): v must be callable");
1453 return NULL;
1454 }
1455 return PyCallIter_New(v, w);
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001456}
1457
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001458PyDoc_STRVAR(iter_doc,
Georg Brandld11ae5d2008-05-16 13:27:32 +00001459"iter(iterable) -> iterator\n\
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001460iter(callable, sentinel) -> iterator\n\
1461\n\
1462Get an iterator from an object. In the first form, the argument must\n\
1463supply its own iterator, or be a sequence.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001464In the second form, the callable is called until it returns the sentinel.");
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001465
1466
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001467/*[clinic input]
1468len as builtin_len
1469
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001470 obj: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001471 /
1472
1473Return the number of items in a container.
1474[clinic start generated code]*/
1475
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001476static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001477builtin_len(PyObject *module, PyObject *obj)
1478/*[clinic end generated code: output=fa7a270d314dfb6c input=bc55598da9e9c9b5]*/
Guido van Rossum3f5da241990-12-20 15:06:42 +00001479{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001480 Py_ssize_t res;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001481
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001482 res = PyObject_Size(obj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001483 if (res < 0 && PyErr_Occurred())
1484 return NULL;
1485 return PyLong_FromSsize_t(res);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001486}
1487
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001488
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001489/*[clinic input]
1490locals as builtin_locals
1491
1492Return a dictionary containing the current scope's local variables.
1493
1494NOTE: Whether or not updates to this dictionary will affect name lookups in
1495the local scope and vice-versa is *implementation dependent* and not
1496covered by any backwards compatibility guarantees.
1497[clinic start generated code]*/
1498
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001499static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001500builtin_locals_impl(PyObject *module)
1501/*[clinic end generated code: output=b46c94015ce11448 input=7874018d478d5c4b]*/
Guido van Rossum872537c1995-07-07 22:43:42 +00001502{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001503 PyObject *d;
Guido van Rossum872537c1995-07-07 22:43:42 +00001504
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001505 d = PyEval_GetLocals();
1506 Py_XINCREF(d);
1507 return d;
Guido van Rossum872537c1995-07-07 22:43:42 +00001508}
1509
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001510
Guido van Rossum79f25d91997-04-29 20:08:16 +00001511static PyObject *
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001512min_max(PyObject *args, PyObject *kwds, int op)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001513{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001514 PyObject *v, *it, *item, *val, *maxitem, *maxval, *keyfunc=NULL;
Raymond Hettinger4d6018f2013-06-24 22:43:02 -07001515 PyObject *emptytuple, *defaultval = NULL;
1516 static char *kwlist[] = {"key", "default", NULL};
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001517 const char *name = op == Py_LT ? "min" : "max";
Raymond Hettinger4d6018f2013-06-24 22:43:02 -07001518 const int positional = PyTuple_Size(args) > 1;
1519 int ret;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001520
Raymond Hettinger4d6018f2013-06-24 22:43:02 -07001521 if (positional)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001522 v = args;
Serhiy Storchakac6792272013-10-19 21:03:34 +03001523 else if (!PyArg_UnpackTuple(args, name, 1, 1, &v))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001524 return NULL;
Tim Peters67d687a2002-04-29 21:27:32 +00001525
Raymond Hettinger4d6018f2013-06-24 22:43:02 -07001526 emptytuple = PyTuple_New(0);
1527 if (emptytuple == NULL)
1528 return NULL;
1529 ret = PyArg_ParseTupleAndKeywords(emptytuple, kwds, "|$OO", kwlist,
1530 &keyfunc, &defaultval);
1531 Py_DECREF(emptytuple);
1532 if (!ret)
1533 return NULL;
1534
1535 if (positional && defaultval != NULL) {
1536 PyErr_Format(PyExc_TypeError,
1537 "Cannot specify a default for %s() with multiple "
1538 "positional arguments", name);
1539 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001540 }
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001541
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001542 it = PyObject_GetIter(v);
1543 if (it == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001544 return NULL;
1545 }
Tim Petersc3074532001-05-03 07:00:32 +00001546
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001547 maxitem = NULL; /* the result */
1548 maxval = NULL; /* the value associated with the result */
1549 while (( item = PyIter_Next(it) )) {
1550 /* get the value from the key function */
1551 if (keyfunc != NULL) {
1552 val = PyObject_CallFunctionObjArgs(keyfunc, item, NULL);
1553 if (val == NULL)
1554 goto Fail_it_item;
1555 }
1556 /* no key function; the value is the item */
1557 else {
1558 val = item;
1559 Py_INCREF(val);
1560 }
Tim Petersc3074532001-05-03 07:00:32 +00001561
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001562 /* maximum value and item are unset; set them */
1563 if (maxval == NULL) {
1564 maxitem = item;
1565 maxval = val;
1566 }
1567 /* maximum value and item are set; update them as necessary */
1568 else {
1569 int cmp = PyObject_RichCompareBool(val, maxval, op);
1570 if (cmp < 0)
1571 goto Fail_it_item_and_val;
1572 else if (cmp > 0) {
1573 Py_DECREF(maxval);
1574 Py_DECREF(maxitem);
1575 maxval = val;
1576 maxitem = item;
1577 }
1578 else {
1579 Py_DECREF(item);
1580 Py_DECREF(val);
1581 }
1582 }
1583 }
1584 if (PyErr_Occurred())
1585 goto Fail_it;
1586 if (maxval == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001587 assert(maxitem == NULL);
Raymond Hettinger4d6018f2013-06-24 22:43:02 -07001588 if (defaultval != NULL) {
1589 Py_INCREF(defaultval);
1590 maxitem = defaultval;
1591 } else {
1592 PyErr_Format(PyExc_ValueError,
1593 "%s() arg is an empty sequence", name);
1594 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001595 }
1596 else
1597 Py_DECREF(maxval);
1598 Py_DECREF(it);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001599 return maxitem;
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001600
1601Fail_it_item_and_val:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001602 Py_DECREF(val);
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001603Fail_it_item:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001604 Py_DECREF(item);
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001605Fail_it:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001606 Py_XDECREF(maxval);
1607 Py_XDECREF(maxitem);
1608 Py_DECREF(it);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001609 return NULL;
Guido van Rossum3f5da241990-12-20 15:06:42 +00001610}
1611
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001612/* AC: cannot convert yet, waiting for *args support */
Guido van Rossum79f25d91997-04-29 20:08:16 +00001613static PyObject *
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001614builtin_min(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001615{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001616 return min_max(args, kwds, Py_LT);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001617}
1618
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001619PyDoc_STRVAR(min_doc,
Raymond Hettinger2a545822014-05-19 22:20:52 +01001620"min(iterable, *[, default=obj, key=func]) -> value\n\
1621min(arg1, arg2, *args, *[, key=func]) -> value\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001622\n\
Raymond Hettinger2a545822014-05-19 22:20:52 +01001623With a single iterable argument, return its smallest item. The\n\
1624default keyword-only argument specifies an object to return if\n\
1625the provided iterable is empty.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001626With two or more arguments, return the smallest argument.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001627
1628
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001629/* AC: cannot convert yet, waiting for *args support */
Guido van Rossum79f25d91997-04-29 20:08:16 +00001630static PyObject *
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001631builtin_max(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001632{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001633 return min_max(args, kwds, Py_GT);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001634}
1635
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001636PyDoc_STRVAR(max_doc,
Raymond Hettinger2a545822014-05-19 22:20:52 +01001637"max(iterable, *[, default=obj, key=func]) -> value\n\
1638max(arg1, arg2, *args, *[, key=func]) -> value\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001639\n\
Raymond Hettinger2a545822014-05-19 22:20:52 +01001640With a single iterable argument, return its biggest item. The\n\
1641default keyword-only argument specifies an object to return if\n\
1642the provided iterable is empty.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001643With two or more arguments, return the largest argument.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001644
1645
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001646/*[clinic input]
1647oct as builtin_oct
1648
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001649 number: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001650 /
1651
1652Return the octal representation of an integer.
1653
1654 >>> oct(342391)
1655 '0o1234567'
1656[clinic start generated code]*/
1657
Guido van Rossum79f25d91997-04-29 20:08:16 +00001658static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001659builtin_oct(PyObject *module, PyObject *number)
1660/*[clinic end generated code: output=40a34656b6875352 input=ad6b274af4016c72]*/
Guido van Rossum006bcd41991-10-24 14:54:44 +00001661{
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001662 return PyNumber_ToBase(number, 8);
Guido van Rossum006bcd41991-10-24 14:54:44 +00001663}
1664
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001665
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001666/*[clinic input]
1667ord as builtin_ord
1668
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001669 c: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001670 /
1671
1672Return the Unicode code point for a one-character string.
1673[clinic start generated code]*/
1674
Guido van Rossum79f25d91997-04-29 20:08:16 +00001675static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001676builtin_ord(PyObject *module, PyObject *c)
1677/*[clinic end generated code: output=4fa5e87a323bae71 input=3064e5d6203ad012]*/
Guido van Rossum3f5da241990-12-20 15:06:42 +00001678{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001679 long ord;
1680 Py_ssize_t size;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001681
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001682 if (PyBytes_Check(c)) {
1683 size = PyBytes_GET_SIZE(c);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001684 if (size == 1) {
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001685 ord = (long)((unsigned char)*PyBytes_AS_STRING(c));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001686 return PyLong_FromLong(ord);
1687 }
1688 }
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001689 else if (PyUnicode_Check(c)) {
1690 if (PyUnicode_READY(c) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001691 return NULL;
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001692 size = PyUnicode_GET_LENGTH(c);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001693 if (size == 1) {
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001694 ord = (long)PyUnicode_READ_CHAR(c, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001695 return PyLong_FromLong(ord);
1696 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001697 }
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001698 else if (PyByteArray_Check(c)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001699 /* XXX Hopefully this is temporary */
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001700 size = PyByteArray_GET_SIZE(c);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001701 if (size == 1) {
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001702 ord = (long)((unsigned char)*PyByteArray_AS_STRING(c));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001703 return PyLong_FromLong(ord);
1704 }
1705 }
1706 else {
1707 PyErr_Format(PyExc_TypeError,
1708 "ord() expected string of length 1, but " \
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001709 "%.200s found", c->ob_type->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001710 return NULL;
1711 }
Guido van Rossum09095f32000-03-10 23:00:52 +00001712
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001713 PyErr_Format(PyExc_TypeError,
1714 "ord() expected a character, "
1715 "but string of length %zd found",
1716 size);
1717 return NULL;
Guido van Rossum3f5da241990-12-20 15:06:42 +00001718}
1719
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001720
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001721/*[clinic input]
1722pow as builtin_pow
1723
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001724 x: object
1725 y: object
1726 z: object = None
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001727 /
1728
1729Equivalent to x**y (with two arguments) or x**y % z (with three arguments)
1730
1731Some types, such as ints, are able to use a more efficient algorithm when
1732invoked using the three argument form.
1733[clinic start generated code]*/
1734
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001735static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001736builtin_pow_impl(PyObject *module, PyObject *x, PyObject *y, PyObject *z)
1737/*[clinic end generated code: output=50a14d5d130d404b input=653d57d38d41fc07]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001738{
1739 return PyNumber_Power(x, y, z);
1740}
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001741
1742
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001743/* AC: cannot convert yet, waiting for *args support */
Guido van Rossum34343512006-11-30 22:13:52 +00001744static PyObject *
1745builtin_print(PyObject *self, PyObject *args, PyObject *kwds)
1746{
Georg Brandlbc3b6822012-01-13 19:41:25 +01001747 static char *kwlist[] = {"sep", "end", "file", "flush", 0};
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001748 static PyObject *dummy_args;
Georg Brandlbc3b6822012-01-13 19:41:25 +01001749 PyObject *sep = NULL, *end = NULL, *file = NULL, *flush = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001750 int i, err;
Guido van Rossum34343512006-11-30 22:13:52 +00001751
Benjamin Peterson00102562012-01-11 21:00:16 -05001752 if (dummy_args == NULL && !(dummy_args = PyTuple_New(0)))
Georg Brandlbc3b6822012-01-13 19:41:25 +01001753 return NULL;
1754 if (!PyArg_ParseTupleAndKeywords(dummy_args, kwds, "|OOOO:print",
1755 kwlist, &sep, &end, &file, &flush))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001756 return NULL;
1757 if (file == NULL || file == Py_None) {
Victor Stinnerbd303c12013-11-07 23:07:29 +01001758 file = _PySys_GetObjectId(&PyId_stdout);
Victor Stinner1e53bba2013-07-16 22:26:05 +02001759 if (file == NULL) {
1760 PyErr_SetString(PyExc_RuntimeError, "lost sys.stdout");
1761 return NULL;
1762 }
1763
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001764 /* sys.stdout may be None when FILE* stdout isn't connected */
1765 if (file == Py_None)
1766 Py_RETURN_NONE;
1767 }
Guido van Rossum34343512006-11-30 22:13:52 +00001768
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001769 if (sep == Py_None) {
1770 sep = NULL;
1771 }
1772 else if (sep && !PyUnicode_Check(sep)) {
1773 PyErr_Format(PyExc_TypeError,
1774 "sep must be None or a string, not %.200s",
1775 sep->ob_type->tp_name);
1776 return NULL;
1777 }
1778 if (end == Py_None) {
1779 end = NULL;
1780 }
1781 else if (end && !PyUnicode_Check(end)) {
1782 PyErr_Format(PyExc_TypeError,
1783 "end must be None or a string, not %.200s",
1784 end->ob_type->tp_name);
1785 return NULL;
1786 }
Guido van Rossum34343512006-11-30 22:13:52 +00001787
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001788 for (i = 0; i < PyTuple_Size(args); i++) {
1789 if (i > 0) {
1790 if (sep == NULL)
1791 err = PyFile_WriteString(" ", file);
1792 else
1793 err = PyFile_WriteObject(sep, file,
1794 Py_PRINT_RAW);
1795 if (err)
1796 return NULL;
1797 }
1798 err = PyFile_WriteObject(PyTuple_GetItem(args, i), file,
1799 Py_PRINT_RAW);
1800 if (err)
1801 return NULL;
1802 }
Guido van Rossum34343512006-11-30 22:13:52 +00001803
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001804 if (end == NULL)
1805 err = PyFile_WriteString("\n", file);
1806 else
1807 err = PyFile_WriteObject(end, file, Py_PRINT_RAW);
1808 if (err)
1809 return NULL;
Guido van Rossum34343512006-11-30 22:13:52 +00001810
Georg Brandlbc3b6822012-01-13 19:41:25 +01001811 if (flush != NULL) {
1812 PyObject *tmp;
1813 int do_flush = PyObject_IsTrue(flush);
1814 if (do_flush == -1)
1815 return NULL;
1816 else if (do_flush) {
Victor Stinner3466bde2016-09-05 18:16:01 -07001817 tmp = _PyObject_CallMethodId(file, &PyId_flush, NULL);
Georg Brandlbc3b6822012-01-13 19:41:25 +01001818 if (tmp == NULL)
1819 return NULL;
1820 else
1821 Py_DECREF(tmp);
1822 }
1823 }
1824
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001825 Py_RETURN_NONE;
Guido van Rossum34343512006-11-30 22:13:52 +00001826}
1827
1828PyDoc_STRVAR(print_doc,
Senthil Kumarane9175bd2012-08-10 13:53:45 -07001829"print(value, ..., sep=' ', end='\\n', file=sys.stdout, flush=False)\n\
Guido van Rossum34343512006-11-30 22:13:52 +00001830\n\
1831Prints the values to a stream, or to sys.stdout by default.\n\
1832Optional keyword arguments:\n\
Senthil Kumarane9175bd2012-08-10 13:53:45 -07001833file: a file-like object (stream); defaults to the current sys.stdout.\n\
1834sep: string inserted between values, default a space.\n\
1835end: string appended after the last value, default a newline.\n\
1836flush: whether to forcibly flush the stream.");
Guido van Rossum34343512006-11-30 22:13:52 +00001837
1838
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001839/*[clinic input]
1840input as builtin_input
1841
1842 prompt: object(c_default="NULL") = None
1843 /
1844
1845Read a string from standard input. The trailing newline is stripped.
1846
1847The prompt string, if given, is printed to standard output without a
1848trailing newline before reading input.
1849
1850If the user hits EOF (*nix: Ctrl-D, Windows: Ctrl-Z+Return), raise EOFError.
1851On *nix systems, readline is used if available.
1852[clinic start generated code]*/
1853
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001854static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001855builtin_input_impl(PyObject *module, PyObject *prompt)
1856/*[clinic end generated code: output=83db5a191e7a0d60 input=5e8bb70c2908fe3c]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001857{
Victor Stinnerbd303c12013-11-07 23:07:29 +01001858 PyObject *fin = _PySys_GetObjectId(&PyId_stdin);
1859 PyObject *fout = _PySys_GetObjectId(&PyId_stdout);
1860 PyObject *ferr = _PySys_GetObjectId(&PyId_stderr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001861 PyObject *tmp;
1862 long fd;
1863 int tty;
Guido van Rossuma88a0332007-02-26 16:59:55 +00001864
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001865 /* Check that stdin/out/err are intact */
1866 if (fin == NULL || fin == Py_None) {
1867 PyErr_SetString(PyExc_RuntimeError,
1868 "input(): lost sys.stdin");
1869 return NULL;
1870 }
1871 if (fout == NULL || fout == Py_None) {
1872 PyErr_SetString(PyExc_RuntimeError,
1873 "input(): lost sys.stdout");
1874 return NULL;
1875 }
1876 if (ferr == NULL || ferr == Py_None) {
1877 PyErr_SetString(PyExc_RuntimeError,
1878 "input(): lost sys.stderr");
1879 return NULL;
1880 }
Guido van Rossumeba76962007-05-27 09:13:28 +00001881
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001882 /* First of all, flush stderr */
Victor Stinner3466bde2016-09-05 18:16:01 -07001883 tmp = _PyObject_CallMethodId(ferr, &PyId_flush, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001884 if (tmp == NULL)
1885 PyErr_Clear();
1886 else
1887 Py_DECREF(tmp);
Guido van Rossumeba76962007-05-27 09:13:28 +00001888
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001889 /* We should only use (GNU) readline if Python's sys.stdin and
1890 sys.stdout are the same as C's stdin and stdout, because we
1891 need to pass it those. */
Victor Stinner3466bde2016-09-05 18:16:01 -07001892 tmp = _PyObject_CallMethodId(fin, &PyId_fileno, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001893 if (tmp == NULL) {
1894 PyErr_Clear();
1895 tty = 0;
1896 }
1897 else {
1898 fd = PyLong_AsLong(tmp);
1899 Py_DECREF(tmp);
1900 if (fd < 0 && PyErr_Occurred())
1901 return NULL;
1902 tty = fd == fileno(stdin) && isatty(fd);
1903 }
1904 if (tty) {
Victor Stinner3466bde2016-09-05 18:16:01 -07001905 tmp = _PyObject_CallMethodId(fout, &PyId_fileno, NULL);
Martin Panterc9a6ab52015-10-10 01:25:38 +00001906 if (tmp == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001907 PyErr_Clear();
Martin Panterc9a6ab52015-10-10 01:25:38 +00001908 tty = 0;
1909 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001910 else {
1911 fd = PyLong_AsLong(tmp);
1912 Py_DECREF(tmp);
1913 if (fd < 0 && PyErr_Occurred())
1914 return NULL;
1915 tty = fd == fileno(stdout) && isatty(fd);
1916 }
1917 }
Guido van Rossumeba76962007-05-27 09:13:28 +00001918
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001919 /* If we're interactive, use (GNU) readline */
1920 if (tty) {
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001921 PyObject *po = NULL;
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001922 char *promptstr;
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001923 char *s = NULL;
1924 PyObject *stdin_encoding = NULL, *stdin_errors = NULL;
1925 PyObject *stdout_encoding = NULL, *stdout_errors = NULL;
1926 char *stdin_encoding_str, *stdin_errors_str;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001927 PyObject *result;
Victor Stinnerc0f1a1a2011-02-23 12:07:37 +00001928 size_t len;
Martin v. Löwis4a7b5d52007-09-04 05:24:49 +00001929
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02001930 stdin_encoding = _PyObject_GetAttrId(fin, &PyId_encoding);
Antoine Pitrou5ee9d8a2011-11-06 00:38:45 +01001931 stdin_errors = _PyObject_GetAttrId(fin, &PyId_errors);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001932 if (!stdin_encoding || !stdin_errors)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001933 /* stdin is a text stream, so it must have an
1934 encoding. */
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001935 goto _readline_errors;
Serhiy Storchaka06515832016-11-20 09:13:07 +02001936 stdin_encoding_str = PyUnicode_AsUTF8(stdin_encoding);
1937 stdin_errors_str = PyUnicode_AsUTF8(stdin_errors);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001938 if (!stdin_encoding_str || !stdin_errors_str)
1939 goto _readline_errors;
Victor Stinner3466bde2016-09-05 18:16:01 -07001940 tmp = _PyObject_CallMethodId(fout, &PyId_flush, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001941 if (tmp == NULL)
1942 PyErr_Clear();
1943 else
1944 Py_DECREF(tmp);
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001945 if (prompt != NULL) {
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001946 /* We have a prompt, encode it as stdout would */
1947 char *stdout_encoding_str, *stdout_errors_str;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001948 PyObject *stringpo;
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02001949 stdout_encoding = _PyObject_GetAttrId(fout, &PyId_encoding);
Antoine Pitrou5ee9d8a2011-11-06 00:38:45 +01001950 stdout_errors = _PyObject_GetAttrId(fout, &PyId_errors);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001951 if (!stdout_encoding || !stdout_errors)
1952 goto _readline_errors;
Serhiy Storchaka06515832016-11-20 09:13:07 +02001953 stdout_encoding_str = PyUnicode_AsUTF8(stdout_encoding);
1954 stdout_errors_str = PyUnicode_AsUTF8(stdout_errors);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001955 if (!stdout_encoding_str || !stdout_errors_str)
1956 goto _readline_errors;
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001957 stringpo = PyObject_Str(prompt);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001958 if (stringpo == NULL)
1959 goto _readline_errors;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001960 po = PyUnicode_AsEncodedString(stringpo,
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001961 stdout_encoding_str, stdout_errors_str);
1962 Py_CLEAR(stdout_encoding);
1963 Py_CLEAR(stdout_errors);
1964 Py_CLEAR(stringpo);
1965 if (po == NULL)
1966 goto _readline_errors;
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03001967 assert(PyBytes_Check(po));
1968 promptstr = PyBytes_AS_STRING(po);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001969 }
1970 else {
1971 po = NULL;
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001972 promptstr = "";
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001973 }
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001974 s = PyOS_Readline(stdin, stdout, promptstr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001975 if (s == NULL) {
Richard Oudkerk614c5782013-04-03 13:44:50 +01001976 PyErr_CheckSignals();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001977 if (!PyErr_Occurred())
1978 PyErr_SetNone(PyExc_KeyboardInterrupt);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001979 goto _readline_errors;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001980 }
Victor Stinnerc0f1a1a2011-02-23 12:07:37 +00001981
1982 len = strlen(s);
1983 if (len == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001984 PyErr_SetNone(PyExc_EOFError);
1985 result = NULL;
1986 }
Victor Stinnerc0f1a1a2011-02-23 12:07:37 +00001987 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001988 if (len > PY_SSIZE_T_MAX) {
1989 PyErr_SetString(PyExc_OverflowError,
1990 "input: input too long");
1991 result = NULL;
1992 }
1993 else {
Victor Stinnerc0f1a1a2011-02-23 12:07:37 +00001994 len--; /* strip trailing '\n' */
1995 if (len != 0 && s[len-1] == '\r')
1996 len--; /* strip trailing '\r' */
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001997 result = PyUnicode_Decode(s, len, stdin_encoding_str,
1998 stdin_errors_str);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001999 }
2000 }
2001 Py_DECREF(stdin_encoding);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01002002 Py_DECREF(stdin_errors);
2003 Py_XDECREF(po);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002004 PyMem_FREE(s);
2005 return result;
Antoine Pitrou0d776b12011-11-06 00:34:26 +01002006 _readline_errors:
2007 Py_XDECREF(stdin_encoding);
2008 Py_XDECREF(stdout_encoding);
2009 Py_XDECREF(stdin_errors);
2010 Py_XDECREF(stdout_errors);
2011 Py_XDECREF(po);
2012 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002013 }
Guido van Rossumeba76962007-05-27 09:13:28 +00002014
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002015 /* Fallback if we're not interactive */
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002016 if (prompt != NULL) {
2017 if (PyFile_WriteObject(prompt, fout, Py_PRINT_RAW) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002018 return NULL;
2019 }
Victor Stinner3466bde2016-09-05 18:16:01 -07002020 tmp = _PyObject_CallMethodId(fout, &PyId_flush, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002021 if (tmp == NULL)
2022 PyErr_Clear();
2023 else
2024 Py_DECREF(tmp);
2025 return PyFile_GetLine(fin, -1);
Guido van Rossuma88a0332007-02-26 16:59:55 +00002026}
2027
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002028
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002029/*[clinic input]
2030repr as builtin_repr
2031
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03002032 obj: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002033 /
2034
2035Return the canonical string representation of the object.
2036
2037For many object types, including most builtins, eval(repr(obj)) == obj.
2038[clinic start generated code]*/
2039
Guido van Rossum79f25d91997-04-29 20:08:16 +00002040static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002041builtin_repr(PyObject *module, PyObject *obj)
2042/*[clinic end generated code: output=7ed3778c44fd0194 input=1c9e6d66d3e3be04]*/
Guido van Rossumc89705d1992-11-26 08:54:07 +00002043{
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002044 return PyObject_Repr(obj);
Guido van Rossumc89705d1992-11-26 08:54:07 +00002045}
2046
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002047
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002048/* AC: cannot convert yet, as needs PEP 457 group support in inspect
2049 * or a semantic change to accept None for "ndigits"
2050 */
Guido van Rossum79f25d91997-04-29 20:08:16 +00002051static PyObject *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002052builtin_round(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum9e51f9b1993-02-12 16:29:05 +00002053{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002054 PyObject *ndigits = NULL;
2055 static char *kwlist[] = {"number", "ndigits", 0};
Benjamin Peterson214a7d22013-04-13 17:19:01 -04002056 PyObject *number, *round, *result;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002057
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002058 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|O:round",
2059 kwlist, &number, &ndigits))
2060 return NULL;
Alex Martelliae211f92007-08-22 23:21:33 +00002061
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002062 if (Py_TYPE(number)->tp_dict == NULL) {
2063 if (PyType_Ready(Py_TYPE(number)) < 0)
2064 return NULL;
2065 }
Guido van Rossum15d3d042007-08-24 02:02:45 +00002066
Benjamin Peterson214a7d22013-04-13 17:19:01 -04002067 round = _PyObject_LookupSpecial(number, &PyId___round__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002068 if (round == NULL) {
Benjamin Peterson214a7d22013-04-13 17:19:01 -04002069 if (!PyErr_Occurred())
2070 PyErr_Format(PyExc_TypeError,
2071 "type %.100s doesn't define __round__ method",
2072 Py_TYPE(number)->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002073 return NULL;
2074 }
Alex Martelliae211f92007-08-22 23:21:33 +00002075
Raymond Hettingerf0f1c232016-09-03 01:55:11 -07002076 if (ndigits == NULL || ndigits == Py_None)
Benjamin Peterson214a7d22013-04-13 17:19:01 -04002077 result = PyObject_CallFunctionObjArgs(round, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002078 else
Benjamin Peterson214a7d22013-04-13 17:19:01 -04002079 result = PyObject_CallFunctionObjArgs(round, ndigits, NULL);
2080 Py_DECREF(round);
2081 return result;
Guido van Rossum9e51f9b1993-02-12 16:29:05 +00002082}
2083
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002084PyDoc_STRVAR(round_doc,
Mark Dickinson1124e712009-01-28 21:25:58 +00002085"round(number[, ndigits]) -> number\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002086\n\
2087Round a number to a given precision in decimal digits (default 0 digits).\n\
Mark Dickinson0d748c22008-07-05 11:29:03 +00002088This returns an int when called with one argument, otherwise the\n\
Georg Brandl809ddaa2008-07-01 20:39:59 +00002089same type as the number. ndigits may be negative.");
Guido van Rossum2fa33db2007-08-23 22:07:24 +00002090
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002091
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002092/*AC: we need to keep the kwds dict intact to easily call into the
2093 * list.sort method, which isn't currently supported in AC. So we just use
2094 * the initially generated signature with a custom implementation.
2095 */
2096/* [disabled clinic input]
2097sorted as builtin_sorted
2098
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03002099 iterable as seq: object
2100 key as keyfunc: object = None
2101 reverse: object = False
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002102
2103Return a new list containing all items from the iterable in ascending order.
2104
Raymond Hettinger7ea386e2016-08-25 21:11:50 -07002105A custom key function can be supplied to customize the sort order, and the
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002106reverse flag can be set to request the result in descending order.
2107[end disabled clinic input]*/
2108
2109PyDoc_STRVAR(builtin_sorted__doc__,
Serhiy Storchaka3a104252017-01-23 12:29:47 +02002110"sorted($module, iterable, /, *, key=None, reverse=False)\n"
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002111"--\n"
2112"\n"
2113"Return a new list containing all items from the iterable in ascending order.\n"
2114"\n"
Raymond Hettinger7ea386e2016-08-25 21:11:50 -07002115"A custom key function can be supplied to customize the sort order, and the\n"
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002116"reverse flag can be set to request the result in descending order.");
2117
2118#define BUILTIN_SORTED_METHODDEF \
2119 {"sorted", (PyCFunction)builtin_sorted, METH_VARARGS|METH_KEYWORDS, builtin_sorted__doc__},
2120
Raymond Hettinger64958a12003-12-17 20:43:33 +00002121static PyObject *
2122builtin_sorted(PyObject *self, PyObject *args, PyObject *kwds)
2123{
Victor Stinner2990fa12016-08-22 23:21:55 +02002124 PyObject *newlist, *v, *seq, *keyfunc=NULL, **newargs;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002125 PyObject *callable;
Serhiy Storchaka398ef5c2017-01-20 08:33:06 +02002126 static char *kwlist[] = {"", "key", "reverse", 0};
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002127 int reverse;
Victor Stinner74319ae2016-08-25 00:04:09 +02002128 Py_ssize_t nargs;
Raymond Hettinger64958a12003-12-17 20:43:33 +00002129
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002130 /* args 1-3 should match listsort in Objects/listobject.c */
2131 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|Oi:sorted",
2132 kwlist, &seq, &keyfunc, &reverse))
2133 return NULL;
Raymond Hettinger64958a12003-12-17 20:43:33 +00002134
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002135 newlist = PySequence_List(seq);
2136 if (newlist == NULL)
2137 return NULL;
Raymond Hettinger64958a12003-12-17 20:43:33 +00002138
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02002139 callable = _PyObject_GetAttrId(newlist, &PyId_sort);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002140 if (callable == NULL) {
2141 Py_DECREF(newlist);
2142 return NULL;
2143 }
Georg Brandl99d7e4e2005-08-31 22:21:15 +00002144
Serhiy Storchaka398ef5c2017-01-20 08:33:06 +02002145 assert(PyTuple_GET_SIZE(args) >= 1);
Victor Stinner2990fa12016-08-22 23:21:55 +02002146 newargs = &PyTuple_GET_ITEM(args, 1);
2147 nargs = PyTuple_GET_SIZE(args) - 1;
2148 v = _PyObject_FastCallDict(callable, newargs, nargs, kwds);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002149 Py_DECREF(callable);
2150 if (v == NULL) {
2151 Py_DECREF(newlist);
2152 return NULL;
2153 }
2154 Py_DECREF(v);
2155 return newlist;
Raymond Hettinger64958a12003-12-17 20:43:33 +00002156}
2157
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002158
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002159/* AC: cannot convert yet, as needs PEP 457 group support in inspect */
Guido van Rossum79f25d91997-04-29 20:08:16 +00002160static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002161builtin_vars(PyObject *self, PyObject *args)
Guido van Rossum2d951851994-08-29 12:52:16 +00002162{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002163 PyObject *v = NULL;
2164 PyObject *d;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002165
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002166 if (!PyArg_UnpackTuple(args, "vars", 0, 1, &v))
2167 return NULL;
2168 if (v == NULL) {
2169 d = PyEval_GetLocals();
Victor Stinner41bb43a2013-10-29 01:19:37 +01002170 if (d == NULL)
2171 return NULL;
2172 Py_INCREF(d);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002173 }
2174 else {
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02002175 d = _PyObject_GetAttrId(v, &PyId___dict__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002176 if (d == NULL) {
2177 PyErr_SetString(PyExc_TypeError,
2178 "vars() argument must have __dict__ attribute");
2179 return NULL;
2180 }
2181 }
2182 return d;
Guido van Rossum2d951851994-08-29 12:52:16 +00002183}
2184
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002185PyDoc_STRVAR(vars_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002186"vars([object]) -> dictionary\n\
2187\n\
2188Without arguments, equivalent to locals().\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002189With an argument, equivalent to object.__dict__.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002190
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002191
2192/*[clinic input]
2193sum as builtin_sum
2194
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03002195 iterable: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002196 start: object(c_default="NULL") = 0
2197 /
2198
2199Return the sum of a 'start' value (default: 0) plus an iterable of numbers
2200
2201When the iterable is empty, return the start value.
2202This function is intended specifically for use with numeric values and may
2203reject non-numeric types.
2204[clinic start generated code]*/
2205
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002206static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002207builtin_sum_impl(PyObject *module, PyObject *iterable, PyObject *start)
2208/*[clinic end generated code: output=df758cec7d1d302f input=3b5b7a9d7611c73a]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002209{
2210 PyObject *result = start;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002211 PyObject *temp, *item, *iter;
Alex Martellia70b1912003-04-22 08:12:33 +00002212
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002213 iter = PyObject_GetIter(iterable);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002214 if (iter == NULL)
2215 return NULL;
Alex Martellia70b1912003-04-22 08:12:33 +00002216
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002217 if (result == NULL) {
2218 result = PyLong_FromLong(0);
2219 if (result == NULL) {
2220 Py_DECREF(iter);
2221 return NULL;
2222 }
2223 } else {
2224 /* reject string values for 'start' parameter */
2225 if (PyUnicode_Check(result)) {
2226 PyErr_SetString(PyExc_TypeError,
2227 "sum() can't sum strings [use ''.join(seq) instead]");
2228 Py_DECREF(iter);
2229 return NULL;
2230 }
Benjamin Petersonce071ca2011-07-29 14:23:47 -05002231 if (PyBytes_Check(result)) {
2232 PyErr_SetString(PyExc_TypeError,
2233 "sum() can't sum bytes [use b''.join(seq) instead]");
Benjamin Peterson405f32c2011-07-29 22:43:45 -05002234 Py_DECREF(iter);
Benjamin Petersonce071ca2011-07-29 14:23:47 -05002235 return NULL;
2236 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002237 if (PyByteArray_Check(result)) {
2238 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson4f921c22011-07-29 14:24:29 -05002239 "sum() can't sum bytearray [use b''.join(seq) instead]");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002240 Py_DECREF(iter);
2241 return NULL;
2242 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002243 Py_INCREF(result);
2244 }
Alex Martellia70b1912003-04-22 08:12:33 +00002245
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002246#ifndef SLOW_SUM
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002247 /* Fast addition by keeping temporary sums in C instead of new Python objects.
2248 Assumes all inputs are the same type. If the assumption fails, default
2249 to the more general routine.
2250 */
2251 if (PyLong_CheckExact(result)) {
2252 int overflow;
2253 long i_result = PyLong_AsLongAndOverflow(result, &overflow);
2254 /* If this already overflowed, don't even enter the loop. */
2255 if (overflow == 0) {
2256 Py_DECREF(result);
2257 result = NULL;
2258 }
2259 while(result == NULL) {
2260 item = PyIter_Next(iter);
2261 if (item == NULL) {
2262 Py_DECREF(iter);
2263 if (PyErr_Occurred())
2264 return NULL;
2265 return PyLong_FromLong(i_result);
2266 }
2267 if (PyLong_CheckExact(item)) {
2268 long b = PyLong_AsLongAndOverflow(item, &overflow);
2269 long x = i_result + b;
2270 if (overflow == 0 && ((x^i_result) >= 0 || (x^b) >= 0)) {
2271 i_result = x;
2272 Py_DECREF(item);
2273 continue;
2274 }
2275 }
2276 /* Either overflowed or is not an int. Restore real objects and process normally */
2277 result = PyLong_FromLong(i_result);
Christian Heimes704e2d32013-07-26 22:49:26 +02002278 if (result == NULL) {
2279 Py_DECREF(item);
2280 Py_DECREF(iter);
2281 return NULL;
2282 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002283 temp = PyNumber_Add(result, item);
2284 Py_DECREF(result);
2285 Py_DECREF(item);
2286 result = temp;
2287 if (result == NULL) {
2288 Py_DECREF(iter);
2289 return NULL;
2290 }
2291 }
2292 }
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002293
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002294 if (PyFloat_CheckExact(result)) {
2295 double f_result = PyFloat_AS_DOUBLE(result);
2296 Py_DECREF(result);
2297 result = NULL;
2298 while(result == NULL) {
2299 item = PyIter_Next(iter);
2300 if (item == NULL) {
2301 Py_DECREF(iter);
2302 if (PyErr_Occurred())
2303 return NULL;
2304 return PyFloat_FromDouble(f_result);
2305 }
2306 if (PyFloat_CheckExact(item)) {
2307 PyFPE_START_PROTECT("add", Py_DECREF(item); Py_DECREF(iter); return 0)
2308 f_result += PyFloat_AS_DOUBLE(item);
2309 PyFPE_END_PROTECT(f_result)
2310 Py_DECREF(item);
2311 continue;
2312 }
2313 if (PyLong_CheckExact(item)) {
2314 long value;
2315 int overflow;
2316 value = PyLong_AsLongAndOverflow(item, &overflow);
2317 if (!overflow) {
2318 PyFPE_START_PROTECT("add", Py_DECREF(item); Py_DECREF(iter); return 0)
2319 f_result += (double)value;
2320 PyFPE_END_PROTECT(f_result)
2321 Py_DECREF(item);
2322 continue;
2323 }
2324 }
2325 result = PyFloat_FromDouble(f_result);
2326 temp = PyNumber_Add(result, item);
2327 Py_DECREF(result);
2328 Py_DECREF(item);
2329 result = temp;
2330 if (result == NULL) {
2331 Py_DECREF(iter);
2332 return NULL;
2333 }
2334 }
2335 }
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002336#endif
2337
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002338 for(;;) {
2339 item = PyIter_Next(iter);
2340 if (item == NULL) {
2341 /* error, or end-of-sequence */
2342 if (PyErr_Occurred()) {
2343 Py_DECREF(result);
2344 result = NULL;
2345 }
2346 break;
2347 }
2348 /* It's tempting to use PyNumber_InPlaceAdd instead of
2349 PyNumber_Add here, to avoid quadratic running time
2350 when doing 'sum(list_of_lists, [])'. However, this
2351 would produce a change in behaviour: a snippet like
Mark Dickinson9acadc52009-10-26 14:19:42 +00002352
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002353 empty = []
2354 sum([[x] for x in range(10)], empty)
Mark Dickinson9acadc52009-10-26 14:19:42 +00002355
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002356 would change the value of empty. */
2357 temp = PyNumber_Add(result, item);
2358 Py_DECREF(result);
2359 Py_DECREF(item);
2360 result = temp;
2361 if (result == NULL)
2362 break;
2363 }
2364 Py_DECREF(iter);
2365 return result;
Alex Martellia70b1912003-04-22 08:12:33 +00002366}
2367
Alex Martellia70b1912003-04-22 08:12:33 +00002368
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002369/*[clinic input]
2370isinstance as builtin_isinstance
2371
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03002372 obj: object
2373 class_or_tuple: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002374 /
2375
2376Return whether an object is an instance of a class or of a subclass thereof.
2377
2378A tuple, as in ``isinstance(x, (A, B, ...))``, may be given as the target to
2379check against. This is equivalent to ``isinstance(x, A) or isinstance(x, B)
2380or ...`` etc.
2381[clinic start generated code]*/
2382
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002383static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002384builtin_isinstance_impl(PyObject *module, PyObject *obj,
Larry Hastings89964c42015-04-14 18:07:59 -04002385 PyObject *class_or_tuple)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002386/*[clinic end generated code: output=6faf01472c13b003 input=ffa743db1daf7549]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002387{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002388 int retval;
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002389
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002390 retval = PyObject_IsInstance(obj, class_or_tuple);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002391 if (retval < 0)
2392 return NULL;
2393 return PyBool_FromLong(retval);
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002394}
2395
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002396
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002397/*[clinic input]
2398issubclass as builtin_issubclass
2399
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03002400 cls: object
2401 class_or_tuple: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002402 /
2403
2404Return whether 'cls' is a derived from another class or is the same class.
2405
2406A tuple, as in ``issubclass(x, (A, B, ...))``, may be given as the target to
2407check against. This is equivalent to ``issubclass(x, A) or issubclass(x, B)
2408or ...`` etc.
2409[clinic start generated code]*/
2410
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002411static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002412builtin_issubclass_impl(PyObject *module, PyObject *cls,
Larry Hastings89964c42015-04-14 18:07:59 -04002413 PyObject *class_or_tuple)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002414/*[clinic end generated code: output=358412410cd7a250 input=af5f35e9ceaddaf6]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002415{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002416 int retval;
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002417
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002418 retval = PyObject_IsSubclass(cls, class_or_tuple);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002419 if (retval < 0)
2420 return NULL;
2421 return PyBool_FromLong(retval);
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002422}
2423
2424
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002425typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002426 PyObject_HEAD
2427 Py_ssize_t tuplesize;
2428 PyObject *ittuple; /* tuple of iterators */
2429 PyObject *result;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002430} zipobject;
2431
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002432static PyObject *
2433zip_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
Barry Warsawbd599b52000-08-03 15:45:29 +00002434{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002435 zipobject *lz;
2436 Py_ssize_t i;
2437 PyObject *ittuple; /* tuple of iterators */
2438 PyObject *result;
2439 Py_ssize_t tuplesize = PySequence_Length(args);
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002440
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002441 if (type == &PyZip_Type && !_PyArg_NoKeywords("zip()", kwds))
2442 return NULL;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002443
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002444 /* args must be a tuple */
2445 assert(PyTuple_Check(args));
Barry Warsawbd599b52000-08-03 15:45:29 +00002446
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002447 /* obtain iterators */
2448 ittuple = PyTuple_New(tuplesize);
2449 if (ittuple == NULL)
2450 return NULL;
2451 for (i=0; i < tuplesize; ++i) {
2452 PyObject *item = PyTuple_GET_ITEM(args, i);
2453 PyObject *it = PyObject_GetIter(item);
2454 if (it == NULL) {
2455 if (PyErr_ExceptionMatches(PyExc_TypeError))
2456 PyErr_Format(PyExc_TypeError,
2457 "zip argument #%zd must support iteration",
2458 i+1);
2459 Py_DECREF(ittuple);
2460 return NULL;
2461 }
2462 PyTuple_SET_ITEM(ittuple, i, it);
2463 }
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002464
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002465 /* create a result holder */
2466 result = PyTuple_New(tuplesize);
2467 if (result == NULL) {
2468 Py_DECREF(ittuple);
2469 return NULL;
2470 }
2471 for (i=0 ; i < tuplesize ; i++) {
2472 Py_INCREF(Py_None);
2473 PyTuple_SET_ITEM(result, i, Py_None);
2474 }
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002475
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002476 /* create zipobject structure */
2477 lz = (zipobject *)type->tp_alloc(type, 0);
2478 if (lz == NULL) {
2479 Py_DECREF(ittuple);
2480 Py_DECREF(result);
2481 return NULL;
2482 }
2483 lz->ittuple = ittuple;
2484 lz->tuplesize = tuplesize;
2485 lz->result = result;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002486
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002487 return (PyObject *)lz;
Barry Warsawbd599b52000-08-03 15:45:29 +00002488}
2489
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002490static void
2491zip_dealloc(zipobject *lz)
2492{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002493 PyObject_GC_UnTrack(lz);
2494 Py_XDECREF(lz->ittuple);
2495 Py_XDECREF(lz->result);
2496 Py_TYPE(lz)->tp_free(lz);
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002497}
2498
2499static int
2500zip_traverse(zipobject *lz, visitproc visit, void *arg)
2501{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002502 Py_VISIT(lz->ittuple);
2503 Py_VISIT(lz->result);
2504 return 0;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002505}
2506
2507static PyObject *
2508zip_next(zipobject *lz)
2509{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002510 Py_ssize_t i;
2511 Py_ssize_t tuplesize = lz->tuplesize;
2512 PyObject *result = lz->result;
2513 PyObject *it;
2514 PyObject *item;
2515 PyObject *olditem;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002516
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002517 if (tuplesize == 0)
2518 return NULL;
2519 if (Py_REFCNT(result) == 1) {
2520 Py_INCREF(result);
2521 for (i=0 ; i < tuplesize ; i++) {
2522 it = PyTuple_GET_ITEM(lz->ittuple, i);
2523 item = (*Py_TYPE(it)->tp_iternext)(it);
Serhiy Storchaka278d03b2013-04-06 22:52:34 +03002524 if (item == NULL) {
2525 Py_DECREF(result);
2526 return NULL;
2527 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002528 olditem = PyTuple_GET_ITEM(result, i);
2529 PyTuple_SET_ITEM(result, i, item);
2530 Py_DECREF(olditem);
2531 }
2532 } else {
2533 result = PyTuple_New(tuplesize);
2534 if (result == NULL)
Serhiy Storchaka278d03b2013-04-06 22:52:34 +03002535 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002536 for (i=0 ; i < tuplesize ; i++) {
2537 it = PyTuple_GET_ITEM(lz->ittuple, i);
2538 item = (*Py_TYPE(it)->tp_iternext)(it);
Serhiy Storchaka278d03b2013-04-06 22:52:34 +03002539 if (item == NULL) {
2540 Py_DECREF(result);
2541 return NULL;
2542 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002543 PyTuple_SET_ITEM(result, i, item);
2544 }
2545 }
2546 return result;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002547}
Barry Warsawbd599b52000-08-03 15:45:29 +00002548
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002549static PyObject *
2550zip_reduce(zipobject *lz)
2551{
2552 /* Just recreate the zip with the internal iterator tuple */
2553 return Py_BuildValue("OO", Py_TYPE(lz), lz->ittuple);
2554}
2555
2556static PyMethodDef zip_methods[] = {
2557 {"__reduce__", (PyCFunction)zip_reduce, METH_NOARGS, reduce_doc},
2558 {NULL, NULL} /* sentinel */
2559};
2560
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002561PyDoc_STRVAR(zip_doc,
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002562"zip(iter1 [,iter2 [...]]) --> zip object\n\
Barry Warsawbd599b52000-08-03 15:45:29 +00002563\n\
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002564Return a zip object whose .__next__() method returns a tuple where\n\
2565the i-th element comes from the i-th iterable argument. The .__next__()\n\
2566method continues until the shortest iterable in the argument sequence\n\
Georg Brandlced51db2008-12-04 18:28:38 +00002567is exhausted and then it raises StopIteration.");
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002568
2569PyTypeObject PyZip_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002570 PyVarObject_HEAD_INIT(&PyType_Type, 0)
2571 "zip", /* tp_name */
2572 sizeof(zipobject), /* tp_basicsize */
2573 0, /* tp_itemsize */
2574 /* methods */
2575 (destructor)zip_dealloc, /* tp_dealloc */
2576 0, /* tp_print */
2577 0, /* tp_getattr */
2578 0, /* tp_setattr */
2579 0, /* tp_reserved */
2580 0, /* tp_repr */
2581 0, /* tp_as_number */
2582 0, /* tp_as_sequence */
2583 0, /* tp_as_mapping */
2584 0, /* tp_hash */
2585 0, /* tp_call */
2586 0, /* tp_str */
2587 PyObject_GenericGetAttr, /* tp_getattro */
2588 0, /* tp_setattro */
2589 0, /* tp_as_buffer */
2590 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
2591 Py_TPFLAGS_BASETYPE, /* tp_flags */
2592 zip_doc, /* tp_doc */
2593 (traverseproc)zip_traverse, /* tp_traverse */
2594 0, /* tp_clear */
2595 0, /* tp_richcompare */
2596 0, /* tp_weaklistoffset */
2597 PyObject_SelfIter, /* tp_iter */
2598 (iternextfunc)zip_next, /* tp_iternext */
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002599 zip_methods, /* tp_methods */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002600 0, /* tp_members */
2601 0, /* tp_getset */
2602 0, /* tp_base */
2603 0, /* tp_dict */
2604 0, /* tp_descr_get */
2605 0, /* tp_descr_set */
2606 0, /* tp_dictoffset */
2607 0, /* tp_init */
2608 PyType_GenericAlloc, /* tp_alloc */
2609 zip_new, /* tp_new */
2610 PyObject_GC_Del, /* tp_free */
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002611};
Barry Warsawbd599b52000-08-03 15:45:29 +00002612
2613
Guido van Rossum79f25d91997-04-29 20:08:16 +00002614static PyMethodDef builtin_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002615 {"__build_class__", (PyCFunction)builtin___build_class__,
2616 METH_VARARGS | METH_KEYWORDS, build_class_doc},
2617 {"__import__", (PyCFunction)builtin___import__, METH_VARARGS | METH_KEYWORDS, import_doc},
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002618 BUILTIN_ABS_METHODDEF
2619 BUILTIN_ALL_METHODDEF
2620 BUILTIN_ANY_METHODDEF
2621 BUILTIN_ASCII_METHODDEF
2622 BUILTIN_BIN_METHODDEF
2623 BUILTIN_CALLABLE_METHODDEF
2624 BUILTIN_CHR_METHODDEF
2625 BUILTIN_COMPILE_METHODDEF
2626 BUILTIN_DELATTR_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002627 {"dir", builtin_dir, METH_VARARGS, dir_doc},
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002628 BUILTIN_DIVMOD_METHODDEF
2629 BUILTIN_EVAL_METHODDEF
2630 BUILTIN_EXEC_METHODDEF
2631 BUILTIN_FORMAT_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002632 {"getattr", builtin_getattr, METH_VARARGS, getattr_doc},
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002633 BUILTIN_GLOBALS_METHODDEF
2634 BUILTIN_HASATTR_METHODDEF
2635 BUILTIN_HASH_METHODDEF
2636 BUILTIN_HEX_METHODDEF
2637 BUILTIN_ID_METHODDEF
2638 BUILTIN_INPUT_METHODDEF
2639 BUILTIN_ISINSTANCE_METHODDEF
2640 BUILTIN_ISSUBCLASS_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002641 {"iter", builtin_iter, METH_VARARGS, iter_doc},
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002642 BUILTIN_LEN_METHODDEF
2643 BUILTIN_LOCALS_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002644 {"max", (PyCFunction)builtin_max, METH_VARARGS | METH_KEYWORDS, max_doc},
2645 {"min", (PyCFunction)builtin_min, METH_VARARGS | METH_KEYWORDS, min_doc},
2646 {"next", (PyCFunction)builtin_next, METH_VARARGS, next_doc},
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002647 BUILTIN_OCT_METHODDEF
2648 BUILTIN_ORD_METHODDEF
2649 BUILTIN_POW_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002650 {"print", (PyCFunction)builtin_print, METH_VARARGS | METH_KEYWORDS, print_doc},
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002651 BUILTIN_REPR_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002652 {"round", (PyCFunction)builtin_round, METH_VARARGS | METH_KEYWORDS, round_doc},
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002653 BUILTIN_SETATTR_METHODDEF
2654 BUILTIN_SORTED_METHODDEF
2655 BUILTIN_SUM_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002656 {"vars", builtin_vars, METH_VARARGS, vars_doc},
2657 {NULL, NULL},
Guido van Rossum3f5da241990-12-20 15:06:42 +00002658};
2659
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002660PyDoc_STRVAR(builtin_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002661"Built-in functions, exceptions, and other objects.\n\
2662\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002663Noteworthy: None is the `nil' object; Ellipsis represents `...' in slices.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002664
Martin v. Löwis1a214512008-06-11 05:26:20 +00002665static struct PyModuleDef builtinsmodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002666 PyModuleDef_HEAD_INIT,
2667 "builtins",
2668 builtin_doc,
2669 -1, /* multiple "initialization" just copies the module dict. */
2670 builtin_methods,
2671 NULL,
2672 NULL,
2673 NULL,
2674 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00002675};
2676
2677
Guido van Rossum25ce5661997-08-02 03:10:38 +00002678PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002679_PyBuiltin_Init(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +00002680{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002681 PyObject *mod, *dict, *debug;
Benjamin Peterson42124a72012-10-30 23:41:54 -04002682
2683 if (PyType_Ready(&PyFilter_Type) < 0 ||
2684 PyType_Ready(&PyMap_Type) < 0 ||
2685 PyType_Ready(&PyZip_Type) < 0)
2686 return NULL;
2687
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002688 mod = PyModule_Create(&builtinsmodule);
2689 if (mod == NULL)
2690 return NULL;
2691 dict = PyModule_GetDict(mod);
Tim Peters4b7625e2001-09-13 21:37:17 +00002692
Tim Peters7571a0f2003-03-23 17:52:28 +00002693#ifdef Py_TRACE_REFS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002694 /* "builtins" exposes a number of statically allocated objects
2695 * that, before this code was added in 2.3, never showed up in
2696 * the list of "all objects" maintained by Py_TRACE_REFS. As a
2697 * result, programs leaking references to None and False (etc)
2698 * couldn't be diagnosed by examining sys.getobjects(0).
2699 */
Tim Peters7571a0f2003-03-23 17:52:28 +00002700#define ADD_TO_ALL(OBJECT) _Py_AddToAllObjects((PyObject *)(OBJECT), 0)
2701#else
2702#define ADD_TO_ALL(OBJECT) (void)0
2703#endif
2704
Tim Peters4b7625e2001-09-13 21:37:17 +00002705#define SETBUILTIN(NAME, OBJECT) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002706 if (PyDict_SetItemString(dict, NAME, (PyObject *)OBJECT) < 0) \
2707 return NULL; \
2708 ADD_TO_ALL(OBJECT)
Tim Peters4b7625e2001-09-13 21:37:17 +00002709
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002710 SETBUILTIN("None", Py_None);
2711 SETBUILTIN("Ellipsis", Py_Ellipsis);
2712 SETBUILTIN("NotImplemented", Py_NotImplemented);
2713 SETBUILTIN("False", Py_False);
2714 SETBUILTIN("True", Py_True);
2715 SETBUILTIN("bool", &PyBool_Type);
2716 SETBUILTIN("memoryview", &PyMemoryView_Type);
2717 SETBUILTIN("bytearray", &PyByteArray_Type);
2718 SETBUILTIN("bytes", &PyBytes_Type);
2719 SETBUILTIN("classmethod", &PyClassMethod_Type);
2720 SETBUILTIN("complex", &PyComplex_Type);
2721 SETBUILTIN("dict", &PyDict_Type);
2722 SETBUILTIN("enumerate", &PyEnum_Type);
2723 SETBUILTIN("filter", &PyFilter_Type);
2724 SETBUILTIN("float", &PyFloat_Type);
2725 SETBUILTIN("frozenset", &PyFrozenSet_Type);
2726 SETBUILTIN("property", &PyProperty_Type);
2727 SETBUILTIN("int", &PyLong_Type);
2728 SETBUILTIN("list", &PyList_Type);
2729 SETBUILTIN("map", &PyMap_Type);
2730 SETBUILTIN("object", &PyBaseObject_Type);
2731 SETBUILTIN("range", &PyRange_Type);
2732 SETBUILTIN("reversed", &PyReversed_Type);
2733 SETBUILTIN("set", &PySet_Type);
2734 SETBUILTIN("slice", &PySlice_Type);
2735 SETBUILTIN("staticmethod", &PyStaticMethod_Type);
2736 SETBUILTIN("str", &PyUnicode_Type);
2737 SETBUILTIN("super", &PySuper_Type);
2738 SETBUILTIN("tuple", &PyTuple_Type);
2739 SETBUILTIN("type", &PyType_Type);
2740 SETBUILTIN("zip", &PyZip_Type);
2741 debug = PyBool_FromLong(Py_OptimizeFlag == 0);
2742 if (PyDict_SetItemString(dict, "__debug__", debug) < 0) {
Serhiy Storchakacfdfbb42016-06-18 09:44:03 +03002743 Py_DECREF(debug);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002744 return NULL;
2745 }
Serhiy Storchakacfdfbb42016-06-18 09:44:03 +03002746 Py_DECREF(debug);
Barry Warsaw757af0e1997-08-29 22:13:51 +00002747
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002748 return mod;
Tim Peters7571a0f2003-03-23 17:52:28 +00002749#undef ADD_TO_ALL
Tim Peters4b7625e2001-09-13 21:37:17 +00002750#undef SETBUILTIN
Guido van Rossum3f5da241990-12-20 15:06:42 +00002751}