blob: 00a85b57415ad177e37e8c56cd7d557c665c0a2a [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*/
Victor Stinner99b95382011-07-04 14:23:54 +020024#ifdef HAVE_MBCS
Mark Hammond26cffde42001-05-14 12:17:34 +000025const char *Py_FileSystemDefaultEncoding = "mbcs";
Martin v. Löwis04dc25c2008-10-03 16:09:28 +000026int Py_HasFileSystemDefaultEncoding = 1;
Just van Rossumb9b8e9c2003-02-10 09:22:01 +000027#elif defined(__APPLE__)
28const char *Py_FileSystemDefaultEncoding = "utf-8";
Martin v. Löwis04dc25c2008-10-03 16:09:28 +000029int Py_HasFileSystemDefaultEncoding = 1;
Victor Stinnerd64e8a72011-07-04 13:48:30 +020030#else
Victor Stinnerb744ba12010-05-15 12:27:16 +000031const char *Py_FileSystemDefaultEncoding = NULL; /* set by initfsencoding() */
Martin v. Löwis04dc25c2008-10-03 16:09:28 +000032int Py_HasFileSystemDefaultEncoding = 0;
Mark Hammond26cffde42001-05-14 12:17:34 +000033#endif
Mark Hammondef8b6542001-05-13 08:04:26 +000034
Victor Stinnerbd303c12013-11-07 23:07:29 +010035_Py_IDENTIFIER(__builtins__);
36_Py_IDENTIFIER(__dict__);
37_Py_IDENTIFIER(__prepare__);
38_Py_IDENTIFIER(__round__);
39_Py_IDENTIFIER(encoding);
40_Py_IDENTIFIER(errors);
Martin v. Löwisbd928fe2011-10-14 10:20:37 +020041_Py_IDENTIFIER(fileno);
42_Py_IDENTIFIER(flush);
Victor Stinnerbd303c12013-11-07 23:07:29 +010043_Py_IDENTIFIER(metaclass);
44_Py_IDENTIFIER(sort);
45_Py_IDENTIFIER(stdin);
46_Py_IDENTIFIER(stdout);
47_Py_IDENTIFIER(stderr);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +020048
Serhiy Storchaka1009bf12015-04-03 23:53:51 +030049#include "clinic/bltinmodule.c.h"
50
Nick Coghlanf9e227e2014-08-17 14:01:19 +100051/* AC: cannot convert yet, waiting for *args support */
Guido van Rossum79f25d91997-04-29 20:08:16 +000052static PyObject *
Guido van Rossum52cc1d82007-03-18 15:41:51 +000053builtin___build_class__(PyObject *self, PyObject *args, PyObject *kwds)
54{
Nick Coghlande31b192011-10-23 22:04:16 +100055 PyObject *func, *name, *bases, *mkw, *meta, *winner, *prep, *ns, *cell;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000056 PyObject *cls = NULL;
Florent Xicluna4d46c2a2011-10-28 15:00:50 +020057 Py_ssize_t nargs;
Victor Stinner0c39b1b2015-03-18 15:02:06 +010058 int isclass = 0; /* initialize to prevent gcc warning */
Guido van Rossum52cc1d82007-03-18 15:41:51 +000059
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000060 assert(args != NULL);
61 if (!PyTuple_Check(args)) {
62 PyErr_SetString(PyExc_TypeError,
63 "__build_class__: args is not a tuple");
64 return NULL;
65 }
66 nargs = PyTuple_GET_SIZE(args);
67 if (nargs < 2) {
68 PyErr_SetString(PyExc_TypeError,
69 "__build_class__: not enough arguments");
70 return NULL;
71 }
72 func = PyTuple_GET_ITEM(args, 0); /* Better be callable */
Benjamin Petersone8e14592013-05-16 14:37:25 -050073 if (!PyFunction_Check(func)) {
74 PyErr_SetString(PyExc_TypeError,
Zachary Ware9b338722014-08-05 14:01:10 -050075 "__build_class__: func must be a function");
Benjamin Petersone8e14592013-05-16 14:37:25 -050076 return NULL;
77 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000078 name = PyTuple_GET_ITEM(args, 1);
79 if (!PyUnicode_Check(name)) {
80 PyErr_SetString(PyExc_TypeError,
81 "__build_class__: name is not a string");
82 return NULL;
83 }
84 bases = PyTuple_GetSlice(args, 2, nargs);
85 if (bases == NULL)
86 return NULL;
Guido van Rossum52cc1d82007-03-18 15:41:51 +000087
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000088 if (kwds == NULL) {
89 meta = NULL;
90 mkw = NULL;
91 }
92 else {
93 mkw = PyDict_Copy(kwds); /* Don't modify kwds passed in! */
94 if (mkw == NULL) {
95 Py_DECREF(bases);
96 return NULL;
Guido van Rossum52cc1d82007-03-18 15:41:51 +000097 }
Victor Stinnerae9f1612013-11-06 22:46:51 +010098 meta = _PyDict_GetItemId(mkw, &PyId_metaclass);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000099 if (meta != NULL) {
100 Py_INCREF(meta);
Victor Stinnerae9f1612013-11-06 22:46:51 +0100101 if (_PyDict_DelItemId(mkw, &PyId_metaclass) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000102 Py_DECREF(meta);
103 Py_DECREF(mkw);
104 Py_DECREF(bases);
105 return NULL;
106 }
Nick Coghlande31b192011-10-23 22:04:16 +1000107 /* metaclass is explicitly given, check if it's indeed a class */
108 isclass = PyType_Check(meta);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000109 }
110 }
111 if (meta == NULL) {
Nick Coghlande31b192011-10-23 22:04:16 +1000112 /* if there are no bases, use type: */
113 if (PyTuple_GET_SIZE(bases) == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000114 meta = (PyObject *) (&PyType_Type);
Nick Coghlande31b192011-10-23 22:04:16 +1000115 }
116 /* else get the type of the first base */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000117 else {
118 PyObject *base0 = PyTuple_GET_ITEM(bases, 0);
119 meta = (PyObject *) (base0->ob_type);
120 }
121 Py_INCREF(meta);
Nick Coghlande31b192011-10-23 22:04:16 +1000122 isclass = 1; /* meta is really a class */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000123 }
Nick Coghlan9715d262011-10-23 22:36:42 +1000124
Nick Coghlande31b192011-10-23 22:04:16 +1000125 if (isclass) {
126 /* meta is really a class, so check for a more derived
127 metaclass, or possible metaclass conflicts: */
128 winner = (PyObject *)_PyType_CalculateMetaclass((PyTypeObject *)meta,
129 bases);
130 if (winner == NULL) {
131 Py_DECREF(meta);
132 Py_XDECREF(mkw);
133 Py_DECREF(bases);
134 return NULL;
135 }
136 if (winner != meta) {
137 Py_DECREF(meta);
138 meta = winner;
139 Py_INCREF(meta);
140 }
141 }
142 /* else: meta is not a class, so we cannot do the metaclass
143 calculation, so we will use the explicitly given object as it is */
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +0200144 prep = _PyObject_GetAttrId(meta, &PyId___prepare__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000145 if (prep == NULL) {
146 if (PyErr_ExceptionMatches(PyExc_AttributeError)) {
147 PyErr_Clear();
148 ns = PyDict_New();
149 }
150 else {
151 Py_DECREF(meta);
152 Py_XDECREF(mkw);
153 Py_DECREF(bases);
154 return NULL;
155 }
156 }
157 else {
Victor Stinner463b86a2016-08-22 23:33:13 +0200158 PyObject *pargs[2] = {name, bases};
159 ns = _PyObject_FastCallDict(prep, pargs, 2, mkw);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000160 Py_DECREF(prep);
161 }
162 if (ns == NULL) {
163 Py_DECREF(meta);
164 Py_XDECREF(mkw);
165 Py_DECREF(bases);
166 return NULL;
167 }
Benjamin Petersone8e14592013-05-16 14:37:25 -0500168 cell = PyEval_EvalCodeEx(PyFunction_GET_CODE(func), PyFunction_GET_GLOBALS(func), ns,
169 NULL, 0, NULL, 0, NULL, 0, NULL,
170 PyFunction_GET_CLOSURE(func));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000171 if (cell != NULL) {
Victor Stinnerd1c2a8e2016-08-23 01:34:35 +0200172 PyObject *margs[3] = {name, bases, ns};
173 cls = _PyObject_FastCallDict(meta, margs, 3, mkw);
Benjamin Peterson8e8fbea2012-06-01 23:57:36 -0700174 if (cls != NULL && PyCell_Check(cell))
175 PyCell_Set(cell, cls);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000176 Py_DECREF(cell);
177 }
178 Py_DECREF(ns);
179 Py_DECREF(meta);
180 Py_XDECREF(mkw);
181 Py_DECREF(bases);
182 return cls;
Guido van Rossum52cc1d82007-03-18 15:41:51 +0000183}
184
185PyDoc_STRVAR(build_class_doc,
186"__build_class__(func, name, *bases, metaclass=None, **kwds) -> class\n\
187\n\
188Internal helper function used by the class statement.");
189
190static PyObject *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000191builtin___import__(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000192{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000193 static char *kwlist[] = {"name", "globals", "locals", "fromlist",
194 "level", 0};
Victor Stinnerfe93faf2011-03-14 15:54:52 -0400195 PyObject *name, *globals = NULL, *locals = NULL, *fromlist = NULL;
Brett Cannonfd074152012-04-14 14:10:13 -0400196 int level = 0;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000197
Victor Stinnerfe93faf2011-03-14 15:54:52 -0400198 if (!PyArg_ParseTupleAndKeywords(args, kwds, "U|OOOi:__import__",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000199 kwlist, &name, &globals, &locals, &fromlist, &level))
200 return NULL;
Victor Stinnerfe93faf2011-03-14 15:54:52 -0400201 return PyImport_ImportModuleLevelObject(name, globals, locals,
202 fromlist, level);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000203}
204
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000205PyDoc_STRVAR(import_doc,
Brett Cannoncb4996a2012-08-06 16:34:44 -0400206"__import__(name, globals=None, locals=None, fromlist=(), level=0) -> module\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000207\n\
Brett Cannon5305a992010-09-27 21:08:38 +0000208Import a module. Because this function is meant for use by the Python\n\
209interpreter and not for general use it is better to use\n\
210importlib.import_module() to programmatically import a module.\n\
211\n\
212The globals argument is only used to determine the context;\n\
213they are not modified. The locals argument is unused. The fromlist\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000214should be a list of names to emulate ``from name import ...'', or an\n\
215empty list to emulate ``import name''.\n\
216When importing a module from a package, note that __import__('A.B', ...)\n\
217returns package A when fromlist is empty, but its submodule B when\n\
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000218fromlist is not empty. Level is used to determine whether to perform \n\
Brett Cannon722d3ae2012-07-30 17:45:54 -0400219absolute or relative imports. 0 is absolute while a positive number\n\
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000220is the number of parent directories to search relative to the current module.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000221
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000222
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000223/*[clinic input]
224abs as builtin_abs
225
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300226 x: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000227 /
228
229Return the absolute value of the argument.
230[clinic start generated code]*/
231
Guido van Rossum79f25d91997-04-29 20:08:16 +0000232static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300233builtin_abs(PyObject *module, PyObject *x)
234/*[clinic end generated code: output=b1b433b9e51356f5 input=bed4ca14e29c20d1]*/
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000235{
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000236 return PyNumber_Absolute(x);
Guido van Rossum3f5da241990-12-20 15:06:42 +0000237}
238
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000239/*[clinic input]
240all as builtin_all
241
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300242 iterable: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000243 /
244
245Return True if bool(x) is True for all values x in the iterable.
246
247If the iterable is empty, return True.
248[clinic start generated code]*/
249
Raymond Hettinger96229b12005-03-11 06:49:40 +0000250static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300251builtin_all(PyObject *module, PyObject *iterable)
252/*[clinic end generated code: output=ca2a7127276f79b3 input=1a7c5d1bc3438a21]*/
Raymond Hettinger96229b12005-03-11 06:49:40 +0000253{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000254 PyObject *it, *item;
255 PyObject *(*iternext)(PyObject *);
256 int cmp;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000257
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000258 it = PyObject_GetIter(iterable);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000259 if (it == NULL)
260 return NULL;
261 iternext = *Py_TYPE(it)->tp_iternext;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000262
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000263 for (;;) {
264 item = iternext(it);
265 if (item == NULL)
266 break;
267 cmp = PyObject_IsTrue(item);
268 Py_DECREF(item);
269 if (cmp < 0) {
270 Py_DECREF(it);
271 return NULL;
272 }
273 if (cmp == 0) {
274 Py_DECREF(it);
275 Py_RETURN_FALSE;
276 }
277 }
278 Py_DECREF(it);
279 if (PyErr_Occurred()) {
280 if (PyErr_ExceptionMatches(PyExc_StopIteration))
281 PyErr_Clear();
282 else
283 return NULL;
284 }
285 Py_RETURN_TRUE;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000286}
287
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000288/*[clinic input]
289any as builtin_any
290
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300291 iterable: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000292 /
293
294Return True if bool(x) is True for any x in the iterable.
295
296If the iterable is empty, return False.
297[clinic start generated code]*/
298
Raymond Hettinger96229b12005-03-11 06:49:40 +0000299static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300300builtin_any(PyObject *module, PyObject *iterable)
301/*[clinic end generated code: output=fa65684748caa60e input=41d7451c23384f24]*/
Raymond Hettinger96229b12005-03-11 06:49:40 +0000302{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000303 PyObject *it, *item;
304 PyObject *(*iternext)(PyObject *);
305 int cmp;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000306
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000307 it = PyObject_GetIter(iterable);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000308 if (it == NULL)
309 return NULL;
310 iternext = *Py_TYPE(it)->tp_iternext;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000311
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000312 for (;;) {
313 item = iternext(it);
314 if (item == NULL)
315 break;
316 cmp = PyObject_IsTrue(item);
317 Py_DECREF(item);
318 if (cmp < 0) {
319 Py_DECREF(it);
320 return NULL;
321 }
Raymond Hettinger5098b582015-10-09 00:42:47 -0400322 if (cmp > 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000323 Py_DECREF(it);
324 Py_RETURN_TRUE;
325 }
326 }
327 Py_DECREF(it);
328 if (PyErr_Occurred()) {
329 if (PyErr_ExceptionMatches(PyExc_StopIteration))
330 PyErr_Clear();
331 else
332 return NULL;
333 }
334 Py_RETURN_FALSE;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000335}
336
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000337/*[clinic input]
338ascii as builtin_ascii
339
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300340 obj: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000341 /
342
343Return an ASCII-only representation of an object.
344
345As repr(), return a string containing a printable representation of an
346object, but escape the non-ASCII characters in the string returned by
347repr() using \\x, \\u or \\U escapes. This generates a string similar
348to that returned by repr() in Python 2.
349[clinic start generated code]*/
350
Georg Brandl559e5d72008-06-11 18:37:52 +0000351static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300352builtin_ascii(PyObject *module, PyObject *obj)
353/*[clinic end generated code: output=6d37b3f0984c7eb9 input=4c62732e1b3a3cc9]*/
Georg Brandl559e5d72008-06-11 18:37:52 +0000354{
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000355 return PyObject_ASCII(obj);
Georg Brandl559e5d72008-06-11 18:37:52 +0000356}
357
Georg Brandl559e5d72008-06-11 18:37:52 +0000358
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000359/*[clinic input]
360bin as builtin_bin
361
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300362 number: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000363 /
364
365Return the binary representation of an integer.
366
367 >>> bin(2796202)
368 '0b1010101010101010101010'
369[clinic start generated code]*/
370
Guido van Rossum79f25d91997-04-29 20:08:16 +0000371static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300372builtin_bin(PyObject *module, PyObject *number)
373/*[clinic end generated code: output=b6fc4ad5e649f4f7 input=53f8a0264bacaf90]*/
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000374{
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000375 return PyNumber_ToBase(number, 2);
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000376}
377
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000378
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000379/*[clinic input]
380callable as builtin_callable
381
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300382 obj: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000383 /
384
385Return whether the object is callable (i.e., some kind of function).
386
387Note that classes are callable, as are instances of classes with a
388__call__() method.
389[clinic start generated code]*/
390
Antoine Pitroue71362d2010-11-27 22:00:11 +0000391static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300392builtin_callable(PyObject *module, PyObject *obj)
393/*[clinic end generated code: output=2b095d59d934cb7e input=1423bab99cc41f58]*/
Antoine Pitroue71362d2010-11-27 22:00:11 +0000394{
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000395 return PyBool_FromLong((long)PyCallable_Check(obj));
Antoine Pitroue71362d2010-11-27 22:00:11 +0000396}
397
Antoine Pitroue71362d2010-11-27 22:00:11 +0000398
Raymond Hettinger17301e92008-03-13 00:19:26 +0000399typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000400 PyObject_HEAD
401 PyObject *func;
402 PyObject *it;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000403} filterobject;
404
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000405static PyObject *
Raymond Hettinger17301e92008-03-13 00:19:26 +0000406filter_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
Guido van Rossum12d12c51993-10-26 17:58:25 +0000407{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000408 PyObject *func, *seq;
409 PyObject *it;
410 filterobject *lz;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000411
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000412 if (type == &PyFilter_Type && !_PyArg_NoKeywords("filter()", kwds))
413 return NULL;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000414
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000415 if (!PyArg_UnpackTuple(args, "filter", 2, 2, &func, &seq))
416 return NULL;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000417
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000418 /* Get iterator. */
419 it = PyObject_GetIter(seq);
420 if (it == NULL)
421 return NULL;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000422
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000423 /* create filterobject structure */
424 lz = (filterobject *)type->tp_alloc(type, 0);
425 if (lz == NULL) {
426 Py_DECREF(it);
427 return NULL;
428 }
429 Py_INCREF(func);
430 lz->func = func;
431 lz->it = it;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000432
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000433 return (PyObject *)lz;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000434}
435
436static void
437filter_dealloc(filterobject *lz)
438{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000439 PyObject_GC_UnTrack(lz);
440 Py_XDECREF(lz->func);
441 Py_XDECREF(lz->it);
442 Py_TYPE(lz)->tp_free(lz);
Raymond Hettinger17301e92008-03-13 00:19:26 +0000443}
444
445static int
446filter_traverse(filterobject *lz, visitproc visit, void *arg)
447{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000448 Py_VISIT(lz->it);
449 Py_VISIT(lz->func);
450 return 0;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000451}
452
453static PyObject *
454filter_next(filterobject *lz)
455{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000456 PyObject *item;
457 PyObject *it = lz->it;
458 long ok;
459 PyObject *(*iternext)(PyObject *);
Raymond Hettingerbd5f0e82015-10-09 01:34:08 -0400460 int checktrue = lz->func == Py_None || lz->func == (PyObject *)&PyBool_Type;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000461
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000462 iternext = *Py_TYPE(it)->tp_iternext;
463 for (;;) {
464 item = iternext(it);
465 if (item == NULL)
466 return NULL;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000467
Raymond Hettingerbd5f0e82015-10-09 01:34:08 -0400468 if (checktrue) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000469 ok = PyObject_IsTrue(item);
470 } else {
471 PyObject *good;
Raymond Hettingerbd5f0e82015-10-09 01:34:08 -0400472 good = PyObject_CallFunctionObjArgs(lz->func, item, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000473 if (good == NULL) {
474 Py_DECREF(item);
475 return NULL;
476 }
477 ok = PyObject_IsTrue(good);
478 Py_DECREF(good);
479 }
Antoine Pitrou6f430e42012-08-15 23:18:25 +0200480 if (ok > 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000481 return item;
482 Py_DECREF(item);
Antoine Pitrou6f430e42012-08-15 23:18:25 +0200483 if (ok < 0)
484 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000485 }
Guido van Rossum12d12c51993-10-26 17:58:25 +0000486}
487
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +0000488static PyObject *
489filter_reduce(filterobject *lz)
490{
491 return Py_BuildValue("O(OO)", Py_TYPE(lz), lz->func, lz->it);
492}
493
494PyDoc_STRVAR(reduce_doc, "Return state information for pickling.");
495
496static PyMethodDef filter_methods[] = {
497 {"__reduce__", (PyCFunction)filter_reduce, METH_NOARGS, reduce_doc},
498 {NULL, NULL} /* sentinel */
499};
500
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000501PyDoc_STRVAR(filter_doc,
Georg Brandld11ae5d2008-05-16 13:27:32 +0000502"filter(function or None, iterable) --> filter object\n\
Guido van Rossumc1f779c2007-07-03 08:25:58 +0000503\n\
Georg Brandld11ae5d2008-05-16 13:27:32 +0000504Return an iterator yielding those items of iterable for which function(item)\n\
Raymond Hettinger17301e92008-03-13 00:19:26 +0000505is true. If function is None, return the items that are true.");
506
507PyTypeObject PyFilter_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000508 PyVarObject_HEAD_INIT(&PyType_Type, 0)
509 "filter", /* tp_name */
510 sizeof(filterobject), /* tp_basicsize */
511 0, /* tp_itemsize */
512 /* methods */
513 (destructor)filter_dealloc, /* tp_dealloc */
514 0, /* tp_print */
515 0, /* tp_getattr */
516 0, /* tp_setattr */
517 0, /* tp_reserved */
518 0, /* tp_repr */
519 0, /* tp_as_number */
520 0, /* tp_as_sequence */
521 0, /* tp_as_mapping */
522 0, /* tp_hash */
523 0, /* tp_call */
524 0, /* tp_str */
525 PyObject_GenericGetAttr, /* tp_getattro */
526 0, /* tp_setattro */
527 0, /* tp_as_buffer */
528 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
529 Py_TPFLAGS_BASETYPE, /* tp_flags */
530 filter_doc, /* tp_doc */
531 (traverseproc)filter_traverse, /* tp_traverse */
532 0, /* tp_clear */
533 0, /* tp_richcompare */
534 0, /* tp_weaklistoffset */
535 PyObject_SelfIter, /* tp_iter */
536 (iternextfunc)filter_next, /* tp_iternext */
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +0000537 filter_methods, /* tp_methods */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000538 0, /* tp_members */
539 0, /* tp_getset */
540 0, /* tp_base */
541 0, /* tp_dict */
542 0, /* tp_descr_get */
543 0, /* tp_descr_set */
544 0, /* tp_dictoffset */
545 0, /* tp_init */
546 PyType_GenericAlloc, /* tp_alloc */
547 filter_new, /* tp_new */
548 PyObject_GC_Del, /* tp_free */
Raymond Hettinger17301e92008-03-13 00:19:26 +0000549};
550
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000551
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000552/*[clinic input]
553format as builtin_format
554
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300555 value: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000556 format_spec: unicode(c_default="NULL") = ''
557 /
558
559Return value.__format__(format_spec)
560
561format_spec defaults to the empty string
562[clinic start generated code]*/
563
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000564static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300565builtin_format_impl(PyObject *module, PyObject *value, PyObject *format_spec)
566/*[clinic end generated code: output=2f40bdfa4954b077 input=6325e751a1b29b86]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000567{
Eric Smith8fd3eba2008-02-17 19:48:00 +0000568 return PyObject_Format(value, format_spec);
Eric Smith8c663262007-08-25 02:26:07 +0000569}
570
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000571/*[clinic input]
572chr as builtin_chr
573
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300574 i: int
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000575 /
576
577Return a Unicode string of one character with ordinal i; 0 <= i <= 0x10ffff.
578[clinic start generated code]*/
579
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000580static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300581builtin_chr_impl(PyObject *module, int i)
582/*[clinic end generated code: output=c733afcd200afcb7 input=3f604ef45a70750d]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000583{
584 return PyUnicode_FromOrdinal(i);
585}
Guido van Rossum09095f32000-03-10 23:00:52 +0000586
587
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +0200588static const char *
Martin Pantereeb896c2015-11-07 02:32:21 +0000589source_as_string(PyObject *cmd, const char *funcname, const char *what, PyCompilerFlags *cf, PyObject **cmd_copy)
Guido van Rossumf15a29f2007-05-04 00:41:39 +0000590{
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +0200591 const char *str;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000592 Py_ssize_t size;
Martin Pantereeb896c2015-11-07 02:32:21 +0000593 Py_buffer view;
Guido van Rossumf15a29f2007-05-04 00:41:39 +0000594
Martin Pantereeb896c2015-11-07 02:32:21 +0000595 *cmd_copy = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000596 if (PyUnicode_Check(cmd)) {
597 cf->cf_flags |= PyCF_IGNORE_COOKIE;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200598 str = PyUnicode_AsUTF8AndSize(cmd, &size);
599 if (str == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000600 return NULL;
601 }
Martin Pantereeb896c2015-11-07 02:32:21 +0000602 else if (PyBytes_Check(cmd)) {
603 str = PyBytes_AS_STRING(cmd);
604 size = PyBytes_GET_SIZE(cmd);
605 }
606 else if (PyByteArray_Check(cmd)) {
607 str = PyByteArray_AS_STRING(cmd);
608 size = PyByteArray_GET_SIZE(cmd);
609 }
610 else if (PyObject_GetBuffer(cmd, &view, PyBUF_SIMPLE) == 0) {
611 /* Copy to NUL-terminated buffer. */
612 *cmd_copy = PyBytes_FromStringAndSize(
613 (const char *)view.buf, view.len);
614 PyBuffer_Release(&view);
615 if (*cmd_copy == NULL) {
616 return NULL;
617 }
618 str = PyBytes_AS_STRING(*cmd_copy);
619 size = PyBytes_GET_SIZE(*cmd_copy);
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +0200620 }
621 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000622 PyErr_Format(PyExc_TypeError,
623 "%s() arg 1 must be a %s object",
624 funcname, what);
625 return NULL;
626 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200627
Serhiy Storchaka3dd3e262015-02-03 01:25:42 +0200628 if (strlen(str) != (size_t)size) {
Serhiy Storchakad8a14472014-09-06 20:07:17 +0300629 PyErr_SetString(PyExc_ValueError,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000630 "source code string cannot contain null bytes");
Martin Pantereeb896c2015-11-07 02:32:21 +0000631 Py_CLEAR(*cmd_copy);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000632 return NULL;
633 }
634 return str;
Guido van Rossumf15a29f2007-05-04 00:41:39 +0000635}
636
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000637/*[clinic input]
638compile as builtin_compile
639
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300640 source: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000641 filename: object(converter="PyUnicode_FSDecoder")
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300642 mode: str
643 flags: int = 0
Serhiy Storchaka8b2e8b62015-05-30 11:30:39 +0300644 dont_inherit: int(c_default="0") = False
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300645 optimize: int = -1
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000646
647Compile source into a code object that can be executed by exec() or eval().
648
649The source code may represent a Python module, statement or expression.
650The filename will be used for run-time error messages.
651The mode must be 'exec' to compile a module, 'single' to compile a
652single (interactive) statement, or 'eval' to compile an expression.
653The flags argument, if present, controls which future statements influence
654the compilation of the code.
Serhiy Storchaka8b2e8b62015-05-30 11:30:39 +0300655The dont_inherit argument, if true, stops the compilation inheriting
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000656the effects of any future statements in effect in the code calling
Serhiy Storchaka8b2e8b62015-05-30 11:30:39 +0300657compile; if absent or false these statements do influence the compilation,
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000658in addition to any features explicitly specified.
659[clinic start generated code]*/
660
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000661static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300662builtin_compile_impl(PyObject *module, PyObject *source, PyObject *filename,
663 const char *mode, int flags, int dont_inherit,
664 int optimize)
665/*[clinic end generated code: output=1fa176e33452bb63 input=9d53e8cfb3c86414]*/
Guido van Rossum5b722181993-03-30 17:46:03 +0000666{
Martin Panter61d6e4a2015-11-07 02:56:11 +0000667 PyObject *source_copy;
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +0200668 const char *str;
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000669 int compile_mode = -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000670 int is_ast;
671 PyCompilerFlags cf;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000672 int start[] = {Py_file_input, Py_eval_input, Py_single_input};
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000673 PyObject *result;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000674
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000675 cf.cf_flags = flags | PyCF_SOURCE_IS_UTF8;
Tim Peters6cd6a822001-08-17 22:11:27 +0000676
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000677 if (flags &
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000678 ~(PyCF_MASK | PyCF_MASK_OBSOLETE | PyCF_DONT_IMPLY_DEDENT | PyCF_ONLY_AST))
679 {
680 PyErr_SetString(PyExc_ValueError,
681 "compile(): unrecognised flags");
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000682 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000683 }
684 /* XXX Warn if (supplied_flags & PyCF_MASK_OBSOLETE) != 0? */
Tim Peters6cd6a822001-08-17 22:11:27 +0000685
Georg Brandl8334fd92010-12-04 10:26:46 +0000686 if (optimize < -1 || optimize > 2) {
687 PyErr_SetString(PyExc_ValueError,
688 "compile(): invalid optimize value");
689 goto error;
690 }
691
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000692 if (!dont_inherit) {
693 PyEval_MergeCompilerFlags(&cf);
694 }
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000695
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000696 if (strcmp(mode, "exec") == 0)
697 compile_mode = 0;
698 else if (strcmp(mode, "eval") == 0)
699 compile_mode = 1;
700 else if (strcmp(mode, "single") == 0)
701 compile_mode = 2;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000702 else {
703 PyErr_SetString(PyExc_ValueError,
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000704 "compile() mode must be 'exec', 'eval' or 'single'");
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000705 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000706 }
Neal Norwitzdb4115f2008-03-31 04:20:05 +0000707
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000708 is_ast = PyAST_Check(source);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000709 if (is_ast == -1)
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000710 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000711 if (is_ast) {
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000712 if (flags & PyCF_ONLY_AST) {
713 Py_INCREF(source);
714 result = source;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000715 }
716 else {
717 PyArena *arena;
718 mod_ty mod;
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000719
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000720 arena = PyArena_New();
Stefan Krah07795df2012-08-20 17:19:50 +0200721 if (arena == NULL)
722 goto error;
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000723 mod = PyAST_obj2mod(source, arena, compile_mode);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000724 if (mod == NULL) {
725 PyArena_Free(arena);
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000726 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000727 }
Benjamin Peterson832bfe22011-08-09 16:15:04 -0500728 if (!PyAST_Validate(mod)) {
729 PyArena_Free(arena);
730 goto error;
731 }
Victor Stinner14e461d2013-08-26 22:28:21 +0200732 result = (PyObject*)PyAST_CompileObject(mod, filename,
733 &cf, optimize, arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000734 PyArena_Free(arena);
735 }
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000736 goto finally;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000737 }
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000738
Martin Panter61d6e4a2015-11-07 02:56:11 +0000739 str = source_as_string(source, "compile", "string, bytes or AST", &cf, &source_copy);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000740 if (str == NULL)
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000741 goto error;
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000742
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000743 result = Py_CompileStringObject(str, filename, start[compile_mode], &cf, optimize);
Martin Panter61d6e4a2015-11-07 02:56:11 +0000744 Py_XDECREF(source_copy);
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000745 goto finally;
746
747error:
748 result = NULL;
749finally:
Victor Stinner14e461d2013-08-26 22:28:21 +0200750 Py_DECREF(filename);
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000751 return result;
Guido van Rossum5b722181993-03-30 17:46:03 +0000752}
753
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000754/* AC: cannot convert yet, as needs PEP 457 group support in inspect */
Guido van Rossum79f25d91997-04-29 20:08:16 +0000755static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000756builtin_dir(PyObject *self, PyObject *args)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000757{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000758 PyObject *arg = NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000759
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000760 if (!PyArg_UnpackTuple(args, "dir", 0, 1, &arg))
761 return NULL;
762 return PyObject_Dir(arg);
Guido van Rossum3f5da241990-12-20 15:06:42 +0000763}
764
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000765PyDoc_STRVAR(dir_doc,
Tim Peters5d2b77c2001-09-03 05:47:38 +0000766"dir([object]) -> list of strings\n"
767"\n"
Georg Brandle32b4222007-03-10 22:13:27 +0000768"If called without an argument, return the names in the current scope.\n"
769"Else, return an alphabetized list of names comprising (some of) the attributes\n"
770"of the given object, and of attributes reachable from it.\n"
771"If the object supplies a method named __dir__, it will be used; otherwise\n"
772"the default dir() logic is used and returns:\n"
773" for a module object: the module's attributes.\n"
774" for a class object: its attributes, and recursively the attributes\n"
775" of its bases.\n"
Guido van Rossumd8faa362007-04-27 19:54:29 +0000776" for any other object: its attributes, its class's attributes, and\n"
Georg Brandle32b4222007-03-10 22:13:27 +0000777" recursively the attributes of its class's base classes.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000778
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000779/*[clinic input]
780divmod as builtin_divmod
Guido van Rossum6a00cd81995-01-07 12:39:01 +0000781
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300782 x: object
783 y: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000784 /
785
Zachary Ware7f227d92016-04-28 14:39:50 -0500786Return the tuple (x//y, x%y). Invariant: div*y + mod == x.
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000787[clinic start generated code]*/
788
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000789static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300790builtin_divmod_impl(PyObject *module, PyObject *x, PyObject *y)
791/*[clinic end generated code: output=b06d8a5f6e0c745e input=175ad9c84ff41a85]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000792{
793 return PyNumber_Divmod(x, y);
794}
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000795
796
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000797/*[clinic input]
798eval as builtin_eval
799
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300800 source: object
801 globals: object = None
802 locals: object = None
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000803 /
804
805Evaluate the given source in the context of globals and locals.
806
807The source may be a string representing a Python expression
808or a code object as returned by compile().
809The globals must be a dictionary and locals can be any mapping,
810defaulting to the current globals and locals.
811If only globals is given, locals defaults to it.
812[clinic start generated code]*/
813
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000814static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300815builtin_eval_impl(PyObject *module, PyObject *source, PyObject *globals,
Larry Hastings89964c42015-04-14 18:07:59 -0400816 PyObject *locals)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300817/*[clinic end generated code: output=0a0824aa70093116 input=11ee718a8640e527]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000818{
Martin Panter61d6e4a2015-11-07 02:56:11 +0000819 PyObject *result, *source_copy;
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +0200820 const char *str;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000821 PyCompilerFlags cf;
Guido van Rossum590baa41993-11-30 13:40:46 +0000822
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000823 if (locals != Py_None && !PyMapping_Check(locals)) {
824 PyErr_SetString(PyExc_TypeError, "locals must be a mapping");
825 return NULL;
826 }
827 if (globals != Py_None && !PyDict_Check(globals)) {
828 PyErr_SetString(PyExc_TypeError, PyMapping_Check(globals) ?
829 "globals must be a real dict; try eval(expr, {}, mapping)"
830 : "globals must be a dict");
831 return NULL;
832 }
833 if (globals == Py_None) {
834 globals = PyEval_GetGlobals();
Victor Stinner41bb43a2013-10-29 01:19:37 +0100835 if (locals == Py_None) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000836 locals = PyEval_GetLocals();
Victor Stinner41bb43a2013-10-29 01:19:37 +0100837 if (locals == NULL)
838 return NULL;
839 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000840 }
841 else if (locals == Py_None)
842 locals = globals;
Tim Peters9fa96be2001-08-17 23:04:59 +0000843
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000844 if (globals == NULL || locals == NULL) {
845 PyErr_SetString(PyExc_TypeError,
846 "eval must be given globals and locals "
847 "when called without a frame");
848 return NULL;
849 }
Georg Brandl77c85e62005-09-15 10:46:13 +0000850
Victor Stinnerb44562b2013-11-06 19:03:11 +0100851 if (_PyDict_GetItemId(globals, &PyId___builtins__) == NULL) {
852 if (_PyDict_SetItemId(globals, &PyId___builtins__,
853 PyEval_GetBuiltins()) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000854 return NULL;
855 }
Tim Peters9fa96be2001-08-17 23:04:59 +0000856
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000857 if (PyCode_Check(source)) {
858 if (PyCode_GetNumFree((PyCodeObject *)source) > 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000859 PyErr_SetString(PyExc_TypeError,
860 "code object passed to eval() may not contain free variables");
861 return NULL;
862 }
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000863 return PyEval_EvalCode(source, globals, locals);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000864 }
Tim Peters9fa96be2001-08-17 23:04:59 +0000865
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000866 cf.cf_flags = PyCF_SOURCE_IS_UTF8;
Martin Panter61d6e4a2015-11-07 02:56:11 +0000867 str = source_as_string(source, "eval", "string, bytes or code", &cf, &source_copy);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000868 if (str == NULL)
869 return NULL;
Just van Rossum3aaf42c2003-02-10 08:21:10 +0000870
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000871 while (*str == ' ' || *str == '\t')
872 str++;
Tim Peters9fa96be2001-08-17 23:04:59 +0000873
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000874 (void)PyEval_MergeCompilerFlags(&cf);
875 result = PyRun_StringFlags(str, Py_eval_input, globals, locals, &cf);
Martin Panter61d6e4a2015-11-07 02:56:11 +0000876 Py_XDECREF(source_copy);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000877 return result;
Guido van Rossum3f5da241990-12-20 15:06:42 +0000878}
879
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000880/*[clinic input]
881exec as builtin_exec
882
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300883 source: object
884 globals: object = None
885 locals: object = None
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000886 /
887
888Execute the given source in the context of globals and locals.
889
890The source may be a string representing one or more Python statements
891or a code object as returned by compile().
892The globals must be a dictionary and locals can be any mapping,
893defaulting to the current globals and locals.
894If only globals is given, locals defaults to it.
895[clinic start generated code]*/
896
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000897static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300898builtin_exec_impl(PyObject *module, PyObject *source, PyObject *globals,
Larry Hastings89964c42015-04-14 18:07:59 -0400899 PyObject *locals)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300900/*[clinic end generated code: output=3c90efc6ab68ef5d input=01ca3e1c01692829]*/
Georg Brandl7cae87c2006-09-06 06:51:57 +0000901{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000902 PyObject *v;
Georg Brandl2cabc562008-08-28 07:57:16 +0000903
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000904 if (globals == Py_None) {
905 globals = PyEval_GetGlobals();
906 if (locals == Py_None) {
907 locals = PyEval_GetLocals();
Victor Stinner41bb43a2013-10-29 01:19:37 +0100908 if (locals == NULL)
909 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000910 }
911 if (!globals || !locals) {
912 PyErr_SetString(PyExc_SystemError,
913 "globals and locals cannot be NULL");
914 return NULL;
915 }
916 }
917 else if (locals == Py_None)
918 locals = globals;
Georg Brandl7cae87c2006-09-06 06:51:57 +0000919
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000920 if (!PyDict_Check(globals)) {
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000921 PyErr_Format(PyExc_TypeError, "exec() globals must be a dict, not %.100s",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000922 globals->ob_type->tp_name);
923 return NULL;
924 }
925 if (!PyMapping_Check(locals)) {
926 PyErr_Format(PyExc_TypeError,
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000927 "locals must be a mapping or None, not %.100s",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000928 locals->ob_type->tp_name);
929 return NULL;
930 }
Victor Stinnerb44562b2013-11-06 19:03:11 +0100931 if (_PyDict_GetItemId(globals, &PyId___builtins__) == NULL) {
932 if (_PyDict_SetItemId(globals, &PyId___builtins__,
933 PyEval_GetBuiltins()) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000934 return NULL;
935 }
936
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000937 if (PyCode_Check(source)) {
938 if (PyCode_GetNumFree((PyCodeObject *)source) > 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000939 PyErr_SetString(PyExc_TypeError,
940 "code object passed to exec() may not "
941 "contain free variables");
942 return NULL;
943 }
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000944 v = PyEval_EvalCode(source, globals, locals);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000945 }
946 else {
Martin Panter61d6e4a2015-11-07 02:56:11 +0000947 PyObject *source_copy;
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +0200948 const char *str;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000949 PyCompilerFlags cf;
950 cf.cf_flags = PyCF_SOURCE_IS_UTF8;
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000951 str = source_as_string(source, "exec",
Martin Panter61d6e4a2015-11-07 02:56:11 +0000952 "string, bytes or code", &cf,
953 &source_copy);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000954 if (str == NULL)
955 return NULL;
956 if (PyEval_MergeCompilerFlags(&cf))
957 v = PyRun_StringFlags(str, Py_file_input, globals,
958 locals, &cf);
959 else
960 v = PyRun_String(str, Py_file_input, globals, locals);
Martin Panter61d6e4a2015-11-07 02:56:11 +0000961 Py_XDECREF(source_copy);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000962 }
963 if (v == NULL)
964 return NULL;
965 Py_DECREF(v);
966 Py_RETURN_NONE;
Georg Brandl7cae87c2006-09-06 06:51:57 +0000967}
968
Georg Brandl7cae87c2006-09-06 06:51:57 +0000969
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000970/* AC: cannot convert yet, as needs PEP 457 group support in inspect */
Guido van Rossum79f25d91997-04-29 20:08:16 +0000971static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000972builtin_getattr(PyObject *self, PyObject *args)
Guido van Rossum33894be1992-01-27 16:53:09 +0000973{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000974 PyObject *v, *result, *dflt = NULL;
975 PyObject *name;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000976
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000977 if (!PyArg_UnpackTuple(args, "getattr", 2, 3, &v, &name, &dflt))
978 return NULL;
Martin v. Löwis5b222132007-06-10 09:51:05 +0000979
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000980 if (!PyUnicode_Check(name)) {
981 PyErr_SetString(PyExc_TypeError,
982 "getattr(): attribute name must be string");
983 return NULL;
984 }
985 result = PyObject_GetAttr(v, name);
986 if (result == NULL && dflt != NULL &&
987 PyErr_ExceptionMatches(PyExc_AttributeError))
988 {
989 PyErr_Clear();
990 Py_INCREF(dflt);
991 result = dflt;
992 }
993 return result;
Guido van Rossum9bfef441993-03-29 10:43:31 +0000994}
995
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000996PyDoc_STRVAR(getattr_doc,
Guido van Rossum950ff291998-06-29 13:38:57 +0000997"getattr(object, name[, default]) -> value\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000998\n\
Guido van Rossum950ff291998-06-29 13:38:57 +0000999Get a named attribute from an object; getattr(x, 'y') is equivalent to x.y.\n\
1000When a default argument is given, it is returned when the attribute doesn't\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001001exist; without it, an exception is raised in that case.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001002
1003
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001004/*[clinic input]
1005globals as builtin_globals
1006
1007Return the dictionary containing the current scope's global variables.
1008
1009NOTE: Updates to this dictionary *will* affect name lookups in the current
1010global scope and vice-versa.
1011[clinic start generated code]*/
1012
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001013static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001014builtin_globals_impl(PyObject *module)
1015/*[clinic end generated code: output=e5dd1527067b94d2 input=9327576f92bb48ba]*/
Guido van Rossum872537c1995-07-07 22:43:42 +00001016{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001017 PyObject *d;
Guido van Rossum872537c1995-07-07 22:43:42 +00001018
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001019 d = PyEval_GetGlobals();
1020 Py_XINCREF(d);
1021 return d;
Guido van Rossum872537c1995-07-07 22:43:42 +00001022}
1023
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001024
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001025/*[clinic input]
1026hasattr as builtin_hasattr
1027
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001028 obj: object
1029 name: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001030 /
1031
1032Return whether the object has an attribute with the given name.
1033
1034This is done by calling getattr(obj, name) and catching AttributeError.
1035[clinic start generated code]*/
1036
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001037static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001038builtin_hasattr_impl(PyObject *module, PyObject *obj, PyObject *name)
1039/*[clinic end generated code: output=a7aff2090a4151e5 input=0faec9787d979542]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001040{
1041 PyObject *v;
1042
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001043 if (!PyUnicode_Check(name)) {
1044 PyErr_SetString(PyExc_TypeError,
1045 "hasattr(): attribute name must be string");
1046 return NULL;
1047 }
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001048 v = PyObject_GetAttr(obj, name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001049 if (v == NULL) {
Benjamin Peterson17689992010-08-24 03:26:23 +00001050 if (PyErr_ExceptionMatches(PyExc_AttributeError)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001051 PyErr_Clear();
Benjamin Peterson17689992010-08-24 03:26:23 +00001052 Py_RETURN_FALSE;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001053 }
Benjamin Peterson17689992010-08-24 03:26:23 +00001054 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001055 }
1056 Py_DECREF(v);
Benjamin Peterson17689992010-08-24 03:26:23 +00001057 Py_RETURN_TRUE;
Guido van Rossum33894be1992-01-27 16:53:09 +00001058}
1059
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001060
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001061/* AC: gdb's integration with CPython relies on builtin_id having
1062 * the *exact* parameter names of "self" and "v", so we ensure we
1063 * preserve those name rather than using the AC defaults.
1064 */
1065/*[clinic input]
1066id as builtin_id
1067
Serhiy Storchaka24182a32016-05-05 16:21:35 +03001068 self: self(type="PyModuleDef *")
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001069 obj as v: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001070 /
1071
1072Return the identity of an object.
1073
1074This is guaranteed to be unique among simultaneously existing objects.
1075(CPython uses the object's memory address.)
1076[clinic start generated code]*/
1077
Guido van Rossum79f25d91997-04-29 20:08:16 +00001078static PyObject *
Serhiy Storchaka24182a32016-05-05 16:21:35 +03001079builtin_id(PyModuleDef *self, PyObject *v)
1080/*[clinic end generated code: output=0aa640785f697f65 input=5a534136419631f4]*/
Guido van Rossum5b722181993-03-30 17:46:03 +00001081{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001082 return PyLong_FromVoidPtr(v);
Guido van Rossum5b722181993-03-30 17:46:03 +00001083}
1084
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001085
Raymond Hettingera6c60372008-03-13 01:26:19 +00001086/* map object ************************************************************/
1087
1088typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001089 PyObject_HEAD
1090 PyObject *iters;
1091 PyObject *func;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001092} mapobject;
1093
Guido van Rossum79f25d91997-04-29 20:08:16 +00001094static PyObject *
Raymond Hettingera6c60372008-03-13 01:26:19 +00001095map_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
Guido van Rossum12d12c51993-10-26 17:58:25 +00001096{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001097 PyObject *it, *iters, *func;
1098 mapobject *lz;
1099 Py_ssize_t numargs, i;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001100
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001101 if (type == &PyMap_Type && !_PyArg_NoKeywords("map()", kwds))
1102 return NULL;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001103
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001104 numargs = PyTuple_Size(args);
1105 if (numargs < 2) {
1106 PyErr_SetString(PyExc_TypeError,
1107 "map() must have at least two arguments.");
1108 return NULL;
1109 }
Raymond Hettingera6c60372008-03-13 01:26:19 +00001110
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001111 iters = PyTuple_New(numargs-1);
1112 if (iters == NULL)
1113 return NULL;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001114
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001115 for (i=1 ; i<numargs ; i++) {
1116 /* Get iterator. */
1117 it = PyObject_GetIter(PyTuple_GET_ITEM(args, i));
1118 if (it == NULL) {
1119 Py_DECREF(iters);
1120 return NULL;
1121 }
1122 PyTuple_SET_ITEM(iters, i-1, it);
1123 }
Raymond Hettingera6c60372008-03-13 01:26:19 +00001124
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001125 /* create mapobject structure */
1126 lz = (mapobject *)type->tp_alloc(type, 0);
1127 if (lz == NULL) {
1128 Py_DECREF(iters);
1129 return NULL;
1130 }
1131 lz->iters = iters;
1132 func = PyTuple_GET_ITEM(args, 0);
1133 Py_INCREF(func);
1134 lz->func = func;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001135
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001136 return (PyObject *)lz;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001137}
1138
1139static void
1140map_dealloc(mapobject *lz)
1141{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001142 PyObject_GC_UnTrack(lz);
1143 Py_XDECREF(lz->iters);
1144 Py_XDECREF(lz->func);
1145 Py_TYPE(lz)->tp_free(lz);
Raymond Hettingera6c60372008-03-13 01:26:19 +00001146}
1147
1148static int
1149map_traverse(mapobject *lz, visitproc visit, void *arg)
1150{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001151 Py_VISIT(lz->iters);
1152 Py_VISIT(lz->func);
1153 return 0;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001154}
1155
1156static PyObject *
1157map_next(mapobject *lz)
1158{
Victor Stinnerf0cba672016-08-24 00:54:47 +02001159 PyObject *val;
1160 PyObject *argtuple;
1161 PyObject *result;
1162 Py_ssize_t numargs, i;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001163
Victor Stinnerf0cba672016-08-24 00:54:47 +02001164 numargs = PyTuple_GET_SIZE(lz->iters);
1165 argtuple = PyTuple_New(numargs);
1166 if (argtuple == NULL)
1167 return NULL;
1168
1169 for (i=0 ; i<numargs ; i++) {
1170 PyObject *it = PyTuple_GET_ITEM(lz->iters, i);
1171 val = Py_TYPE(it)->tp_iternext(it);
1172 if (val == NULL) {
1173 Py_DECREF(argtuple);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001174 return NULL;
1175 }
Victor Stinnerf0cba672016-08-24 00:54:47 +02001176 PyTuple_SET_ITEM(argtuple, i, val);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001177 }
Victor Stinnerf0cba672016-08-24 00:54:47 +02001178 result = PyObject_Call(lz->func, argtuple, NULL);
1179 Py_DECREF(argtuple);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001180 return result;
Guido van Rossum12d12c51993-10-26 17:58:25 +00001181}
1182
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001183static PyObject *
1184map_reduce(mapobject *lz)
1185{
1186 Py_ssize_t numargs = PyTuple_GET_SIZE(lz->iters);
1187 PyObject *args = PyTuple_New(numargs+1);
1188 Py_ssize_t i;
1189 if (args == NULL)
1190 return NULL;
1191 Py_INCREF(lz->func);
1192 PyTuple_SET_ITEM(args, 0, lz->func);
1193 for (i = 0; i<numargs; i++){
1194 PyObject *it = PyTuple_GET_ITEM(lz->iters, i);
1195 Py_INCREF(it);
1196 PyTuple_SET_ITEM(args, i+1, it);
1197 }
1198
1199 return Py_BuildValue("ON", Py_TYPE(lz), args);
1200}
1201
1202static PyMethodDef map_methods[] = {
1203 {"__reduce__", (PyCFunction)map_reduce, METH_NOARGS, reduce_doc},
1204 {NULL, NULL} /* sentinel */
1205};
1206
1207
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001208PyDoc_STRVAR(map_doc,
Raymond Hettingera6c60372008-03-13 01:26:19 +00001209"map(func, *iterables) --> map object\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001210\n\
Raymond Hettingera6c60372008-03-13 01:26:19 +00001211Make an iterator that computes the function using arguments from\n\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001212each of the iterables. Stops when the shortest iterable is exhausted.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001213
Raymond Hettingera6c60372008-03-13 01:26:19 +00001214PyTypeObject PyMap_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001215 PyVarObject_HEAD_INIT(&PyType_Type, 0)
1216 "map", /* tp_name */
1217 sizeof(mapobject), /* tp_basicsize */
1218 0, /* tp_itemsize */
1219 /* methods */
1220 (destructor)map_dealloc, /* tp_dealloc */
1221 0, /* tp_print */
1222 0, /* tp_getattr */
1223 0, /* tp_setattr */
1224 0, /* tp_reserved */
1225 0, /* tp_repr */
1226 0, /* tp_as_number */
1227 0, /* tp_as_sequence */
1228 0, /* tp_as_mapping */
1229 0, /* tp_hash */
1230 0, /* tp_call */
1231 0, /* tp_str */
1232 PyObject_GenericGetAttr, /* tp_getattro */
1233 0, /* tp_setattro */
1234 0, /* tp_as_buffer */
1235 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
1236 Py_TPFLAGS_BASETYPE, /* tp_flags */
1237 map_doc, /* tp_doc */
1238 (traverseproc)map_traverse, /* tp_traverse */
1239 0, /* tp_clear */
1240 0, /* tp_richcompare */
1241 0, /* tp_weaklistoffset */
1242 PyObject_SelfIter, /* tp_iter */
1243 (iternextfunc)map_next, /* tp_iternext */
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001244 map_methods, /* tp_methods */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001245 0, /* tp_members */
1246 0, /* tp_getset */
1247 0, /* tp_base */
1248 0, /* tp_dict */
1249 0, /* tp_descr_get */
1250 0, /* tp_descr_set */
1251 0, /* tp_dictoffset */
1252 0, /* tp_init */
1253 PyType_GenericAlloc, /* tp_alloc */
1254 map_new, /* tp_new */
1255 PyObject_GC_Del, /* tp_free */
Raymond Hettingera6c60372008-03-13 01:26:19 +00001256};
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001257
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001258
1259/* AC: cannot convert yet, as needs PEP 457 group support in inspect */
Guido van Rossum79f25d91997-04-29 20:08:16 +00001260static PyObject *
Georg Brandla18af4e2007-04-21 15:47:16 +00001261builtin_next(PyObject *self, PyObject *args)
1262{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001263 PyObject *it, *res;
1264 PyObject *def = NULL;
Georg Brandla18af4e2007-04-21 15:47:16 +00001265
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001266 if (!PyArg_UnpackTuple(args, "next", 1, 2, &it, &def))
1267 return NULL;
1268 if (!PyIter_Check(it)) {
1269 PyErr_Format(PyExc_TypeError,
Philip Jenvey50add042011-11-06 16:37:52 -08001270 "'%.200s' object is not an iterator",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001271 it->ob_type->tp_name);
1272 return NULL;
1273 }
1274
1275 res = (*it->ob_type->tp_iternext)(it);
1276 if (res != NULL) {
1277 return res;
1278 } else if (def != NULL) {
1279 if (PyErr_Occurred()) {
1280 if(!PyErr_ExceptionMatches(PyExc_StopIteration))
1281 return NULL;
1282 PyErr_Clear();
1283 }
1284 Py_INCREF(def);
1285 return def;
1286 } else if (PyErr_Occurred()) {
1287 return NULL;
1288 } else {
1289 PyErr_SetNone(PyExc_StopIteration);
1290 return NULL;
1291 }
Georg Brandla18af4e2007-04-21 15:47:16 +00001292}
1293
1294PyDoc_STRVAR(next_doc,
1295"next(iterator[, default])\n\
1296\n\
1297Return the next item from the iterator. If default is given and the iterator\n\
1298is exhausted, it is returned instead of raising StopIteration.");
1299
1300
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001301/*[clinic input]
1302setattr as builtin_setattr
1303
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001304 obj: object
1305 name: object
1306 value: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001307 /
1308
1309Sets the named attribute on the given object to the specified value.
1310
1311setattr(x, 'y', v) is equivalent to ``x.y = v''
1312[clinic start generated code]*/
1313
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001314static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001315builtin_setattr_impl(PyObject *module, PyObject *obj, PyObject *name,
Larry Hastings89964c42015-04-14 18:07:59 -04001316 PyObject *value)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001317/*[clinic end generated code: output=dc2ce1d1add9acb4 input=bd2b7ca6875a1899]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001318{
1319 if (PyObject_SetAttr(obj, name, value) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001320 return NULL;
1321 Py_INCREF(Py_None);
1322 return Py_None;
Guido van Rossum33894be1992-01-27 16:53:09 +00001323}
1324
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001325
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001326/*[clinic input]
1327delattr as builtin_delattr
1328
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001329 obj: object
1330 name: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001331 /
1332
1333Deletes the named attribute from the given object.
1334
1335delattr(x, 'y') is equivalent to ``del x.y''
1336[clinic start generated code]*/
1337
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001338static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001339builtin_delattr_impl(PyObject *module, PyObject *obj, PyObject *name)
1340/*[clinic end generated code: output=85134bc58dff79fa input=db16685d6b4b9410]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001341{
1342 if (PyObject_SetAttr(obj, name, (PyObject *)NULL) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001343 return NULL;
1344 Py_INCREF(Py_None);
1345 return Py_None;
Guido van Rossum14144fc1994-08-29 12:53:40 +00001346}
1347
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001348
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001349/*[clinic input]
1350hash as builtin_hash
1351
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001352 obj: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001353 /
1354
1355Return the hash value for the given object.
1356
1357Two objects that compare equal must also have the same hash value, but the
1358reverse is not necessarily true.
1359[clinic start generated code]*/
1360
Guido van Rossum79f25d91997-04-29 20:08:16 +00001361static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001362builtin_hash(PyObject *module, PyObject *obj)
1363/*[clinic end generated code: output=237668e9d7688db7 input=58c48be822bf9c54]*/
Guido van Rossum9bfef441993-03-29 10:43:31 +00001364{
Benjamin Peterson8f67d082010-10-17 20:54:53 +00001365 Py_hash_t x;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001366
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001367 x = PyObject_Hash(obj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001368 if (x == -1)
1369 return NULL;
Benjamin Peterson8f67d082010-10-17 20:54:53 +00001370 return PyLong_FromSsize_t(x);
Guido van Rossum9bfef441993-03-29 10:43:31 +00001371}
1372
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001373
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001374/*[clinic input]
1375hex as builtin_hex
1376
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001377 number: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001378 /
1379
1380Return the hexadecimal representation of an integer.
1381
1382 >>> hex(12648430)
1383 '0xc0ffee'
1384[clinic start generated code]*/
1385
Guido van Rossum79f25d91997-04-29 20:08:16 +00001386static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001387builtin_hex(PyObject *module, PyObject *number)
1388/*[clinic end generated code: output=e46b612169099408 input=e645aff5fc7d540e]*/
Guido van Rossum006bcd41991-10-24 14:54:44 +00001389{
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001390 return PyNumber_ToBase(number, 16);
Guido van Rossum006bcd41991-10-24 14:54:44 +00001391}
1392
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001393
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001394/* AC: cannot convert yet, as needs PEP 457 group support in inspect */
Guido van Rossum79f25d91997-04-29 20:08:16 +00001395static PyObject *
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001396builtin_iter(PyObject *self, PyObject *args)
1397{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001398 PyObject *v, *w = NULL;
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001399
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001400 if (!PyArg_UnpackTuple(args, "iter", 1, 2, &v, &w))
1401 return NULL;
1402 if (w == NULL)
1403 return PyObject_GetIter(v);
1404 if (!PyCallable_Check(v)) {
1405 PyErr_SetString(PyExc_TypeError,
1406 "iter(v, w): v must be callable");
1407 return NULL;
1408 }
1409 return PyCallIter_New(v, w);
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001410}
1411
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001412PyDoc_STRVAR(iter_doc,
Georg Brandld11ae5d2008-05-16 13:27:32 +00001413"iter(iterable) -> iterator\n\
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001414iter(callable, sentinel) -> iterator\n\
1415\n\
1416Get an iterator from an object. In the first form, the argument must\n\
1417supply its own iterator, or be a sequence.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001418In the second form, the callable is called until it returns the sentinel.");
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001419
1420
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001421/*[clinic input]
1422len as builtin_len
1423
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001424 obj: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001425 /
1426
1427Return the number of items in a container.
1428[clinic start generated code]*/
1429
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001430static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001431builtin_len(PyObject *module, PyObject *obj)
1432/*[clinic end generated code: output=fa7a270d314dfb6c input=bc55598da9e9c9b5]*/
Guido van Rossum3f5da241990-12-20 15:06:42 +00001433{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001434 Py_ssize_t res;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001435
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001436 res = PyObject_Size(obj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001437 if (res < 0 && PyErr_Occurred())
1438 return NULL;
1439 return PyLong_FromSsize_t(res);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001440}
1441
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001442
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001443/*[clinic input]
1444locals as builtin_locals
1445
1446Return a dictionary containing the current scope's local variables.
1447
1448NOTE: Whether or not updates to this dictionary will affect name lookups in
1449the local scope and vice-versa is *implementation dependent* and not
1450covered by any backwards compatibility guarantees.
1451[clinic start generated code]*/
1452
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001453static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001454builtin_locals_impl(PyObject *module)
1455/*[clinic end generated code: output=b46c94015ce11448 input=7874018d478d5c4b]*/
Guido van Rossum872537c1995-07-07 22:43:42 +00001456{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001457 PyObject *d;
Guido van Rossum872537c1995-07-07 22:43:42 +00001458
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001459 d = PyEval_GetLocals();
1460 Py_XINCREF(d);
1461 return d;
Guido van Rossum872537c1995-07-07 22:43:42 +00001462}
1463
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001464
Guido van Rossum79f25d91997-04-29 20:08:16 +00001465static PyObject *
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001466min_max(PyObject *args, PyObject *kwds, int op)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001467{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001468 PyObject *v, *it, *item, *val, *maxitem, *maxval, *keyfunc=NULL;
Raymond Hettinger4d6018f2013-06-24 22:43:02 -07001469 PyObject *emptytuple, *defaultval = NULL;
1470 static char *kwlist[] = {"key", "default", NULL};
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001471 const char *name = op == Py_LT ? "min" : "max";
Raymond Hettinger4d6018f2013-06-24 22:43:02 -07001472 const int positional = PyTuple_Size(args) > 1;
1473 int ret;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001474
Raymond Hettinger4d6018f2013-06-24 22:43:02 -07001475 if (positional)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001476 v = args;
Serhiy Storchakac6792272013-10-19 21:03:34 +03001477 else if (!PyArg_UnpackTuple(args, name, 1, 1, &v))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001478 return NULL;
Tim Peters67d687a2002-04-29 21:27:32 +00001479
Raymond Hettinger4d6018f2013-06-24 22:43:02 -07001480 emptytuple = PyTuple_New(0);
1481 if (emptytuple == NULL)
1482 return NULL;
1483 ret = PyArg_ParseTupleAndKeywords(emptytuple, kwds, "|$OO", kwlist,
1484 &keyfunc, &defaultval);
1485 Py_DECREF(emptytuple);
1486 if (!ret)
1487 return NULL;
1488
1489 if (positional && defaultval != NULL) {
1490 PyErr_Format(PyExc_TypeError,
1491 "Cannot specify a default for %s() with multiple "
1492 "positional arguments", name);
1493 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001494 }
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001495
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001496 it = PyObject_GetIter(v);
1497 if (it == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001498 return NULL;
1499 }
Tim Petersc3074532001-05-03 07:00:32 +00001500
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001501 maxitem = NULL; /* the result */
1502 maxval = NULL; /* the value associated with the result */
1503 while (( item = PyIter_Next(it) )) {
1504 /* get the value from the key function */
1505 if (keyfunc != NULL) {
1506 val = PyObject_CallFunctionObjArgs(keyfunc, item, NULL);
1507 if (val == NULL)
1508 goto Fail_it_item;
1509 }
1510 /* no key function; the value is the item */
1511 else {
1512 val = item;
1513 Py_INCREF(val);
1514 }
Tim Petersc3074532001-05-03 07:00:32 +00001515
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001516 /* maximum value and item are unset; set them */
1517 if (maxval == NULL) {
1518 maxitem = item;
1519 maxval = val;
1520 }
1521 /* maximum value and item are set; update them as necessary */
1522 else {
1523 int cmp = PyObject_RichCompareBool(val, maxval, op);
1524 if (cmp < 0)
1525 goto Fail_it_item_and_val;
1526 else if (cmp > 0) {
1527 Py_DECREF(maxval);
1528 Py_DECREF(maxitem);
1529 maxval = val;
1530 maxitem = item;
1531 }
1532 else {
1533 Py_DECREF(item);
1534 Py_DECREF(val);
1535 }
1536 }
1537 }
1538 if (PyErr_Occurred())
1539 goto Fail_it;
1540 if (maxval == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001541 assert(maxitem == NULL);
Raymond Hettinger4d6018f2013-06-24 22:43:02 -07001542 if (defaultval != NULL) {
1543 Py_INCREF(defaultval);
1544 maxitem = defaultval;
1545 } else {
1546 PyErr_Format(PyExc_ValueError,
1547 "%s() arg is an empty sequence", name);
1548 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001549 }
1550 else
1551 Py_DECREF(maxval);
1552 Py_DECREF(it);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001553 return maxitem;
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001554
1555Fail_it_item_and_val:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001556 Py_DECREF(val);
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001557Fail_it_item:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001558 Py_DECREF(item);
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001559Fail_it:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001560 Py_XDECREF(maxval);
1561 Py_XDECREF(maxitem);
1562 Py_DECREF(it);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001563 return NULL;
Guido van Rossum3f5da241990-12-20 15:06:42 +00001564}
1565
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001566/* AC: cannot convert yet, waiting for *args support */
Guido van Rossum79f25d91997-04-29 20:08:16 +00001567static PyObject *
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001568builtin_min(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001569{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001570 return min_max(args, kwds, Py_LT);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001571}
1572
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001573PyDoc_STRVAR(min_doc,
Raymond Hettinger2a545822014-05-19 22:20:52 +01001574"min(iterable, *[, default=obj, key=func]) -> value\n\
1575min(arg1, arg2, *args, *[, key=func]) -> value\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001576\n\
Raymond Hettinger2a545822014-05-19 22:20:52 +01001577With a single iterable argument, return its smallest item. The\n\
1578default keyword-only argument specifies an object to return if\n\
1579the provided iterable is empty.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001580With two or more arguments, return the smallest argument.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001581
1582
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001583/* AC: cannot convert yet, waiting for *args support */
Guido van Rossum79f25d91997-04-29 20:08:16 +00001584static PyObject *
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001585builtin_max(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001586{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001587 return min_max(args, kwds, Py_GT);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001588}
1589
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001590PyDoc_STRVAR(max_doc,
Raymond Hettinger2a545822014-05-19 22:20:52 +01001591"max(iterable, *[, default=obj, key=func]) -> value\n\
1592max(arg1, arg2, *args, *[, key=func]) -> value\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001593\n\
Raymond Hettinger2a545822014-05-19 22:20:52 +01001594With a single iterable argument, return its biggest item. The\n\
1595default keyword-only argument specifies an object to return if\n\
1596the provided iterable is empty.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001597With two or more arguments, return the largest argument.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001598
1599
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001600/*[clinic input]
1601oct as builtin_oct
1602
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001603 number: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001604 /
1605
1606Return the octal representation of an integer.
1607
1608 >>> oct(342391)
1609 '0o1234567'
1610[clinic start generated code]*/
1611
Guido van Rossum79f25d91997-04-29 20:08:16 +00001612static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001613builtin_oct(PyObject *module, PyObject *number)
1614/*[clinic end generated code: output=40a34656b6875352 input=ad6b274af4016c72]*/
Guido van Rossum006bcd41991-10-24 14:54:44 +00001615{
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001616 return PyNumber_ToBase(number, 8);
Guido van Rossum006bcd41991-10-24 14:54:44 +00001617}
1618
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001619
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001620/*[clinic input]
1621ord as builtin_ord
1622
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001623 c: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001624 /
1625
1626Return the Unicode code point for a one-character string.
1627[clinic start generated code]*/
1628
Guido van Rossum79f25d91997-04-29 20:08:16 +00001629static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001630builtin_ord(PyObject *module, PyObject *c)
1631/*[clinic end generated code: output=4fa5e87a323bae71 input=3064e5d6203ad012]*/
Guido van Rossum3f5da241990-12-20 15:06:42 +00001632{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001633 long ord;
1634 Py_ssize_t size;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001635
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001636 if (PyBytes_Check(c)) {
1637 size = PyBytes_GET_SIZE(c);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001638 if (size == 1) {
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001639 ord = (long)((unsigned char)*PyBytes_AS_STRING(c));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001640 return PyLong_FromLong(ord);
1641 }
1642 }
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001643 else if (PyUnicode_Check(c)) {
1644 if (PyUnicode_READY(c) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001645 return NULL;
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001646 size = PyUnicode_GET_LENGTH(c);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001647 if (size == 1) {
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001648 ord = (long)PyUnicode_READ_CHAR(c, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001649 return PyLong_FromLong(ord);
1650 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001651 }
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001652 else if (PyByteArray_Check(c)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001653 /* XXX Hopefully this is temporary */
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001654 size = PyByteArray_GET_SIZE(c);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001655 if (size == 1) {
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001656 ord = (long)((unsigned char)*PyByteArray_AS_STRING(c));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001657 return PyLong_FromLong(ord);
1658 }
1659 }
1660 else {
1661 PyErr_Format(PyExc_TypeError,
1662 "ord() expected string of length 1, but " \
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001663 "%.200s found", c->ob_type->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001664 return NULL;
1665 }
Guido van Rossum09095f32000-03-10 23:00:52 +00001666
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001667 PyErr_Format(PyExc_TypeError,
1668 "ord() expected a character, "
1669 "but string of length %zd found",
1670 size);
1671 return NULL;
Guido van Rossum3f5da241990-12-20 15:06:42 +00001672}
1673
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001674
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001675/*[clinic input]
1676pow as builtin_pow
1677
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001678 x: object
1679 y: object
1680 z: object = None
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001681 /
1682
1683Equivalent to x**y (with two arguments) or x**y % z (with three arguments)
1684
1685Some types, such as ints, are able to use a more efficient algorithm when
1686invoked using the three argument form.
1687[clinic start generated code]*/
1688
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001689static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001690builtin_pow_impl(PyObject *module, PyObject *x, PyObject *y, PyObject *z)
1691/*[clinic end generated code: output=50a14d5d130d404b input=653d57d38d41fc07]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001692{
1693 return PyNumber_Power(x, y, z);
1694}
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001695
1696
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001697/* AC: cannot convert yet, waiting for *args support */
Guido van Rossum34343512006-11-30 22:13:52 +00001698static PyObject *
1699builtin_print(PyObject *self, PyObject *args, PyObject *kwds)
1700{
Georg Brandlbc3b6822012-01-13 19:41:25 +01001701 static char *kwlist[] = {"sep", "end", "file", "flush", 0};
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001702 static PyObject *dummy_args;
Georg Brandlbc3b6822012-01-13 19:41:25 +01001703 PyObject *sep = NULL, *end = NULL, *file = NULL, *flush = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001704 int i, err;
Guido van Rossum34343512006-11-30 22:13:52 +00001705
Benjamin Peterson00102562012-01-11 21:00:16 -05001706 if (dummy_args == NULL && !(dummy_args = PyTuple_New(0)))
Georg Brandlbc3b6822012-01-13 19:41:25 +01001707 return NULL;
1708 if (!PyArg_ParseTupleAndKeywords(dummy_args, kwds, "|OOOO:print",
1709 kwlist, &sep, &end, &file, &flush))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001710 return NULL;
1711 if (file == NULL || file == Py_None) {
Victor Stinnerbd303c12013-11-07 23:07:29 +01001712 file = _PySys_GetObjectId(&PyId_stdout);
Victor Stinner1e53bba2013-07-16 22:26:05 +02001713 if (file == NULL) {
1714 PyErr_SetString(PyExc_RuntimeError, "lost sys.stdout");
1715 return NULL;
1716 }
1717
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001718 /* sys.stdout may be None when FILE* stdout isn't connected */
1719 if (file == Py_None)
1720 Py_RETURN_NONE;
1721 }
Guido van Rossum34343512006-11-30 22:13:52 +00001722
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001723 if (sep == Py_None) {
1724 sep = NULL;
1725 }
1726 else if (sep && !PyUnicode_Check(sep)) {
1727 PyErr_Format(PyExc_TypeError,
1728 "sep must be None or a string, not %.200s",
1729 sep->ob_type->tp_name);
1730 return NULL;
1731 }
1732 if (end == Py_None) {
1733 end = NULL;
1734 }
1735 else if (end && !PyUnicode_Check(end)) {
1736 PyErr_Format(PyExc_TypeError,
1737 "end must be None or a string, not %.200s",
1738 end->ob_type->tp_name);
1739 return NULL;
1740 }
Guido van Rossum34343512006-11-30 22:13:52 +00001741
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001742 for (i = 0; i < PyTuple_Size(args); i++) {
1743 if (i > 0) {
1744 if (sep == NULL)
1745 err = PyFile_WriteString(" ", file);
1746 else
1747 err = PyFile_WriteObject(sep, file,
1748 Py_PRINT_RAW);
1749 if (err)
1750 return NULL;
1751 }
1752 err = PyFile_WriteObject(PyTuple_GetItem(args, i), file,
1753 Py_PRINT_RAW);
1754 if (err)
1755 return NULL;
1756 }
Guido van Rossum34343512006-11-30 22:13:52 +00001757
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001758 if (end == NULL)
1759 err = PyFile_WriteString("\n", file);
1760 else
1761 err = PyFile_WriteObject(end, file, Py_PRINT_RAW);
1762 if (err)
1763 return NULL;
Guido van Rossum34343512006-11-30 22:13:52 +00001764
Georg Brandlbc3b6822012-01-13 19:41:25 +01001765 if (flush != NULL) {
1766 PyObject *tmp;
1767 int do_flush = PyObject_IsTrue(flush);
1768 if (do_flush == -1)
1769 return NULL;
1770 else if (do_flush) {
Victor Stinnereaa28832013-11-07 00:01:51 +01001771 tmp = _PyObject_CallMethodId(file, &PyId_flush, "");
Georg Brandlbc3b6822012-01-13 19:41:25 +01001772 if (tmp == NULL)
1773 return NULL;
1774 else
1775 Py_DECREF(tmp);
1776 }
1777 }
1778
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001779 Py_RETURN_NONE;
Guido van Rossum34343512006-11-30 22:13:52 +00001780}
1781
1782PyDoc_STRVAR(print_doc,
Senthil Kumarane9175bd2012-08-10 13:53:45 -07001783"print(value, ..., sep=' ', end='\\n', file=sys.stdout, flush=False)\n\
Guido van Rossum34343512006-11-30 22:13:52 +00001784\n\
1785Prints the values to a stream, or to sys.stdout by default.\n\
1786Optional keyword arguments:\n\
Senthil Kumarane9175bd2012-08-10 13:53:45 -07001787file: a file-like object (stream); defaults to the current sys.stdout.\n\
1788sep: string inserted between values, default a space.\n\
1789end: string appended after the last value, default a newline.\n\
1790flush: whether to forcibly flush the stream.");
Guido van Rossum34343512006-11-30 22:13:52 +00001791
1792
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001793/*[clinic input]
1794input as builtin_input
1795
1796 prompt: object(c_default="NULL") = None
1797 /
1798
1799Read a string from standard input. The trailing newline is stripped.
1800
1801The prompt string, if given, is printed to standard output without a
1802trailing newline before reading input.
1803
1804If the user hits EOF (*nix: Ctrl-D, Windows: Ctrl-Z+Return), raise EOFError.
1805On *nix systems, readline is used if available.
1806[clinic start generated code]*/
1807
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001808static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001809builtin_input_impl(PyObject *module, PyObject *prompt)
1810/*[clinic end generated code: output=83db5a191e7a0d60 input=5e8bb70c2908fe3c]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001811{
Victor Stinnerbd303c12013-11-07 23:07:29 +01001812 PyObject *fin = _PySys_GetObjectId(&PyId_stdin);
1813 PyObject *fout = _PySys_GetObjectId(&PyId_stdout);
1814 PyObject *ferr = _PySys_GetObjectId(&PyId_stderr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001815 PyObject *tmp;
1816 long fd;
1817 int tty;
Guido van Rossuma88a0332007-02-26 16:59:55 +00001818
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001819 /* Check that stdin/out/err are intact */
1820 if (fin == NULL || fin == Py_None) {
1821 PyErr_SetString(PyExc_RuntimeError,
1822 "input(): lost sys.stdin");
1823 return NULL;
1824 }
1825 if (fout == NULL || fout == Py_None) {
1826 PyErr_SetString(PyExc_RuntimeError,
1827 "input(): lost sys.stdout");
1828 return NULL;
1829 }
1830 if (ferr == NULL || ferr == Py_None) {
1831 PyErr_SetString(PyExc_RuntimeError,
1832 "input(): lost sys.stderr");
1833 return NULL;
1834 }
Guido van Rossumeba76962007-05-27 09:13:28 +00001835
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001836 /* First of all, flush stderr */
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001837 tmp = _PyObject_CallMethodId(ferr, &PyId_flush, "");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001838 if (tmp == NULL)
1839 PyErr_Clear();
1840 else
1841 Py_DECREF(tmp);
Guido van Rossumeba76962007-05-27 09:13:28 +00001842
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001843 /* We should only use (GNU) readline if Python's sys.stdin and
1844 sys.stdout are the same as C's stdin and stdout, because we
1845 need to pass it those. */
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001846 tmp = _PyObject_CallMethodId(fin, &PyId_fileno, "");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001847 if (tmp == NULL) {
1848 PyErr_Clear();
1849 tty = 0;
1850 }
1851 else {
1852 fd = PyLong_AsLong(tmp);
1853 Py_DECREF(tmp);
1854 if (fd < 0 && PyErr_Occurred())
1855 return NULL;
1856 tty = fd == fileno(stdin) && isatty(fd);
1857 }
1858 if (tty) {
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001859 tmp = _PyObject_CallMethodId(fout, &PyId_fileno, "");
Martin Panterc9a6ab52015-10-10 01:25:38 +00001860 if (tmp == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001861 PyErr_Clear();
Martin Panterc9a6ab52015-10-10 01:25:38 +00001862 tty = 0;
1863 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001864 else {
1865 fd = PyLong_AsLong(tmp);
1866 Py_DECREF(tmp);
1867 if (fd < 0 && PyErr_Occurred())
1868 return NULL;
1869 tty = fd == fileno(stdout) && isatty(fd);
1870 }
1871 }
Guido van Rossumeba76962007-05-27 09:13:28 +00001872
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001873 /* If we're interactive, use (GNU) readline */
1874 if (tty) {
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001875 PyObject *po = NULL;
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001876 char *promptstr;
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001877 char *s = NULL;
1878 PyObject *stdin_encoding = NULL, *stdin_errors = NULL;
1879 PyObject *stdout_encoding = NULL, *stdout_errors = NULL;
1880 char *stdin_encoding_str, *stdin_errors_str;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001881 PyObject *result;
Victor Stinnerc0f1a1a2011-02-23 12:07:37 +00001882 size_t len;
Martin v. Löwis4a7b5d52007-09-04 05:24:49 +00001883
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02001884 stdin_encoding = _PyObject_GetAttrId(fin, &PyId_encoding);
Antoine Pitrou5ee9d8a2011-11-06 00:38:45 +01001885 stdin_errors = _PyObject_GetAttrId(fin, &PyId_errors);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001886 if (!stdin_encoding || !stdin_errors)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001887 /* stdin is a text stream, so it must have an
1888 encoding. */
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001889 goto _readline_errors;
Victor Stinner306f0102010-05-19 01:06:22 +00001890 stdin_encoding_str = _PyUnicode_AsString(stdin_encoding);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001891 stdin_errors_str = _PyUnicode_AsString(stdin_errors);
1892 if (!stdin_encoding_str || !stdin_errors_str)
1893 goto _readline_errors;
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001894 tmp = _PyObject_CallMethodId(fout, &PyId_flush, "");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001895 if (tmp == NULL)
1896 PyErr_Clear();
1897 else
1898 Py_DECREF(tmp);
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001899 if (prompt != NULL) {
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001900 /* We have a prompt, encode it as stdout would */
1901 char *stdout_encoding_str, *stdout_errors_str;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001902 PyObject *stringpo;
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02001903 stdout_encoding = _PyObject_GetAttrId(fout, &PyId_encoding);
Antoine Pitrou5ee9d8a2011-11-06 00:38:45 +01001904 stdout_errors = _PyObject_GetAttrId(fout, &PyId_errors);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001905 if (!stdout_encoding || !stdout_errors)
1906 goto _readline_errors;
Victor Stinner306f0102010-05-19 01:06:22 +00001907 stdout_encoding_str = _PyUnicode_AsString(stdout_encoding);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001908 stdout_errors_str = _PyUnicode_AsString(stdout_errors);
1909 if (!stdout_encoding_str || !stdout_errors_str)
1910 goto _readline_errors;
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001911 stringpo = PyObject_Str(prompt);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001912 if (stringpo == NULL)
1913 goto _readline_errors;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001914 po = PyUnicode_AsEncodedString(stringpo,
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001915 stdout_encoding_str, stdout_errors_str);
1916 Py_CLEAR(stdout_encoding);
1917 Py_CLEAR(stdout_errors);
1918 Py_CLEAR(stringpo);
1919 if (po == NULL)
1920 goto _readline_errors;
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03001921 assert(PyBytes_Check(po));
1922 promptstr = PyBytes_AS_STRING(po);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001923 }
1924 else {
1925 po = NULL;
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001926 promptstr = "";
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001927 }
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001928 s = PyOS_Readline(stdin, stdout, promptstr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001929 if (s == NULL) {
Richard Oudkerk614c5782013-04-03 13:44:50 +01001930 PyErr_CheckSignals();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001931 if (!PyErr_Occurred())
1932 PyErr_SetNone(PyExc_KeyboardInterrupt);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001933 goto _readline_errors;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001934 }
Victor Stinnerc0f1a1a2011-02-23 12:07:37 +00001935
1936 len = strlen(s);
1937 if (len == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001938 PyErr_SetNone(PyExc_EOFError);
1939 result = NULL;
1940 }
Victor Stinnerc0f1a1a2011-02-23 12:07:37 +00001941 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001942 if (len > PY_SSIZE_T_MAX) {
1943 PyErr_SetString(PyExc_OverflowError,
1944 "input: input too long");
1945 result = NULL;
1946 }
1947 else {
Victor Stinnerc0f1a1a2011-02-23 12:07:37 +00001948 len--; /* strip trailing '\n' */
1949 if (len != 0 && s[len-1] == '\r')
1950 len--; /* strip trailing '\r' */
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001951 result = PyUnicode_Decode(s, len, stdin_encoding_str,
1952 stdin_errors_str);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001953 }
1954 }
1955 Py_DECREF(stdin_encoding);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001956 Py_DECREF(stdin_errors);
1957 Py_XDECREF(po);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001958 PyMem_FREE(s);
1959 return result;
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001960 _readline_errors:
1961 Py_XDECREF(stdin_encoding);
1962 Py_XDECREF(stdout_encoding);
1963 Py_XDECREF(stdin_errors);
1964 Py_XDECREF(stdout_errors);
1965 Py_XDECREF(po);
1966 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001967 }
Guido van Rossumeba76962007-05-27 09:13:28 +00001968
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001969 /* Fallback if we're not interactive */
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001970 if (prompt != NULL) {
1971 if (PyFile_WriteObject(prompt, fout, Py_PRINT_RAW) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001972 return NULL;
1973 }
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001974 tmp = _PyObject_CallMethodId(fout, &PyId_flush, "");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001975 if (tmp == NULL)
1976 PyErr_Clear();
1977 else
1978 Py_DECREF(tmp);
1979 return PyFile_GetLine(fin, -1);
Guido van Rossuma88a0332007-02-26 16:59:55 +00001980}
1981
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001982
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001983/*[clinic input]
1984repr as builtin_repr
1985
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001986 obj: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001987 /
1988
1989Return the canonical string representation of the object.
1990
1991For many object types, including most builtins, eval(repr(obj)) == obj.
1992[clinic start generated code]*/
1993
Guido van Rossum79f25d91997-04-29 20:08:16 +00001994static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001995builtin_repr(PyObject *module, PyObject *obj)
1996/*[clinic end generated code: output=7ed3778c44fd0194 input=1c9e6d66d3e3be04]*/
Guido van Rossumc89705d1992-11-26 08:54:07 +00001997{
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001998 return PyObject_Repr(obj);
Guido van Rossumc89705d1992-11-26 08:54:07 +00001999}
2000
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002001
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002002/* AC: cannot convert yet, as needs PEP 457 group support in inspect
2003 * or a semantic change to accept None for "ndigits"
2004 */
Guido van Rossum79f25d91997-04-29 20:08:16 +00002005static PyObject *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002006builtin_round(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum9e51f9b1993-02-12 16:29:05 +00002007{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002008 PyObject *ndigits = NULL;
2009 static char *kwlist[] = {"number", "ndigits", 0};
Benjamin Peterson214a7d22013-04-13 17:19:01 -04002010 PyObject *number, *round, *result;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002011
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002012 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|O:round",
2013 kwlist, &number, &ndigits))
2014 return NULL;
Alex Martelliae211f92007-08-22 23:21:33 +00002015
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002016 if (Py_TYPE(number)->tp_dict == NULL) {
2017 if (PyType_Ready(Py_TYPE(number)) < 0)
2018 return NULL;
2019 }
Guido van Rossum15d3d042007-08-24 02:02:45 +00002020
Benjamin Peterson214a7d22013-04-13 17:19:01 -04002021 round = _PyObject_LookupSpecial(number, &PyId___round__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002022 if (round == NULL) {
Benjamin Peterson214a7d22013-04-13 17:19:01 -04002023 if (!PyErr_Occurred())
2024 PyErr_Format(PyExc_TypeError,
2025 "type %.100s doesn't define __round__ method",
2026 Py_TYPE(number)->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002027 return NULL;
2028 }
Alex Martelliae211f92007-08-22 23:21:33 +00002029
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002030 if (ndigits == NULL)
Benjamin Peterson214a7d22013-04-13 17:19:01 -04002031 result = PyObject_CallFunctionObjArgs(round, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002032 else
Benjamin Peterson214a7d22013-04-13 17:19:01 -04002033 result = PyObject_CallFunctionObjArgs(round, ndigits, NULL);
2034 Py_DECREF(round);
2035 return result;
Guido van Rossum9e51f9b1993-02-12 16:29:05 +00002036}
2037
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002038PyDoc_STRVAR(round_doc,
Mark Dickinson1124e712009-01-28 21:25:58 +00002039"round(number[, ndigits]) -> number\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002040\n\
2041Round a number to a given precision in decimal digits (default 0 digits).\n\
Mark Dickinson0d748c22008-07-05 11:29:03 +00002042This returns an int when called with one argument, otherwise the\n\
Georg Brandl809ddaa2008-07-01 20:39:59 +00002043same type as the number. ndigits may be negative.");
Guido van Rossum2fa33db2007-08-23 22:07:24 +00002044
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002045
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002046/*AC: we need to keep the kwds dict intact to easily call into the
2047 * list.sort method, which isn't currently supported in AC. So we just use
2048 * the initially generated signature with a custom implementation.
2049 */
2050/* [disabled clinic input]
2051sorted as builtin_sorted
2052
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03002053 iterable as seq: object
2054 key as keyfunc: object = None
2055 reverse: object = False
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002056
2057Return a new list containing all items from the iterable in ascending order.
2058
2059A custom key function can be supplied to customise the sort order, and the
2060reverse flag can be set to request the result in descending order.
2061[end disabled clinic input]*/
2062
2063PyDoc_STRVAR(builtin_sorted__doc__,
2064"sorted($module, iterable, key=None, reverse=False)\n"
2065"--\n"
2066"\n"
2067"Return a new list containing all items from the iterable in ascending order.\n"
2068"\n"
2069"A custom key function can be supplied to customise the sort order, and the\n"
2070"reverse flag can be set to request the result in descending order.");
2071
2072#define BUILTIN_SORTED_METHODDEF \
2073 {"sorted", (PyCFunction)builtin_sorted, METH_VARARGS|METH_KEYWORDS, builtin_sorted__doc__},
2074
Raymond Hettinger64958a12003-12-17 20:43:33 +00002075static PyObject *
2076builtin_sorted(PyObject *self, PyObject *args, PyObject *kwds)
2077{
Victor Stinner2990fa12016-08-22 23:21:55 +02002078 PyObject *newlist, *v, *seq, *keyfunc=NULL, **newargs;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002079 PyObject *callable;
2080 static char *kwlist[] = {"iterable", "key", "reverse", 0};
2081 int reverse;
Victor Stinner2990fa12016-08-22 23:21:55 +02002082 int nargs;
Raymond Hettinger64958a12003-12-17 20:43:33 +00002083
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002084 /* args 1-3 should match listsort in Objects/listobject.c */
2085 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|Oi:sorted",
2086 kwlist, &seq, &keyfunc, &reverse))
2087 return NULL;
Raymond Hettinger64958a12003-12-17 20:43:33 +00002088
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002089 newlist = PySequence_List(seq);
2090 if (newlist == NULL)
2091 return NULL;
Raymond Hettinger64958a12003-12-17 20:43:33 +00002092
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02002093 callable = _PyObject_GetAttrId(newlist, &PyId_sort);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002094 if (callable == NULL) {
2095 Py_DECREF(newlist);
2096 return NULL;
2097 }
Georg Brandl99d7e4e2005-08-31 22:21:15 +00002098
Victor Stinner2990fa12016-08-22 23:21:55 +02002099 newargs = &PyTuple_GET_ITEM(args, 1);
2100 nargs = PyTuple_GET_SIZE(args) - 1;
2101 v = _PyObject_FastCallDict(callable, newargs, nargs, kwds);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002102 Py_DECREF(callable);
2103 if (v == NULL) {
2104 Py_DECREF(newlist);
2105 return NULL;
2106 }
2107 Py_DECREF(v);
2108 return newlist;
Raymond Hettinger64958a12003-12-17 20:43:33 +00002109}
2110
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002111
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002112/* AC: cannot convert yet, as needs PEP 457 group support in inspect */
Guido van Rossum79f25d91997-04-29 20:08:16 +00002113static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002114builtin_vars(PyObject *self, PyObject *args)
Guido van Rossum2d951851994-08-29 12:52:16 +00002115{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002116 PyObject *v = NULL;
2117 PyObject *d;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002118
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002119 if (!PyArg_UnpackTuple(args, "vars", 0, 1, &v))
2120 return NULL;
2121 if (v == NULL) {
2122 d = PyEval_GetLocals();
Victor Stinner41bb43a2013-10-29 01:19:37 +01002123 if (d == NULL)
2124 return NULL;
2125 Py_INCREF(d);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002126 }
2127 else {
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02002128 d = _PyObject_GetAttrId(v, &PyId___dict__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002129 if (d == NULL) {
2130 PyErr_SetString(PyExc_TypeError,
2131 "vars() argument must have __dict__ attribute");
2132 return NULL;
2133 }
2134 }
2135 return d;
Guido van Rossum2d951851994-08-29 12:52:16 +00002136}
2137
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002138PyDoc_STRVAR(vars_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002139"vars([object]) -> dictionary\n\
2140\n\
2141Without arguments, equivalent to locals().\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002142With an argument, equivalent to object.__dict__.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002143
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002144
2145/*[clinic input]
2146sum as builtin_sum
2147
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03002148 iterable: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002149 start: object(c_default="NULL") = 0
2150 /
2151
2152Return the sum of a 'start' value (default: 0) plus an iterable of numbers
2153
2154When the iterable is empty, return the start value.
2155This function is intended specifically for use with numeric values and may
2156reject non-numeric types.
2157[clinic start generated code]*/
2158
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002159static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002160builtin_sum_impl(PyObject *module, PyObject *iterable, PyObject *start)
2161/*[clinic end generated code: output=df758cec7d1d302f input=3b5b7a9d7611c73a]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002162{
2163 PyObject *result = start;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002164 PyObject *temp, *item, *iter;
Alex Martellia70b1912003-04-22 08:12:33 +00002165
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002166 iter = PyObject_GetIter(iterable);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002167 if (iter == NULL)
2168 return NULL;
Alex Martellia70b1912003-04-22 08:12:33 +00002169
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002170 if (result == NULL) {
2171 result = PyLong_FromLong(0);
2172 if (result == NULL) {
2173 Py_DECREF(iter);
2174 return NULL;
2175 }
2176 } else {
2177 /* reject string values for 'start' parameter */
2178 if (PyUnicode_Check(result)) {
2179 PyErr_SetString(PyExc_TypeError,
2180 "sum() can't sum strings [use ''.join(seq) instead]");
2181 Py_DECREF(iter);
2182 return NULL;
2183 }
Benjamin Petersonce071ca2011-07-29 14:23:47 -05002184 if (PyBytes_Check(result)) {
2185 PyErr_SetString(PyExc_TypeError,
2186 "sum() can't sum bytes [use b''.join(seq) instead]");
Benjamin Peterson405f32c2011-07-29 22:43:45 -05002187 Py_DECREF(iter);
Benjamin Petersonce071ca2011-07-29 14:23:47 -05002188 return NULL;
2189 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002190 if (PyByteArray_Check(result)) {
2191 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson4f921c22011-07-29 14:24:29 -05002192 "sum() can't sum bytearray [use b''.join(seq) instead]");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002193 Py_DECREF(iter);
2194 return NULL;
2195 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002196 Py_INCREF(result);
2197 }
Alex Martellia70b1912003-04-22 08:12:33 +00002198
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002199#ifndef SLOW_SUM
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002200 /* Fast addition by keeping temporary sums in C instead of new Python objects.
2201 Assumes all inputs are the same type. If the assumption fails, default
2202 to the more general routine.
2203 */
2204 if (PyLong_CheckExact(result)) {
2205 int overflow;
2206 long i_result = PyLong_AsLongAndOverflow(result, &overflow);
2207 /* If this already overflowed, don't even enter the loop. */
2208 if (overflow == 0) {
2209 Py_DECREF(result);
2210 result = NULL;
2211 }
2212 while(result == NULL) {
2213 item = PyIter_Next(iter);
2214 if (item == NULL) {
2215 Py_DECREF(iter);
2216 if (PyErr_Occurred())
2217 return NULL;
2218 return PyLong_FromLong(i_result);
2219 }
2220 if (PyLong_CheckExact(item)) {
2221 long b = PyLong_AsLongAndOverflow(item, &overflow);
2222 long x = i_result + b;
2223 if (overflow == 0 && ((x^i_result) >= 0 || (x^b) >= 0)) {
2224 i_result = x;
2225 Py_DECREF(item);
2226 continue;
2227 }
2228 }
2229 /* Either overflowed or is not an int. Restore real objects and process normally */
2230 result = PyLong_FromLong(i_result);
Christian Heimes704e2d32013-07-26 22:49:26 +02002231 if (result == NULL) {
2232 Py_DECREF(item);
2233 Py_DECREF(iter);
2234 return NULL;
2235 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002236 temp = PyNumber_Add(result, item);
2237 Py_DECREF(result);
2238 Py_DECREF(item);
2239 result = temp;
2240 if (result == NULL) {
2241 Py_DECREF(iter);
2242 return NULL;
2243 }
2244 }
2245 }
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002246
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002247 if (PyFloat_CheckExact(result)) {
2248 double f_result = PyFloat_AS_DOUBLE(result);
2249 Py_DECREF(result);
2250 result = NULL;
2251 while(result == NULL) {
2252 item = PyIter_Next(iter);
2253 if (item == NULL) {
2254 Py_DECREF(iter);
2255 if (PyErr_Occurred())
2256 return NULL;
2257 return PyFloat_FromDouble(f_result);
2258 }
2259 if (PyFloat_CheckExact(item)) {
2260 PyFPE_START_PROTECT("add", Py_DECREF(item); Py_DECREF(iter); return 0)
2261 f_result += PyFloat_AS_DOUBLE(item);
2262 PyFPE_END_PROTECT(f_result)
2263 Py_DECREF(item);
2264 continue;
2265 }
2266 if (PyLong_CheckExact(item)) {
2267 long value;
2268 int overflow;
2269 value = PyLong_AsLongAndOverflow(item, &overflow);
2270 if (!overflow) {
2271 PyFPE_START_PROTECT("add", Py_DECREF(item); Py_DECREF(iter); return 0)
2272 f_result += (double)value;
2273 PyFPE_END_PROTECT(f_result)
2274 Py_DECREF(item);
2275 continue;
2276 }
2277 }
2278 result = PyFloat_FromDouble(f_result);
2279 temp = PyNumber_Add(result, item);
2280 Py_DECREF(result);
2281 Py_DECREF(item);
2282 result = temp;
2283 if (result == NULL) {
2284 Py_DECREF(iter);
2285 return NULL;
2286 }
2287 }
2288 }
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002289#endif
2290
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002291 for(;;) {
2292 item = PyIter_Next(iter);
2293 if (item == NULL) {
2294 /* error, or end-of-sequence */
2295 if (PyErr_Occurred()) {
2296 Py_DECREF(result);
2297 result = NULL;
2298 }
2299 break;
2300 }
2301 /* It's tempting to use PyNumber_InPlaceAdd instead of
2302 PyNumber_Add here, to avoid quadratic running time
2303 when doing 'sum(list_of_lists, [])'. However, this
2304 would produce a change in behaviour: a snippet like
Mark Dickinson9acadc52009-10-26 14:19:42 +00002305
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002306 empty = []
2307 sum([[x] for x in range(10)], empty)
Mark Dickinson9acadc52009-10-26 14:19:42 +00002308
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002309 would change the value of empty. */
2310 temp = PyNumber_Add(result, item);
2311 Py_DECREF(result);
2312 Py_DECREF(item);
2313 result = temp;
2314 if (result == NULL)
2315 break;
2316 }
2317 Py_DECREF(iter);
2318 return result;
Alex Martellia70b1912003-04-22 08:12:33 +00002319}
2320
Alex Martellia70b1912003-04-22 08:12:33 +00002321
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002322/*[clinic input]
2323isinstance as builtin_isinstance
2324
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03002325 obj: object
2326 class_or_tuple: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002327 /
2328
2329Return whether an object is an instance of a class or of a subclass thereof.
2330
2331A tuple, as in ``isinstance(x, (A, B, ...))``, may be given as the target to
2332check against. This is equivalent to ``isinstance(x, A) or isinstance(x, B)
2333or ...`` etc.
2334[clinic start generated code]*/
2335
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002336static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002337builtin_isinstance_impl(PyObject *module, PyObject *obj,
Larry Hastings89964c42015-04-14 18:07:59 -04002338 PyObject *class_or_tuple)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002339/*[clinic end generated code: output=6faf01472c13b003 input=ffa743db1daf7549]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002340{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002341 int retval;
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002342
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002343 retval = PyObject_IsInstance(obj, class_or_tuple);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002344 if (retval < 0)
2345 return NULL;
2346 return PyBool_FromLong(retval);
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002347}
2348
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002349
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002350/*[clinic input]
2351issubclass as builtin_issubclass
2352
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03002353 cls: object
2354 class_or_tuple: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002355 /
2356
2357Return whether 'cls' is a derived from another class or is the same class.
2358
2359A tuple, as in ``issubclass(x, (A, B, ...))``, may be given as the target to
2360check against. This is equivalent to ``issubclass(x, A) or issubclass(x, B)
2361or ...`` etc.
2362[clinic start generated code]*/
2363
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002364static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002365builtin_issubclass_impl(PyObject *module, PyObject *cls,
Larry Hastings89964c42015-04-14 18:07:59 -04002366 PyObject *class_or_tuple)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002367/*[clinic end generated code: output=358412410cd7a250 input=af5f35e9ceaddaf6]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002368{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002369 int retval;
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002370
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002371 retval = PyObject_IsSubclass(cls, class_or_tuple);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002372 if (retval < 0)
2373 return NULL;
2374 return PyBool_FromLong(retval);
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002375}
2376
2377
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002378typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002379 PyObject_HEAD
2380 Py_ssize_t tuplesize;
2381 PyObject *ittuple; /* tuple of iterators */
2382 PyObject *result;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002383} zipobject;
2384
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002385static PyObject *
2386zip_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
Barry Warsawbd599b52000-08-03 15:45:29 +00002387{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002388 zipobject *lz;
2389 Py_ssize_t i;
2390 PyObject *ittuple; /* tuple of iterators */
2391 PyObject *result;
2392 Py_ssize_t tuplesize = PySequence_Length(args);
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002393
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002394 if (type == &PyZip_Type && !_PyArg_NoKeywords("zip()", kwds))
2395 return NULL;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002396
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002397 /* args must be a tuple */
2398 assert(PyTuple_Check(args));
Barry Warsawbd599b52000-08-03 15:45:29 +00002399
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002400 /* obtain iterators */
2401 ittuple = PyTuple_New(tuplesize);
2402 if (ittuple == NULL)
2403 return NULL;
2404 for (i=0; i < tuplesize; ++i) {
2405 PyObject *item = PyTuple_GET_ITEM(args, i);
2406 PyObject *it = PyObject_GetIter(item);
2407 if (it == NULL) {
2408 if (PyErr_ExceptionMatches(PyExc_TypeError))
2409 PyErr_Format(PyExc_TypeError,
2410 "zip argument #%zd must support iteration",
2411 i+1);
2412 Py_DECREF(ittuple);
2413 return NULL;
2414 }
2415 PyTuple_SET_ITEM(ittuple, i, it);
2416 }
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002417
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002418 /* create a result holder */
2419 result = PyTuple_New(tuplesize);
2420 if (result == NULL) {
2421 Py_DECREF(ittuple);
2422 return NULL;
2423 }
2424 for (i=0 ; i < tuplesize ; i++) {
2425 Py_INCREF(Py_None);
2426 PyTuple_SET_ITEM(result, i, Py_None);
2427 }
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002428
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002429 /* create zipobject structure */
2430 lz = (zipobject *)type->tp_alloc(type, 0);
2431 if (lz == NULL) {
2432 Py_DECREF(ittuple);
2433 Py_DECREF(result);
2434 return NULL;
2435 }
2436 lz->ittuple = ittuple;
2437 lz->tuplesize = tuplesize;
2438 lz->result = result;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002439
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002440 return (PyObject *)lz;
Barry Warsawbd599b52000-08-03 15:45:29 +00002441}
2442
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002443static void
2444zip_dealloc(zipobject *lz)
2445{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002446 PyObject_GC_UnTrack(lz);
2447 Py_XDECREF(lz->ittuple);
2448 Py_XDECREF(lz->result);
2449 Py_TYPE(lz)->tp_free(lz);
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002450}
2451
2452static int
2453zip_traverse(zipobject *lz, visitproc visit, void *arg)
2454{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002455 Py_VISIT(lz->ittuple);
2456 Py_VISIT(lz->result);
2457 return 0;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002458}
2459
2460static PyObject *
2461zip_next(zipobject *lz)
2462{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002463 Py_ssize_t i;
2464 Py_ssize_t tuplesize = lz->tuplesize;
2465 PyObject *result = lz->result;
2466 PyObject *it;
2467 PyObject *item;
2468 PyObject *olditem;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002469
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002470 if (tuplesize == 0)
2471 return NULL;
2472 if (Py_REFCNT(result) == 1) {
2473 Py_INCREF(result);
2474 for (i=0 ; i < tuplesize ; i++) {
2475 it = PyTuple_GET_ITEM(lz->ittuple, i);
2476 item = (*Py_TYPE(it)->tp_iternext)(it);
Serhiy Storchaka278d03b2013-04-06 22:52:34 +03002477 if (item == NULL) {
2478 Py_DECREF(result);
2479 return NULL;
2480 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002481 olditem = PyTuple_GET_ITEM(result, i);
2482 PyTuple_SET_ITEM(result, i, item);
2483 Py_DECREF(olditem);
2484 }
2485 } else {
2486 result = PyTuple_New(tuplesize);
2487 if (result == NULL)
Serhiy Storchaka278d03b2013-04-06 22:52:34 +03002488 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002489 for (i=0 ; i < tuplesize ; i++) {
2490 it = PyTuple_GET_ITEM(lz->ittuple, i);
2491 item = (*Py_TYPE(it)->tp_iternext)(it);
Serhiy Storchaka278d03b2013-04-06 22:52:34 +03002492 if (item == NULL) {
2493 Py_DECREF(result);
2494 return NULL;
2495 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002496 PyTuple_SET_ITEM(result, i, item);
2497 }
2498 }
2499 return result;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002500}
Barry Warsawbd599b52000-08-03 15:45:29 +00002501
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002502static PyObject *
2503zip_reduce(zipobject *lz)
2504{
2505 /* Just recreate the zip with the internal iterator tuple */
2506 return Py_BuildValue("OO", Py_TYPE(lz), lz->ittuple);
2507}
2508
2509static PyMethodDef zip_methods[] = {
2510 {"__reduce__", (PyCFunction)zip_reduce, METH_NOARGS, reduce_doc},
2511 {NULL, NULL} /* sentinel */
2512};
2513
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002514PyDoc_STRVAR(zip_doc,
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002515"zip(iter1 [,iter2 [...]]) --> zip object\n\
Barry Warsawbd599b52000-08-03 15:45:29 +00002516\n\
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002517Return a zip object whose .__next__() method returns a tuple where\n\
2518the i-th element comes from the i-th iterable argument. The .__next__()\n\
2519method continues until the shortest iterable in the argument sequence\n\
Georg Brandlced51db2008-12-04 18:28:38 +00002520is exhausted and then it raises StopIteration.");
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002521
2522PyTypeObject PyZip_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002523 PyVarObject_HEAD_INIT(&PyType_Type, 0)
2524 "zip", /* tp_name */
2525 sizeof(zipobject), /* tp_basicsize */
2526 0, /* tp_itemsize */
2527 /* methods */
2528 (destructor)zip_dealloc, /* tp_dealloc */
2529 0, /* tp_print */
2530 0, /* tp_getattr */
2531 0, /* tp_setattr */
2532 0, /* tp_reserved */
2533 0, /* tp_repr */
2534 0, /* tp_as_number */
2535 0, /* tp_as_sequence */
2536 0, /* tp_as_mapping */
2537 0, /* tp_hash */
2538 0, /* tp_call */
2539 0, /* tp_str */
2540 PyObject_GenericGetAttr, /* tp_getattro */
2541 0, /* tp_setattro */
2542 0, /* tp_as_buffer */
2543 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
2544 Py_TPFLAGS_BASETYPE, /* tp_flags */
2545 zip_doc, /* tp_doc */
2546 (traverseproc)zip_traverse, /* tp_traverse */
2547 0, /* tp_clear */
2548 0, /* tp_richcompare */
2549 0, /* tp_weaklistoffset */
2550 PyObject_SelfIter, /* tp_iter */
2551 (iternextfunc)zip_next, /* tp_iternext */
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002552 zip_methods, /* tp_methods */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002553 0, /* tp_members */
2554 0, /* tp_getset */
2555 0, /* tp_base */
2556 0, /* tp_dict */
2557 0, /* tp_descr_get */
2558 0, /* tp_descr_set */
2559 0, /* tp_dictoffset */
2560 0, /* tp_init */
2561 PyType_GenericAlloc, /* tp_alloc */
2562 zip_new, /* tp_new */
2563 PyObject_GC_Del, /* tp_free */
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002564};
Barry Warsawbd599b52000-08-03 15:45:29 +00002565
2566
Guido van Rossum79f25d91997-04-29 20:08:16 +00002567static PyMethodDef builtin_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002568 {"__build_class__", (PyCFunction)builtin___build_class__,
2569 METH_VARARGS | METH_KEYWORDS, build_class_doc},
2570 {"__import__", (PyCFunction)builtin___import__, METH_VARARGS | METH_KEYWORDS, import_doc},
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002571 BUILTIN_ABS_METHODDEF
2572 BUILTIN_ALL_METHODDEF
2573 BUILTIN_ANY_METHODDEF
2574 BUILTIN_ASCII_METHODDEF
2575 BUILTIN_BIN_METHODDEF
2576 BUILTIN_CALLABLE_METHODDEF
2577 BUILTIN_CHR_METHODDEF
2578 BUILTIN_COMPILE_METHODDEF
2579 BUILTIN_DELATTR_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002580 {"dir", builtin_dir, METH_VARARGS, dir_doc},
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002581 BUILTIN_DIVMOD_METHODDEF
2582 BUILTIN_EVAL_METHODDEF
2583 BUILTIN_EXEC_METHODDEF
2584 BUILTIN_FORMAT_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002585 {"getattr", builtin_getattr, METH_VARARGS, getattr_doc},
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002586 BUILTIN_GLOBALS_METHODDEF
2587 BUILTIN_HASATTR_METHODDEF
2588 BUILTIN_HASH_METHODDEF
2589 BUILTIN_HEX_METHODDEF
2590 BUILTIN_ID_METHODDEF
2591 BUILTIN_INPUT_METHODDEF
2592 BUILTIN_ISINSTANCE_METHODDEF
2593 BUILTIN_ISSUBCLASS_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002594 {"iter", builtin_iter, METH_VARARGS, iter_doc},
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002595 BUILTIN_LEN_METHODDEF
2596 BUILTIN_LOCALS_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002597 {"max", (PyCFunction)builtin_max, METH_VARARGS | METH_KEYWORDS, max_doc},
2598 {"min", (PyCFunction)builtin_min, METH_VARARGS | METH_KEYWORDS, min_doc},
2599 {"next", (PyCFunction)builtin_next, METH_VARARGS, next_doc},
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002600 BUILTIN_OCT_METHODDEF
2601 BUILTIN_ORD_METHODDEF
2602 BUILTIN_POW_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002603 {"print", (PyCFunction)builtin_print, METH_VARARGS | METH_KEYWORDS, print_doc},
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002604 BUILTIN_REPR_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002605 {"round", (PyCFunction)builtin_round, METH_VARARGS | METH_KEYWORDS, round_doc},
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002606 BUILTIN_SETATTR_METHODDEF
2607 BUILTIN_SORTED_METHODDEF
2608 BUILTIN_SUM_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002609 {"vars", builtin_vars, METH_VARARGS, vars_doc},
2610 {NULL, NULL},
Guido van Rossum3f5da241990-12-20 15:06:42 +00002611};
2612
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002613PyDoc_STRVAR(builtin_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002614"Built-in functions, exceptions, and other objects.\n\
2615\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002616Noteworthy: None is the `nil' object; Ellipsis represents `...' in slices.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002617
Martin v. Löwis1a214512008-06-11 05:26:20 +00002618static struct PyModuleDef builtinsmodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002619 PyModuleDef_HEAD_INIT,
2620 "builtins",
2621 builtin_doc,
2622 -1, /* multiple "initialization" just copies the module dict. */
2623 builtin_methods,
2624 NULL,
2625 NULL,
2626 NULL,
2627 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00002628};
2629
2630
Guido van Rossum25ce5661997-08-02 03:10:38 +00002631PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002632_PyBuiltin_Init(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +00002633{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002634 PyObject *mod, *dict, *debug;
Benjamin Peterson42124a72012-10-30 23:41:54 -04002635
2636 if (PyType_Ready(&PyFilter_Type) < 0 ||
2637 PyType_Ready(&PyMap_Type) < 0 ||
2638 PyType_Ready(&PyZip_Type) < 0)
2639 return NULL;
2640
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002641 mod = PyModule_Create(&builtinsmodule);
2642 if (mod == NULL)
2643 return NULL;
2644 dict = PyModule_GetDict(mod);
Tim Peters4b7625e2001-09-13 21:37:17 +00002645
Tim Peters7571a0f2003-03-23 17:52:28 +00002646#ifdef Py_TRACE_REFS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002647 /* "builtins" exposes a number of statically allocated objects
2648 * that, before this code was added in 2.3, never showed up in
2649 * the list of "all objects" maintained by Py_TRACE_REFS. As a
2650 * result, programs leaking references to None and False (etc)
2651 * couldn't be diagnosed by examining sys.getobjects(0).
2652 */
Tim Peters7571a0f2003-03-23 17:52:28 +00002653#define ADD_TO_ALL(OBJECT) _Py_AddToAllObjects((PyObject *)(OBJECT), 0)
2654#else
2655#define ADD_TO_ALL(OBJECT) (void)0
2656#endif
2657
Tim Peters4b7625e2001-09-13 21:37:17 +00002658#define SETBUILTIN(NAME, OBJECT) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002659 if (PyDict_SetItemString(dict, NAME, (PyObject *)OBJECT) < 0) \
2660 return NULL; \
2661 ADD_TO_ALL(OBJECT)
Tim Peters4b7625e2001-09-13 21:37:17 +00002662
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002663 SETBUILTIN("None", Py_None);
2664 SETBUILTIN("Ellipsis", Py_Ellipsis);
2665 SETBUILTIN("NotImplemented", Py_NotImplemented);
2666 SETBUILTIN("False", Py_False);
2667 SETBUILTIN("True", Py_True);
2668 SETBUILTIN("bool", &PyBool_Type);
2669 SETBUILTIN("memoryview", &PyMemoryView_Type);
2670 SETBUILTIN("bytearray", &PyByteArray_Type);
2671 SETBUILTIN("bytes", &PyBytes_Type);
2672 SETBUILTIN("classmethod", &PyClassMethod_Type);
2673 SETBUILTIN("complex", &PyComplex_Type);
2674 SETBUILTIN("dict", &PyDict_Type);
2675 SETBUILTIN("enumerate", &PyEnum_Type);
2676 SETBUILTIN("filter", &PyFilter_Type);
2677 SETBUILTIN("float", &PyFloat_Type);
2678 SETBUILTIN("frozenset", &PyFrozenSet_Type);
2679 SETBUILTIN("property", &PyProperty_Type);
2680 SETBUILTIN("int", &PyLong_Type);
2681 SETBUILTIN("list", &PyList_Type);
2682 SETBUILTIN("map", &PyMap_Type);
2683 SETBUILTIN("object", &PyBaseObject_Type);
2684 SETBUILTIN("range", &PyRange_Type);
2685 SETBUILTIN("reversed", &PyReversed_Type);
2686 SETBUILTIN("set", &PySet_Type);
2687 SETBUILTIN("slice", &PySlice_Type);
2688 SETBUILTIN("staticmethod", &PyStaticMethod_Type);
2689 SETBUILTIN("str", &PyUnicode_Type);
2690 SETBUILTIN("super", &PySuper_Type);
2691 SETBUILTIN("tuple", &PyTuple_Type);
2692 SETBUILTIN("type", &PyType_Type);
2693 SETBUILTIN("zip", &PyZip_Type);
2694 debug = PyBool_FromLong(Py_OptimizeFlag == 0);
2695 if (PyDict_SetItemString(dict, "__debug__", debug) < 0) {
Serhiy Storchakacfdfbb42016-06-18 09:44:03 +03002696 Py_DECREF(debug);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002697 return NULL;
2698 }
Serhiy Storchakacfdfbb42016-06-18 09:44:03 +03002699 Py_DECREF(debug);
Barry Warsaw757af0e1997-08-29 22:13:51 +00002700
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002701 return mod;
Tim Peters7571a0f2003-03-23 17:52:28 +00002702#undef ADD_TO_ALL
Tim Peters4b7625e2001-09-13 21:37:17 +00002703#undef SETBUILTIN
Guido van Rossum3f5da241990-12-20 15:06:42 +00002704}