blob: 220c92ddc57fbc041f6b6afdab4f1c384c81bac8 [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 {
158 PyObject *pargs = PyTuple_Pack(2, name, bases);
159 if (pargs == NULL) {
160 Py_DECREF(prep);
161 Py_DECREF(meta);
162 Py_XDECREF(mkw);
163 Py_DECREF(bases);
164 return NULL;
165 }
166 ns = PyEval_CallObjectWithKeywords(prep, pargs, mkw);
167 Py_DECREF(pargs);
168 Py_DECREF(prep);
169 }
170 if (ns == NULL) {
171 Py_DECREF(meta);
172 Py_XDECREF(mkw);
173 Py_DECREF(bases);
174 return NULL;
175 }
Benjamin Petersone8e14592013-05-16 14:37:25 -0500176 cell = PyEval_EvalCodeEx(PyFunction_GET_CODE(func), PyFunction_GET_GLOBALS(func), ns,
177 NULL, 0, NULL, 0, NULL, 0, NULL,
178 PyFunction_GET_CLOSURE(func));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000179 if (cell != NULL) {
180 PyObject *margs;
181 margs = PyTuple_Pack(3, name, bases, ns);
182 if (margs != NULL) {
183 cls = PyEval_CallObjectWithKeywords(meta, margs, mkw);
184 Py_DECREF(margs);
185 }
Benjamin Peterson8e8fbea2012-06-01 23:57:36 -0700186 if (cls != NULL && PyCell_Check(cell))
187 PyCell_Set(cell, cls);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000188 Py_DECREF(cell);
189 }
190 Py_DECREF(ns);
191 Py_DECREF(meta);
192 Py_XDECREF(mkw);
193 Py_DECREF(bases);
194 return cls;
Guido van Rossum52cc1d82007-03-18 15:41:51 +0000195}
196
197PyDoc_STRVAR(build_class_doc,
198"__build_class__(func, name, *bases, metaclass=None, **kwds) -> class\n\
199\n\
200Internal helper function used by the class statement.");
201
202static PyObject *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000203builtin___import__(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000204{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000205 static char *kwlist[] = {"name", "globals", "locals", "fromlist",
206 "level", 0};
Victor Stinnerfe93faf2011-03-14 15:54:52 -0400207 PyObject *name, *globals = NULL, *locals = NULL, *fromlist = NULL;
Brett Cannonfd074152012-04-14 14:10:13 -0400208 int level = 0;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000209
Victor Stinnerfe93faf2011-03-14 15:54:52 -0400210 if (!PyArg_ParseTupleAndKeywords(args, kwds, "U|OOOi:__import__",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000211 kwlist, &name, &globals, &locals, &fromlist, &level))
212 return NULL;
Victor Stinnerfe93faf2011-03-14 15:54:52 -0400213 return PyImport_ImportModuleLevelObject(name, globals, locals,
214 fromlist, level);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000215}
216
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000217PyDoc_STRVAR(import_doc,
Brett Cannoncb4996a2012-08-06 16:34:44 -0400218"__import__(name, globals=None, locals=None, fromlist=(), level=0) -> module\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000219\n\
Brett Cannon5305a992010-09-27 21:08:38 +0000220Import a module. Because this function is meant for use by the Python\n\
221interpreter and not for general use it is better to use\n\
222importlib.import_module() to programmatically import a module.\n\
223\n\
224The globals argument is only used to determine the context;\n\
225they are not modified. The locals argument is unused. The fromlist\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000226should be a list of names to emulate ``from name import ...'', or an\n\
227empty list to emulate ``import name''.\n\
228When importing a module from a package, note that __import__('A.B', ...)\n\
229returns package A when fromlist is empty, but its submodule B when\n\
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000230fromlist is not empty. Level is used to determine whether to perform \n\
Brett Cannon722d3ae2012-07-30 17:45:54 -0400231absolute or relative imports. 0 is absolute while a positive number\n\
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000232is the number of parent directories to search relative to the current module.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000233
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000234
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000235/*[clinic input]
236abs as builtin_abs
237
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300238 x: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000239 /
240
241Return the absolute value of the argument.
242[clinic start generated code]*/
243
Guido van Rossum79f25d91997-04-29 20:08:16 +0000244static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300245builtin_abs(PyObject *module, PyObject *x)
246/*[clinic end generated code: output=b1b433b9e51356f5 input=bed4ca14e29c20d1]*/
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000247{
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000248 return PyNumber_Absolute(x);
Guido van Rossum3f5da241990-12-20 15:06:42 +0000249}
250
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000251/*[clinic input]
252all as builtin_all
253
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300254 iterable: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000255 /
256
257Return True if bool(x) is True for all values x in the iterable.
258
259If the iterable is empty, return True.
260[clinic start generated code]*/
261
Raymond Hettinger96229b12005-03-11 06:49:40 +0000262static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300263builtin_all(PyObject *module, PyObject *iterable)
264/*[clinic end generated code: output=ca2a7127276f79b3 input=1a7c5d1bc3438a21]*/
Raymond Hettinger96229b12005-03-11 06:49:40 +0000265{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000266 PyObject *it, *item;
267 PyObject *(*iternext)(PyObject *);
268 int cmp;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000269
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000270 it = PyObject_GetIter(iterable);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000271 if (it == NULL)
272 return NULL;
273 iternext = *Py_TYPE(it)->tp_iternext;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000274
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000275 for (;;) {
276 item = iternext(it);
277 if (item == NULL)
278 break;
279 cmp = PyObject_IsTrue(item);
280 Py_DECREF(item);
281 if (cmp < 0) {
282 Py_DECREF(it);
283 return NULL;
284 }
285 if (cmp == 0) {
286 Py_DECREF(it);
287 Py_RETURN_FALSE;
288 }
289 }
290 Py_DECREF(it);
291 if (PyErr_Occurred()) {
292 if (PyErr_ExceptionMatches(PyExc_StopIteration))
293 PyErr_Clear();
294 else
295 return NULL;
296 }
297 Py_RETURN_TRUE;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000298}
299
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000300/*[clinic input]
301any as builtin_any
302
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300303 iterable: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000304 /
305
306Return True if bool(x) is True for any x in the iterable.
307
308If the iterable is empty, return False.
309[clinic start generated code]*/
310
Raymond Hettinger96229b12005-03-11 06:49:40 +0000311static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300312builtin_any(PyObject *module, PyObject *iterable)
313/*[clinic end generated code: output=fa65684748caa60e input=41d7451c23384f24]*/
Raymond Hettinger96229b12005-03-11 06:49:40 +0000314{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000315 PyObject *it, *item;
316 PyObject *(*iternext)(PyObject *);
317 int cmp;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000318
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000319 it = PyObject_GetIter(iterable);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000320 if (it == NULL)
321 return NULL;
322 iternext = *Py_TYPE(it)->tp_iternext;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000323
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000324 for (;;) {
325 item = iternext(it);
326 if (item == NULL)
327 break;
328 cmp = PyObject_IsTrue(item);
329 Py_DECREF(item);
330 if (cmp < 0) {
331 Py_DECREF(it);
332 return NULL;
333 }
Raymond Hettinger5098b582015-10-09 00:42:47 -0400334 if (cmp > 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000335 Py_DECREF(it);
336 Py_RETURN_TRUE;
337 }
338 }
339 Py_DECREF(it);
340 if (PyErr_Occurred()) {
341 if (PyErr_ExceptionMatches(PyExc_StopIteration))
342 PyErr_Clear();
343 else
344 return NULL;
345 }
346 Py_RETURN_FALSE;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000347}
348
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000349/*[clinic input]
350ascii as builtin_ascii
351
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300352 obj: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000353 /
354
355Return an ASCII-only representation of an object.
356
357As repr(), return a string containing a printable representation of an
358object, but escape the non-ASCII characters in the string returned by
359repr() using \\x, \\u or \\U escapes. This generates a string similar
360to that returned by repr() in Python 2.
361[clinic start generated code]*/
362
Georg Brandl559e5d72008-06-11 18:37:52 +0000363static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300364builtin_ascii(PyObject *module, PyObject *obj)
365/*[clinic end generated code: output=6d37b3f0984c7eb9 input=4c62732e1b3a3cc9]*/
Georg Brandl559e5d72008-06-11 18:37:52 +0000366{
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000367 return PyObject_ASCII(obj);
Georg Brandl559e5d72008-06-11 18:37:52 +0000368}
369
Georg Brandl559e5d72008-06-11 18:37:52 +0000370
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000371/*[clinic input]
372bin as builtin_bin
373
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300374 number: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000375 /
376
377Return the binary representation of an integer.
378
379 >>> bin(2796202)
380 '0b1010101010101010101010'
381[clinic start generated code]*/
382
Guido van Rossum79f25d91997-04-29 20:08:16 +0000383static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300384builtin_bin(PyObject *module, PyObject *number)
385/*[clinic end generated code: output=b6fc4ad5e649f4f7 input=53f8a0264bacaf90]*/
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000386{
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000387 return PyNumber_ToBase(number, 2);
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000388}
389
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000390
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000391/*[clinic input]
392callable as builtin_callable
393
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300394 obj: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000395 /
396
397Return whether the object is callable (i.e., some kind of function).
398
399Note that classes are callable, as are instances of classes with a
400__call__() method.
401[clinic start generated code]*/
402
Antoine Pitroue71362d2010-11-27 22:00:11 +0000403static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300404builtin_callable(PyObject *module, PyObject *obj)
405/*[clinic end generated code: output=2b095d59d934cb7e input=1423bab99cc41f58]*/
Antoine Pitroue71362d2010-11-27 22:00:11 +0000406{
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000407 return PyBool_FromLong((long)PyCallable_Check(obj));
Antoine Pitroue71362d2010-11-27 22:00:11 +0000408}
409
Antoine Pitroue71362d2010-11-27 22:00:11 +0000410
Raymond Hettinger17301e92008-03-13 00:19:26 +0000411typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000412 PyObject_HEAD
413 PyObject *func;
414 PyObject *it;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000415} filterobject;
416
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000417static PyObject *
Raymond Hettinger17301e92008-03-13 00:19:26 +0000418filter_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
Guido van Rossum12d12c51993-10-26 17:58:25 +0000419{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000420 PyObject *func, *seq;
421 PyObject *it;
422 filterobject *lz;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000423
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000424 if (type == &PyFilter_Type && !_PyArg_NoKeywords("filter()", kwds))
425 return NULL;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000426
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000427 if (!PyArg_UnpackTuple(args, "filter", 2, 2, &func, &seq))
428 return NULL;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000429
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000430 /* Get iterator. */
431 it = PyObject_GetIter(seq);
432 if (it == NULL)
433 return NULL;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000434
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000435 /* create filterobject structure */
436 lz = (filterobject *)type->tp_alloc(type, 0);
437 if (lz == NULL) {
438 Py_DECREF(it);
439 return NULL;
440 }
441 Py_INCREF(func);
442 lz->func = func;
443 lz->it = it;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000444
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000445 return (PyObject *)lz;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000446}
447
448static void
449filter_dealloc(filterobject *lz)
450{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000451 PyObject_GC_UnTrack(lz);
452 Py_XDECREF(lz->func);
453 Py_XDECREF(lz->it);
454 Py_TYPE(lz)->tp_free(lz);
Raymond Hettinger17301e92008-03-13 00:19:26 +0000455}
456
457static int
458filter_traverse(filterobject *lz, visitproc visit, void *arg)
459{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000460 Py_VISIT(lz->it);
461 Py_VISIT(lz->func);
462 return 0;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000463}
464
465static PyObject *
466filter_next(filterobject *lz)
467{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000468 PyObject *item;
469 PyObject *it = lz->it;
470 long ok;
471 PyObject *(*iternext)(PyObject *);
Raymond Hettingerbd5f0e82015-10-09 01:34:08 -0400472 int checktrue = lz->func == Py_None || lz->func == (PyObject *)&PyBool_Type;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000473
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000474 iternext = *Py_TYPE(it)->tp_iternext;
475 for (;;) {
476 item = iternext(it);
477 if (item == NULL)
478 return NULL;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000479
Raymond Hettingerbd5f0e82015-10-09 01:34:08 -0400480 if (checktrue) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000481 ok = PyObject_IsTrue(item);
482 } else {
483 PyObject *good;
Raymond Hettingerbd5f0e82015-10-09 01:34:08 -0400484 good = PyObject_CallFunctionObjArgs(lz->func, item, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000485 if (good == NULL) {
486 Py_DECREF(item);
487 return NULL;
488 }
489 ok = PyObject_IsTrue(good);
490 Py_DECREF(good);
491 }
Antoine Pitrou6f430e42012-08-15 23:18:25 +0200492 if (ok > 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000493 return item;
494 Py_DECREF(item);
Antoine Pitrou6f430e42012-08-15 23:18:25 +0200495 if (ok < 0)
496 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000497 }
Guido van Rossum12d12c51993-10-26 17:58:25 +0000498}
499
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +0000500static PyObject *
501filter_reduce(filterobject *lz)
502{
503 return Py_BuildValue("O(OO)", Py_TYPE(lz), lz->func, lz->it);
504}
505
506PyDoc_STRVAR(reduce_doc, "Return state information for pickling.");
507
508static PyMethodDef filter_methods[] = {
509 {"__reduce__", (PyCFunction)filter_reduce, METH_NOARGS, reduce_doc},
510 {NULL, NULL} /* sentinel */
511};
512
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000513PyDoc_STRVAR(filter_doc,
Georg Brandld11ae5d2008-05-16 13:27:32 +0000514"filter(function or None, iterable) --> filter object\n\
Guido van Rossumc1f779c2007-07-03 08:25:58 +0000515\n\
Georg Brandld11ae5d2008-05-16 13:27:32 +0000516Return an iterator yielding those items of iterable for which function(item)\n\
Raymond Hettinger17301e92008-03-13 00:19:26 +0000517is true. If function is None, return the items that are true.");
518
519PyTypeObject PyFilter_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000520 PyVarObject_HEAD_INIT(&PyType_Type, 0)
521 "filter", /* tp_name */
522 sizeof(filterobject), /* tp_basicsize */
523 0, /* tp_itemsize */
524 /* methods */
525 (destructor)filter_dealloc, /* tp_dealloc */
526 0, /* tp_print */
527 0, /* tp_getattr */
528 0, /* tp_setattr */
529 0, /* tp_reserved */
530 0, /* tp_repr */
531 0, /* tp_as_number */
532 0, /* tp_as_sequence */
533 0, /* tp_as_mapping */
534 0, /* tp_hash */
535 0, /* tp_call */
536 0, /* tp_str */
537 PyObject_GenericGetAttr, /* tp_getattro */
538 0, /* tp_setattro */
539 0, /* tp_as_buffer */
540 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
541 Py_TPFLAGS_BASETYPE, /* tp_flags */
542 filter_doc, /* tp_doc */
543 (traverseproc)filter_traverse, /* tp_traverse */
544 0, /* tp_clear */
545 0, /* tp_richcompare */
546 0, /* tp_weaklistoffset */
547 PyObject_SelfIter, /* tp_iter */
548 (iternextfunc)filter_next, /* tp_iternext */
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +0000549 filter_methods, /* tp_methods */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000550 0, /* tp_members */
551 0, /* tp_getset */
552 0, /* tp_base */
553 0, /* tp_dict */
554 0, /* tp_descr_get */
555 0, /* tp_descr_set */
556 0, /* tp_dictoffset */
557 0, /* tp_init */
558 PyType_GenericAlloc, /* tp_alloc */
559 filter_new, /* tp_new */
560 PyObject_GC_Del, /* tp_free */
Raymond Hettinger17301e92008-03-13 00:19:26 +0000561};
562
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000563
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000564/*[clinic input]
565format as builtin_format
566
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300567 value: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000568 format_spec: unicode(c_default="NULL") = ''
569 /
570
571Return value.__format__(format_spec)
572
573format_spec defaults to the empty string
574[clinic start generated code]*/
575
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000576static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300577builtin_format_impl(PyObject *module, PyObject *value, PyObject *format_spec)
578/*[clinic end generated code: output=2f40bdfa4954b077 input=6325e751a1b29b86]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000579{
Eric Smith8fd3eba2008-02-17 19:48:00 +0000580 return PyObject_Format(value, format_spec);
Eric Smith8c663262007-08-25 02:26:07 +0000581}
582
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000583/*[clinic input]
584chr as builtin_chr
585
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300586 i: int
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000587 /
588
589Return a Unicode string of one character with ordinal i; 0 <= i <= 0x10ffff.
590[clinic start generated code]*/
591
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000592static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300593builtin_chr_impl(PyObject *module, int i)
594/*[clinic end generated code: output=c733afcd200afcb7 input=3f604ef45a70750d]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000595{
596 return PyUnicode_FromOrdinal(i);
597}
Guido van Rossum09095f32000-03-10 23:00:52 +0000598
599
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +0200600static const char *
Martin Pantereeb896c2015-11-07 02:32:21 +0000601source_as_string(PyObject *cmd, const char *funcname, const char *what, PyCompilerFlags *cf, PyObject **cmd_copy)
Guido van Rossumf15a29f2007-05-04 00:41:39 +0000602{
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +0200603 const char *str;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000604 Py_ssize_t size;
Martin Pantereeb896c2015-11-07 02:32:21 +0000605 Py_buffer view;
Guido van Rossumf15a29f2007-05-04 00:41:39 +0000606
Martin Pantereeb896c2015-11-07 02:32:21 +0000607 *cmd_copy = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000608 if (PyUnicode_Check(cmd)) {
609 cf->cf_flags |= PyCF_IGNORE_COOKIE;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200610 str = PyUnicode_AsUTF8AndSize(cmd, &size);
611 if (str == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000612 return NULL;
613 }
Martin Pantereeb896c2015-11-07 02:32:21 +0000614 else if (PyBytes_Check(cmd)) {
615 str = PyBytes_AS_STRING(cmd);
616 size = PyBytes_GET_SIZE(cmd);
617 }
618 else if (PyByteArray_Check(cmd)) {
619 str = PyByteArray_AS_STRING(cmd);
620 size = PyByteArray_GET_SIZE(cmd);
621 }
622 else if (PyObject_GetBuffer(cmd, &view, PyBUF_SIMPLE) == 0) {
623 /* Copy to NUL-terminated buffer. */
624 *cmd_copy = PyBytes_FromStringAndSize(
625 (const char *)view.buf, view.len);
626 PyBuffer_Release(&view);
627 if (*cmd_copy == NULL) {
628 return NULL;
629 }
630 str = PyBytes_AS_STRING(*cmd_copy);
631 size = PyBytes_GET_SIZE(*cmd_copy);
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +0200632 }
633 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000634 PyErr_Format(PyExc_TypeError,
635 "%s() arg 1 must be a %s object",
636 funcname, what);
637 return NULL;
638 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200639
Serhiy Storchaka3dd3e262015-02-03 01:25:42 +0200640 if (strlen(str) != (size_t)size) {
Serhiy Storchakad8a14472014-09-06 20:07:17 +0300641 PyErr_SetString(PyExc_ValueError,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000642 "source code string cannot contain null bytes");
Martin Pantereeb896c2015-11-07 02:32:21 +0000643 Py_CLEAR(*cmd_copy);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000644 return NULL;
645 }
646 return str;
Guido van Rossumf15a29f2007-05-04 00:41:39 +0000647}
648
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000649/*[clinic input]
650compile as builtin_compile
651
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300652 source: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000653 filename: object(converter="PyUnicode_FSDecoder")
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300654 mode: str
655 flags: int = 0
Serhiy Storchaka8b2e8b62015-05-30 11:30:39 +0300656 dont_inherit: int(c_default="0") = False
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300657 optimize: int = -1
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000658
659Compile source into a code object that can be executed by exec() or eval().
660
661The source code may represent a Python module, statement or expression.
662The filename will be used for run-time error messages.
663The mode must be 'exec' to compile a module, 'single' to compile a
664single (interactive) statement, or 'eval' to compile an expression.
665The flags argument, if present, controls which future statements influence
666the compilation of the code.
Serhiy Storchaka8b2e8b62015-05-30 11:30:39 +0300667The dont_inherit argument, if true, stops the compilation inheriting
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000668the effects of any future statements in effect in the code calling
Serhiy Storchaka8b2e8b62015-05-30 11:30:39 +0300669compile; if absent or false these statements do influence the compilation,
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000670in addition to any features explicitly specified.
671[clinic start generated code]*/
672
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000673static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300674builtin_compile_impl(PyObject *module, PyObject *source, PyObject *filename,
675 const char *mode, int flags, int dont_inherit,
676 int optimize)
677/*[clinic end generated code: output=1fa176e33452bb63 input=9d53e8cfb3c86414]*/
Guido van Rossum5b722181993-03-30 17:46:03 +0000678{
Martin Panter61d6e4a2015-11-07 02:56:11 +0000679 PyObject *source_copy;
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +0200680 const char *str;
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000681 int compile_mode = -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000682 int is_ast;
683 PyCompilerFlags cf;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000684 int start[] = {Py_file_input, Py_eval_input, Py_single_input};
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000685 PyObject *result;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000686
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000687 cf.cf_flags = flags | PyCF_SOURCE_IS_UTF8;
Tim Peters6cd6a822001-08-17 22:11:27 +0000688
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000689 if (flags &
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000690 ~(PyCF_MASK | PyCF_MASK_OBSOLETE | PyCF_DONT_IMPLY_DEDENT | PyCF_ONLY_AST))
691 {
692 PyErr_SetString(PyExc_ValueError,
693 "compile(): unrecognised flags");
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000694 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000695 }
696 /* XXX Warn if (supplied_flags & PyCF_MASK_OBSOLETE) != 0? */
Tim Peters6cd6a822001-08-17 22:11:27 +0000697
Georg Brandl8334fd92010-12-04 10:26:46 +0000698 if (optimize < -1 || optimize > 2) {
699 PyErr_SetString(PyExc_ValueError,
700 "compile(): invalid optimize value");
701 goto error;
702 }
703
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000704 if (!dont_inherit) {
705 PyEval_MergeCompilerFlags(&cf);
706 }
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000707
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000708 if (strcmp(mode, "exec") == 0)
709 compile_mode = 0;
710 else if (strcmp(mode, "eval") == 0)
711 compile_mode = 1;
712 else if (strcmp(mode, "single") == 0)
713 compile_mode = 2;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000714 else {
715 PyErr_SetString(PyExc_ValueError,
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000716 "compile() mode must be 'exec', 'eval' or 'single'");
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000717 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000718 }
Neal Norwitzdb4115f2008-03-31 04:20:05 +0000719
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000720 is_ast = PyAST_Check(source);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000721 if (is_ast == -1)
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000722 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000723 if (is_ast) {
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000724 if (flags & PyCF_ONLY_AST) {
725 Py_INCREF(source);
726 result = source;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000727 }
728 else {
729 PyArena *arena;
730 mod_ty mod;
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000731
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000732 arena = PyArena_New();
Stefan Krah07795df2012-08-20 17:19:50 +0200733 if (arena == NULL)
734 goto error;
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000735 mod = PyAST_obj2mod(source, arena, compile_mode);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000736 if (mod == NULL) {
737 PyArena_Free(arena);
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000738 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000739 }
Benjamin Peterson832bfe22011-08-09 16:15:04 -0500740 if (!PyAST_Validate(mod)) {
741 PyArena_Free(arena);
742 goto error;
743 }
Victor Stinner14e461d2013-08-26 22:28:21 +0200744 result = (PyObject*)PyAST_CompileObject(mod, filename,
745 &cf, optimize, arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000746 PyArena_Free(arena);
747 }
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000748 goto finally;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000749 }
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000750
Martin Panter61d6e4a2015-11-07 02:56:11 +0000751 str = source_as_string(source, "compile", "string, bytes or AST", &cf, &source_copy);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000752 if (str == NULL)
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000753 goto error;
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000754
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000755 result = Py_CompileStringObject(str, filename, start[compile_mode], &cf, optimize);
Martin Panter61d6e4a2015-11-07 02:56:11 +0000756 Py_XDECREF(source_copy);
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000757 goto finally;
758
759error:
760 result = NULL;
761finally:
Victor Stinner14e461d2013-08-26 22:28:21 +0200762 Py_DECREF(filename);
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000763 return result;
Guido van Rossum5b722181993-03-30 17:46:03 +0000764}
765
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000766/* AC: cannot convert yet, as needs PEP 457 group support in inspect */
Guido van Rossum79f25d91997-04-29 20:08:16 +0000767static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000768builtin_dir(PyObject *self, PyObject *args)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000769{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000770 PyObject *arg = NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000771
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000772 if (!PyArg_UnpackTuple(args, "dir", 0, 1, &arg))
773 return NULL;
774 return PyObject_Dir(arg);
Guido van Rossum3f5da241990-12-20 15:06:42 +0000775}
776
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000777PyDoc_STRVAR(dir_doc,
Tim Peters5d2b77c2001-09-03 05:47:38 +0000778"dir([object]) -> list of strings\n"
779"\n"
Georg Brandle32b4222007-03-10 22:13:27 +0000780"If called without an argument, return the names in the current scope.\n"
781"Else, return an alphabetized list of names comprising (some of) the attributes\n"
782"of the given object, and of attributes reachable from it.\n"
783"If the object supplies a method named __dir__, it will be used; otherwise\n"
784"the default dir() logic is used and returns:\n"
785" for a module object: the module's attributes.\n"
786" for a class object: its attributes, and recursively the attributes\n"
787" of its bases.\n"
Guido van Rossumd8faa362007-04-27 19:54:29 +0000788" for any other object: its attributes, its class's attributes, and\n"
Georg Brandle32b4222007-03-10 22:13:27 +0000789" recursively the attributes of its class's base classes.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000790
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000791/*[clinic input]
792divmod as builtin_divmod
Guido van Rossum6a00cd81995-01-07 12:39:01 +0000793
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300794 x: object
795 y: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000796 /
797
Zachary Ware7f227d92016-04-28 14:39:50 -0500798Return the tuple (x//y, x%y). Invariant: div*y + mod == x.
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000799[clinic start generated code]*/
800
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000801static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300802builtin_divmod_impl(PyObject *module, PyObject *x, PyObject *y)
803/*[clinic end generated code: output=b06d8a5f6e0c745e input=175ad9c84ff41a85]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000804{
805 return PyNumber_Divmod(x, y);
806}
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000807
808
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000809/*[clinic input]
810eval as builtin_eval
811
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300812 source: object
813 globals: object = None
814 locals: object = None
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000815 /
816
817Evaluate the given source in the context of globals and locals.
818
819The source may be a string representing a Python expression
820or a code object as returned by compile().
821The globals must be a dictionary and locals can be any mapping,
822defaulting to the current globals and locals.
823If only globals is given, locals defaults to it.
824[clinic start generated code]*/
825
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000826static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300827builtin_eval_impl(PyObject *module, PyObject *source, PyObject *globals,
Larry Hastings89964c42015-04-14 18:07:59 -0400828 PyObject *locals)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300829/*[clinic end generated code: output=0a0824aa70093116 input=11ee718a8640e527]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000830{
Martin Panter61d6e4a2015-11-07 02:56:11 +0000831 PyObject *result, *source_copy;
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +0200832 const char *str;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000833 PyCompilerFlags cf;
Guido van Rossum590baa41993-11-30 13:40:46 +0000834
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000835 if (locals != Py_None && !PyMapping_Check(locals)) {
836 PyErr_SetString(PyExc_TypeError, "locals must be a mapping");
837 return NULL;
838 }
839 if (globals != Py_None && !PyDict_Check(globals)) {
840 PyErr_SetString(PyExc_TypeError, PyMapping_Check(globals) ?
841 "globals must be a real dict; try eval(expr, {}, mapping)"
842 : "globals must be a dict");
843 return NULL;
844 }
845 if (globals == Py_None) {
846 globals = PyEval_GetGlobals();
Victor Stinner41bb43a2013-10-29 01:19:37 +0100847 if (locals == Py_None) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000848 locals = PyEval_GetLocals();
Victor Stinner41bb43a2013-10-29 01:19:37 +0100849 if (locals == NULL)
850 return NULL;
851 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000852 }
853 else if (locals == Py_None)
854 locals = globals;
Tim Peters9fa96be2001-08-17 23:04:59 +0000855
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000856 if (globals == NULL || locals == NULL) {
857 PyErr_SetString(PyExc_TypeError,
858 "eval must be given globals and locals "
859 "when called without a frame");
860 return NULL;
861 }
Georg Brandl77c85e62005-09-15 10:46:13 +0000862
Victor Stinnerb44562b2013-11-06 19:03:11 +0100863 if (_PyDict_GetItemId(globals, &PyId___builtins__) == NULL) {
864 if (_PyDict_SetItemId(globals, &PyId___builtins__,
865 PyEval_GetBuiltins()) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000866 return NULL;
867 }
Tim Peters9fa96be2001-08-17 23:04:59 +0000868
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000869 if (PyCode_Check(source)) {
870 if (PyCode_GetNumFree((PyCodeObject *)source) > 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000871 PyErr_SetString(PyExc_TypeError,
872 "code object passed to eval() may not contain free variables");
873 return NULL;
874 }
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000875 return PyEval_EvalCode(source, globals, locals);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000876 }
Tim Peters9fa96be2001-08-17 23:04:59 +0000877
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000878 cf.cf_flags = PyCF_SOURCE_IS_UTF8;
Martin Panter61d6e4a2015-11-07 02:56:11 +0000879 str = source_as_string(source, "eval", "string, bytes or code", &cf, &source_copy);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000880 if (str == NULL)
881 return NULL;
Just van Rossum3aaf42c2003-02-10 08:21:10 +0000882
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000883 while (*str == ' ' || *str == '\t')
884 str++;
Tim Peters9fa96be2001-08-17 23:04:59 +0000885
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000886 (void)PyEval_MergeCompilerFlags(&cf);
887 result = PyRun_StringFlags(str, Py_eval_input, globals, locals, &cf);
Martin Panter61d6e4a2015-11-07 02:56:11 +0000888 Py_XDECREF(source_copy);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000889 return result;
Guido van Rossum3f5da241990-12-20 15:06:42 +0000890}
891
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000892/*[clinic input]
893exec as builtin_exec
894
Serhiy Storchaka7e810a62015-05-30 11:09:35 +0300895 source: object
896 globals: object = None
897 locals: object = None
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000898 /
899
900Execute the given source in the context of globals and locals.
901
902The source may be a string representing one or more Python statements
903or a code object as returned by compile().
904The globals must be a dictionary and locals can be any mapping,
905defaulting to the current globals and locals.
906If only globals is given, locals defaults to it.
907[clinic start generated code]*/
908
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000909static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300910builtin_exec_impl(PyObject *module, PyObject *source, PyObject *globals,
Larry Hastings89964c42015-04-14 18:07:59 -0400911 PyObject *locals)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300912/*[clinic end generated code: output=3c90efc6ab68ef5d input=01ca3e1c01692829]*/
Georg Brandl7cae87c2006-09-06 06:51:57 +0000913{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000914 PyObject *v;
Georg Brandl2cabc562008-08-28 07:57:16 +0000915
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000916 if (globals == Py_None) {
917 globals = PyEval_GetGlobals();
918 if (locals == Py_None) {
919 locals = PyEval_GetLocals();
Victor Stinner41bb43a2013-10-29 01:19:37 +0100920 if (locals == NULL)
921 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000922 }
923 if (!globals || !locals) {
924 PyErr_SetString(PyExc_SystemError,
925 "globals and locals cannot be NULL");
926 return NULL;
927 }
928 }
929 else if (locals == Py_None)
930 locals = globals;
Georg Brandl7cae87c2006-09-06 06:51:57 +0000931
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000932 if (!PyDict_Check(globals)) {
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000933 PyErr_Format(PyExc_TypeError, "exec() globals must be a dict, not %.100s",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000934 globals->ob_type->tp_name);
935 return NULL;
936 }
937 if (!PyMapping_Check(locals)) {
938 PyErr_Format(PyExc_TypeError,
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000939 "locals must be a mapping or None, not %.100s",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000940 locals->ob_type->tp_name);
941 return NULL;
942 }
Victor Stinnerb44562b2013-11-06 19:03:11 +0100943 if (_PyDict_GetItemId(globals, &PyId___builtins__) == NULL) {
944 if (_PyDict_SetItemId(globals, &PyId___builtins__,
945 PyEval_GetBuiltins()) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000946 return NULL;
947 }
948
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000949 if (PyCode_Check(source)) {
950 if (PyCode_GetNumFree((PyCodeObject *)source) > 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000951 PyErr_SetString(PyExc_TypeError,
952 "code object passed to exec() may not "
953 "contain free variables");
954 return NULL;
955 }
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000956 v = PyEval_EvalCode(source, globals, locals);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000957 }
958 else {
Martin Panter61d6e4a2015-11-07 02:56:11 +0000959 PyObject *source_copy;
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +0200960 const char *str;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000961 PyCompilerFlags cf;
962 cf.cf_flags = PyCF_SOURCE_IS_UTF8;
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000963 str = source_as_string(source, "exec",
Martin Panter61d6e4a2015-11-07 02:56:11 +0000964 "string, bytes or code", &cf,
965 &source_copy);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000966 if (str == NULL)
967 return NULL;
968 if (PyEval_MergeCompilerFlags(&cf))
969 v = PyRun_StringFlags(str, Py_file_input, globals,
970 locals, &cf);
971 else
972 v = PyRun_String(str, Py_file_input, globals, locals);
Martin Panter61d6e4a2015-11-07 02:56:11 +0000973 Py_XDECREF(source_copy);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000974 }
975 if (v == NULL)
976 return NULL;
977 Py_DECREF(v);
978 Py_RETURN_NONE;
Georg Brandl7cae87c2006-09-06 06:51:57 +0000979}
980
Georg Brandl7cae87c2006-09-06 06:51:57 +0000981
Nick Coghlanf9e227e2014-08-17 14:01:19 +1000982/* AC: cannot convert yet, as needs PEP 457 group support in inspect */
Guido van Rossum79f25d91997-04-29 20:08:16 +0000983static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000984builtin_getattr(PyObject *self, PyObject *args)
Guido van Rossum33894be1992-01-27 16:53:09 +0000985{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000986 PyObject *v, *result, *dflt = NULL;
987 PyObject *name;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000988
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000989 if (!PyArg_UnpackTuple(args, "getattr", 2, 3, &v, &name, &dflt))
990 return NULL;
Martin v. Löwis5b222132007-06-10 09:51:05 +0000991
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000992 if (!PyUnicode_Check(name)) {
993 PyErr_SetString(PyExc_TypeError,
994 "getattr(): attribute name must be string");
995 return NULL;
996 }
997 result = PyObject_GetAttr(v, name);
998 if (result == NULL && dflt != NULL &&
999 PyErr_ExceptionMatches(PyExc_AttributeError))
1000 {
1001 PyErr_Clear();
1002 Py_INCREF(dflt);
1003 result = dflt;
1004 }
1005 return result;
Guido van Rossum9bfef441993-03-29 10:43:31 +00001006}
1007
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001008PyDoc_STRVAR(getattr_doc,
Guido van Rossum950ff291998-06-29 13:38:57 +00001009"getattr(object, name[, default]) -> value\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001010\n\
Guido van Rossum950ff291998-06-29 13:38:57 +00001011Get a named attribute from an object; getattr(x, 'y') is equivalent to x.y.\n\
1012When a default argument is given, it is returned when the attribute doesn't\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001013exist; without it, an exception is raised in that case.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001014
1015
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001016/*[clinic input]
1017globals as builtin_globals
1018
1019Return the dictionary containing the current scope's global variables.
1020
1021NOTE: Updates to this dictionary *will* affect name lookups in the current
1022global scope and vice-versa.
1023[clinic start generated code]*/
1024
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001025static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001026builtin_globals_impl(PyObject *module)
1027/*[clinic end generated code: output=e5dd1527067b94d2 input=9327576f92bb48ba]*/
Guido van Rossum872537c1995-07-07 22:43:42 +00001028{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001029 PyObject *d;
Guido van Rossum872537c1995-07-07 22:43:42 +00001030
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001031 d = PyEval_GetGlobals();
1032 Py_XINCREF(d);
1033 return d;
Guido van Rossum872537c1995-07-07 22:43:42 +00001034}
1035
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001036
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001037/*[clinic input]
1038hasattr as builtin_hasattr
1039
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001040 obj: object
1041 name: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001042 /
1043
1044Return whether the object has an attribute with the given name.
1045
1046This is done by calling getattr(obj, name) and catching AttributeError.
1047[clinic start generated code]*/
1048
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001049static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001050builtin_hasattr_impl(PyObject *module, PyObject *obj, PyObject *name)
1051/*[clinic end generated code: output=a7aff2090a4151e5 input=0faec9787d979542]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001052{
1053 PyObject *v;
1054
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001055 if (!PyUnicode_Check(name)) {
1056 PyErr_SetString(PyExc_TypeError,
1057 "hasattr(): attribute name must be string");
1058 return NULL;
1059 }
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001060 v = PyObject_GetAttr(obj, name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001061 if (v == NULL) {
Benjamin Peterson17689992010-08-24 03:26:23 +00001062 if (PyErr_ExceptionMatches(PyExc_AttributeError)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001063 PyErr_Clear();
Benjamin Peterson17689992010-08-24 03:26:23 +00001064 Py_RETURN_FALSE;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001065 }
Benjamin Peterson17689992010-08-24 03:26:23 +00001066 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001067 }
1068 Py_DECREF(v);
Benjamin Peterson17689992010-08-24 03:26:23 +00001069 Py_RETURN_TRUE;
Guido van Rossum33894be1992-01-27 16:53:09 +00001070}
1071
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001072
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001073/* AC: gdb's integration with CPython relies on builtin_id having
1074 * the *exact* parameter names of "self" and "v", so we ensure we
1075 * preserve those name rather than using the AC defaults.
1076 */
1077/*[clinic input]
1078id as builtin_id
1079
Serhiy Storchaka24182a32016-05-05 16:21:35 +03001080 self: self(type="PyModuleDef *")
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001081 obj as v: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001082 /
1083
1084Return the identity of an object.
1085
1086This is guaranteed to be unique among simultaneously existing objects.
1087(CPython uses the object's memory address.)
1088[clinic start generated code]*/
1089
Guido van Rossum79f25d91997-04-29 20:08:16 +00001090static PyObject *
Serhiy Storchaka24182a32016-05-05 16:21:35 +03001091builtin_id(PyModuleDef *self, PyObject *v)
1092/*[clinic end generated code: output=0aa640785f697f65 input=5a534136419631f4]*/
Guido van Rossum5b722181993-03-30 17:46:03 +00001093{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001094 return PyLong_FromVoidPtr(v);
Guido van Rossum5b722181993-03-30 17:46:03 +00001095}
1096
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001097
Raymond Hettingera6c60372008-03-13 01:26:19 +00001098/* map object ************************************************************/
1099
1100typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001101 PyObject_HEAD
1102 PyObject *iters;
1103 PyObject *func;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001104} mapobject;
1105
Guido van Rossum79f25d91997-04-29 20:08:16 +00001106static PyObject *
Raymond Hettingera6c60372008-03-13 01:26:19 +00001107map_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
Guido van Rossum12d12c51993-10-26 17:58:25 +00001108{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001109 PyObject *it, *iters, *func;
1110 mapobject *lz;
1111 Py_ssize_t numargs, i;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001112
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001113 if (type == &PyMap_Type && !_PyArg_NoKeywords("map()", kwds))
1114 return NULL;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001115
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001116 numargs = PyTuple_Size(args);
1117 if (numargs < 2) {
1118 PyErr_SetString(PyExc_TypeError,
1119 "map() must have at least two arguments.");
1120 return NULL;
1121 }
Raymond Hettingera6c60372008-03-13 01:26:19 +00001122
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001123 iters = PyTuple_New(numargs-1);
1124 if (iters == NULL)
1125 return NULL;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001126
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001127 for (i=1 ; i<numargs ; i++) {
1128 /* Get iterator. */
1129 it = PyObject_GetIter(PyTuple_GET_ITEM(args, i));
1130 if (it == NULL) {
1131 Py_DECREF(iters);
1132 return NULL;
1133 }
1134 PyTuple_SET_ITEM(iters, i-1, it);
1135 }
Raymond Hettingera6c60372008-03-13 01:26:19 +00001136
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001137 /* create mapobject structure */
1138 lz = (mapobject *)type->tp_alloc(type, 0);
1139 if (lz == NULL) {
1140 Py_DECREF(iters);
1141 return NULL;
1142 }
1143 lz->iters = iters;
1144 func = PyTuple_GET_ITEM(args, 0);
1145 Py_INCREF(func);
1146 lz->func = func;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001147
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001148 return (PyObject *)lz;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001149}
1150
1151static void
1152map_dealloc(mapobject *lz)
1153{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001154 PyObject_GC_UnTrack(lz);
1155 Py_XDECREF(lz->iters);
1156 Py_XDECREF(lz->func);
1157 Py_TYPE(lz)->tp_free(lz);
Raymond Hettingera6c60372008-03-13 01:26:19 +00001158}
1159
1160static int
1161map_traverse(mapobject *lz, visitproc visit, void *arg)
1162{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001163 Py_VISIT(lz->iters);
1164 Py_VISIT(lz->func);
1165 return 0;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001166}
1167
1168static PyObject *
1169map_next(mapobject *lz)
1170{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001171 PyObject *val;
1172 PyObject *argtuple;
1173 PyObject *result;
1174 Py_ssize_t numargs, i;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001175
Raymond Hettinger501b4a72015-08-18 08:07:16 -07001176 numargs = PyTuple_GET_SIZE(lz->iters);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001177 argtuple = PyTuple_New(numargs);
1178 if (argtuple == NULL)
1179 return NULL;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001180
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001181 for (i=0 ; i<numargs ; i++) {
Raymond Hettingerf1094142015-08-18 00:20:20 -07001182 PyObject *it = PyTuple_GET_ITEM(lz->iters, i);
1183 val = Py_TYPE(it)->tp_iternext(it);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001184 if (val == NULL) {
1185 Py_DECREF(argtuple);
1186 return NULL;
1187 }
1188 PyTuple_SET_ITEM(argtuple, i, val);
1189 }
1190 result = PyObject_Call(lz->func, argtuple, NULL);
1191 Py_DECREF(argtuple);
1192 return result;
Guido van Rossum12d12c51993-10-26 17:58:25 +00001193}
1194
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001195static PyObject *
1196map_reduce(mapobject *lz)
1197{
1198 Py_ssize_t numargs = PyTuple_GET_SIZE(lz->iters);
1199 PyObject *args = PyTuple_New(numargs+1);
1200 Py_ssize_t i;
1201 if (args == NULL)
1202 return NULL;
1203 Py_INCREF(lz->func);
1204 PyTuple_SET_ITEM(args, 0, lz->func);
1205 for (i = 0; i<numargs; i++){
1206 PyObject *it = PyTuple_GET_ITEM(lz->iters, i);
1207 Py_INCREF(it);
1208 PyTuple_SET_ITEM(args, i+1, it);
1209 }
1210
1211 return Py_BuildValue("ON", Py_TYPE(lz), args);
1212}
1213
1214static PyMethodDef map_methods[] = {
1215 {"__reduce__", (PyCFunction)map_reduce, METH_NOARGS, reduce_doc},
1216 {NULL, NULL} /* sentinel */
1217};
1218
1219
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001220PyDoc_STRVAR(map_doc,
Raymond Hettingera6c60372008-03-13 01:26:19 +00001221"map(func, *iterables) --> map object\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001222\n\
Raymond Hettingera6c60372008-03-13 01:26:19 +00001223Make an iterator that computes the function using arguments from\n\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001224each of the iterables. Stops when the shortest iterable is exhausted.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001225
Raymond Hettingera6c60372008-03-13 01:26:19 +00001226PyTypeObject PyMap_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001227 PyVarObject_HEAD_INIT(&PyType_Type, 0)
1228 "map", /* tp_name */
1229 sizeof(mapobject), /* tp_basicsize */
1230 0, /* tp_itemsize */
1231 /* methods */
1232 (destructor)map_dealloc, /* tp_dealloc */
1233 0, /* tp_print */
1234 0, /* tp_getattr */
1235 0, /* tp_setattr */
1236 0, /* tp_reserved */
1237 0, /* tp_repr */
1238 0, /* tp_as_number */
1239 0, /* tp_as_sequence */
1240 0, /* tp_as_mapping */
1241 0, /* tp_hash */
1242 0, /* tp_call */
1243 0, /* tp_str */
1244 PyObject_GenericGetAttr, /* tp_getattro */
1245 0, /* tp_setattro */
1246 0, /* tp_as_buffer */
1247 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
1248 Py_TPFLAGS_BASETYPE, /* tp_flags */
1249 map_doc, /* tp_doc */
1250 (traverseproc)map_traverse, /* tp_traverse */
1251 0, /* tp_clear */
1252 0, /* tp_richcompare */
1253 0, /* tp_weaklistoffset */
1254 PyObject_SelfIter, /* tp_iter */
1255 (iternextfunc)map_next, /* tp_iternext */
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001256 map_methods, /* tp_methods */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001257 0, /* tp_members */
1258 0, /* tp_getset */
1259 0, /* tp_base */
1260 0, /* tp_dict */
1261 0, /* tp_descr_get */
1262 0, /* tp_descr_set */
1263 0, /* tp_dictoffset */
1264 0, /* tp_init */
1265 PyType_GenericAlloc, /* tp_alloc */
1266 map_new, /* tp_new */
1267 PyObject_GC_Del, /* tp_free */
Raymond Hettingera6c60372008-03-13 01:26:19 +00001268};
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001269
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001270
1271/* AC: cannot convert yet, as needs PEP 457 group support in inspect */
Guido van Rossum79f25d91997-04-29 20:08:16 +00001272static PyObject *
Georg Brandla18af4e2007-04-21 15:47:16 +00001273builtin_next(PyObject *self, PyObject *args)
1274{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001275 PyObject *it, *res;
1276 PyObject *def = NULL;
Georg Brandla18af4e2007-04-21 15:47:16 +00001277
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001278 if (!PyArg_UnpackTuple(args, "next", 1, 2, &it, &def))
1279 return NULL;
1280 if (!PyIter_Check(it)) {
1281 PyErr_Format(PyExc_TypeError,
Philip Jenvey50add042011-11-06 16:37:52 -08001282 "'%.200s' object is not an iterator",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001283 it->ob_type->tp_name);
1284 return NULL;
1285 }
1286
1287 res = (*it->ob_type->tp_iternext)(it);
1288 if (res != NULL) {
1289 return res;
1290 } else if (def != NULL) {
1291 if (PyErr_Occurred()) {
1292 if(!PyErr_ExceptionMatches(PyExc_StopIteration))
1293 return NULL;
1294 PyErr_Clear();
1295 }
1296 Py_INCREF(def);
1297 return def;
1298 } else if (PyErr_Occurred()) {
1299 return NULL;
1300 } else {
1301 PyErr_SetNone(PyExc_StopIteration);
1302 return NULL;
1303 }
Georg Brandla18af4e2007-04-21 15:47:16 +00001304}
1305
1306PyDoc_STRVAR(next_doc,
1307"next(iterator[, default])\n\
1308\n\
1309Return the next item from the iterator. If default is given and the iterator\n\
1310is exhausted, it is returned instead of raising StopIteration.");
1311
1312
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001313/*[clinic input]
1314setattr as builtin_setattr
1315
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001316 obj: object
1317 name: object
1318 value: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001319 /
1320
1321Sets the named attribute on the given object to the specified value.
1322
1323setattr(x, 'y', v) is equivalent to ``x.y = v''
1324[clinic start generated code]*/
1325
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001326static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001327builtin_setattr_impl(PyObject *module, PyObject *obj, PyObject *name,
Larry Hastings89964c42015-04-14 18:07:59 -04001328 PyObject *value)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001329/*[clinic end generated code: output=dc2ce1d1add9acb4 input=bd2b7ca6875a1899]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001330{
1331 if (PyObject_SetAttr(obj, name, value) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001332 return NULL;
1333 Py_INCREF(Py_None);
1334 return Py_None;
Guido van Rossum33894be1992-01-27 16:53:09 +00001335}
1336
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001337
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001338/*[clinic input]
1339delattr as builtin_delattr
1340
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001341 obj: object
1342 name: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001343 /
1344
1345Deletes the named attribute from the given object.
1346
1347delattr(x, 'y') is equivalent to ``del x.y''
1348[clinic start generated code]*/
1349
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001350static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001351builtin_delattr_impl(PyObject *module, PyObject *obj, PyObject *name)
1352/*[clinic end generated code: output=85134bc58dff79fa input=db16685d6b4b9410]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001353{
1354 if (PyObject_SetAttr(obj, name, (PyObject *)NULL) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001355 return NULL;
1356 Py_INCREF(Py_None);
1357 return Py_None;
Guido van Rossum14144fc1994-08-29 12:53:40 +00001358}
1359
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001360
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001361/*[clinic input]
1362hash as builtin_hash
1363
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001364 obj: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001365 /
1366
1367Return the hash value for the given object.
1368
1369Two objects that compare equal must also have the same hash value, but the
1370reverse is not necessarily true.
1371[clinic start generated code]*/
1372
Guido van Rossum79f25d91997-04-29 20:08:16 +00001373static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001374builtin_hash(PyObject *module, PyObject *obj)
1375/*[clinic end generated code: output=237668e9d7688db7 input=58c48be822bf9c54]*/
Guido van Rossum9bfef441993-03-29 10:43:31 +00001376{
Benjamin Peterson8f67d082010-10-17 20:54:53 +00001377 Py_hash_t x;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001378
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001379 x = PyObject_Hash(obj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001380 if (x == -1)
1381 return NULL;
Benjamin Peterson8f67d082010-10-17 20:54:53 +00001382 return PyLong_FromSsize_t(x);
Guido van Rossum9bfef441993-03-29 10:43:31 +00001383}
1384
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001385
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001386/*[clinic input]
1387hex as builtin_hex
1388
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001389 number: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001390 /
1391
1392Return the hexadecimal representation of an integer.
1393
1394 >>> hex(12648430)
1395 '0xc0ffee'
1396[clinic start generated code]*/
1397
Guido van Rossum79f25d91997-04-29 20:08:16 +00001398static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001399builtin_hex(PyObject *module, PyObject *number)
1400/*[clinic end generated code: output=e46b612169099408 input=e645aff5fc7d540e]*/
Guido van Rossum006bcd41991-10-24 14:54:44 +00001401{
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001402 return PyNumber_ToBase(number, 16);
Guido van Rossum006bcd41991-10-24 14:54:44 +00001403}
1404
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001405
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001406/* AC: cannot convert yet, as needs PEP 457 group support in inspect */
Guido van Rossum79f25d91997-04-29 20:08:16 +00001407static PyObject *
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001408builtin_iter(PyObject *self, PyObject *args)
1409{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001410 PyObject *v, *w = NULL;
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001411
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001412 if (!PyArg_UnpackTuple(args, "iter", 1, 2, &v, &w))
1413 return NULL;
1414 if (w == NULL)
1415 return PyObject_GetIter(v);
1416 if (!PyCallable_Check(v)) {
1417 PyErr_SetString(PyExc_TypeError,
1418 "iter(v, w): v must be callable");
1419 return NULL;
1420 }
1421 return PyCallIter_New(v, w);
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001422}
1423
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001424PyDoc_STRVAR(iter_doc,
Georg Brandld11ae5d2008-05-16 13:27:32 +00001425"iter(iterable) -> iterator\n\
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001426iter(callable, sentinel) -> iterator\n\
1427\n\
1428Get an iterator from an object. In the first form, the argument must\n\
1429supply its own iterator, or be a sequence.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001430In the second form, the callable is called until it returns the sentinel.");
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001431
1432
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001433/*[clinic input]
1434len as builtin_len
1435
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001436 obj: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001437 /
1438
1439Return the number of items in a container.
1440[clinic start generated code]*/
1441
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001442static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001443builtin_len(PyObject *module, PyObject *obj)
1444/*[clinic end generated code: output=fa7a270d314dfb6c input=bc55598da9e9c9b5]*/
Guido van Rossum3f5da241990-12-20 15:06:42 +00001445{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001446 Py_ssize_t res;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001447
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001448 res = PyObject_Size(obj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001449 if (res < 0 && PyErr_Occurred())
1450 return NULL;
1451 return PyLong_FromSsize_t(res);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001452}
1453
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001454
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001455/*[clinic input]
1456locals as builtin_locals
1457
1458Return a dictionary containing the current scope's local variables.
1459
1460NOTE: Whether or not updates to this dictionary will affect name lookups in
1461the local scope and vice-versa is *implementation dependent* and not
1462covered by any backwards compatibility guarantees.
1463[clinic start generated code]*/
1464
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001465static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001466builtin_locals_impl(PyObject *module)
1467/*[clinic end generated code: output=b46c94015ce11448 input=7874018d478d5c4b]*/
Guido van Rossum872537c1995-07-07 22:43:42 +00001468{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001469 PyObject *d;
Guido van Rossum872537c1995-07-07 22:43:42 +00001470
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001471 d = PyEval_GetLocals();
1472 Py_XINCREF(d);
1473 return d;
Guido van Rossum872537c1995-07-07 22:43:42 +00001474}
1475
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001476
Guido van Rossum79f25d91997-04-29 20:08:16 +00001477static PyObject *
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001478min_max(PyObject *args, PyObject *kwds, int op)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001479{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001480 PyObject *v, *it, *item, *val, *maxitem, *maxval, *keyfunc=NULL;
Raymond Hettinger4d6018f2013-06-24 22:43:02 -07001481 PyObject *emptytuple, *defaultval = NULL;
1482 static char *kwlist[] = {"key", "default", NULL};
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001483 const char *name = op == Py_LT ? "min" : "max";
Raymond Hettinger4d6018f2013-06-24 22:43:02 -07001484 const int positional = PyTuple_Size(args) > 1;
1485 int ret;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001486
Raymond Hettinger4d6018f2013-06-24 22:43:02 -07001487 if (positional)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001488 v = args;
Serhiy Storchakac6792272013-10-19 21:03:34 +03001489 else if (!PyArg_UnpackTuple(args, name, 1, 1, &v))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001490 return NULL;
Tim Peters67d687a2002-04-29 21:27:32 +00001491
Raymond Hettinger4d6018f2013-06-24 22:43:02 -07001492 emptytuple = PyTuple_New(0);
1493 if (emptytuple == NULL)
1494 return NULL;
1495 ret = PyArg_ParseTupleAndKeywords(emptytuple, kwds, "|$OO", kwlist,
1496 &keyfunc, &defaultval);
1497 Py_DECREF(emptytuple);
1498 if (!ret)
1499 return NULL;
1500
1501 if (positional && defaultval != NULL) {
1502 PyErr_Format(PyExc_TypeError,
1503 "Cannot specify a default for %s() with multiple "
1504 "positional arguments", name);
1505 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001506 }
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001507
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001508 it = PyObject_GetIter(v);
1509 if (it == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001510 return NULL;
1511 }
Tim Petersc3074532001-05-03 07:00:32 +00001512
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001513 maxitem = NULL; /* the result */
1514 maxval = NULL; /* the value associated with the result */
1515 while (( item = PyIter_Next(it) )) {
1516 /* get the value from the key function */
1517 if (keyfunc != NULL) {
1518 val = PyObject_CallFunctionObjArgs(keyfunc, item, NULL);
1519 if (val == NULL)
1520 goto Fail_it_item;
1521 }
1522 /* no key function; the value is the item */
1523 else {
1524 val = item;
1525 Py_INCREF(val);
1526 }
Tim Petersc3074532001-05-03 07:00:32 +00001527
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001528 /* maximum value and item are unset; set them */
1529 if (maxval == NULL) {
1530 maxitem = item;
1531 maxval = val;
1532 }
1533 /* maximum value and item are set; update them as necessary */
1534 else {
1535 int cmp = PyObject_RichCompareBool(val, maxval, op);
1536 if (cmp < 0)
1537 goto Fail_it_item_and_val;
1538 else if (cmp > 0) {
1539 Py_DECREF(maxval);
1540 Py_DECREF(maxitem);
1541 maxval = val;
1542 maxitem = item;
1543 }
1544 else {
1545 Py_DECREF(item);
1546 Py_DECREF(val);
1547 }
1548 }
1549 }
1550 if (PyErr_Occurred())
1551 goto Fail_it;
1552 if (maxval == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001553 assert(maxitem == NULL);
Raymond Hettinger4d6018f2013-06-24 22:43:02 -07001554 if (defaultval != NULL) {
1555 Py_INCREF(defaultval);
1556 maxitem = defaultval;
1557 } else {
1558 PyErr_Format(PyExc_ValueError,
1559 "%s() arg is an empty sequence", name);
1560 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001561 }
1562 else
1563 Py_DECREF(maxval);
1564 Py_DECREF(it);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001565 return maxitem;
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001566
1567Fail_it_item_and_val:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001568 Py_DECREF(val);
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001569Fail_it_item:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001570 Py_DECREF(item);
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001571Fail_it:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001572 Py_XDECREF(maxval);
1573 Py_XDECREF(maxitem);
1574 Py_DECREF(it);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001575 return NULL;
Guido van Rossum3f5da241990-12-20 15:06:42 +00001576}
1577
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001578/* AC: cannot convert yet, waiting for *args support */
Guido van Rossum79f25d91997-04-29 20:08:16 +00001579static PyObject *
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001580builtin_min(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001581{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001582 return min_max(args, kwds, Py_LT);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001583}
1584
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001585PyDoc_STRVAR(min_doc,
Raymond Hettinger2a545822014-05-19 22:20:52 +01001586"min(iterable, *[, default=obj, key=func]) -> value\n\
1587min(arg1, arg2, *args, *[, key=func]) -> value\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001588\n\
Raymond Hettinger2a545822014-05-19 22:20:52 +01001589With a single iterable argument, return its smallest item. The\n\
1590default keyword-only argument specifies an object to return if\n\
1591the provided iterable is empty.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001592With two or more arguments, return the smallest argument.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001593
1594
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001595/* AC: cannot convert yet, waiting for *args support */
Guido van Rossum79f25d91997-04-29 20:08:16 +00001596static PyObject *
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001597builtin_max(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001598{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001599 return min_max(args, kwds, Py_GT);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001600}
1601
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001602PyDoc_STRVAR(max_doc,
Raymond Hettinger2a545822014-05-19 22:20:52 +01001603"max(iterable, *[, default=obj, key=func]) -> value\n\
1604max(arg1, arg2, *args, *[, key=func]) -> value\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001605\n\
Raymond Hettinger2a545822014-05-19 22:20:52 +01001606With a single iterable argument, return its biggest item. The\n\
1607default keyword-only argument specifies an object to return if\n\
1608the provided iterable is empty.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001609With two or more arguments, return the largest argument.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001610
1611
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001612/*[clinic input]
1613oct as builtin_oct
1614
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001615 number: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001616 /
1617
1618Return the octal representation of an integer.
1619
1620 >>> oct(342391)
1621 '0o1234567'
1622[clinic start generated code]*/
1623
Guido van Rossum79f25d91997-04-29 20:08:16 +00001624static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001625builtin_oct(PyObject *module, PyObject *number)
1626/*[clinic end generated code: output=40a34656b6875352 input=ad6b274af4016c72]*/
Guido van Rossum006bcd41991-10-24 14:54:44 +00001627{
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001628 return PyNumber_ToBase(number, 8);
Guido van Rossum006bcd41991-10-24 14:54:44 +00001629}
1630
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001631
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001632/*[clinic input]
1633ord as builtin_ord
1634
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001635 c: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001636 /
1637
1638Return the Unicode code point for a one-character string.
1639[clinic start generated code]*/
1640
Guido van Rossum79f25d91997-04-29 20:08:16 +00001641static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001642builtin_ord(PyObject *module, PyObject *c)
1643/*[clinic end generated code: output=4fa5e87a323bae71 input=3064e5d6203ad012]*/
Guido van Rossum3f5da241990-12-20 15:06:42 +00001644{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001645 long ord;
1646 Py_ssize_t size;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001647
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001648 if (PyBytes_Check(c)) {
1649 size = PyBytes_GET_SIZE(c);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001650 if (size == 1) {
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001651 ord = (long)((unsigned char)*PyBytes_AS_STRING(c));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001652 return PyLong_FromLong(ord);
1653 }
1654 }
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001655 else if (PyUnicode_Check(c)) {
1656 if (PyUnicode_READY(c) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001657 return NULL;
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001658 size = PyUnicode_GET_LENGTH(c);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001659 if (size == 1) {
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001660 ord = (long)PyUnicode_READ_CHAR(c, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001661 return PyLong_FromLong(ord);
1662 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001663 }
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001664 else if (PyByteArray_Check(c)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001665 /* XXX Hopefully this is temporary */
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001666 size = PyByteArray_GET_SIZE(c);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001667 if (size == 1) {
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001668 ord = (long)((unsigned char)*PyByteArray_AS_STRING(c));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001669 return PyLong_FromLong(ord);
1670 }
1671 }
1672 else {
1673 PyErr_Format(PyExc_TypeError,
1674 "ord() expected string of length 1, but " \
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001675 "%.200s found", c->ob_type->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001676 return NULL;
1677 }
Guido van Rossum09095f32000-03-10 23:00:52 +00001678
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001679 PyErr_Format(PyExc_TypeError,
1680 "ord() expected a character, "
1681 "but string of length %zd found",
1682 size);
1683 return NULL;
Guido van Rossum3f5da241990-12-20 15:06:42 +00001684}
1685
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001686
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001687/*[clinic input]
1688pow as builtin_pow
1689
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001690 x: object
1691 y: object
1692 z: object = None
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001693 /
1694
1695Equivalent to x**y (with two arguments) or x**y % z (with three arguments)
1696
1697Some types, such as ints, are able to use a more efficient algorithm when
1698invoked using the three argument form.
1699[clinic start generated code]*/
1700
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001701static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001702builtin_pow_impl(PyObject *module, PyObject *x, PyObject *y, PyObject *z)
1703/*[clinic end generated code: output=50a14d5d130d404b input=653d57d38d41fc07]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001704{
1705 return PyNumber_Power(x, y, z);
1706}
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001707
1708
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001709/* AC: cannot convert yet, waiting for *args support */
Guido van Rossum34343512006-11-30 22:13:52 +00001710static PyObject *
1711builtin_print(PyObject *self, PyObject *args, PyObject *kwds)
1712{
Georg Brandlbc3b6822012-01-13 19:41:25 +01001713 static char *kwlist[] = {"sep", "end", "file", "flush", 0};
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001714 static PyObject *dummy_args;
Georg Brandlbc3b6822012-01-13 19:41:25 +01001715 PyObject *sep = NULL, *end = NULL, *file = NULL, *flush = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001716 int i, err;
Guido van Rossum34343512006-11-30 22:13:52 +00001717
Benjamin Peterson00102562012-01-11 21:00:16 -05001718 if (dummy_args == NULL && !(dummy_args = PyTuple_New(0)))
Georg Brandlbc3b6822012-01-13 19:41:25 +01001719 return NULL;
1720 if (!PyArg_ParseTupleAndKeywords(dummy_args, kwds, "|OOOO:print",
1721 kwlist, &sep, &end, &file, &flush))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001722 return NULL;
1723 if (file == NULL || file == Py_None) {
Victor Stinnerbd303c12013-11-07 23:07:29 +01001724 file = _PySys_GetObjectId(&PyId_stdout);
Victor Stinner1e53bba2013-07-16 22:26:05 +02001725 if (file == NULL) {
1726 PyErr_SetString(PyExc_RuntimeError, "lost sys.stdout");
1727 return NULL;
1728 }
1729
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001730 /* sys.stdout may be None when FILE* stdout isn't connected */
1731 if (file == Py_None)
1732 Py_RETURN_NONE;
1733 }
Guido van Rossum34343512006-11-30 22:13:52 +00001734
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001735 if (sep == Py_None) {
1736 sep = NULL;
1737 }
1738 else if (sep && !PyUnicode_Check(sep)) {
1739 PyErr_Format(PyExc_TypeError,
1740 "sep must be None or a string, not %.200s",
1741 sep->ob_type->tp_name);
1742 return NULL;
1743 }
1744 if (end == Py_None) {
1745 end = NULL;
1746 }
1747 else if (end && !PyUnicode_Check(end)) {
1748 PyErr_Format(PyExc_TypeError,
1749 "end must be None or a string, not %.200s",
1750 end->ob_type->tp_name);
1751 return NULL;
1752 }
Guido van Rossum34343512006-11-30 22:13:52 +00001753
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001754 for (i = 0; i < PyTuple_Size(args); i++) {
1755 if (i > 0) {
1756 if (sep == NULL)
1757 err = PyFile_WriteString(" ", file);
1758 else
1759 err = PyFile_WriteObject(sep, file,
1760 Py_PRINT_RAW);
1761 if (err)
1762 return NULL;
1763 }
1764 err = PyFile_WriteObject(PyTuple_GetItem(args, i), file,
1765 Py_PRINT_RAW);
1766 if (err)
1767 return NULL;
1768 }
Guido van Rossum34343512006-11-30 22:13:52 +00001769
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001770 if (end == NULL)
1771 err = PyFile_WriteString("\n", file);
1772 else
1773 err = PyFile_WriteObject(end, file, Py_PRINT_RAW);
1774 if (err)
1775 return NULL;
Guido van Rossum34343512006-11-30 22:13:52 +00001776
Georg Brandlbc3b6822012-01-13 19:41:25 +01001777 if (flush != NULL) {
1778 PyObject *tmp;
1779 int do_flush = PyObject_IsTrue(flush);
1780 if (do_flush == -1)
1781 return NULL;
1782 else if (do_flush) {
Victor Stinnereaa28832013-11-07 00:01:51 +01001783 tmp = _PyObject_CallMethodId(file, &PyId_flush, "");
Georg Brandlbc3b6822012-01-13 19:41:25 +01001784 if (tmp == NULL)
1785 return NULL;
1786 else
1787 Py_DECREF(tmp);
1788 }
1789 }
1790
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001791 Py_RETURN_NONE;
Guido van Rossum34343512006-11-30 22:13:52 +00001792}
1793
1794PyDoc_STRVAR(print_doc,
Senthil Kumarane9175bd2012-08-10 13:53:45 -07001795"print(value, ..., sep=' ', end='\\n', file=sys.stdout, flush=False)\n\
Guido van Rossum34343512006-11-30 22:13:52 +00001796\n\
1797Prints the values to a stream, or to sys.stdout by default.\n\
1798Optional keyword arguments:\n\
Senthil Kumarane9175bd2012-08-10 13:53:45 -07001799file: a file-like object (stream); defaults to the current sys.stdout.\n\
1800sep: string inserted between values, default a space.\n\
1801end: string appended after the last value, default a newline.\n\
1802flush: whether to forcibly flush the stream.");
Guido van Rossum34343512006-11-30 22:13:52 +00001803
1804
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001805/*[clinic input]
1806input as builtin_input
1807
1808 prompt: object(c_default="NULL") = None
1809 /
1810
1811Read a string from standard input. The trailing newline is stripped.
1812
1813The prompt string, if given, is printed to standard output without a
1814trailing newline before reading input.
1815
1816If the user hits EOF (*nix: Ctrl-D, Windows: Ctrl-Z+Return), raise EOFError.
1817On *nix systems, readline is used if available.
1818[clinic start generated code]*/
1819
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001820static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001821builtin_input_impl(PyObject *module, PyObject *prompt)
1822/*[clinic end generated code: output=83db5a191e7a0d60 input=5e8bb70c2908fe3c]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001823{
Victor Stinnerbd303c12013-11-07 23:07:29 +01001824 PyObject *fin = _PySys_GetObjectId(&PyId_stdin);
1825 PyObject *fout = _PySys_GetObjectId(&PyId_stdout);
1826 PyObject *ferr = _PySys_GetObjectId(&PyId_stderr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001827 PyObject *tmp;
1828 long fd;
1829 int tty;
Guido van Rossuma88a0332007-02-26 16:59:55 +00001830
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001831 /* Check that stdin/out/err are intact */
1832 if (fin == NULL || fin == Py_None) {
1833 PyErr_SetString(PyExc_RuntimeError,
1834 "input(): lost sys.stdin");
1835 return NULL;
1836 }
1837 if (fout == NULL || fout == Py_None) {
1838 PyErr_SetString(PyExc_RuntimeError,
1839 "input(): lost sys.stdout");
1840 return NULL;
1841 }
1842 if (ferr == NULL || ferr == Py_None) {
1843 PyErr_SetString(PyExc_RuntimeError,
1844 "input(): lost sys.stderr");
1845 return NULL;
1846 }
Guido van Rossumeba76962007-05-27 09:13:28 +00001847
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001848 /* First of all, flush stderr */
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001849 tmp = _PyObject_CallMethodId(ferr, &PyId_flush, "");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001850 if (tmp == NULL)
1851 PyErr_Clear();
1852 else
1853 Py_DECREF(tmp);
Guido van Rossumeba76962007-05-27 09:13:28 +00001854
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001855 /* We should only use (GNU) readline if Python's sys.stdin and
1856 sys.stdout are the same as C's stdin and stdout, because we
1857 need to pass it those. */
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001858 tmp = _PyObject_CallMethodId(fin, &PyId_fileno, "");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001859 if (tmp == NULL) {
1860 PyErr_Clear();
1861 tty = 0;
1862 }
1863 else {
1864 fd = PyLong_AsLong(tmp);
1865 Py_DECREF(tmp);
1866 if (fd < 0 && PyErr_Occurred())
1867 return NULL;
1868 tty = fd == fileno(stdin) && isatty(fd);
1869 }
1870 if (tty) {
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001871 tmp = _PyObject_CallMethodId(fout, &PyId_fileno, "");
Martin Panterc9a6ab52015-10-10 01:25:38 +00001872 if (tmp == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001873 PyErr_Clear();
Martin Panterc9a6ab52015-10-10 01:25:38 +00001874 tty = 0;
1875 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001876 else {
1877 fd = PyLong_AsLong(tmp);
1878 Py_DECREF(tmp);
1879 if (fd < 0 && PyErr_Occurred())
1880 return NULL;
1881 tty = fd == fileno(stdout) && isatty(fd);
1882 }
1883 }
Guido van Rossumeba76962007-05-27 09:13:28 +00001884
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001885 /* If we're interactive, use (GNU) readline */
1886 if (tty) {
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001887 PyObject *po = NULL;
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001888 char *promptstr;
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001889 char *s = NULL;
1890 PyObject *stdin_encoding = NULL, *stdin_errors = NULL;
1891 PyObject *stdout_encoding = NULL, *stdout_errors = NULL;
1892 char *stdin_encoding_str, *stdin_errors_str;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001893 PyObject *result;
Victor Stinnerc0f1a1a2011-02-23 12:07:37 +00001894 size_t len;
Martin v. Löwis4a7b5d52007-09-04 05:24:49 +00001895
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02001896 stdin_encoding = _PyObject_GetAttrId(fin, &PyId_encoding);
Antoine Pitrou5ee9d8a2011-11-06 00:38:45 +01001897 stdin_errors = _PyObject_GetAttrId(fin, &PyId_errors);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001898 if (!stdin_encoding || !stdin_errors)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001899 /* stdin is a text stream, so it must have an
1900 encoding. */
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001901 goto _readline_errors;
Victor Stinner306f0102010-05-19 01:06:22 +00001902 stdin_encoding_str = _PyUnicode_AsString(stdin_encoding);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001903 stdin_errors_str = _PyUnicode_AsString(stdin_errors);
1904 if (!stdin_encoding_str || !stdin_errors_str)
1905 goto _readline_errors;
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001906 tmp = _PyObject_CallMethodId(fout, &PyId_flush, "");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001907 if (tmp == NULL)
1908 PyErr_Clear();
1909 else
1910 Py_DECREF(tmp);
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001911 if (prompt != NULL) {
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001912 /* We have a prompt, encode it as stdout would */
1913 char *stdout_encoding_str, *stdout_errors_str;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001914 PyObject *stringpo;
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02001915 stdout_encoding = _PyObject_GetAttrId(fout, &PyId_encoding);
Antoine Pitrou5ee9d8a2011-11-06 00:38:45 +01001916 stdout_errors = _PyObject_GetAttrId(fout, &PyId_errors);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001917 if (!stdout_encoding || !stdout_errors)
1918 goto _readline_errors;
Victor Stinner306f0102010-05-19 01:06:22 +00001919 stdout_encoding_str = _PyUnicode_AsString(stdout_encoding);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001920 stdout_errors_str = _PyUnicode_AsString(stdout_errors);
1921 if (!stdout_encoding_str || !stdout_errors_str)
1922 goto _readline_errors;
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001923 stringpo = PyObject_Str(prompt);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001924 if (stringpo == NULL)
1925 goto _readline_errors;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001926 po = PyUnicode_AsEncodedString(stringpo,
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001927 stdout_encoding_str, stdout_errors_str);
1928 Py_CLEAR(stdout_encoding);
1929 Py_CLEAR(stdout_errors);
1930 Py_CLEAR(stringpo);
1931 if (po == NULL)
1932 goto _readline_errors;
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03001933 assert(PyBytes_Check(po));
1934 promptstr = PyBytes_AS_STRING(po);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001935 }
1936 else {
1937 po = NULL;
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001938 promptstr = "";
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001939 }
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001940 s = PyOS_Readline(stdin, stdout, promptstr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001941 if (s == NULL) {
Richard Oudkerk614c5782013-04-03 13:44:50 +01001942 PyErr_CheckSignals();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001943 if (!PyErr_Occurred())
1944 PyErr_SetNone(PyExc_KeyboardInterrupt);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001945 goto _readline_errors;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001946 }
Victor Stinnerc0f1a1a2011-02-23 12:07:37 +00001947
1948 len = strlen(s);
1949 if (len == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001950 PyErr_SetNone(PyExc_EOFError);
1951 result = NULL;
1952 }
Victor Stinnerc0f1a1a2011-02-23 12:07:37 +00001953 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001954 if (len > PY_SSIZE_T_MAX) {
1955 PyErr_SetString(PyExc_OverflowError,
1956 "input: input too long");
1957 result = NULL;
1958 }
1959 else {
Victor Stinnerc0f1a1a2011-02-23 12:07:37 +00001960 len--; /* strip trailing '\n' */
1961 if (len != 0 && s[len-1] == '\r')
1962 len--; /* strip trailing '\r' */
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001963 result = PyUnicode_Decode(s, len, stdin_encoding_str,
1964 stdin_errors_str);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001965 }
1966 }
1967 Py_DECREF(stdin_encoding);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001968 Py_DECREF(stdin_errors);
1969 Py_XDECREF(po);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001970 PyMem_FREE(s);
1971 return result;
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001972 _readline_errors:
1973 Py_XDECREF(stdin_encoding);
1974 Py_XDECREF(stdout_encoding);
1975 Py_XDECREF(stdin_errors);
1976 Py_XDECREF(stdout_errors);
1977 Py_XDECREF(po);
1978 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001979 }
Guido van Rossumeba76962007-05-27 09:13:28 +00001980
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001981 /* Fallback if we're not interactive */
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001982 if (prompt != NULL) {
1983 if (PyFile_WriteObject(prompt, fout, Py_PRINT_RAW) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001984 return NULL;
1985 }
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001986 tmp = _PyObject_CallMethodId(fout, &PyId_flush, "");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001987 if (tmp == NULL)
1988 PyErr_Clear();
1989 else
1990 Py_DECREF(tmp);
1991 return PyFile_GetLine(fin, -1);
Guido van Rossuma88a0332007-02-26 16:59:55 +00001992}
1993
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001994
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001995/*[clinic input]
1996repr as builtin_repr
1997
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03001998 obj: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10001999 /
2000
2001Return the canonical string representation of the object.
2002
2003For many object types, including most builtins, eval(repr(obj)) == obj.
2004[clinic start generated code]*/
2005
Guido van Rossum79f25d91997-04-29 20:08:16 +00002006static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002007builtin_repr(PyObject *module, PyObject *obj)
2008/*[clinic end generated code: output=7ed3778c44fd0194 input=1c9e6d66d3e3be04]*/
Guido van Rossumc89705d1992-11-26 08:54:07 +00002009{
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002010 return PyObject_Repr(obj);
Guido van Rossumc89705d1992-11-26 08:54:07 +00002011}
2012
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002013
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002014/* AC: cannot convert yet, as needs PEP 457 group support in inspect
2015 * or a semantic change to accept None for "ndigits"
2016 */
Guido van Rossum79f25d91997-04-29 20:08:16 +00002017static PyObject *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002018builtin_round(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum9e51f9b1993-02-12 16:29:05 +00002019{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002020 PyObject *ndigits = NULL;
2021 static char *kwlist[] = {"number", "ndigits", 0};
Benjamin Peterson214a7d22013-04-13 17:19:01 -04002022 PyObject *number, *round, *result;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002023
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002024 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|O:round",
2025 kwlist, &number, &ndigits))
2026 return NULL;
Alex Martelliae211f92007-08-22 23:21:33 +00002027
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002028 if (Py_TYPE(number)->tp_dict == NULL) {
2029 if (PyType_Ready(Py_TYPE(number)) < 0)
2030 return NULL;
2031 }
Guido van Rossum15d3d042007-08-24 02:02:45 +00002032
Benjamin Peterson214a7d22013-04-13 17:19:01 -04002033 round = _PyObject_LookupSpecial(number, &PyId___round__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002034 if (round == NULL) {
Benjamin Peterson214a7d22013-04-13 17:19:01 -04002035 if (!PyErr_Occurred())
2036 PyErr_Format(PyExc_TypeError,
2037 "type %.100s doesn't define __round__ method",
2038 Py_TYPE(number)->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002039 return NULL;
2040 }
Alex Martelliae211f92007-08-22 23:21:33 +00002041
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002042 if (ndigits == NULL)
Benjamin Peterson214a7d22013-04-13 17:19:01 -04002043 result = PyObject_CallFunctionObjArgs(round, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002044 else
Benjamin Peterson214a7d22013-04-13 17:19:01 -04002045 result = PyObject_CallFunctionObjArgs(round, ndigits, NULL);
2046 Py_DECREF(round);
2047 return result;
Guido van Rossum9e51f9b1993-02-12 16:29:05 +00002048}
2049
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002050PyDoc_STRVAR(round_doc,
Mark Dickinson1124e712009-01-28 21:25:58 +00002051"round(number[, ndigits]) -> number\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002052\n\
2053Round a number to a given precision in decimal digits (default 0 digits).\n\
Mark Dickinson0d748c22008-07-05 11:29:03 +00002054This returns an int when called with one argument, otherwise the\n\
Georg Brandl809ddaa2008-07-01 20:39:59 +00002055same type as the number. ndigits may be negative.");
Guido van Rossum2fa33db2007-08-23 22:07:24 +00002056
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002057
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002058/*AC: we need to keep the kwds dict intact to easily call into the
2059 * list.sort method, which isn't currently supported in AC. So we just use
2060 * the initially generated signature with a custom implementation.
2061 */
2062/* [disabled clinic input]
2063sorted as builtin_sorted
2064
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03002065 iterable as seq: object
2066 key as keyfunc: object = None
2067 reverse: object = False
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002068
2069Return a new list containing all items from the iterable in ascending order.
2070
2071A custom key function can be supplied to customise the sort order, and the
2072reverse flag can be set to request the result in descending order.
2073[end disabled clinic input]*/
2074
2075PyDoc_STRVAR(builtin_sorted__doc__,
2076"sorted($module, iterable, key=None, reverse=False)\n"
2077"--\n"
2078"\n"
2079"Return a new list containing all items from the iterable in ascending order.\n"
2080"\n"
2081"A custom key function can be supplied to customise the sort order, and the\n"
2082"reverse flag can be set to request the result in descending order.");
2083
2084#define BUILTIN_SORTED_METHODDEF \
2085 {"sorted", (PyCFunction)builtin_sorted, METH_VARARGS|METH_KEYWORDS, builtin_sorted__doc__},
2086
Raymond Hettinger64958a12003-12-17 20:43:33 +00002087static PyObject *
2088builtin_sorted(PyObject *self, PyObject *args, PyObject *kwds)
2089{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002090 PyObject *newlist, *v, *seq, *keyfunc=NULL, *newargs;
2091 PyObject *callable;
2092 static char *kwlist[] = {"iterable", "key", "reverse", 0};
2093 int reverse;
Raymond Hettinger64958a12003-12-17 20:43:33 +00002094
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002095 /* args 1-3 should match listsort in Objects/listobject.c */
2096 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|Oi:sorted",
2097 kwlist, &seq, &keyfunc, &reverse))
2098 return NULL;
Raymond Hettinger64958a12003-12-17 20:43:33 +00002099
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002100 newlist = PySequence_List(seq);
2101 if (newlist == NULL)
2102 return NULL;
Raymond Hettinger64958a12003-12-17 20:43:33 +00002103
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02002104 callable = _PyObject_GetAttrId(newlist, &PyId_sort);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002105 if (callable == NULL) {
2106 Py_DECREF(newlist);
2107 return NULL;
2108 }
Georg Brandl99d7e4e2005-08-31 22:21:15 +00002109
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002110 newargs = PyTuple_GetSlice(args, 1, 4);
2111 if (newargs == NULL) {
2112 Py_DECREF(newlist);
2113 Py_DECREF(callable);
2114 return NULL;
2115 }
Raymond Hettinger64958a12003-12-17 20:43:33 +00002116
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002117 v = PyObject_Call(callable, newargs, kwds);
2118 Py_DECREF(newargs);
2119 Py_DECREF(callable);
2120 if (v == NULL) {
2121 Py_DECREF(newlist);
2122 return NULL;
2123 }
2124 Py_DECREF(v);
2125 return newlist;
Raymond Hettinger64958a12003-12-17 20:43:33 +00002126}
2127
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002128
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002129/* AC: cannot convert yet, as needs PEP 457 group support in inspect */
Guido van Rossum79f25d91997-04-29 20:08:16 +00002130static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002131builtin_vars(PyObject *self, PyObject *args)
Guido van Rossum2d951851994-08-29 12:52:16 +00002132{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002133 PyObject *v = NULL;
2134 PyObject *d;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002135
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002136 if (!PyArg_UnpackTuple(args, "vars", 0, 1, &v))
2137 return NULL;
2138 if (v == NULL) {
2139 d = PyEval_GetLocals();
Victor Stinner41bb43a2013-10-29 01:19:37 +01002140 if (d == NULL)
2141 return NULL;
2142 Py_INCREF(d);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002143 }
2144 else {
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02002145 d = _PyObject_GetAttrId(v, &PyId___dict__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002146 if (d == NULL) {
2147 PyErr_SetString(PyExc_TypeError,
2148 "vars() argument must have __dict__ attribute");
2149 return NULL;
2150 }
2151 }
2152 return d;
Guido van Rossum2d951851994-08-29 12:52:16 +00002153}
2154
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002155PyDoc_STRVAR(vars_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002156"vars([object]) -> dictionary\n\
2157\n\
2158Without arguments, equivalent to locals().\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002159With an argument, equivalent to object.__dict__.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002160
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002161
2162/*[clinic input]
2163sum as builtin_sum
2164
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03002165 iterable: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002166 start: object(c_default="NULL") = 0
2167 /
2168
2169Return the sum of a 'start' value (default: 0) plus an iterable of numbers
2170
2171When the iterable is empty, return the start value.
2172This function is intended specifically for use with numeric values and may
2173reject non-numeric types.
2174[clinic start generated code]*/
2175
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002176static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002177builtin_sum_impl(PyObject *module, PyObject *iterable, PyObject *start)
2178/*[clinic end generated code: output=df758cec7d1d302f input=3b5b7a9d7611c73a]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002179{
2180 PyObject *result = start;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002181 PyObject *temp, *item, *iter;
Alex Martellia70b1912003-04-22 08:12:33 +00002182
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002183 iter = PyObject_GetIter(iterable);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002184 if (iter == NULL)
2185 return NULL;
Alex Martellia70b1912003-04-22 08:12:33 +00002186
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002187 if (result == NULL) {
2188 result = PyLong_FromLong(0);
2189 if (result == NULL) {
2190 Py_DECREF(iter);
2191 return NULL;
2192 }
2193 } else {
2194 /* reject string values for 'start' parameter */
2195 if (PyUnicode_Check(result)) {
2196 PyErr_SetString(PyExc_TypeError,
2197 "sum() can't sum strings [use ''.join(seq) instead]");
2198 Py_DECREF(iter);
2199 return NULL;
2200 }
Benjamin Petersonce071ca2011-07-29 14:23:47 -05002201 if (PyBytes_Check(result)) {
2202 PyErr_SetString(PyExc_TypeError,
2203 "sum() can't sum bytes [use b''.join(seq) instead]");
Benjamin Peterson405f32c2011-07-29 22:43:45 -05002204 Py_DECREF(iter);
Benjamin Petersonce071ca2011-07-29 14:23:47 -05002205 return NULL;
2206 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002207 if (PyByteArray_Check(result)) {
2208 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson4f921c22011-07-29 14:24:29 -05002209 "sum() can't sum bytearray [use b''.join(seq) instead]");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002210 Py_DECREF(iter);
2211 return NULL;
2212 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002213 Py_INCREF(result);
2214 }
Alex Martellia70b1912003-04-22 08:12:33 +00002215
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002216#ifndef SLOW_SUM
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002217 /* Fast addition by keeping temporary sums in C instead of new Python objects.
2218 Assumes all inputs are the same type. If the assumption fails, default
2219 to the more general routine.
2220 */
2221 if (PyLong_CheckExact(result)) {
2222 int overflow;
2223 long i_result = PyLong_AsLongAndOverflow(result, &overflow);
2224 /* If this already overflowed, don't even enter the loop. */
2225 if (overflow == 0) {
2226 Py_DECREF(result);
2227 result = NULL;
2228 }
2229 while(result == NULL) {
2230 item = PyIter_Next(iter);
2231 if (item == NULL) {
2232 Py_DECREF(iter);
2233 if (PyErr_Occurred())
2234 return NULL;
2235 return PyLong_FromLong(i_result);
2236 }
2237 if (PyLong_CheckExact(item)) {
2238 long b = PyLong_AsLongAndOverflow(item, &overflow);
2239 long x = i_result + b;
2240 if (overflow == 0 && ((x^i_result) >= 0 || (x^b) >= 0)) {
2241 i_result = x;
2242 Py_DECREF(item);
2243 continue;
2244 }
2245 }
2246 /* Either overflowed or is not an int. Restore real objects and process normally */
2247 result = PyLong_FromLong(i_result);
Christian Heimes704e2d32013-07-26 22:49:26 +02002248 if (result == NULL) {
2249 Py_DECREF(item);
2250 Py_DECREF(iter);
2251 return NULL;
2252 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002253 temp = PyNumber_Add(result, item);
2254 Py_DECREF(result);
2255 Py_DECREF(item);
2256 result = temp;
2257 if (result == NULL) {
2258 Py_DECREF(iter);
2259 return NULL;
2260 }
2261 }
2262 }
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002263
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002264 if (PyFloat_CheckExact(result)) {
2265 double f_result = PyFloat_AS_DOUBLE(result);
2266 Py_DECREF(result);
2267 result = NULL;
2268 while(result == NULL) {
2269 item = PyIter_Next(iter);
2270 if (item == NULL) {
2271 Py_DECREF(iter);
2272 if (PyErr_Occurred())
2273 return NULL;
2274 return PyFloat_FromDouble(f_result);
2275 }
2276 if (PyFloat_CheckExact(item)) {
2277 PyFPE_START_PROTECT("add", Py_DECREF(item); Py_DECREF(iter); return 0)
2278 f_result += PyFloat_AS_DOUBLE(item);
2279 PyFPE_END_PROTECT(f_result)
2280 Py_DECREF(item);
2281 continue;
2282 }
2283 if (PyLong_CheckExact(item)) {
2284 long value;
2285 int overflow;
2286 value = PyLong_AsLongAndOverflow(item, &overflow);
2287 if (!overflow) {
2288 PyFPE_START_PROTECT("add", Py_DECREF(item); Py_DECREF(iter); return 0)
2289 f_result += (double)value;
2290 PyFPE_END_PROTECT(f_result)
2291 Py_DECREF(item);
2292 continue;
2293 }
2294 }
2295 result = PyFloat_FromDouble(f_result);
2296 temp = PyNumber_Add(result, item);
2297 Py_DECREF(result);
2298 Py_DECREF(item);
2299 result = temp;
2300 if (result == NULL) {
2301 Py_DECREF(iter);
2302 return NULL;
2303 }
2304 }
2305 }
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002306#endif
2307
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002308 for(;;) {
2309 item = PyIter_Next(iter);
2310 if (item == NULL) {
2311 /* error, or end-of-sequence */
2312 if (PyErr_Occurred()) {
2313 Py_DECREF(result);
2314 result = NULL;
2315 }
2316 break;
2317 }
2318 /* It's tempting to use PyNumber_InPlaceAdd instead of
2319 PyNumber_Add here, to avoid quadratic running time
2320 when doing 'sum(list_of_lists, [])'. However, this
2321 would produce a change in behaviour: a snippet like
Mark Dickinson9acadc52009-10-26 14:19:42 +00002322
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002323 empty = []
2324 sum([[x] for x in range(10)], empty)
Mark Dickinson9acadc52009-10-26 14:19:42 +00002325
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002326 would change the value of empty. */
2327 temp = PyNumber_Add(result, item);
2328 Py_DECREF(result);
2329 Py_DECREF(item);
2330 result = temp;
2331 if (result == NULL)
2332 break;
2333 }
2334 Py_DECREF(iter);
2335 return result;
Alex Martellia70b1912003-04-22 08:12:33 +00002336}
2337
Alex Martellia70b1912003-04-22 08:12:33 +00002338
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002339/*[clinic input]
2340isinstance as builtin_isinstance
2341
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03002342 obj: object
2343 class_or_tuple: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002344 /
2345
2346Return whether an object is an instance of a class or of a subclass thereof.
2347
2348A tuple, as in ``isinstance(x, (A, B, ...))``, may be given as the target to
2349check against. This is equivalent to ``isinstance(x, A) or isinstance(x, B)
2350or ...`` etc.
2351[clinic start generated code]*/
2352
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002353static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002354builtin_isinstance_impl(PyObject *module, PyObject *obj,
Larry Hastings89964c42015-04-14 18:07:59 -04002355 PyObject *class_or_tuple)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002356/*[clinic end generated code: output=6faf01472c13b003 input=ffa743db1daf7549]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002357{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002358 int retval;
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002359
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002360 retval = PyObject_IsInstance(obj, class_or_tuple);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002361 if (retval < 0)
2362 return NULL;
2363 return PyBool_FromLong(retval);
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002364}
2365
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002366
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002367/*[clinic input]
2368issubclass as builtin_issubclass
2369
Serhiy Storchaka7e810a62015-05-30 11:09:35 +03002370 cls: object
2371 class_or_tuple: object
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002372 /
2373
2374Return whether 'cls' is a derived from another class or is the same class.
2375
2376A tuple, as in ``issubclass(x, (A, B, ...))``, may be given as the target to
2377check against. This is equivalent to ``issubclass(x, A) or issubclass(x, B)
2378or ...`` etc.
2379[clinic start generated code]*/
2380
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002381static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002382builtin_issubclass_impl(PyObject *module, PyObject *cls,
Larry Hastings89964c42015-04-14 18:07:59 -04002383 PyObject *class_or_tuple)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002384/*[clinic end generated code: output=358412410cd7a250 input=af5f35e9ceaddaf6]*/
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002385{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002386 int retval;
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002387
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002388 retval = PyObject_IsSubclass(cls, class_or_tuple);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002389 if (retval < 0)
2390 return NULL;
2391 return PyBool_FromLong(retval);
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002392}
2393
2394
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002395typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002396 PyObject_HEAD
2397 Py_ssize_t tuplesize;
2398 PyObject *ittuple; /* tuple of iterators */
2399 PyObject *result;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002400} zipobject;
2401
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002402static PyObject *
2403zip_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
Barry Warsawbd599b52000-08-03 15:45:29 +00002404{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002405 zipobject *lz;
2406 Py_ssize_t i;
2407 PyObject *ittuple; /* tuple of iterators */
2408 PyObject *result;
2409 Py_ssize_t tuplesize = PySequence_Length(args);
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002410
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002411 if (type == &PyZip_Type && !_PyArg_NoKeywords("zip()", kwds))
2412 return NULL;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002413
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002414 /* args must be a tuple */
2415 assert(PyTuple_Check(args));
Barry Warsawbd599b52000-08-03 15:45:29 +00002416
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002417 /* obtain iterators */
2418 ittuple = PyTuple_New(tuplesize);
2419 if (ittuple == NULL)
2420 return NULL;
2421 for (i=0; i < tuplesize; ++i) {
2422 PyObject *item = PyTuple_GET_ITEM(args, i);
2423 PyObject *it = PyObject_GetIter(item);
2424 if (it == NULL) {
2425 if (PyErr_ExceptionMatches(PyExc_TypeError))
2426 PyErr_Format(PyExc_TypeError,
2427 "zip argument #%zd must support iteration",
2428 i+1);
2429 Py_DECREF(ittuple);
2430 return NULL;
2431 }
2432 PyTuple_SET_ITEM(ittuple, i, it);
2433 }
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002434
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002435 /* create a result holder */
2436 result = PyTuple_New(tuplesize);
2437 if (result == NULL) {
2438 Py_DECREF(ittuple);
2439 return NULL;
2440 }
2441 for (i=0 ; i < tuplesize ; i++) {
2442 Py_INCREF(Py_None);
2443 PyTuple_SET_ITEM(result, i, Py_None);
2444 }
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002445
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002446 /* create zipobject structure */
2447 lz = (zipobject *)type->tp_alloc(type, 0);
2448 if (lz == NULL) {
2449 Py_DECREF(ittuple);
2450 Py_DECREF(result);
2451 return NULL;
2452 }
2453 lz->ittuple = ittuple;
2454 lz->tuplesize = tuplesize;
2455 lz->result = result;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002456
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002457 return (PyObject *)lz;
Barry Warsawbd599b52000-08-03 15:45:29 +00002458}
2459
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002460static void
2461zip_dealloc(zipobject *lz)
2462{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002463 PyObject_GC_UnTrack(lz);
2464 Py_XDECREF(lz->ittuple);
2465 Py_XDECREF(lz->result);
2466 Py_TYPE(lz)->tp_free(lz);
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002467}
2468
2469static int
2470zip_traverse(zipobject *lz, visitproc visit, void *arg)
2471{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002472 Py_VISIT(lz->ittuple);
2473 Py_VISIT(lz->result);
2474 return 0;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002475}
2476
2477static PyObject *
2478zip_next(zipobject *lz)
2479{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002480 Py_ssize_t i;
2481 Py_ssize_t tuplesize = lz->tuplesize;
2482 PyObject *result = lz->result;
2483 PyObject *it;
2484 PyObject *item;
2485 PyObject *olditem;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002486
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002487 if (tuplesize == 0)
2488 return NULL;
2489 if (Py_REFCNT(result) == 1) {
2490 Py_INCREF(result);
2491 for (i=0 ; i < tuplesize ; i++) {
2492 it = PyTuple_GET_ITEM(lz->ittuple, i);
2493 item = (*Py_TYPE(it)->tp_iternext)(it);
Serhiy Storchaka278d03b2013-04-06 22:52:34 +03002494 if (item == NULL) {
2495 Py_DECREF(result);
2496 return NULL;
2497 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002498 olditem = PyTuple_GET_ITEM(result, i);
2499 PyTuple_SET_ITEM(result, i, item);
2500 Py_DECREF(olditem);
2501 }
2502 } else {
2503 result = PyTuple_New(tuplesize);
2504 if (result == NULL)
Serhiy Storchaka278d03b2013-04-06 22:52:34 +03002505 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002506 for (i=0 ; i < tuplesize ; i++) {
2507 it = PyTuple_GET_ITEM(lz->ittuple, i);
2508 item = (*Py_TYPE(it)->tp_iternext)(it);
Serhiy Storchaka278d03b2013-04-06 22:52:34 +03002509 if (item == NULL) {
2510 Py_DECREF(result);
2511 return NULL;
2512 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002513 PyTuple_SET_ITEM(result, i, item);
2514 }
2515 }
2516 return result;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002517}
Barry Warsawbd599b52000-08-03 15:45:29 +00002518
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002519static PyObject *
2520zip_reduce(zipobject *lz)
2521{
2522 /* Just recreate the zip with the internal iterator tuple */
2523 return Py_BuildValue("OO", Py_TYPE(lz), lz->ittuple);
2524}
2525
2526static PyMethodDef zip_methods[] = {
2527 {"__reduce__", (PyCFunction)zip_reduce, METH_NOARGS, reduce_doc},
2528 {NULL, NULL} /* sentinel */
2529};
2530
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002531PyDoc_STRVAR(zip_doc,
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002532"zip(iter1 [,iter2 [...]]) --> zip object\n\
Barry Warsawbd599b52000-08-03 15:45:29 +00002533\n\
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002534Return a zip object whose .__next__() method returns a tuple where\n\
2535the i-th element comes from the i-th iterable argument. The .__next__()\n\
2536method continues until the shortest iterable in the argument sequence\n\
Georg Brandlced51db2008-12-04 18:28:38 +00002537is exhausted and then it raises StopIteration.");
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002538
2539PyTypeObject PyZip_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002540 PyVarObject_HEAD_INIT(&PyType_Type, 0)
2541 "zip", /* tp_name */
2542 sizeof(zipobject), /* tp_basicsize */
2543 0, /* tp_itemsize */
2544 /* methods */
2545 (destructor)zip_dealloc, /* tp_dealloc */
2546 0, /* tp_print */
2547 0, /* tp_getattr */
2548 0, /* tp_setattr */
2549 0, /* tp_reserved */
2550 0, /* tp_repr */
2551 0, /* tp_as_number */
2552 0, /* tp_as_sequence */
2553 0, /* tp_as_mapping */
2554 0, /* tp_hash */
2555 0, /* tp_call */
2556 0, /* tp_str */
2557 PyObject_GenericGetAttr, /* tp_getattro */
2558 0, /* tp_setattro */
2559 0, /* tp_as_buffer */
2560 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
2561 Py_TPFLAGS_BASETYPE, /* tp_flags */
2562 zip_doc, /* tp_doc */
2563 (traverseproc)zip_traverse, /* tp_traverse */
2564 0, /* tp_clear */
2565 0, /* tp_richcompare */
2566 0, /* tp_weaklistoffset */
2567 PyObject_SelfIter, /* tp_iter */
2568 (iternextfunc)zip_next, /* tp_iternext */
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002569 zip_methods, /* tp_methods */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002570 0, /* tp_members */
2571 0, /* tp_getset */
2572 0, /* tp_base */
2573 0, /* tp_dict */
2574 0, /* tp_descr_get */
2575 0, /* tp_descr_set */
2576 0, /* tp_dictoffset */
2577 0, /* tp_init */
2578 PyType_GenericAlloc, /* tp_alloc */
2579 zip_new, /* tp_new */
2580 PyObject_GC_Del, /* tp_free */
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002581};
Barry Warsawbd599b52000-08-03 15:45:29 +00002582
2583
Guido van Rossum79f25d91997-04-29 20:08:16 +00002584static PyMethodDef builtin_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002585 {"__build_class__", (PyCFunction)builtin___build_class__,
2586 METH_VARARGS | METH_KEYWORDS, build_class_doc},
2587 {"__import__", (PyCFunction)builtin___import__, METH_VARARGS | METH_KEYWORDS, import_doc},
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002588 BUILTIN_ABS_METHODDEF
2589 BUILTIN_ALL_METHODDEF
2590 BUILTIN_ANY_METHODDEF
2591 BUILTIN_ASCII_METHODDEF
2592 BUILTIN_BIN_METHODDEF
2593 BUILTIN_CALLABLE_METHODDEF
2594 BUILTIN_CHR_METHODDEF
2595 BUILTIN_COMPILE_METHODDEF
2596 BUILTIN_DELATTR_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002597 {"dir", builtin_dir, METH_VARARGS, dir_doc},
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002598 BUILTIN_DIVMOD_METHODDEF
2599 BUILTIN_EVAL_METHODDEF
2600 BUILTIN_EXEC_METHODDEF
2601 BUILTIN_FORMAT_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002602 {"getattr", builtin_getattr, METH_VARARGS, getattr_doc},
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002603 BUILTIN_GLOBALS_METHODDEF
2604 BUILTIN_HASATTR_METHODDEF
2605 BUILTIN_HASH_METHODDEF
2606 BUILTIN_HEX_METHODDEF
2607 BUILTIN_ID_METHODDEF
2608 BUILTIN_INPUT_METHODDEF
2609 BUILTIN_ISINSTANCE_METHODDEF
2610 BUILTIN_ISSUBCLASS_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002611 {"iter", builtin_iter, METH_VARARGS, iter_doc},
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002612 BUILTIN_LEN_METHODDEF
2613 BUILTIN_LOCALS_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002614 {"max", (PyCFunction)builtin_max, METH_VARARGS | METH_KEYWORDS, max_doc},
2615 {"min", (PyCFunction)builtin_min, METH_VARARGS | METH_KEYWORDS, min_doc},
2616 {"next", (PyCFunction)builtin_next, METH_VARARGS, next_doc},
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002617 BUILTIN_OCT_METHODDEF
2618 BUILTIN_ORD_METHODDEF
2619 BUILTIN_POW_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002620 {"print", (PyCFunction)builtin_print, METH_VARARGS | METH_KEYWORDS, print_doc},
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002621 BUILTIN_REPR_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002622 {"round", (PyCFunction)builtin_round, METH_VARARGS | METH_KEYWORDS, round_doc},
Nick Coghlanf9e227e2014-08-17 14:01:19 +10002623 BUILTIN_SETATTR_METHODDEF
2624 BUILTIN_SORTED_METHODDEF
2625 BUILTIN_SUM_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002626 {"vars", builtin_vars, METH_VARARGS, vars_doc},
2627 {NULL, NULL},
Guido van Rossum3f5da241990-12-20 15:06:42 +00002628};
2629
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002630PyDoc_STRVAR(builtin_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002631"Built-in functions, exceptions, and other objects.\n\
2632\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002633Noteworthy: None is the `nil' object; Ellipsis represents `...' in slices.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002634
Martin v. Löwis1a214512008-06-11 05:26:20 +00002635static struct PyModuleDef builtinsmodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002636 PyModuleDef_HEAD_INIT,
2637 "builtins",
2638 builtin_doc,
2639 -1, /* multiple "initialization" just copies the module dict. */
2640 builtin_methods,
2641 NULL,
2642 NULL,
2643 NULL,
2644 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00002645};
2646
2647
Guido van Rossum25ce5661997-08-02 03:10:38 +00002648PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002649_PyBuiltin_Init(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +00002650{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002651 PyObject *mod, *dict, *debug;
Benjamin Peterson42124a72012-10-30 23:41:54 -04002652
2653 if (PyType_Ready(&PyFilter_Type) < 0 ||
2654 PyType_Ready(&PyMap_Type) < 0 ||
2655 PyType_Ready(&PyZip_Type) < 0)
2656 return NULL;
2657
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002658 mod = PyModule_Create(&builtinsmodule);
2659 if (mod == NULL)
2660 return NULL;
2661 dict = PyModule_GetDict(mod);
Tim Peters4b7625e2001-09-13 21:37:17 +00002662
Tim Peters7571a0f2003-03-23 17:52:28 +00002663#ifdef Py_TRACE_REFS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002664 /* "builtins" exposes a number of statically allocated objects
2665 * that, before this code was added in 2.3, never showed up in
2666 * the list of "all objects" maintained by Py_TRACE_REFS. As a
2667 * result, programs leaking references to None and False (etc)
2668 * couldn't be diagnosed by examining sys.getobjects(0).
2669 */
Tim Peters7571a0f2003-03-23 17:52:28 +00002670#define ADD_TO_ALL(OBJECT) _Py_AddToAllObjects((PyObject *)(OBJECT), 0)
2671#else
2672#define ADD_TO_ALL(OBJECT) (void)0
2673#endif
2674
Tim Peters4b7625e2001-09-13 21:37:17 +00002675#define SETBUILTIN(NAME, OBJECT) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002676 if (PyDict_SetItemString(dict, NAME, (PyObject *)OBJECT) < 0) \
2677 return NULL; \
2678 ADD_TO_ALL(OBJECT)
Tim Peters4b7625e2001-09-13 21:37:17 +00002679
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002680 SETBUILTIN("None", Py_None);
2681 SETBUILTIN("Ellipsis", Py_Ellipsis);
2682 SETBUILTIN("NotImplemented", Py_NotImplemented);
2683 SETBUILTIN("False", Py_False);
2684 SETBUILTIN("True", Py_True);
2685 SETBUILTIN("bool", &PyBool_Type);
2686 SETBUILTIN("memoryview", &PyMemoryView_Type);
2687 SETBUILTIN("bytearray", &PyByteArray_Type);
2688 SETBUILTIN("bytes", &PyBytes_Type);
2689 SETBUILTIN("classmethod", &PyClassMethod_Type);
2690 SETBUILTIN("complex", &PyComplex_Type);
2691 SETBUILTIN("dict", &PyDict_Type);
2692 SETBUILTIN("enumerate", &PyEnum_Type);
2693 SETBUILTIN("filter", &PyFilter_Type);
2694 SETBUILTIN("float", &PyFloat_Type);
2695 SETBUILTIN("frozenset", &PyFrozenSet_Type);
2696 SETBUILTIN("property", &PyProperty_Type);
2697 SETBUILTIN("int", &PyLong_Type);
2698 SETBUILTIN("list", &PyList_Type);
2699 SETBUILTIN("map", &PyMap_Type);
2700 SETBUILTIN("object", &PyBaseObject_Type);
2701 SETBUILTIN("range", &PyRange_Type);
2702 SETBUILTIN("reversed", &PyReversed_Type);
2703 SETBUILTIN("set", &PySet_Type);
2704 SETBUILTIN("slice", &PySlice_Type);
2705 SETBUILTIN("staticmethod", &PyStaticMethod_Type);
2706 SETBUILTIN("str", &PyUnicode_Type);
2707 SETBUILTIN("super", &PySuper_Type);
2708 SETBUILTIN("tuple", &PyTuple_Type);
2709 SETBUILTIN("type", &PyType_Type);
2710 SETBUILTIN("zip", &PyZip_Type);
2711 debug = PyBool_FromLong(Py_OptimizeFlag == 0);
2712 if (PyDict_SetItemString(dict, "__debug__", debug) < 0) {
Serhiy Storchakacfdfbb42016-06-18 09:44:03 +03002713 Py_DECREF(debug);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002714 return NULL;
2715 }
Serhiy Storchakacfdfbb42016-06-18 09:44:03 +03002716 Py_DECREF(debug);
Barry Warsaw757af0e1997-08-29 22:13:51 +00002717
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002718 return mod;
Tim Peters7571a0f2003-03-23 17:52:28 +00002719#undef ADD_TO_ALL
Tim Peters4b7625e2001-09-13 21:37:17 +00002720#undef SETBUILTIN
Guido van Rossum3f5da241990-12-20 15:06:42 +00002721}