blob: 745457fed9866a87ecbf003db1b8dd4255587940 [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
Guido van Rossum79f25d91997-04-29 20:08:16 +000049static PyObject *
Guido van Rossum52cc1d82007-03-18 15:41:51 +000050builtin___build_class__(PyObject *self, PyObject *args, PyObject *kwds)
51{
Nick Coghlande31b192011-10-23 22:04:16 +100052 PyObject *func, *name, *bases, *mkw, *meta, *winner, *prep, *ns, *cell;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000053 PyObject *cls = NULL;
Florent Xicluna4d46c2a2011-10-28 15:00:50 +020054 Py_ssize_t nargs;
Nick Coghlande31b192011-10-23 22:04:16 +100055 int isclass;
Guido van Rossum52cc1d82007-03-18 15:41:51 +000056
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000057 assert(args != NULL);
58 if (!PyTuple_Check(args)) {
59 PyErr_SetString(PyExc_TypeError,
60 "__build_class__: args is not a tuple");
61 return NULL;
62 }
63 nargs = PyTuple_GET_SIZE(args);
64 if (nargs < 2) {
65 PyErr_SetString(PyExc_TypeError,
66 "__build_class__: not enough arguments");
67 return NULL;
68 }
69 func = PyTuple_GET_ITEM(args, 0); /* Better be callable */
Benjamin Petersone8e14592013-05-16 14:37:25 -050070 if (!PyFunction_Check(func)) {
71 PyErr_SetString(PyExc_TypeError,
72 "__build__class__: func must be a function");
73 return NULL;
74 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000075 name = PyTuple_GET_ITEM(args, 1);
76 if (!PyUnicode_Check(name)) {
77 PyErr_SetString(PyExc_TypeError,
78 "__build_class__: name is not a string");
79 return NULL;
80 }
81 bases = PyTuple_GetSlice(args, 2, nargs);
82 if (bases == NULL)
83 return NULL;
Guido van Rossum52cc1d82007-03-18 15:41:51 +000084
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000085 if (kwds == NULL) {
86 meta = NULL;
87 mkw = NULL;
88 }
89 else {
90 mkw = PyDict_Copy(kwds); /* Don't modify kwds passed in! */
91 if (mkw == NULL) {
92 Py_DECREF(bases);
93 return NULL;
Guido van Rossum52cc1d82007-03-18 15:41:51 +000094 }
Victor Stinnerae9f1612013-11-06 22:46:51 +010095 meta = _PyDict_GetItemId(mkw, &PyId_metaclass);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000096 if (meta != NULL) {
97 Py_INCREF(meta);
Victor Stinnerae9f1612013-11-06 22:46:51 +010098 if (_PyDict_DelItemId(mkw, &PyId_metaclass) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000099 Py_DECREF(meta);
100 Py_DECREF(mkw);
101 Py_DECREF(bases);
102 return NULL;
103 }
Nick Coghlande31b192011-10-23 22:04:16 +1000104 /* metaclass is explicitly given, check if it's indeed a class */
105 isclass = PyType_Check(meta);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000106 }
107 }
108 if (meta == NULL) {
Nick Coghlande31b192011-10-23 22:04:16 +1000109 /* if there are no bases, use type: */
110 if (PyTuple_GET_SIZE(bases) == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000111 meta = (PyObject *) (&PyType_Type);
Nick Coghlande31b192011-10-23 22:04:16 +1000112 }
113 /* else get the type of the first base */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000114 else {
115 PyObject *base0 = PyTuple_GET_ITEM(bases, 0);
116 meta = (PyObject *) (base0->ob_type);
117 }
118 Py_INCREF(meta);
Nick Coghlande31b192011-10-23 22:04:16 +1000119 isclass = 1; /* meta is really a class */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000120 }
Nick Coghlan9715d262011-10-23 22:36:42 +1000121
Nick Coghlande31b192011-10-23 22:04:16 +1000122 if (isclass) {
123 /* meta is really a class, so check for a more derived
124 metaclass, or possible metaclass conflicts: */
125 winner = (PyObject *)_PyType_CalculateMetaclass((PyTypeObject *)meta,
126 bases);
127 if (winner == NULL) {
128 Py_DECREF(meta);
129 Py_XDECREF(mkw);
130 Py_DECREF(bases);
131 return NULL;
132 }
133 if (winner != meta) {
134 Py_DECREF(meta);
135 meta = winner;
136 Py_INCREF(meta);
137 }
138 }
139 /* else: meta is not a class, so we cannot do the metaclass
140 calculation, so we will use the explicitly given object as it is */
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +0200141 prep = _PyObject_GetAttrId(meta, &PyId___prepare__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000142 if (prep == NULL) {
143 if (PyErr_ExceptionMatches(PyExc_AttributeError)) {
144 PyErr_Clear();
145 ns = PyDict_New();
146 }
147 else {
148 Py_DECREF(meta);
149 Py_XDECREF(mkw);
150 Py_DECREF(bases);
151 return NULL;
152 }
153 }
154 else {
155 PyObject *pargs = PyTuple_Pack(2, name, bases);
156 if (pargs == NULL) {
157 Py_DECREF(prep);
158 Py_DECREF(meta);
159 Py_XDECREF(mkw);
160 Py_DECREF(bases);
161 return NULL;
162 }
163 ns = PyEval_CallObjectWithKeywords(prep, pargs, mkw);
164 Py_DECREF(pargs);
165 Py_DECREF(prep);
166 }
167 if (ns == NULL) {
168 Py_DECREF(meta);
169 Py_XDECREF(mkw);
170 Py_DECREF(bases);
171 return NULL;
172 }
Benjamin Petersone8e14592013-05-16 14:37:25 -0500173 cell = PyEval_EvalCodeEx(PyFunction_GET_CODE(func), PyFunction_GET_GLOBALS(func), ns,
174 NULL, 0, NULL, 0, NULL, 0, NULL,
175 PyFunction_GET_CLOSURE(func));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000176 if (cell != NULL) {
177 PyObject *margs;
178 margs = PyTuple_Pack(3, name, bases, ns);
179 if (margs != NULL) {
180 cls = PyEval_CallObjectWithKeywords(meta, margs, mkw);
181 Py_DECREF(margs);
182 }
Benjamin Peterson8e8fbea2012-06-01 23:57:36 -0700183 if (cls != NULL && PyCell_Check(cell))
184 PyCell_Set(cell, cls);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000185 Py_DECREF(cell);
186 }
187 Py_DECREF(ns);
188 Py_DECREF(meta);
189 Py_XDECREF(mkw);
190 Py_DECREF(bases);
191 return cls;
Guido van Rossum52cc1d82007-03-18 15:41:51 +0000192}
193
194PyDoc_STRVAR(build_class_doc,
195"__build_class__(func, name, *bases, metaclass=None, **kwds) -> class\n\
196\n\
197Internal helper function used by the class statement.");
198
199static PyObject *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000200builtin___import__(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000201{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000202 static char *kwlist[] = {"name", "globals", "locals", "fromlist",
203 "level", 0};
Victor Stinnerfe93faf2011-03-14 15:54:52 -0400204 PyObject *name, *globals = NULL, *locals = NULL, *fromlist = NULL;
Brett Cannonfd074152012-04-14 14:10:13 -0400205 int level = 0;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000206
Victor Stinnerfe93faf2011-03-14 15:54:52 -0400207 if (!PyArg_ParseTupleAndKeywords(args, kwds, "U|OOOi:__import__",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000208 kwlist, &name, &globals, &locals, &fromlist, &level))
209 return NULL;
Victor Stinnerfe93faf2011-03-14 15:54:52 -0400210 return PyImport_ImportModuleLevelObject(name, globals, locals,
211 fromlist, level);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000212}
213
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000214PyDoc_STRVAR(import_doc,
Brett Cannoncb4996a2012-08-06 16:34:44 -0400215"__import__(name, globals=None, locals=None, fromlist=(), level=0) -> module\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000216\n\
Brett Cannon5305a992010-09-27 21:08:38 +0000217Import a module. Because this function is meant for use by the Python\n\
218interpreter and not for general use it is better to use\n\
219importlib.import_module() to programmatically import a module.\n\
220\n\
221The globals argument is only used to determine the context;\n\
222they are not modified. The locals argument is unused. The fromlist\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000223should be a list of names to emulate ``from name import ...'', or an\n\
224empty list to emulate ``import name''.\n\
225When importing a module from a package, note that __import__('A.B', ...)\n\
226returns package A when fromlist is empty, but its submodule B when\n\
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000227fromlist is not empty. Level is used to determine whether to perform \n\
Brett Cannon722d3ae2012-07-30 17:45:54 -0400228absolute or relative imports. 0 is absolute while a positive number\n\
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000229is the number of parent directories to search relative to the current module.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000230
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000231
Guido van Rossum79f25d91997-04-29 20:08:16 +0000232static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000233builtin_abs(PyObject *self, PyObject *v)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000234{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000235 return PyNumber_Absolute(v);
Guido van Rossum3f5da241990-12-20 15:06:42 +0000236}
237
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000238PyDoc_STRVAR(abs_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000239"abs(number) -> number\n\
240\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000241Return the absolute value of the argument.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000242
Raymond Hettinger96229b12005-03-11 06:49:40 +0000243static PyObject *
244builtin_all(PyObject *self, PyObject *v)
245{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000246 PyObject *it, *item;
247 PyObject *(*iternext)(PyObject *);
248 int cmp;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000249
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000250 it = PyObject_GetIter(v);
251 if (it == NULL)
252 return NULL;
253 iternext = *Py_TYPE(it)->tp_iternext;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000254
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000255 for (;;) {
256 item = iternext(it);
257 if (item == NULL)
258 break;
259 cmp = PyObject_IsTrue(item);
260 Py_DECREF(item);
261 if (cmp < 0) {
262 Py_DECREF(it);
263 return NULL;
264 }
265 if (cmp == 0) {
266 Py_DECREF(it);
267 Py_RETURN_FALSE;
268 }
269 }
270 Py_DECREF(it);
271 if (PyErr_Occurred()) {
272 if (PyErr_ExceptionMatches(PyExc_StopIteration))
273 PyErr_Clear();
274 else
275 return NULL;
276 }
277 Py_RETURN_TRUE;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000278}
279
280PyDoc_STRVAR(all_doc,
281"all(iterable) -> bool\n\
282\n\
Ezio Melottib19ed572013-02-15 23:35:14 +0200283Return True if bool(x) is True for all values x in the iterable.\n\
284If the iterable is empty, return True.");
Raymond Hettinger96229b12005-03-11 06:49:40 +0000285
286static PyObject *
287builtin_any(PyObject *self, PyObject *v)
288{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000289 PyObject *it, *item;
290 PyObject *(*iternext)(PyObject *);
291 int cmp;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000292
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000293 it = PyObject_GetIter(v);
294 if (it == NULL)
295 return NULL;
296 iternext = *Py_TYPE(it)->tp_iternext;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000297
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000298 for (;;) {
299 item = iternext(it);
300 if (item == NULL)
301 break;
302 cmp = PyObject_IsTrue(item);
303 Py_DECREF(item);
304 if (cmp < 0) {
305 Py_DECREF(it);
306 return NULL;
307 }
308 if (cmp == 1) {
309 Py_DECREF(it);
310 Py_RETURN_TRUE;
311 }
312 }
313 Py_DECREF(it);
314 if (PyErr_Occurred()) {
315 if (PyErr_ExceptionMatches(PyExc_StopIteration))
316 PyErr_Clear();
317 else
318 return NULL;
319 }
320 Py_RETURN_FALSE;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000321}
322
323PyDoc_STRVAR(any_doc,
324"any(iterable) -> bool\n\
325\n\
Ezio Melottib19ed572013-02-15 23:35:14 +0200326Return True if bool(x) is True for any x in the iterable.\n\
327If the iterable is empty, return False.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000328
Georg Brandl559e5d72008-06-11 18:37:52 +0000329static PyObject *
330builtin_ascii(PyObject *self, PyObject *v)
331{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000332 return PyObject_ASCII(v);
Georg Brandl559e5d72008-06-11 18:37:52 +0000333}
334
335PyDoc_STRVAR(ascii_doc,
336"ascii(object) -> string\n\
337\n\
338As repr(), return a string containing a printable representation of an\n\
339object, but escape the non-ASCII characters in the string returned by\n\
340repr() using \\x, \\u or \\U escapes. This generates a string similar\n\
341to that returned by repr() in Python 2.");
342
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000343
Guido van Rossum79f25d91997-04-29 20:08:16 +0000344static PyObject *
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000345builtin_bin(PyObject *self, PyObject *v)
346{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000347 return PyNumber_ToBase(v, 2);
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000348}
349
350PyDoc_STRVAR(bin_doc,
351"bin(number) -> string\n\
352\n\
Zachary Warea4b7a752013-11-24 01:19:09 -0600353Return the binary representation of an integer.\n\
354\n\
355 >>> bin(2796202)\n\
356 '0b1010101010101010101010'\n\
357");
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000358
359
Antoine Pitroue71362d2010-11-27 22:00:11 +0000360static PyObject *
361builtin_callable(PyObject *self, PyObject *v)
362{
363 return PyBool_FromLong((long)PyCallable_Check(v));
364}
365
366PyDoc_STRVAR(callable_doc,
367"callable(object) -> bool\n\
368\n\
369Return whether the object is callable (i.e., some kind of function).\n\
370Note that classes are callable, as are instances of classes with a\n\
371__call__() method.");
372
373
Raymond Hettinger17301e92008-03-13 00:19:26 +0000374typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000375 PyObject_HEAD
376 PyObject *func;
377 PyObject *it;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000378} filterobject;
379
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000380static PyObject *
Raymond Hettinger17301e92008-03-13 00:19:26 +0000381filter_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
Guido van Rossum12d12c51993-10-26 17:58:25 +0000382{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000383 PyObject *func, *seq;
384 PyObject *it;
385 filterobject *lz;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000386
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000387 if (type == &PyFilter_Type && !_PyArg_NoKeywords("filter()", kwds))
388 return NULL;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000389
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000390 if (!PyArg_UnpackTuple(args, "filter", 2, 2, &func, &seq))
391 return NULL;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000392
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000393 /* Get iterator. */
394 it = PyObject_GetIter(seq);
395 if (it == NULL)
396 return NULL;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000397
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000398 /* create filterobject structure */
399 lz = (filterobject *)type->tp_alloc(type, 0);
400 if (lz == NULL) {
401 Py_DECREF(it);
402 return NULL;
403 }
404 Py_INCREF(func);
405 lz->func = func;
406 lz->it = it;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000407
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000408 return (PyObject *)lz;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000409}
410
411static void
412filter_dealloc(filterobject *lz)
413{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000414 PyObject_GC_UnTrack(lz);
415 Py_XDECREF(lz->func);
416 Py_XDECREF(lz->it);
417 Py_TYPE(lz)->tp_free(lz);
Raymond Hettinger17301e92008-03-13 00:19:26 +0000418}
419
420static int
421filter_traverse(filterobject *lz, visitproc visit, void *arg)
422{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000423 Py_VISIT(lz->it);
424 Py_VISIT(lz->func);
425 return 0;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000426}
427
428static PyObject *
429filter_next(filterobject *lz)
430{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000431 PyObject *item;
432 PyObject *it = lz->it;
433 long ok;
434 PyObject *(*iternext)(PyObject *);
Raymond Hettinger17301e92008-03-13 00:19:26 +0000435
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000436 iternext = *Py_TYPE(it)->tp_iternext;
437 for (;;) {
438 item = iternext(it);
439 if (item == NULL)
440 return NULL;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000441
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000442 if (lz->func == Py_None || lz->func == (PyObject *)&PyBool_Type) {
443 ok = PyObject_IsTrue(item);
444 } else {
445 PyObject *good;
446 good = PyObject_CallFunctionObjArgs(lz->func,
447 item, NULL);
448 if (good == NULL) {
449 Py_DECREF(item);
450 return NULL;
451 }
452 ok = PyObject_IsTrue(good);
453 Py_DECREF(good);
454 }
Antoine Pitrou6f430e42012-08-15 23:18:25 +0200455 if (ok > 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000456 return item;
457 Py_DECREF(item);
Antoine Pitrou6f430e42012-08-15 23:18:25 +0200458 if (ok < 0)
459 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000460 }
Guido van Rossum12d12c51993-10-26 17:58:25 +0000461}
462
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +0000463static PyObject *
464filter_reduce(filterobject *lz)
465{
466 return Py_BuildValue("O(OO)", Py_TYPE(lz), lz->func, lz->it);
467}
468
469PyDoc_STRVAR(reduce_doc, "Return state information for pickling.");
470
471static PyMethodDef filter_methods[] = {
472 {"__reduce__", (PyCFunction)filter_reduce, METH_NOARGS, reduce_doc},
473 {NULL, NULL} /* sentinel */
474};
475
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000476PyDoc_STRVAR(filter_doc,
Georg Brandld11ae5d2008-05-16 13:27:32 +0000477"filter(function or None, iterable) --> filter object\n\
Guido van Rossumc1f779c2007-07-03 08:25:58 +0000478\n\
Georg Brandld11ae5d2008-05-16 13:27:32 +0000479Return an iterator yielding those items of iterable for which function(item)\n\
Raymond Hettinger17301e92008-03-13 00:19:26 +0000480is true. If function is None, return the items that are true.");
481
482PyTypeObject PyFilter_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000483 PyVarObject_HEAD_INIT(&PyType_Type, 0)
484 "filter", /* tp_name */
485 sizeof(filterobject), /* tp_basicsize */
486 0, /* tp_itemsize */
487 /* methods */
488 (destructor)filter_dealloc, /* tp_dealloc */
489 0, /* tp_print */
490 0, /* tp_getattr */
491 0, /* tp_setattr */
492 0, /* tp_reserved */
493 0, /* tp_repr */
494 0, /* tp_as_number */
495 0, /* tp_as_sequence */
496 0, /* tp_as_mapping */
497 0, /* tp_hash */
498 0, /* tp_call */
499 0, /* tp_str */
500 PyObject_GenericGetAttr, /* tp_getattro */
501 0, /* tp_setattro */
502 0, /* tp_as_buffer */
503 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
504 Py_TPFLAGS_BASETYPE, /* tp_flags */
505 filter_doc, /* tp_doc */
506 (traverseproc)filter_traverse, /* tp_traverse */
507 0, /* tp_clear */
508 0, /* tp_richcompare */
509 0, /* tp_weaklistoffset */
510 PyObject_SelfIter, /* tp_iter */
511 (iternextfunc)filter_next, /* tp_iternext */
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +0000512 filter_methods, /* tp_methods */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000513 0, /* tp_members */
514 0, /* tp_getset */
515 0, /* tp_base */
516 0, /* tp_dict */
517 0, /* tp_descr_get */
518 0, /* tp_descr_set */
519 0, /* tp_dictoffset */
520 0, /* tp_init */
521 PyType_GenericAlloc, /* tp_alloc */
522 filter_new, /* tp_new */
523 PyObject_GC_Del, /* tp_free */
Raymond Hettinger17301e92008-03-13 00:19:26 +0000524};
525
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000526
Eric Smith8c663262007-08-25 02:26:07 +0000527static PyObject *
528builtin_format(PyObject *self, PyObject *args)
529{
Christian Heimes94b7d3d2007-12-11 20:20:39 +0000530 PyObject *value;
Eric Smith8fd3eba2008-02-17 19:48:00 +0000531 PyObject *format_spec = NULL;
Eric Smith8c663262007-08-25 02:26:07 +0000532
Eric Smith8fd3eba2008-02-17 19:48:00 +0000533 if (!PyArg_ParseTuple(args, "O|U:format", &value, &format_spec))
Benjamin Petersona12d5c62012-01-03 16:47:22 -0600534 return NULL;
Eric Smith8c663262007-08-25 02:26:07 +0000535
Eric Smith8fd3eba2008-02-17 19:48:00 +0000536 return PyObject_Format(value, format_spec);
Eric Smith8c663262007-08-25 02:26:07 +0000537}
538
Eric Smith8c663262007-08-25 02:26:07 +0000539PyDoc_STRVAR(format_doc,
Eric Smith81936692007-08-31 01:14:01 +0000540"format(value[, format_spec]) -> string\n\
Eric Smith8c663262007-08-25 02:26:07 +0000541\n\
Eric Smith81936692007-08-31 01:14:01 +0000542Returns value.__format__(format_spec)\n\
543format_spec defaults to \"\"");
544
Guido van Rossum7fcf2242007-05-04 17:43:11 +0000545static PyObject *
Walter Dörwalde7efd592007-06-05 20:07:21 +0000546builtin_chr(PyObject *self, PyObject *args)
Guido van Rossum09095f32000-03-10 23:00:52 +0000547{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000548 int x;
Guido van Rossum09095f32000-03-10 23:00:52 +0000549
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000550 if (!PyArg_ParseTuple(args, "i:chr", &x))
551 return NULL;
Fredrik Lundh0dcf67e2001-06-26 20:01:56 +0000552
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000553 return PyUnicode_FromOrdinal(x);
Guido van Rossum09095f32000-03-10 23:00:52 +0000554}
555
Victor Stinner63ab8752011-11-22 03:31:20 +0100556PyDoc_STRVAR(chr_doc,
Guido van Rossum84fc66d2007-05-03 17:18:26 +0000557"chr(i) -> Unicode character\n\
Guido van Rossum09095f32000-03-10 23:00:52 +0000558\n\
Victor Stinner63ab8752011-11-22 03:31:20 +0100559Return a Unicode string of one character with ordinal i; 0 <= i <= 0x10ffff.");
Guido van Rossum09095f32000-03-10 23:00:52 +0000560
561
Guido van Rossumf15a29f2007-05-04 00:41:39 +0000562static char *
Benjamin Petersonf5b52242009-03-02 23:31:26 +0000563source_as_string(PyObject *cmd, char *funcname, char *what, PyCompilerFlags *cf)
Guido van Rossumf15a29f2007-05-04 00:41:39 +0000564{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000565 char *str;
566 Py_ssize_t size;
Guido van Rossumf15a29f2007-05-04 00:41:39 +0000567
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000568 if (PyUnicode_Check(cmd)) {
569 cf->cf_flags |= PyCF_IGNORE_COOKIE;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200570 str = PyUnicode_AsUTF8AndSize(cmd, &size);
571 if (str == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000572 return NULL;
573 }
574 else if (!PyObject_CheckReadBuffer(cmd)) {
575 PyErr_Format(PyExc_TypeError,
576 "%s() arg 1 must be a %s object",
577 funcname, what);
578 return NULL;
579 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200580 else if (PyObject_AsReadBuffer(cmd, (const void **)&str, &size) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000581 return NULL;
582 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200583
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000584 if (strlen(str) != size) {
585 PyErr_SetString(PyExc_TypeError,
586 "source code string cannot contain null bytes");
587 return NULL;
588 }
589 return str;
Guido van Rossumf15a29f2007-05-04 00:41:39 +0000590}
591
Guido van Rossum79f25d91997-04-29 20:08:16 +0000592static PyObject *
Guido van Rossumd8faa362007-04-27 19:54:29 +0000593builtin_compile(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum5b722181993-03-30 17:46:03 +0000594{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000595 char *str;
Victor Stinner14e461d2013-08-26 22:28:21 +0200596 PyObject *filename;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000597 char *startstr;
598 int mode = -1;
599 int dont_inherit = 0;
600 int supplied_flags = 0;
Georg Brandl8334fd92010-12-04 10:26:46 +0000601 int optimize = -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000602 int is_ast;
603 PyCompilerFlags cf;
604 PyObject *cmd;
605 static char *kwlist[] = {"source", "filename", "mode", "flags",
Georg Brandl8334fd92010-12-04 10:26:46 +0000606 "dont_inherit", "optimize", NULL};
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000607 int start[] = {Py_file_input, Py_eval_input, Py_single_input};
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000608 PyObject *result;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000609
Georg Brandl8334fd92010-12-04 10:26:46 +0000610 if (!PyArg_ParseTupleAndKeywords(args, kwds, "OO&s|iii:compile", kwlist,
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000611 &cmd,
Victor Stinner14e461d2013-08-26 22:28:21 +0200612 PyUnicode_FSDecoder, &filename,
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000613 &startstr, &supplied_flags,
Georg Brandl8334fd92010-12-04 10:26:46 +0000614 &dont_inherit, &optimize))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000615 return NULL;
Tim Peters6cd6a822001-08-17 22:11:27 +0000616
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000617 cf.cf_flags = supplied_flags | PyCF_SOURCE_IS_UTF8;
Just van Rossum3aaf42c2003-02-10 08:21:10 +0000618
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000619 if (supplied_flags &
620 ~(PyCF_MASK | PyCF_MASK_OBSOLETE | PyCF_DONT_IMPLY_DEDENT | PyCF_ONLY_AST))
621 {
622 PyErr_SetString(PyExc_ValueError,
623 "compile(): unrecognised flags");
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000624 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000625 }
626 /* XXX Warn if (supplied_flags & PyCF_MASK_OBSOLETE) != 0? */
Tim Peters6cd6a822001-08-17 22:11:27 +0000627
Georg Brandl8334fd92010-12-04 10:26:46 +0000628 if (optimize < -1 || optimize > 2) {
629 PyErr_SetString(PyExc_ValueError,
630 "compile(): invalid optimize value");
631 goto error;
632 }
633
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000634 if (!dont_inherit) {
635 PyEval_MergeCompilerFlags(&cf);
636 }
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000637
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000638 if (strcmp(startstr, "exec") == 0)
639 mode = 0;
640 else if (strcmp(startstr, "eval") == 0)
641 mode = 1;
642 else if (strcmp(startstr, "single") == 0)
643 mode = 2;
644 else {
645 PyErr_SetString(PyExc_ValueError,
646 "compile() arg 3 must be 'exec', 'eval' or 'single'");
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000647 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000648 }
Neal Norwitzdb4115f2008-03-31 04:20:05 +0000649
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000650 is_ast = PyAST_Check(cmd);
651 if (is_ast == -1)
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000652 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000653 if (is_ast) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000654 if (supplied_flags & PyCF_ONLY_AST) {
655 Py_INCREF(cmd);
656 result = cmd;
657 }
658 else {
659 PyArena *arena;
660 mod_ty mod;
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000661
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000662 arena = PyArena_New();
Stefan Krah07795df2012-08-20 17:19:50 +0200663 if (arena == NULL)
664 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000665 mod = PyAST_obj2mod(cmd, arena, mode);
666 if (mod == NULL) {
667 PyArena_Free(arena);
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000668 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000669 }
Benjamin Peterson832bfe22011-08-09 16:15:04 -0500670 if (!PyAST_Validate(mod)) {
671 PyArena_Free(arena);
672 goto error;
673 }
Victor Stinner14e461d2013-08-26 22:28:21 +0200674 result = (PyObject*)PyAST_CompileObject(mod, filename,
675 &cf, optimize, arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000676 PyArena_Free(arena);
677 }
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000678 goto finally;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000679 }
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000680
Philip Jenveyf76f0ee2012-12-13 15:44:18 -0800681 str = source_as_string(cmd, "compile", "string, bytes or AST", &cf);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000682 if (str == NULL)
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000683 goto error;
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000684
Victor Stinner14e461d2013-08-26 22:28:21 +0200685 result = Py_CompileStringObject(str, filename, start[mode], &cf, optimize);
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000686 goto finally;
687
688error:
689 result = NULL;
690finally:
Victor Stinner14e461d2013-08-26 22:28:21 +0200691 Py_DECREF(filename);
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000692 return result;
Guido van Rossum5b722181993-03-30 17:46:03 +0000693}
694
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000695PyDoc_STRVAR(compile_doc,
Tim Peters6cd6a822001-08-17 22:11:27 +0000696"compile(source, filename, mode[, flags[, dont_inherit]]) -> code object\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000697\n\
Benjamin Peterson933142a2013-12-06 20:12:39 -0500698Compile the source (a Python module, statement or expression)\n\
Georg Brandl7cae87c2006-09-06 06:51:57 +0000699into a code object that can be executed by exec() or eval().\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000700The filename will be used for run-time error messages.\n\
701The mode must be 'exec' to compile a module, 'single' to compile a\n\
Tim Peters6cd6a822001-08-17 22:11:27 +0000702single (interactive) statement, or 'eval' to compile an expression.\n\
703The flags argument, if present, controls which future statements influence\n\
704the compilation of the code.\n\
705The dont_inherit argument, if non-zero, stops the compilation inheriting\n\
706the effects of any future statements in effect in the code calling\n\
707compile; if absent or zero these statements do influence the compilation,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000708in addition to any features explicitly specified.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000709
Guido van Rossum79f25d91997-04-29 20:08:16 +0000710static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000711builtin_dir(PyObject *self, PyObject *args)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000712{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000713 PyObject *arg = NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000714
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000715 if (!PyArg_UnpackTuple(args, "dir", 0, 1, &arg))
716 return NULL;
717 return PyObject_Dir(arg);
Guido van Rossum3f5da241990-12-20 15:06:42 +0000718}
719
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000720PyDoc_STRVAR(dir_doc,
Tim Peters5d2b77c2001-09-03 05:47:38 +0000721"dir([object]) -> list of strings\n"
722"\n"
Georg Brandle32b4222007-03-10 22:13:27 +0000723"If called without an argument, return the names in the current scope.\n"
724"Else, return an alphabetized list of names comprising (some of) the attributes\n"
725"of the given object, and of attributes reachable from it.\n"
726"If the object supplies a method named __dir__, it will be used; otherwise\n"
727"the default dir() logic is used and returns:\n"
728" for a module object: the module's attributes.\n"
729" for a class object: its attributes, and recursively the attributes\n"
730" of its bases.\n"
Guido van Rossumd8faa362007-04-27 19:54:29 +0000731" for any other object: its attributes, its class's attributes, and\n"
Georg Brandle32b4222007-03-10 22:13:27 +0000732" recursively the attributes of its class's base classes.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000733
Guido van Rossum79f25d91997-04-29 20:08:16 +0000734static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000735builtin_divmod(PyObject *self, PyObject *args)
Guido van Rossum6a00cd81995-01-07 12:39:01 +0000736{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000737 PyObject *v, *w;
Guido van Rossum6a00cd81995-01-07 12:39:01 +0000738
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000739 if (!PyArg_UnpackTuple(args, "divmod", 2, 2, &v, &w))
740 return NULL;
741 return PyNumber_Divmod(v, w);
Guido van Rossum3f5da241990-12-20 15:06:42 +0000742}
743
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000744PyDoc_STRVAR(divmod_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000745"divmod(x, y) -> (div, mod)\n\
746\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000747Return the tuple ((x-x%y)/y, x%y). Invariant: div*y + mod == x.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000748
749
Guido van Rossum79f25d91997-04-29 20:08:16 +0000750static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000751builtin_eval(PyObject *self, PyObject *args)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000752{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000753 PyObject *cmd, *result, *tmp = NULL;
754 PyObject *globals = Py_None, *locals = Py_None;
755 char *str;
756 PyCompilerFlags cf;
Guido van Rossum590baa41993-11-30 13:40:46 +0000757
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000758 if (!PyArg_UnpackTuple(args, "eval", 1, 3, &cmd, &globals, &locals))
759 return NULL;
760 if (locals != Py_None && !PyMapping_Check(locals)) {
761 PyErr_SetString(PyExc_TypeError, "locals must be a mapping");
762 return NULL;
763 }
764 if (globals != Py_None && !PyDict_Check(globals)) {
765 PyErr_SetString(PyExc_TypeError, PyMapping_Check(globals) ?
766 "globals must be a real dict; try eval(expr, {}, mapping)"
767 : "globals must be a dict");
768 return NULL;
769 }
770 if (globals == Py_None) {
771 globals = PyEval_GetGlobals();
Victor Stinner41bb43a2013-10-29 01:19:37 +0100772 if (locals == Py_None) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000773 locals = PyEval_GetLocals();
Victor Stinner41bb43a2013-10-29 01:19:37 +0100774 if (locals == NULL)
775 return NULL;
776 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000777 }
778 else if (locals == Py_None)
779 locals = globals;
Tim Peters9fa96be2001-08-17 23:04:59 +0000780
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000781 if (globals == NULL || locals == NULL) {
782 PyErr_SetString(PyExc_TypeError,
783 "eval must be given globals and locals "
784 "when called without a frame");
785 return NULL;
786 }
Georg Brandl77c85e62005-09-15 10:46:13 +0000787
Victor Stinnerb44562b2013-11-06 19:03:11 +0100788 if (_PyDict_GetItemId(globals, &PyId___builtins__) == NULL) {
789 if (_PyDict_SetItemId(globals, &PyId___builtins__,
790 PyEval_GetBuiltins()) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000791 return NULL;
792 }
Tim Peters9fa96be2001-08-17 23:04:59 +0000793
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000794 if (PyCode_Check(cmd)) {
795 if (PyCode_GetNumFree((PyCodeObject *)cmd) > 0) {
796 PyErr_SetString(PyExc_TypeError,
797 "code object passed to eval() may not contain free variables");
798 return NULL;
799 }
Martin v. Löwis4d0d4712010-12-03 20:14:31 +0000800 return PyEval_EvalCode(cmd, globals, locals);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000801 }
Tim Peters9fa96be2001-08-17 23:04:59 +0000802
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000803 cf.cf_flags = PyCF_SOURCE_IS_UTF8;
804 str = source_as_string(cmd, "eval", "string, bytes or code", &cf);
805 if (str == NULL)
806 return NULL;
Just van Rossum3aaf42c2003-02-10 08:21:10 +0000807
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000808 while (*str == ' ' || *str == '\t')
809 str++;
Tim Peters9fa96be2001-08-17 23:04:59 +0000810
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000811 (void)PyEval_MergeCompilerFlags(&cf);
812 result = PyRun_StringFlags(str, Py_eval_input, globals, locals, &cf);
813 Py_XDECREF(tmp);
814 return result;
Guido van Rossum3f5da241990-12-20 15:06:42 +0000815}
816
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000817PyDoc_STRVAR(eval_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000818"eval(source[, globals[, locals]]) -> value\n\
819\n\
820Evaluate the source in the context of globals and locals.\n\
821The source may be a string representing a Python expression\n\
822or a code object as returned by compile().\n\
Thomas Wouters89f507f2006-12-13 04:49:30 +0000823The globals must be a dictionary and locals can be any mapping,\n\
Raymond Hettinger214b1c32004-07-02 06:41:07 +0000824defaulting to the current globals and locals.\n\
825If only globals is given, locals defaults to it.\n");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000826
Georg Brandl7cae87c2006-09-06 06:51:57 +0000827static PyObject *
828builtin_exec(PyObject *self, PyObject *args)
829{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000830 PyObject *v;
831 PyObject *prog, *globals = Py_None, *locals = Py_None;
Georg Brandl7cae87c2006-09-06 06:51:57 +0000832
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000833 if (!PyArg_UnpackTuple(args, "exec", 1, 3, &prog, &globals, &locals))
834 return NULL;
Georg Brandl2cabc562008-08-28 07:57:16 +0000835
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000836 if (globals == Py_None) {
837 globals = PyEval_GetGlobals();
838 if (locals == Py_None) {
839 locals = PyEval_GetLocals();
Victor Stinner41bb43a2013-10-29 01:19:37 +0100840 if (locals == NULL)
841 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000842 }
843 if (!globals || !locals) {
844 PyErr_SetString(PyExc_SystemError,
845 "globals and locals cannot be NULL");
846 return NULL;
847 }
848 }
849 else if (locals == Py_None)
850 locals = globals;
Georg Brandl7cae87c2006-09-06 06:51:57 +0000851
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000852 if (!PyDict_Check(globals)) {
853 PyErr_Format(PyExc_TypeError, "exec() arg 2 must be a dict, not %.100s",
854 globals->ob_type->tp_name);
855 return NULL;
856 }
857 if (!PyMapping_Check(locals)) {
858 PyErr_Format(PyExc_TypeError,
859 "arg 3 must be a mapping or None, not %.100s",
860 locals->ob_type->tp_name);
861 return NULL;
862 }
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 }
868
869 if (PyCode_Check(prog)) {
870 if (PyCode_GetNumFree((PyCodeObject *)prog) > 0) {
871 PyErr_SetString(PyExc_TypeError,
872 "code object passed to exec() may not "
873 "contain free variables");
874 return NULL;
875 }
Martin v. Löwis4d0d4712010-12-03 20:14:31 +0000876 v = PyEval_EvalCode(prog, globals, locals);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000877 }
878 else {
879 char *str;
880 PyCompilerFlags cf;
881 cf.cf_flags = PyCF_SOURCE_IS_UTF8;
882 str = source_as_string(prog, "exec",
883 "string, bytes or code", &cf);
884 if (str == NULL)
885 return NULL;
886 if (PyEval_MergeCompilerFlags(&cf))
887 v = PyRun_StringFlags(str, Py_file_input, globals,
888 locals, &cf);
889 else
890 v = PyRun_String(str, Py_file_input, globals, locals);
891 }
892 if (v == NULL)
893 return NULL;
894 Py_DECREF(v);
895 Py_RETURN_NONE;
Georg Brandl7cae87c2006-09-06 06:51:57 +0000896}
897
898PyDoc_STRVAR(exec_doc,
899"exec(object[, globals[, locals]])\n\
900\n\
Mark Dickinson480e8e32009-12-19 21:19:35 +0000901Read and execute code from an object, which can be a string or a code\n\
Benjamin Peterson38090262009-01-04 15:30:39 +0000902object.\n\
Georg Brandl7cae87c2006-09-06 06:51:57 +0000903The globals and locals are dictionaries, defaulting to the current\n\
904globals and locals. If only globals is given, locals defaults to it.");
905
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000906
Guido van Rossum79f25d91997-04-29 20:08:16 +0000907static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000908builtin_getattr(PyObject *self, PyObject *args)
Guido van Rossum33894be1992-01-27 16:53:09 +0000909{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000910 PyObject *v, *result, *dflt = NULL;
911 PyObject *name;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000912
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000913 if (!PyArg_UnpackTuple(args, "getattr", 2, 3, &v, &name, &dflt))
914 return NULL;
Martin v. Löwis5b222132007-06-10 09:51:05 +0000915
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000916 if (!PyUnicode_Check(name)) {
917 PyErr_SetString(PyExc_TypeError,
918 "getattr(): attribute name must be string");
919 return NULL;
920 }
921 result = PyObject_GetAttr(v, name);
922 if (result == NULL && dflt != NULL &&
923 PyErr_ExceptionMatches(PyExc_AttributeError))
924 {
925 PyErr_Clear();
926 Py_INCREF(dflt);
927 result = dflt;
928 }
929 return result;
Guido van Rossum9bfef441993-03-29 10:43:31 +0000930}
931
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000932PyDoc_STRVAR(getattr_doc,
Guido van Rossum950ff291998-06-29 13:38:57 +0000933"getattr(object, name[, default]) -> value\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000934\n\
Guido van Rossum950ff291998-06-29 13:38:57 +0000935Get a named attribute from an object; getattr(x, 'y') is equivalent to x.y.\n\
936When a default argument is given, it is returned when the attribute doesn't\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000937exist; without it, an exception is raised in that case.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000938
939
Guido van Rossum79f25d91997-04-29 20:08:16 +0000940static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000941builtin_globals(PyObject *self)
Guido van Rossum872537c1995-07-07 22:43:42 +0000942{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000943 PyObject *d;
Guido van Rossum872537c1995-07-07 22:43:42 +0000944
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000945 d = PyEval_GetGlobals();
946 Py_XINCREF(d);
947 return d;
Guido van Rossum872537c1995-07-07 22:43:42 +0000948}
949
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000950PyDoc_STRVAR(globals_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000951"globals() -> dictionary\n\
952\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000953Return the dictionary containing the current scope's global variables.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000954
955
Guido van Rossum79f25d91997-04-29 20:08:16 +0000956static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000957builtin_hasattr(PyObject *self, PyObject *args)
Guido van Rossum9bfef441993-03-29 10:43:31 +0000958{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000959 PyObject *v;
960 PyObject *name;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000961
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000962 if (!PyArg_UnpackTuple(args, "hasattr", 2, 2, &v, &name))
963 return NULL;
964 if (!PyUnicode_Check(name)) {
965 PyErr_SetString(PyExc_TypeError,
966 "hasattr(): attribute name must be string");
967 return NULL;
968 }
969 v = PyObject_GetAttr(v, name);
970 if (v == NULL) {
Benjamin Peterson17689992010-08-24 03:26:23 +0000971 if (PyErr_ExceptionMatches(PyExc_AttributeError)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000972 PyErr_Clear();
Benjamin Peterson17689992010-08-24 03:26:23 +0000973 Py_RETURN_FALSE;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000974 }
Benjamin Peterson17689992010-08-24 03:26:23 +0000975 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000976 }
977 Py_DECREF(v);
Benjamin Peterson17689992010-08-24 03:26:23 +0000978 Py_RETURN_TRUE;
Guido van Rossum33894be1992-01-27 16:53:09 +0000979}
980
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000981PyDoc_STRVAR(hasattr_doc,
Guido van Rossum77f6a652002-04-03 22:41:51 +0000982"hasattr(object, name) -> bool\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000983\n\
984Return whether the object has an attribute with the given name.\n\
Benjamin Peterson17689992010-08-24 03:26:23 +0000985(This is done by calling getattr(object, name) and catching AttributeError.)");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000986
987
Guido van Rossum79f25d91997-04-29 20:08:16 +0000988static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000989builtin_id(PyObject *self, PyObject *v)
Guido van Rossum5b722181993-03-30 17:46:03 +0000990{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000991 return PyLong_FromVoidPtr(v);
Guido van Rossum5b722181993-03-30 17:46:03 +0000992}
993
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000994PyDoc_STRVAR(id_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000995"id(object) -> integer\n\
996\n\
997Return the identity of an object. This is guaranteed to be unique among\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000998simultaneously existing objects. (Hint: it's the object's memory address.)");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000999
1000
Raymond Hettingera6c60372008-03-13 01:26:19 +00001001/* map object ************************************************************/
1002
1003typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001004 PyObject_HEAD
1005 PyObject *iters;
1006 PyObject *func;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001007} mapobject;
1008
Guido van Rossum79f25d91997-04-29 20:08:16 +00001009static PyObject *
Raymond Hettingera6c60372008-03-13 01:26:19 +00001010map_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
Guido van Rossum12d12c51993-10-26 17:58:25 +00001011{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001012 PyObject *it, *iters, *func;
1013 mapobject *lz;
1014 Py_ssize_t numargs, i;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001015
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001016 if (type == &PyMap_Type && !_PyArg_NoKeywords("map()", kwds))
1017 return NULL;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001018
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001019 numargs = PyTuple_Size(args);
1020 if (numargs < 2) {
1021 PyErr_SetString(PyExc_TypeError,
1022 "map() must have at least two arguments.");
1023 return NULL;
1024 }
Raymond Hettingera6c60372008-03-13 01:26:19 +00001025
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001026 iters = PyTuple_New(numargs-1);
1027 if (iters == NULL)
1028 return NULL;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001029
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001030 for (i=1 ; i<numargs ; i++) {
1031 /* Get iterator. */
1032 it = PyObject_GetIter(PyTuple_GET_ITEM(args, i));
1033 if (it == NULL) {
1034 Py_DECREF(iters);
1035 return NULL;
1036 }
1037 PyTuple_SET_ITEM(iters, i-1, it);
1038 }
Raymond Hettingera6c60372008-03-13 01:26:19 +00001039
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001040 /* create mapobject structure */
1041 lz = (mapobject *)type->tp_alloc(type, 0);
1042 if (lz == NULL) {
1043 Py_DECREF(iters);
1044 return NULL;
1045 }
1046 lz->iters = iters;
1047 func = PyTuple_GET_ITEM(args, 0);
1048 Py_INCREF(func);
1049 lz->func = func;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001050
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001051 return (PyObject *)lz;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001052}
1053
1054static void
1055map_dealloc(mapobject *lz)
1056{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001057 PyObject_GC_UnTrack(lz);
1058 Py_XDECREF(lz->iters);
1059 Py_XDECREF(lz->func);
1060 Py_TYPE(lz)->tp_free(lz);
Raymond Hettingera6c60372008-03-13 01:26:19 +00001061}
1062
1063static int
1064map_traverse(mapobject *lz, visitproc visit, void *arg)
1065{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001066 Py_VISIT(lz->iters);
1067 Py_VISIT(lz->func);
1068 return 0;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001069}
1070
1071static PyObject *
1072map_next(mapobject *lz)
1073{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001074 PyObject *val;
1075 PyObject *argtuple;
1076 PyObject *result;
1077 Py_ssize_t numargs, i;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001078
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001079 numargs = PyTuple_Size(lz->iters);
1080 argtuple = PyTuple_New(numargs);
1081 if (argtuple == NULL)
1082 return NULL;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001083
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001084 for (i=0 ; i<numargs ; i++) {
1085 val = PyIter_Next(PyTuple_GET_ITEM(lz->iters, i));
1086 if (val == NULL) {
1087 Py_DECREF(argtuple);
1088 return NULL;
1089 }
1090 PyTuple_SET_ITEM(argtuple, i, val);
1091 }
1092 result = PyObject_Call(lz->func, argtuple, NULL);
1093 Py_DECREF(argtuple);
1094 return result;
Guido van Rossum12d12c51993-10-26 17:58:25 +00001095}
1096
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001097static PyObject *
1098map_reduce(mapobject *lz)
1099{
1100 Py_ssize_t numargs = PyTuple_GET_SIZE(lz->iters);
1101 PyObject *args = PyTuple_New(numargs+1);
1102 Py_ssize_t i;
1103 if (args == NULL)
1104 return NULL;
1105 Py_INCREF(lz->func);
1106 PyTuple_SET_ITEM(args, 0, lz->func);
1107 for (i = 0; i<numargs; i++){
1108 PyObject *it = PyTuple_GET_ITEM(lz->iters, i);
1109 Py_INCREF(it);
1110 PyTuple_SET_ITEM(args, i+1, it);
1111 }
1112
1113 return Py_BuildValue("ON", Py_TYPE(lz), args);
1114}
1115
1116static PyMethodDef map_methods[] = {
1117 {"__reduce__", (PyCFunction)map_reduce, METH_NOARGS, reduce_doc},
1118 {NULL, NULL} /* sentinel */
1119};
1120
1121
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001122PyDoc_STRVAR(map_doc,
Raymond Hettingera6c60372008-03-13 01:26:19 +00001123"map(func, *iterables) --> map object\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001124\n\
Raymond Hettingera6c60372008-03-13 01:26:19 +00001125Make an iterator that computes the function using arguments from\n\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001126each of the iterables. Stops when the shortest iterable is exhausted.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001127
Raymond Hettingera6c60372008-03-13 01:26:19 +00001128PyTypeObject PyMap_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001129 PyVarObject_HEAD_INIT(&PyType_Type, 0)
1130 "map", /* tp_name */
1131 sizeof(mapobject), /* tp_basicsize */
1132 0, /* tp_itemsize */
1133 /* methods */
1134 (destructor)map_dealloc, /* tp_dealloc */
1135 0, /* tp_print */
1136 0, /* tp_getattr */
1137 0, /* tp_setattr */
1138 0, /* tp_reserved */
1139 0, /* tp_repr */
1140 0, /* tp_as_number */
1141 0, /* tp_as_sequence */
1142 0, /* tp_as_mapping */
1143 0, /* tp_hash */
1144 0, /* tp_call */
1145 0, /* tp_str */
1146 PyObject_GenericGetAttr, /* tp_getattro */
1147 0, /* tp_setattro */
1148 0, /* tp_as_buffer */
1149 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
1150 Py_TPFLAGS_BASETYPE, /* tp_flags */
1151 map_doc, /* tp_doc */
1152 (traverseproc)map_traverse, /* tp_traverse */
1153 0, /* tp_clear */
1154 0, /* tp_richcompare */
1155 0, /* tp_weaklistoffset */
1156 PyObject_SelfIter, /* tp_iter */
1157 (iternextfunc)map_next, /* tp_iternext */
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001158 map_methods, /* tp_methods */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001159 0, /* tp_members */
1160 0, /* tp_getset */
1161 0, /* tp_base */
1162 0, /* tp_dict */
1163 0, /* tp_descr_get */
1164 0, /* tp_descr_set */
1165 0, /* tp_dictoffset */
1166 0, /* tp_init */
1167 PyType_GenericAlloc, /* tp_alloc */
1168 map_new, /* tp_new */
1169 PyObject_GC_Del, /* tp_free */
Raymond Hettingera6c60372008-03-13 01:26:19 +00001170};
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001171
Guido van Rossum79f25d91997-04-29 20:08:16 +00001172static PyObject *
Georg Brandla18af4e2007-04-21 15:47:16 +00001173builtin_next(PyObject *self, PyObject *args)
1174{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001175 PyObject *it, *res;
1176 PyObject *def = NULL;
Georg Brandla18af4e2007-04-21 15:47:16 +00001177
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001178 if (!PyArg_UnpackTuple(args, "next", 1, 2, &it, &def))
1179 return NULL;
1180 if (!PyIter_Check(it)) {
1181 PyErr_Format(PyExc_TypeError,
Philip Jenvey50add042011-11-06 16:37:52 -08001182 "'%.200s' object is not an iterator",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001183 it->ob_type->tp_name);
1184 return NULL;
1185 }
1186
1187 res = (*it->ob_type->tp_iternext)(it);
1188 if (res != NULL) {
1189 return res;
1190 } else if (def != NULL) {
1191 if (PyErr_Occurred()) {
1192 if(!PyErr_ExceptionMatches(PyExc_StopIteration))
1193 return NULL;
1194 PyErr_Clear();
1195 }
1196 Py_INCREF(def);
1197 return def;
1198 } else if (PyErr_Occurred()) {
1199 return NULL;
1200 } else {
1201 PyErr_SetNone(PyExc_StopIteration);
1202 return NULL;
1203 }
Georg Brandla18af4e2007-04-21 15:47:16 +00001204}
1205
1206PyDoc_STRVAR(next_doc,
1207"next(iterator[, default])\n\
1208\n\
1209Return the next item from the iterator. If default is given and the iterator\n\
1210is exhausted, it is returned instead of raising StopIteration.");
1211
1212
1213static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001214builtin_setattr(PyObject *self, PyObject *args)
Guido van Rossum33894be1992-01-27 16:53:09 +00001215{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001216 PyObject *v;
1217 PyObject *name;
1218 PyObject *value;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001219
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001220 if (!PyArg_UnpackTuple(args, "setattr", 3, 3, &v, &name, &value))
1221 return NULL;
1222 if (PyObject_SetAttr(v, name, value) != 0)
1223 return NULL;
1224 Py_INCREF(Py_None);
1225 return Py_None;
Guido van Rossum33894be1992-01-27 16:53:09 +00001226}
1227
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001228PyDoc_STRVAR(setattr_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001229"setattr(object, name, value)\n\
1230\n\
1231Set a named attribute on an object; setattr(x, 'y', v) is equivalent to\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001232``x.y = v''.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001233
1234
Guido van Rossum79f25d91997-04-29 20:08:16 +00001235static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001236builtin_delattr(PyObject *self, PyObject *args)
Guido van Rossum14144fc1994-08-29 12:53:40 +00001237{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001238 PyObject *v;
1239 PyObject *name;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001240
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001241 if (!PyArg_UnpackTuple(args, "delattr", 2, 2, &v, &name))
1242 return NULL;
1243 if (PyObject_SetAttr(v, name, (PyObject *)NULL) != 0)
1244 return NULL;
1245 Py_INCREF(Py_None);
1246 return Py_None;
Guido van Rossum14144fc1994-08-29 12:53:40 +00001247}
1248
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001249PyDoc_STRVAR(delattr_doc,
Guido van Rossumdf12a591998-11-23 22:13:04 +00001250"delattr(object, name)\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001251\n\
1252Delete a named attribute on an object; delattr(x, 'y') is equivalent to\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001253``del x.y''.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001254
1255
Guido van Rossum79f25d91997-04-29 20:08:16 +00001256static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001257builtin_hash(PyObject *self, PyObject *v)
Guido van Rossum9bfef441993-03-29 10:43:31 +00001258{
Benjamin Peterson8f67d082010-10-17 20:54:53 +00001259 Py_hash_t x;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001260
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001261 x = PyObject_Hash(v);
1262 if (x == -1)
1263 return NULL;
Benjamin Peterson8f67d082010-10-17 20:54:53 +00001264 return PyLong_FromSsize_t(x);
Guido van Rossum9bfef441993-03-29 10:43:31 +00001265}
1266
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001267PyDoc_STRVAR(hash_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001268"hash(object) -> integer\n\
1269\n\
1270Return a hash value for the object. Two objects with the same value have\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001271the same hash value. The reverse is not necessarily true, but likely.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001272
1273
Guido van Rossum79f25d91997-04-29 20:08:16 +00001274static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001275builtin_hex(PyObject *self, PyObject *v)
Guido van Rossum006bcd41991-10-24 14:54:44 +00001276{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001277 return PyNumber_ToBase(v, 16);
Guido van Rossum006bcd41991-10-24 14:54:44 +00001278}
1279
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001280PyDoc_STRVAR(hex_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001281"hex(number) -> string\n\
1282\n\
Zachary Warea4b7a752013-11-24 01:19:09 -06001283Return the hexadecimal representation of an integer.\n\
1284\n\
1285 >>> hex(3735928559)\n\
1286 '0xdeadbeef'\n\
1287");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001288
1289
Guido van Rossum79f25d91997-04-29 20:08:16 +00001290static PyObject *
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001291builtin_iter(PyObject *self, PyObject *args)
1292{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001293 PyObject *v, *w = NULL;
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001294
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001295 if (!PyArg_UnpackTuple(args, "iter", 1, 2, &v, &w))
1296 return NULL;
1297 if (w == NULL)
1298 return PyObject_GetIter(v);
1299 if (!PyCallable_Check(v)) {
1300 PyErr_SetString(PyExc_TypeError,
1301 "iter(v, w): v must be callable");
1302 return NULL;
1303 }
1304 return PyCallIter_New(v, w);
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001305}
1306
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001307PyDoc_STRVAR(iter_doc,
Georg Brandld11ae5d2008-05-16 13:27:32 +00001308"iter(iterable) -> iterator\n\
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001309iter(callable, sentinel) -> iterator\n\
1310\n\
1311Get an iterator from an object. In the first form, the argument must\n\
1312supply its own iterator, or be a sequence.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001313In the second form, the callable is called until it returns the sentinel.");
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001314
1315
1316static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001317builtin_len(PyObject *self, PyObject *v)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001318{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001319 Py_ssize_t res;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001320
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001321 res = PyObject_Size(v);
1322 if (res < 0 && PyErr_Occurred())
1323 return NULL;
1324 return PyLong_FromSsize_t(res);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001325}
1326
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001327PyDoc_STRVAR(len_doc,
Larry Hastings5c661892014-01-24 06:17:25 -08001328"len(module, object)\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001329\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001330Return the number of items of a sequence or mapping.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001331
1332
Guido van Rossum79f25d91997-04-29 20:08:16 +00001333static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001334builtin_locals(PyObject *self)
Guido van Rossum872537c1995-07-07 22:43:42 +00001335{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001336 PyObject *d;
Guido van Rossum872537c1995-07-07 22:43:42 +00001337
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001338 d = PyEval_GetLocals();
1339 Py_XINCREF(d);
1340 return d;
Guido van Rossum872537c1995-07-07 22:43:42 +00001341}
1342
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001343PyDoc_STRVAR(locals_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001344"locals() -> dictionary\n\
1345\n\
Raymond Hettinger69bf8f32003-01-04 02:16:22 +00001346Update and return a dictionary containing the current scope's local variables.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001347
1348
Guido van Rossum79f25d91997-04-29 20:08:16 +00001349static PyObject *
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001350min_max(PyObject *args, PyObject *kwds, int op)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001351{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001352 PyObject *v, *it, *item, *val, *maxitem, *maxval, *keyfunc=NULL;
Raymond Hettinger4d6018f2013-06-24 22:43:02 -07001353 PyObject *emptytuple, *defaultval = NULL;
1354 static char *kwlist[] = {"key", "default", NULL};
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001355 const char *name = op == Py_LT ? "min" : "max";
Raymond Hettinger4d6018f2013-06-24 22:43:02 -07001356 const int positional = PyTuple_Size(args) > 1;
1357 int ret;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001358
Raymond Hettinger4d6018f2013-06-24 22:43:02 -07001359 if (positional)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001360 v = args;
Serhiy Storchakac6792272013-10-19 21:03:34 +03001361 else if (!PyArg_UnpackTuple(args, name, 1, 1, &v))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001362 return NULL;
Tim Peters67d687a2002-04-29 21:27:32 +00001363
Raymond Hettinger4d6018f2013-06-24 22:43:02 -07001364 emptytuple = PyTuple_New(0);
1365 if (emptytuple == NULL)
1366 return NULL;
1367 ret = PyArg_ParseTupleAndKeywords(emptytuple, kwds, "|$OO", kwlist,
1368 &keyfunc, &defaultval);
1369 Py_DECREF(emptytuple);
1370 if (!ret)
1371 return NULL;
1372
1373 if (positional && defaultval != NULL) {
1374 PyErr_Format(PyExc_TypeError,
1375 "Cannot specify a default for %s() with multiple "
1376 "positional arguments", name);
1377 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001378 }
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001379
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001380 it = PyObject_GetIter(v);
1381 if (it == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001382 return NULL;
1383 }
Tim Petersc3074532001-05-03 07:00:32 +00001384
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001385 maxitem = NULL; /* the result */
1386 maxval = NULL; /* the value associated with the result */
1387 while (( item = PyIter_Next(it) )) {
1388 /* get the value from the key function */
1389 if (keyfunc != NULL) {
1390 val = PyObject_CallFunctionObjArgs(keyfunc, item, NULL);
1391 if (val == NULL)
1392 goto Fail_it_item;
1393 }
1394 /* no key function; the value is the item */
1395 else {
1396 val = item;
1397 Py_INCREF(val);
1398 }
Tim Petersc3074532001-05-03 07:00:32 +00001399
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001400 /* maximum value and item are unset; set them */
1401 if (maxval == NULL) {
1402 maxitem = item;
1403 maxval = val;
1404 }
1405 /* maximum value and item are set; update them as necessary */
1406 else {
1407 int cmp = PyObject_RichCompareBool(val, maxval, op);
1408 if (cmp < 0)
1409 goto Fail_it_item_and_val;
1410 else if (cmp > 0) {
1411 Py_DECREF(maxval);
1412 Py_DECREF(maxitem);
1413 maxval = val;
1414 maxitem = item;
1415 }
1416 else {
1417 Py_DECREF(item);
1418 Py_DECREF(val);
1419 }
1420 }
1421 }
1422 if (PyErr_Occurred())
1423 goto Fail_it;
1424 if (maxval == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001425 assert(maxitem == NULL);
Raymond Hettinger4d6018f2013-06-24 22:43:02 -07001426 if (defaultval != NULL) {
1427 Py_INCREF(defaultval);
1428 maxitem = defaultval;
1429 } else {
1430 PyErr_Format(PyExc_ValueError,
1431 "%s() arg is an empty sequence", name);
1432 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001433 }
1434 else
1435 Py_DECREF(maxval);
1436 Py_DECREF(it);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001437 return maxitem;
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001438
1439Fail_it_item_and_val:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001440 Py_DECREF(val);
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001441Fail_it_item:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001442 Py_DECREF(item);
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001443Fail_it:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001444 Py_XDECREF(maxval);
1445 Py_XDECREF(maxitem);
1446 Py_DECREF(it);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001447 return NULL;
Guido van Rossum3f5da241990-12-20 15:06:42 +00001448}
1449
Guido van Rossum79f25d91997-04-29 20:08:16 +00001450static PyObject *
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001451builtin_min(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001452{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001453 return min_max(args, kwds, Py_LT);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001454}
1455
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001456PyDoc_STRVAR(min_doc,
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001457"min(iterable[, key=func]) -> value\n\
1458min(a, b, c, ...[, key=func]) -> value\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001459\n\
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001460With a single iterable argument, return its smallest item.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001461With two or more arguments, return the smallest argument.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001462
1463
Guido van Rossum79f25d91997-04-29 20:08:16 +00001464static PyObject *
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001465builtin_max(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001466{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001467 return min_max(args, kwds, Py_GT);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001468}
1469
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001470PyDoc_STRVAR(max_doc,
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001471"max(iterable[, key=func]) -> value\n\
1472max(a, b, c, ...[, key=func]) -> value\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001473\n\
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001474With a single iterable argument, return its largest item.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001475With two or more arguments, return the largest argument.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001476
1477
Guido van Rossum79f25d91997-04-29 20:08:16 +00001478static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001479builtin_oct(PyObject *self, PyObject *v)
Guido van Rossum006bcd41991-10-24 14:54:44 +00001480{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001481 return PyNumber_ToBase(v, 8);
Guido van Rossum006bcd41991-10-24 14:54:44 +00001482}
1483
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001484PyDoc_STRVAR(oct_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001485"oct(number) -> string\n\
1486\n\
Zachary Warea4b7a752013-11-24 01:19:09 -06001487Return the octal representation of an integer.\n\
1488\n\
1489 >>> oct(342391)\n\
1490 '0o1234567'\n\
1491");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001492
1493
Guido van Rossum79f25d91997-04-29 20:08:16 +00001494static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001495builtin_ord(PyObject *self, PyObject* obj)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001496{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001497 long ord;
1498 Py_ssize_t size;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001499
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001500 if (PyBytes_Check(obj)) {
1501 size = PyBytes_GET_SIZE(obj);
1502 if (size == 1) {
1503 ord = (long)((unsigned char)*PyBytes_AS_STRING(obj));
1504 return PyLong_FromLong(ord);
1505 }
1506 }
1507 else if (PyUnicode_Check(obj)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001508 if (PyUnicode_READY(obj) == -1)
1509 return NULL;
1510 size = PyUnicode_GET_LENGTH(obj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001511 if (size == 1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001512 ord = (long)PyUnicode_READ_CHAR(obj, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001513 return PyLong_FromLong(ord);
1514 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001515 }
1516 else if (PyByteArray_Check(obj)) {
1517 /* XXX Hopefully this is temporary */
1518 size = PyByteArray_GET_SIZE(obj);
1519 if (size == 1) {
1520 ord = (long)((unsigned char)*PyByteArray_AS_STRING(obj));
1521 return PyLong_FromLong(ord);
1522 }
1523 }
1524 else {
1525 PyErr_Format(PyExc_TypeError,
1526 "ord() expected string of length 1, but " \
1527 "%.200s found", obj->ob_type->tp_name);
1528 return NULL;
1529 }
Guido van Rossum09095f32000-03-10 23:00:52 +00001530
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001531 PyErr_Format(PyExc_TypeError,
1532 "ord() expected a character, "
1533 "but string of length %zd found",
1534 size);
1535 return NULL;
Guido van Rossum3f5da241990-12-20 15:06:42 +00001536}
1537
Guido van Rossum307fa8c2007-07-16 20:46:27 +00001538PyDoc_VAR(ord_doc) = PyDoc_STR(
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001539"ord(c) -> integer\n\
1540\n\
Guido van Rossum8ac004e2007-07-15 13:00:05 +00001541Return the integer ordinal of a one-character string."
Antoine Pitrouedc60182012-06-23 14:19:58 +02001542);
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001543
1544
Guido van Rossum79f25d91997-04-29 20:08:16 +00001545static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001546builtin_pow(PyObject *self, PyObject *args)
Guido van Rossum6a00cd81995-01-07 12:39:01 +00001547{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001548 PyObject *v, *w, *z = Py_None;
Guido van Rossum6a00cd81995-01-07 12:39:01 +00001549
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001550 if (!PyArg_UnpackTuple(args, "pow", 2, 3, &v, &w, &z))
1551 return NULL;
1552 return PyNumber_Power(v, w, z);
Guido van Rossumd4905451991-05-05 20:00:36 +00001553}
1554
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001555PyDoc_STRVAR(pow_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001556"pow(x, y[, z]) -> number\n\
1557\n\
1558With two arguments, equivalent to x**y. With three arguments,\n\
Serhiy Storchaka95949422013-08-27 19:40:23 +03001559equivalent to (x**y) % z, but may be more efficient (e.g. for ints).");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001560
1561
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001562
Guido van Rossum34343512006-11-30 22:13:52 +00001563static PyObject *
1564builtin_print(PyObject *self, PyObject *args, PyObject *kwds)
1565{
Georg Brandlbc3b6822012-01-13 19:41:25 +01001566 static char *kwlist[] = {"sep", "end", "file", "flush", 0};
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001567 static PyObject *dummy_args;
Georg Brandlbc3b6822012-01-13 19:41:25 +01001568 PyObject *sep = NULL, *end = NULL, *file = NULL, *flush = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001569 int i, err;
Guido van Rossum34343512006-11-30 22:13:52 +00001570
Benjamin Peterson00102562012-01-11 21:00:16 -05001571 if (dummy_args == NULL && !(dummy_args = PyTuple_New(0)))
Georg Brandlbc3b6822012-01-13 19:41:25 +01001572 return NULL;
1573 if (!PyArg_ParseTupleAndKeywords(dummy_args, kwds, "|OOOO:print",
1574 kwlist, &sep, &end, &file, &flush))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001575 return NULL;
1576 if (file == NULL || file == Py_None) {
Victor Stinnerbd303c12013-11-07 23:07:29 +01001577 file = _PySys_GetObjectId(&PyId_stdout);
Victor Stinner1e53bba2013-07-16 22:26:05 +02001578 if (file == NULL) {
1579 PyErr_SetString(PyExc_RuntimeError, "lost sys.stdout");
1580 return NULL;
1581 }
1582
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001583 /* sys.stdout may be None when FILE* stdout isn't connected */
1584 if (file == Py_None)
1585 Py_RETURN_NONE;
1586 }
Guido van Rossum34343512006-11-30 22:13:52 +00001587
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001588 if (sep == Py_None) {
1589 sep = NULL;
1590 }
1591 else if (sep && !PyUnicode_Check(sep)) {
1592 PyErr_Format(PyExc_TypeError,
1593 "sep must be None or a string, not %.200s",
1594 sep->ob_type->tp_name);
1595 return NULL;
1596 }
1597 if (end == Py_None) {
1598 end = NULL;
1599 }
1600 else if (end && !PyUnicode_Check(end)) {
1601 PyErr_Format(PyExc_TypeError,
1602 "end must be None or a string, not %.200s",
1603 end->ob_type->tp_name);
1604 return NULL;
1605 }
Guido van Rossum34343512006-11-30 22:13:52 +00001606
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001607 for (i = 0; i < PyTuple_Size(args); i++) {
1608 if (i > 0) {
1609 if (sep == NULL)
1610 err = PyFile_WriteString(" ", file);
1611 else
1612 err = PyFile_WriteObject(sep, file,
1613 Py_PRINT_RAW);
1614 if (err)
1615 return NULL;
1616 }
1617 err = PyFile_WriteObject(PyTuple_GetItem(args, i), file,
1618 Py_PRINT_RAW);
1619 if (err)
1620 return NULL;
1621 }
Guido van Rossum34343512006-11-30 22:13:52 +00001622
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001623 if (end == NULL)
1624 err = PyFile_WriteString("\n", file);
1625 else
1626 err = PyFile_WriteObject(end, file, Py_PRINT_RAW);
1627 if (err)
1628 return NULL;
Guido van Rossum34343512006-11-30 22:13:52 +00001629
Georg Brandlbc3b6822012-01-13 19:41:25 +01001630 if (flush != NULL) {
1631 PyObject *tmp;
1632 int do_flush = PyObject_IsTrue(flush);
1633 if (do_flush == -1)
1634 return NULL;
1635 else if (do_flush) {
Victor Stinnereaa28832013-11-07 00:01:51 +01001636 tmp = _PyObject_CallMethodId(file, &PyId_flush, "");
Georg Brandlbc3b6822012-01-13 19:41:25 +01001637 if (tmp == NULL)
1638 return NULL;
1639 else
1640 Py_DECREF(tmp);
1641 }
1642 }
1643
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001644 Py_RETURN_NONE;
Guido van Rossum34343512006-11-30 22:13:52 +00001645}
1646
1647PyDoc_STRVAR(print_doc,
Senthil Kumarane9175bd2012-08-10 13:53:45 -07001648"print(value, ..., sep=' ', end='\\n', file=sys.stdout, flush=False)\n\
Guido van Rossum34343512006-11-30 22:13:52 +00001649\n\
1650Prints the values to a stream, or to sys.stdout by default.\n\
1651Optional keyword arguments:\n\
Senthil Kumarane9175bd2012-08-10 13:53:45 -07001652file: a file-like object (stream); defaults to the current sys.stdout.\n\
1653sep: string inserted between values, default a space.\n\
1654end: string appended after the last value, default a newline.\n\
1655flush: whether to forcibly flush the stream.");
Guido van Rossum34343512006-11-30 22:13:52 +00001656
1657
Guido van Rossuma88a0332007-02-26 16:59:55 +00001658static PyObject *
1659builtin_input(PyObject *self, PyObject *args)
1660{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001661 PyObject *promptarg = NULL;
Victor Stinnerbd303c12013-11-07 23:07:29 +01001662 PyObject *fin = _PySys_GetObjectId(&PyId_stdin);
1663 PyObject *fout = _PySys_GetObjectId(&PyId_stdout);
1664 PyObject *ferr = _PySys_GetObjectId(&PyId_stderr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001665 PyObject *tmp;
1666 long fd;
1667 int tty;
Guido van Rossuma88a0332007-02-26 16:59:55 +00001668
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001669 /* Parse arguments */
1670 if (!PyArg_UnpackTuple(args, "input", 0, 1, &promptarg))
1671 return NULL;
Guido van Rossuma88a0332007-02-26 16:59:55 +00001672
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001673 /* Check that stdin/out/err are intact */
1674 if (fin == NULL || fin == Py_None) {
1675 PyErr_SetString(PyExc_RuntimeError,
1676 "input(): lost sys.stdin");
1677 return NULL;
1678 }
1679 if (fout == NULL || fout == Py_None) {
1680 PyErr_SetString(PyExc_RuntimeError,
1681 "input(): lost sys.stdout");
1682 return NULL;
1683 }
1684 if (ferr == NULL || ferr == Py_None) {
1685 PyErr_SetString(PyExc_RuntimeError,
1686 "input(): lost sys.stderr");
1687 return NULL;
1688 }
Guido van Rossumeba76962007-05-27 09:13:28 +00001689
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001690 /* First of all, flush stderr */
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001691 tmp = _PyObject_CallMethodId(ferr, &PyId_flush, "");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001692 if (tmp == NULL)
1693 PyErr_Clear();
1694 else
1695 Py_DECREF(tmp);
Guido van Rossumeba76962007-05-27 09:13:28 +00001696
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001697 /* We should only use (GNU) readline if Python's sys.stdin and
1698 sys.stdout are the same as C's stdin and stdout, because we
1699 need to pass it those. */
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001700 tmp = _PyObject_CallMethodId(fin, &PyId_fileno, "");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001701 if (tmp == NULL) {
1702 PyErr_Clear();
1703 tty = 0;
1704 }
1705 else {
1706 fd = PyLong_AsLong(tmp);
1707 Py_DECREF(tmp);
1708 if (fd < 0 && PyErr_Occurred())
1709 return NULL;
1710 tty = fd == fileno(stdin) && isatty(fd);
1711 }
1712 if (tty) {
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001713 tmp = _PyObject_CallMethodId(fout, &PyId_fileno, "");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001714 if (tmp == NULL)
1715 PyErr_Clear();
1716 else {
1717 fd = PyLong_AsLong(tmp);
1718 Py_DECREF(tmp);
1719 if (fd < 0 && PyErr_Occurred())
1720 return NULL;
1721 tty = fd == fileno(stdout) && isatty(fd);
1722 }
1723 }
Guido van Rossumeba76962007-05-27 09:13:28 +00001724
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001725 /* If we're interactive, use (GNU) readline */
1726 if (tty) {
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001727 PyObject *po = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001728 char *prompt;
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001729 char *s = NULL;
1730 PyObject *stdin_encoding = NULL, *stdin_errors = NULL;
1731 PyObject *stdout_encoding = NULL, *stdout_errors = NULL;
1732 char *stdin_encoding_str, *stdin_errors_str;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001733 PyObject *result;
Victor Stinnerc0f1a1a2011-02-23 12:07:37 +00001734 size_t len;
Martin v. Löwis4a7b5d52007-09-04 05:24:49 +00001735
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02001736 stdin_encoding = _PyObject_GetAttrId(fin, &PyId_encoding);
Antoine Pitrou5ee9d8a2011-11-06 00:38:45 +01001737 stdin_errors = _PyObject_GetAttrId(fin, &PyId_errors);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001738 if (!stdin_encoding || !stdin_errors)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001739 /* stdin is a text stream, so it must have an
1740 encoding. */
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001741 goto _readline_errors;
Victor Stinner306f0102010-05-19 01:06:22 +00001742 stdin_encoding_str = _PyUnicode_AsString(stdin_encoding);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001743 stdin_errors_str = _PyUnicode_AsString(stdin_errors);
1744 if (!stdin_encoding_str || !stdin_errors_str)
1745 goto _readline_errors;
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001746 tmp = _PyObject_CallMethodId(fout, &PyId_flush, "");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001747 if (tmp == NULL)
1748 PyErr_Clear();
1749 else
1750 Py_DECREF(tmp);
1751 if (promptarg != NULL) {
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001752 /* We have a prompt, encode it as stdout would */
1753 char *stdout_encoding_str, *stdout_errors_str;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001754 PyObject *stringpo;
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02001755 stdout_encoding = _PyObject_GetAttrId(fout, &PyId_encoding);
Antoine Pitrou5ee9d8a2011-11-06 00:38:45 +01001756 stdout_errors = _PyObject_GetAttrId(fout, &PyId_errors);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001757 if (!stdout_encoding || !stdout_errors)
1758 goto _readline_errors;
Victor Stinner306f0102010-05-19 01:06:22 +00001759 stdout_encoding_str = _PyUnicode_AsString(stdout_encoding);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001760 stdout_errors_str = _PyUnicode_AsString(stdout_errors);
1761 if (!stdout_encoding_str || !stdout_errors_str)
1762 goto _readline_errors;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001763 stringpo = PyObject_Str(promptarg);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001764 if (stringpo == NULL)
1765 goto _readline_errors;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001766 po = PyUnicode_AsEncodedString(stringpo,
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001767 stdout_encoding_str, stdout_errors_str);
1768 Py_CLEAR(stdout_encoding);
1769 Py_CLEAR(stdout_errors);
1770 Py_CLEAR(stringpo);
1771 if (po == NULL)
1772 goto _readline_errors;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001773 prompt = PyBytes_AsString(po);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001774 if (prompt == NULL)
1775 goto _readline_errors;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001776 }
1777 else {
1778 po = NULL;
1779 prompt = "";
1780 }
1781 s = PyOS_Readline(stdin, stdout, prompt);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001782 if (s == NULL) {
Richard Oudkerk614c5782013-04-03 13:44:50 +01001783 PyErr_CheckSignals();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001784 if (!PyErr_Occurred())
1785 PyErr_SetNone(PyExc_KeyboardInterrupt);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001786 goto _readline_errors;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001787 }
Victor Stinnerc0f1a1a2011-02-23 12:07:37 +00001788
1789 len = strlen(s);
1790 if (len == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001791 PyErr_SetNone(PyExc_EOFError);
1792 result = NULL;
1793 }
Victor Stinnerc0f1a1a2011-02-23 12:07:37 +00001794 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001795 if (len > PY_SSIZE_T_MAX) {
1796 PyErr_SetString(PyExc_OverflowError,
1797 "input: input too long");
1798 result = NULL;
1799 }
1800 else {
Victor Stinnerc0f1a1a2011-02-23 12:07:37 +00001801 len--; /* strip trailing '\n' */
1802 if (len != 0 && s[len-1] == '\r')
1803 len--; /* strip trailing '\r' */
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001804 result = PyUnicode_Decode(s, len, stdin_encoding_str,
1805 stdin_errors_str);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001806 }
1807 }
1808 Py_DECREF(stdin_encoding);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001809 Py_DECREF(stdin_errors);
1810 Py_XDECREF(po);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001811 PyMem_FREE(s);
1812 return result;
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001813 _readline_errors:
1814 Py_XDECREF(stdin_encoding);
1815 Py_XDECREF(stdout_encoding);
1816 Py_XDECREF(stdin_errors);
1817 Py_XDECREF(stdout_errors);
1818 Py_XDECREF(po);
1819 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001820 }
Guido van Rossumeba76962007-05-27 09:13:28 +00001821
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001822 /* Fallback if we're not interactive */
1823 if (promptarg != NULL) {
1824 if (PyFile_WriteObject(promptarg, fout, Py_PRINT_RAW) != 0)
1825 return NULL;
1826 }
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001827 tmp = _PyObject_CallMethodId(fout, &PyId_flush, "");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001828 if (tmp == NULL)
1829 PyErr_Clear();
1830 else
1831 Py_DECREF(tmp);
1832 return PyFile_GetLine(fin, -1);
Guido van Rossuma88a0332007-02-26 16:59:55 +00001833}
1834
1835PyDoc_STRVAR(input_doc,
1836"input([prompt]) -> string\n\
1837\n\
1838Read a string from standard input. The trailing newline is stripped.\n\
1839If the user hits EOF (Unix: Ctl-D, Windows: Ctl-Z+Return), raise EOFError.\n\
1840On Unix, GNU readline is used if enabled. The prompt string, if given,\n\
1841is printed without a trailing newline before reading.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001842
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001843
Guido van Rossum79f25d91997-04-29 20:08:16 +00001844static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001845builtin_repr(PyObject *self, PyObject *v)
Guido van Rossumc89705d1992-11-26 08:54:07 +00001846{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001847 return PyObject_Repr(v);
Guido van Rossumc89705d1992-11-26 08:54:07 +00001848}
1849
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001850PyDoc_STRVAR(repr_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001851"repr(object) -> string\n\
1852\n\
1853Return the canonical string representation of the object.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001854For most object types, eval(repr(object)) == object.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001855
1856
Guido van Rossum79f25d91997-04-29 20:08:16 +00001857static PyObject *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001858builtin_round(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum9e51f9b1993-02-12 16:29:05 +00001859{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001860 PyObject *ndigits = NULL;
1861 static char *kwlist[] = {"number", "ndigits", 0};
Benjamin Peterson214a7d22013-04-13 17:19:01 -04001862 PyObject *number, *round, *result;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001863
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001864 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|O:round",
1865 kwlist, &number, &ndigits))
1866 return NULL;
Alex Martelliae211f92007-08-22 23:21:33 +00001867
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001868 if (Py_TYPE(number)->tp_dict == NULL) {
1869 if (PyType_Ready(Py_TYPE(number)) < 0)
1870 return NULL;
1871 }
Guido van Rossum15d3d042007-08-24 02:02:45 +00001872
Benjamin Peterson214a7d22013-04-13 17:19:01 -04001873 round = _PyObject_LookupSpecial(number, &PyId___round__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001874 if (round == NULL) {
Benjamin Peterson214a7d22013-04-13 17:19:01 -04001875 if (!PyErr_Occurred())
1876 PyErr_Format(PyExc_TypeError,
1877 "type %.100s doesn't define __round__ method",
1878 Py_TYPE(number)->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001879 return NULL;
1880 }
Alex Martelliae211f92007-08-22 23:21:33 +00001881
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001882 if (ndigits == NULL)
Benjamin Peterson214a7d22013-04-13 17:19:01 -04001883 result = PyObject_CallFunctionObjArgs(round, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001884 else
Benjamin Peterson214a7d22013-04-13 17:19:01 -04001885 result = PyObject_CallFunctionObjArgs(round, ndigits, NULL);
1886 Py_DECREF(round);
1887 return result;
Guido van Rossum9e51f9b1993-02-12 16:29:05 +00001888}
1889
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001890PyDoc_STRVAR(round_doc,
Mark Dickinson1124e712009-01-28 21:25:58 +00001891"round(number[, ndigits]) -> number\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001892\n\
1893Round a number to a given precision in decimal digits (default 0 digits).\n\
Mark Dickinson0d748c22008-07-05 11:29:03 +00001894This returns an int when called with one argument, otherwise the\n\
Georg Brandl809ddaa2008-07-01 20:39:59 +00001895same type as the number. ndigits may be negative.");
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001896
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001897
Raymond Hettinger64958a12003-12-17 20:43:33 +00001898static PyObject *
1899builtin_sorted(PyObject *self, PyObject *args, PyObject *kwds)
1900{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001901 PyObject *newlist, *v, *seq, *keyfunc=NULL, *newargs;
1902 PyObject *callable;
1903 static char *kwlist[] = {"iterable", "key", "reverse", 0};
1904 int reverse;
Raymond Hettinger64958a12003-12-17 20:43:33 +00001905
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001906 /* args 1-3 should match listsort in Objects/listobject.c */
1907 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|Oi:sorted",
1908 kwlist, &seq, &keyfunc, &reverse))
1909 return NULL;
Raymond Hettinger64958a12003-12-17 20:43:33 +00001910
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001911 newlist = PySequence_List(seq);
1912 if (newlist == NULL)
1913 return NULL;
Raymond Hettinger64958a12003-12-17 20:43:33 +00001914
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02001915 callable = _PyObject_GetAttrId(newlist, &PyId_sort);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001916 if (callable == NULL) {
1917 Py_DECREF(newlist);
1918 return NULL;
1919 }
Georg Brandl99d7e4e2005-08-31 22:21:15 +00001920
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001921 newargs = PyTuple_GetSlice(args, 1, 4);
1922 if (newargs == NULL) {
1923 Py_DECREF(newlist);
1924 Py_DECREF(callable);
1925 return NULL;
1926 }
Raymond Hettinger64958a12003-12-17 20:43:33 +00001927
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001928 v = PyObject_Call(callable, newargs, kwds);
1929 Py_DECREF(newargs);
1930 Py_DECREF(callable);
1931 if (v == NULL) {
1932 Py_DECREF(newlist);
1933 return NULL;
1934 }
1935 Py_DECREF(v);
1936 return newlist;
Raymond Hettinger64958a12003-12-17 20:43:33 +00001937}
1938
1939PyDoc_STRVAR(sorted_doc,
Raymond Hettinger70b64fc2008-01-30 20:15:17 +00001940"sorted(iterable, key=None, reverse=False) --> new sorted list");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001941
Guido van Rossum79f25d91997-04-29 20:08:16 +00001942static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001943builtin_vars(PyObject *self, PyObject *args)
Guido van Rossum2d951851994-08-29 12:52:16 +00001944{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001945 PyObject *v = NULL;
1946 PyObject *d;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001947
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001948 if (!PyArg_UnpackTuple(args, "vars", 0, 1, &v))
1949 return NULL;
1950 if (v == NULL) {
1951 d = PyEval_GetLocals();
Victor Stinner41bb43a2013-10-29 01:19:37 +01001952 if (d == NULL)
1953 return NULL;
1954 Py_INCREF(d);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001955 }
1956 else {
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02001957 d = _PyObject_GetAttrId(v, &PyId___dict__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001958 if (d == NULL) {
1959 PyErr_SetString(PyExc_TypeError,
1960 "vars() argument must have __dict__ attribute");
1961 return NULL;
1962 }
1963 }
1964 return d;
Guido van Rossum2d951851994-08-29 12:52:16 +00001965}
1966
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001967PyDoc_STRVAR(vars_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001968"vars([object]) -> dictionary\n\
1969\n\
1970Without arguments, equivalent to locals().\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001971With an argument, equivalent to object.__dict__.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001972
Alex Martellia70b1912003-04-22 08:12:33 +00001973static PyObject*
1974builtin_sum(PyObject *self, PyObject *args)
1975{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001976 PyObject *seq;
1977 PyObject *result = NULL;
1978 PyObject *temp, *item, *iter;
Alex Martellia70b1912003-04-22 08:12:33 +00001979
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001980 if (!PyArg_UnpackTuple(args, "sum", 1, 2, &seq, &result))
1981 return NULL;
Alex Martellia70b1912003-04-22 08:12:33 +00001982
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001983 iter = PyObject_GetIter(seq);
1984 if (iter == NULL)
1985 return NULL;
Alex Martellia70b1912003-04-22 08:12:33 +00001986
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001987 if (result == NULL) {
1988 result = PyLong_FromLong(0);
1989 if (result == NULL) {
1990 Py_DECREF(iter);
1991 return NULL;
1992 }
1993 } else {
1994 /* reject string values for 'start' parameter */
1995 if (PyUnicode_Check(result)) {
1996 PyErr_SetString(PyExc_TypeError,
1997 "sum() can't sum strings [use ''.join(seq) instead]");
1998 Py_DECREF(iter);
1999 return NULL;
2000 }
Benjamin Petersonce071ca2011-07-29 14:23:47 -05002001 if (PyBytes_Check(result)) {
2002 PyErr_SetString(PyExc_TypeError,
2003 "sum() can't sum bytes [use b''.join(seq) instead]");
Benjamin Peterson405f32c2011-07-29 22:43:45 -05002004 Py_DECREF(iter);
Benjamin Petersonce071ca2011-07-29 14:23:47 -05002005 return NULL;
2006 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002007 if (PyByteArray_Check(result)) {
2008 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson4f921c22011-07-29 14:24:29 -05002009 "sum() can't sum bytearray [use b''.join(seq) instead]");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002010 Py_DECREF(iter);
2011 return NULL;
2012 }
Guido van Rossum3172c5d2007-10-16 18:12:55 +00002013
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002014 Py_INCREF(result);
2015 }
Alex Martellia70b1912003-04-22 08:12:33 +00002016
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002017#ifndef SLOW_SUM
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002018 /* Fast addition by keeping temporary sums in C instead of new Python objects.
2019 Assumes all inputs are the same type. If the assumption fails, default
2020 to the more general routine.
2021 */
2022 if (PyLong_CheckExact(result)) {
2023 int overflow;
2024 long i_result = PyLong_AsLongAndOverflow(result, &overflow);
2025 /* If this already overflowed, don't even enter the loop. */
2026 if (overflow == 0) {
2027 Py_DECREF(result);
2028 result = NULL;
2029 }
2030 while(result == NULL) {
2031 item = PyIter_Next(iter);
2032 if (item == NULL) {
2033 Py_DECREF(iter);
2034 if (PyErr_Occurred())
2035 return NULL;
2036 return PyLong_FromLong(i_result);
2037 }
2038 if (PyLong_CheckExact(item)) {
2039 long b = PyLong_AsLongAndOverflow(item, &overflow);
2040 long x = i_result + b;
2041 if (overflow == 0 && ((x^i_result) >= 0 || (x^b) >= 0)) {
2042 i_result = x;
2043 Py_DECREF(item);
2044 continue;
2045 }
2046 }
2047 /* Either overflowed or is not an int. Restore real objects and process normally */
2048 result = PyLong_FromLong(i_result);
Christian Heimes704e2d32013-07-26 22:49:26 +02002049 if (result == NULL) {
2050 Py_DECREF(item);
2051 Py_DECREF(iter);
2052 return NULL;
2053 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002054 temp = PyNumber_Add(result, item);
2055 Py_DECREF(result);
2056 Py_DECREF(item);
2057 result = temp;
2058 if (result == NULL) {
2059 Py_DECREF(iter);
2060 return NULL;
2061 }
2062 }
2063 }
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002064
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002065 if (PyFloat_CheckExact(result)) {
2066 double f_result = PyFloat_AS_DOUBLE(result);
2067 Py_DECREF(result);
2068 result = NULL;
2069 while(result == NULL) {
2070 item = PyIter_Next(iter);
2071 if (item == NULL) {
2072 Py_DECREF(iter);
2073 if (PyErr_Occurred())
2074 return NULL;
2075 return PyFloat_FromDouble(f_result);
2076 }
2077 if (PyFloat_CheckExact(item)) {
2078 PyFPE_START_PROTECT("add", Py_DECREF(item); Py_DECREF(iter); return 0)
2079 f_result += PyFloat_AS_DOUBLE(item);
2080 PyFPE_END_PROTECT(f_result)
2081 Py_DECREF(item);
2082 continue;
2083 }
2084 if (PyLong_CheckExact(item)) {
2085 long value;
2086 int overflow;
2087 value = PyLong_AsLongAndOverflow(item, &overflow);
2088 if (!overflow) {
2089 PyFPE_START_PROTECT("add", Py_DECREF(item); Py_DECREF(iter); return 0)
2090 f_result += (double)value;
2091 PyFPE_END_PROTECT(f_result)
2092 Py_DECREF(item);
2093 continue;
2094 }
2095 }
2096 result = PyFloat_FromDouble(f_result);
2097 temp = PyNumber_Add(result, item);
2098 Py_DECREF(result);
2099 Py_DECREF(item);
2100 result = temp;
2101 if (result == NULL) {
2102 Py_DECREF(iter);
2103 return NULL;
2104 }
2105 }
2106 }
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002107#endif
2108
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002109 for(;;) {
2110 item = PyIter_Next(iter);
2111 if (item == NULL) {
2112 /* error, or end-of-sequence */
2113 if (PyErr_Occurred()) {
2114 Py_DECREF(result);
2115 result = NULL;
2116 }
2117 break;
2118 }
2119 /* It's tempting to use PyNumber_InPlaceAdd instead of
2120 PyNumber_Add here, to avoid quadratic running time
2121 when doing 'sum(list_of_lists, [])'. However, this
2122 would produce a change in behaviour: a snippet like
Mark Dickinson9acadc52009-10-26 14:19:42 +00002123
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002124 empty = []
2125 sum([[x] for x in range(10)], empty)
Mark Dickinson9acadc52009-10-26 14:19:42 +00002126
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002127 would change the value of empty. */
2128 temp = PyNumber_Add(result, item);
2129 Py_DECREF(result);
2130 Py_DECREF(item);
2131 result = temp;
2132 if (result == NULL)
2133 break;
2134 }
2135 Py_DECREF(iter);
2136 return result;
Alex Martellia70b1912003-04-22 08:12:33 +00002137}
2138
2139PyDoc_STRVAR(sum_doc,
Georg Brandld11ae5d2008-05-16 13:27:32 +00002140"sum(iterable[, start]) -> value\n\
Alex Martellia70b1912003-04-22 08:12:33 +00002141\n\
R David Murray87ead112013-07-10 16:22:14 -04002142Return the sum of an iterable of numbers (NOT strings) plus the value\n\
Georg Brandld11ae5d2008-05-16 13:27:32 +00002143of parameter 'start' (which defaults to 0). When the iterable is\n\
R David Murray87ead112013-07-10 16:22:14 -04002144empty, return start.");
Alex Martellia70b1912003-04-22 08:12:33 +00002145
2146
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002147static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002148builtin_isinstance(PyObject *self, PyObject *args)
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002149{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002150 PyObject *inst;
2151 PyObject *cls;
2152 int retval;
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002153
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002154 if (!PyArg_UnpackTuple(args, "isinstance", 2, 2, &inst, &cls))
2155 return NULL;
Guido van Rossumf5dd9141997-12-02 19:11:45 +00002156
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002157 retval = PyObject_IsInstance(inst, cls);
2158 if (retval < 0)
2159 return NULL;
2160 return PyBool_FromLong(retval);
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002161}
2162
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002163PyDoc_STRVAR(isinstance_doc,
Guido van Rossum77f6a652002-04-03 22:41:51 +00002164"isinstance(object, class-or-type-or-tuple) -> bool\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002165\n\
2166Return whether an object is an instance of a class or of a subclass thereof.\n\
Guido van Rossum03290ec2001-10-07 20:54:12 +00002167With a type as second argument, return whether that is the object's type.\n\
2168The form using a tuple, isinstance(x, (A, B, ...)), is a shortcut for\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002169isinstance(x, A) or isinstance(x, B) or ... (etc.).");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002170
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002171
2172static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002173builtin_issubclass(PyObject *self, PyObject *args)
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002174{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002175 PyObject *derived;
2176 PyObject *cls;
2177 int retval;
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002178
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002179 if (!PyArg_UnpackTuple(args, "issubclass", 2, 2, &derived, &cls))
2180 return NULL;
Guido van Rossum668213d1999-06-16 17:28:37 +00002181
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002182 retval = PyObject_IsSubclass(derived, cls);
2183 if (retval < 0)
2184 return NULL;
2185 return PyBool_FromLong(retval);
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002186}
2187
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002188PyDoc_STRVAR(issubclass_doc,
Guido van Rossum77f6a652002-04-03 22:41:51 +00002189"issubclass(C, B) -> bool\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002190\n\
Walter Dörwaldd9a6ad32002-12-12 16:41:44 +00002191Return whether class C is a subclass (i.e., a derived class) of class B.\n\
2192When using a tuple as the second argument issubclass(X, (A, B, ...)),\n\
2193is a shortcut for issubclass(X, A) or issubclass(X, B) or ... (etc.).");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002194
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002195
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002196typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002197 PyObject_HEAD
2198 Py_ssize_t tuplesize;
2199 PyObject *ittuple; /* tuple of iterators */
2200 PyObject *result;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002201} zipobject;
2202
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002203static PyObject *
2204zip_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
Barry Warsawbd599b52000-08-03 15:45:29 +00002205{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002206 zipobject *lz;
2207 Py_ssize_t i;
2208 PyObject *ittuple; /* tuple of iterators */
2209 PyObject *result;
2210 Py_ssize_t tuplesize = PySequence_Length(args);
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002211
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002212 if (type == &PyZip_Type && !_PyArg_NoKeywords("zip()", kwds))
2213 return NULL;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002214
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002215 /* args must be a tuple */
2216 assert(PyTuple_Check(args));
Barry Warsawbd599b52000-08-03 15:45:29 +00002217
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002218 /* obtain iterators */
2219 ittuple = PyTuple_New(tuplesize);
2220 if (ittuple == NULL)
2221 return NULL;
2222 for (i=0; i < tuplesize; ++i) {
2223 PyObject *item = PyTuple_GET_ITEM(args, i);
2224 PyObject *it = PyObject_GetIter(item);
2225 if (it == NULL) {
2226 if (PyErr_ExceptionMatches(PyExc_TypeError))
2227 PyErr_Format(PyExc_TypeError,
2228 "zip argument #%zd must support iteration",
2229 i+1);
2230 Py_DECREF(ittuple);
2231 return NULL;
2232 }
2233 PyTuple_SET_ITEM(ittuple, i, it);
2234 }
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002235
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002236 /* create a result holder */
2237 result = PyTuple_New(tuplesize);
2238 if (result == NULL) {
2239 Py_DECREF(ittuple);
2240 return NULL;
2241 }
2242 for (i=0 ; i < tuplesize ; i++) {
2243 Py_INCREF(Py_None);
2244 PyTuple_SET_ITEM(result, i, Py_None);
2245 }
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002246
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002247 /* create zipobject structure */
2248 lz = (zipobject *)type->tp_alloc(type, 0);
2249 if (lz == NULL) {
2250 Py_DECREF(ittuple);
2251 Py_DECREF(result);
2252 return NULL;
2253 }
2254 lz->ittuple = ittuple;
2255 lz->tuplesize = tuplesize;
2256 lz->result = result;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002257
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002258 return (PyObject *)lz;
Barry Warsawbd599b52000-08-03 15:45:29 +00002259}
2260
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002261static void
2262zip_dealloc(zipobject *lz)
2263{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002264 PyObject_GC_UnTrack(lz);
2265 Py_XDECREF(lz->ittuple);
2266 Py_XDECREF(lz->result);
2267 Py_TYPE(lz)->tp_free(lz);
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002268}
2269
2270static int
2271zip_traverse(zipobject *lz, visitproc visit, void *arg)
2272{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002273 Py_VISIT(lz->ittuple);
2274 Py_VISIT(lz->result);
2275 return 0;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002276}
2277
2278static PyObject *
2279zip_next(zipobject *lz)
2280{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002281 Py_ssize_t i;
2282 Py_ssize_t tuplesize = lz->tuplesize;
2283 PyObject *result = lz->result;
2284 PyObject *it;
2285 PyObject *item;
2286 PyObject *olditem;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002287
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002288 if (tuplesize == 0)
2289 return NULL;
2290 if (Py_REFCNT(result) == 1) {
2291 Py_INCREF(result);
2292 for (i=0 ; i < tuplesize ; i++) {
2293 it = PyTuple_GET_ITEM(lz->ittuple, i);
2294 item = (*Py_TYPE(it)->tp_iternext)(it);
Serhiy Storchaka278d03b2013-04-06 22:52:34 +03002295 if (item == NULL) {
2296 Py_DECREF(result);
2297 return NULL;
2298 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002299 olditem = PyTuple_GET_ITEM(result, i);
2300 PyTuple_SET_ITEM(result, i, item);
2301 Py_DECREF(olditem);
2302 }
2303 } else {
2304 result = PyTuple_New(tuplesize);
2305 if (result == NULL)
Serhiy Storchaka278d03b2013-04-06 22:52:34 +03002306 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002307 for (i=0 ; i < tuplesize ; i++) {
2308 it = PyTuple_GET_ITEM(lz->ittuple, i);
2309 item = (*Py_TYPE(it)->tp_iternext)(it);
Serhiy Storchaka278d03b2013-04-06 22:52:34 +03002310 if (item == NULL) {
2311 Py_DECREF(result);
2312 return NULL;
2313 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002314 PyTuple_SET_ITEM(result, i, item);
2315 }
2316 }
2317 return result;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002318}
Barry Warsawbd599b52000-08-03 15:45:29 +00002319
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002320static PyObject *
2321zip_reduce(zipobject *lz)
2322{
2323 /* Just recreate the zip with the internal iterator tuple */
2324 return Py_BuildValue("OO", Py_TYPE(lz), lz->ittuple);
2325}
2326
2327static PyMethodDef zip_methods[] = {
2328 {"__reduce__", (PyCFunction)zip_reduce, METH_NOARGS, reduce_doc},
2329 {NULL, NULL} /* sentinel */
2330};
2331
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002332PyDoc_STRVAR(zip_doc,
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002333"zip(iter1 [,iter2 [...]]) --> zip object\n\
Barry Warsawbd599b52000-08-03 15:45:29 +00002334\n\
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002335Return a zip object whose .__next__() method returns a tuple where\n\
2336the i-th element comes from the i-th iterable argument. The .__next__()\n\
2337method continues until the shortest iterable in the argument sequence\n\
Georg Brandlced51db2008-12-04 18:28:38 +00002338is exhausted and then it raises StopIteration.");
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002339
2340PyTypeObject PyZip_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002341 PyVarObject_HEAD_INIT(&PyType_Type, 0)
2342 "zip", /* tp_name */
2343 sizeof(zipobject), /* tp_basicsize */
2344 0, /* tp_itemsize */
2345 /* methods */
2346 (destructor)zip_dealloc, /* tp_dealloc */
2347 0, /* tp_print */
2348 0, /* tp_getattr */
2349 0, /* tp_setattr */
2350 0, /* tp_reserved */
2351 0, /* tp_repr */
2352 0, /* tp_as_number */
2353 0, /* tp_as_sequence */
2354 0, /* tp_as_mapping */
2355 0, /* tp_hash */
2356 0, /* tp_call */
2357 0, /* tp_str */
2358 PyObject_GenericGetAttr, /* tp_getattro */
2359 0, /* tp_setattro */
2360 0, /* tp_as_buffer */
2361 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
2362 Py_TPFLAGS_BASETYPE, /* tp_flags */
2363 zip_doc, /* tp_doc */
2364 (traverseproc)zip_traverse, /* tp_traverse */
2365 0, /* tp_clear */
2366 0, /* tp_richcompare */
2367 0, /* tp_weaklistoffset */
2368 PyObject_SelfIter, /* tp_iter */
2369 (iternextfunc)zip_next, /* tp_iternext */
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002370 zip_methods, /* tp_methods */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002371 0, /* tp_members */
2372 0, /* tp_getset */
2373 0, /* tp_base */
2374 0, /* tp_dict */
2375 0, /* tp_descr_get */
2376 0, /* tp_descr_set */
2377 0, /* tp_dictoffset */
2378 0, /* tp_init */
2379 PyType_GenericAlloc, /* tp_alloc */
2380 zip_new, /* tp_new */
2381 PyObject_GC_Del, /* tp_free */
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002382};
Barry Warsawbd599b52000-08-03 15:45:29 +00002383
2384
Guido van Rossum79f25d91997-04-29 20:08:16 +00002385static PyMethodDef builtin_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002386 {"__build_class__", (PyCFunction)builtin___build_class__,
2387 METH_VARARGS | METH_KEYWORDS, build_class_doc},
2388 {"__import__", (PyCFunction)builtin___import__, METH_VARARGS | METH_KEYWORDS, import_doc},
2389 {"abs", builtin_abs, METH_O, abs_doc},
2390 {"all", builtin_all, METH_O, all_doc},
2391 {"any", builtin_any, METH_O, any_doc},
2392 {"ascii", builtin_ascii, METH_O, ascii_doc},
2393 {"bin", builtin_bin, METH_O, bin_doc},
Antoine Pitroue71362d2010-11-27 22:00:11 +00002394 {"callable", builtin_callable, METH_O, callable_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002395 {"chr", builtin_chr, METH_VARARGS, chr_doc},
2396 {"compile", (PyCFunction)builtin_compile, METH_VARARGS | METH_KEYWORDS, compile_doc},
2397 {"delattr", builtin_delattr, METH_VARARGS, delattr_doc},
2398 {"dir", builtin_dir, METH_VARARGS, dir_doc},
2399 {"divmod", builtin_divmod, METH_VARARGS, divmod_doc},
2400 {"eval", builtin_eval, METH_VARARGS, eval_doc},
2401 {"exec", builtin_exec, METH_VARARGS, exec_doc},
2402 {"format", builtin_format, METH_VARARGS, format_doc},
2403 {"getattr", builtin_getattr, METH_VARARGS, getattr_doc},
2404 {"globals", (PyCFunction)builtin_globals, METH_NOARGS, globals_doc},
2405 {"hasattr", builtin_hasattr, METH_VARARGS, hasattr_doc},
2406 {"hash", builtin_hash, METH_O, hash_doc},
2407 {"hex", builtin_hex, METH_O, hex_doc},
2408 {"id", builtin_id, METH_O, id_doc},
2409 {"input", builtin_input, METH_VARARGS, input_doc},
2410 {"isinstance", builtin_isinstance, METH_VARARGS, isinstance_doc},
2411 {"issubclass", builtin_issubclass, METH_VARARGS, issubclass_doc},
2412 {"iter", builtin_iter, METH_VARARGS, iter_doc},
2413 {"len", builtin_len, METH_O, len_doc},
2414 {"locals", (PyCFunction)builtin_locals, METH_NOARGS, locals_doc},
2415 {"max", (PyCFunction)builtin_max, METH_VARARGS | METH_KEYWORDS, max_doc},
2416 {"min", (PyCFunction)builtin_min, METH_VARARGS | METH_KEYWORDS, min_doc},
2417 {"next", (PyCFunction)builtin_next, METH_VARARGS, next_doc},
2418 {"oct", builtin_oct, METH_O, oct_doc},
2419 {"ord", builtin_ord, METH_O, ord_doc},
2420 {"pow", builtin_pow, METH_VARARGS, pow_doc},
2421 {"print", (PyCFunction)builtin_print, METH_VARARGS | METH_KEYWORDS, print_doc},
2422 {"repr", builtin_repr, METH_O, repr_doc},
2423 {"round", (PyCFunction)builtin_round, METH_VARARGS | METH_KEYWORDS, round_doc},
2424 {"setattr", builtin_setattr, METH_VARARGS, setattr_doc},
2425 {"sorted", (PyCFunction)builtin_sorted, METH_VARARGS | METH_KEYWORDS, sorted_doc},
2426 {"sum", builtin_sum, METH_VARARGS, sum_doc},
2427 {"vars", builtin_vars, METH_VARARGS, vars_doc},
2428 {NULL, NULL},
Guido van Rossum3f5da241990-12-20 15:06:42 +00002429};
2430
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002431PyDoc_STRVAR(builtin_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002432"Built-in functions, exceptions, and other objects.\n\
2433\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002434Noteworthy: None is the `nil' object; Ellipsis represents `...' in slices.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002435
Martin v. Löwis1a214512008-06-11 05:26:20 +00002436static struct PyModuleDef builtinsmodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002437 PyModuleDef_HEAD_INIT,
2438 "builtins",
2439 builtin_doc,
2440 -1, /* multiple "initialization" just copies the module dict. */
2441 builtin_methods,
2442 NULL,
2443 NULL,
2444 NULL,
2445 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00002446};
2447
2448
Guido van Rossum25ce5661997-08-02 03:10:38 +00002449PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002450_PyBuiltin_Init(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +00002451{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002452 PyObject *mod, *dict, *debug;
Benjamin Peterson42124a72012-10-30 23:41:54 -04002453
2454 if (PyType_Ready(&PyFilter_Type) < 0 ||
2455 PyType_Ready(&PyMap_Type) < 0 ||
2456 PyType_Ready(&PyZip_Type) < 0)
2457 return NULL;
2458
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002459 mod = PyModule_Create(&builtinsmodule);
2460 if (mod == NULL)
2461 return NULL;
2462 dict = PyModule_GetDict(mod);
Tim Peters4b7625e2001-09-13 21:37:17 +00002463
Tim Peters7571a0f2003-03-23 17:52:28 +00002464#ifdef Py_TRACE_REFS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002465 /* "builtins" exposes a number of statically allocated objects
2466 * that, before this code was added in 2.3, never showed up in
2467 * the list of "all objects" maintained by Py_TRACE_REFS. As a
2468 * result, programs leaking references to None and False (etc)
2469 * couldn't be diagnosed by examining sys.getobjects(0).
2470 */
Tim Peters7571a0f2003-03-23 17:52:28 +00002471#define ADD_TO_ALL(OBJECT) _Py_AddToAllObjects((PyObject *)(OBJECT), 0)
2472#else
2473#define ADD_TO_ALL(OBJECT) (void)0
2474#endif
2475
Tim Peters4b7625e2001-09-13 21:37:17 +00002476#define SETBUILTIN(NAME, OBJECT) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002477 if (PyDict_SetItemString(dict, NAME, (PyObject *)OBJECT) < 0) \
2478 return NULL; \
2479 ADD_TO_ALL(OBJECT)
Tim Peters4b7625e2001-09-13 21:37:17 +00002480
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002481 SETBUILTIN("None", Py_None);
2482 SETBUILTIN("Ellipsis", Py_Ellipsis);
2483 SETBUILTIN("NotImplemented", Py_NotImplemented);
2484 SETBUILTIN("False", Py_False);
2485 SETBUILTIN("True", Py_True);
2486 SETBUILTIN("bool", &PyBool_Type);
2487 SETBUILTIN("memoryview", &PyMemoryView_Type);
2488 SETBUILTIN("bytearray", &PyByteArray_Type);
2489 SETBUILTIN("bytes", &PyBytes_Type);
2490 SETBUILTIN("classmethod", &PyClassMethod_Type);
2491 SETBUILTIN("complex", &PyComplex_Type);
2492 SETBUILTIN("dict", &PyDict_Type);
2493 SETBUILTIN("enumerate", &PyEnum_Type);
2494 SETBUILTIN("filter", &PyFilter_Type);
2495 SETBUILTIN("float", &PyFloat_Type);
2496 SETBUILTIN("frozenset", &PyFrozenSet_Type);
2497 SETBUILTIN("property", &PyProperty_Type);
2498 SETBUILTIN("int", &PyLong_Type);
2499 SETBUILTIN("list", &PyList_Type);
2500 SETBUILTIN("map", &PyMap_Type);
2501 SETBUILTIN("object", &PyBaseObject_Type);
2502 SETBUILTIN("range", &PyRange_Type);
2503 SETBUILTIN("reversed", &PyReversed_Type);
2504 SETBUILTIN("set", &PySet_Type);
2505 SETBUILTIN("slice", &PySlice_Type);
2506 SETBUILTIN("staticmethod", &PyStaticMethod_Type);
2507 SETBUILTIN("str", &PyUnicode_Type);
2508 SETBUILTIN("super", &PySuper_Type);
2509 SETBUILTIN("tuple", &PyTuple_Type);
2510 SETBUILTIN("type", &PyType_Type);
2511 SETBUILTIN("zip", &PyZip_Type);
2512 debug = PyBool_FromLong(Py_OptimizeFlag == 0);
2513 if (PyDict_SetItemString(dict, "__debug__", debug) < 0) {
2514 Py_XDECREF(debug);
2515 return NULL;
2516 }
2517 Py_XDECREF(debug);
Barry Warsaw757af0e1997-08-29 22:13:51 +00002518
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002519 return mod;
Tim Peters7571a0f2003-03-23 17:52:28 +00002520#undef ADD_TO_ALL
Tim Peters4b7625e2001-09-13 21:37:17 +00002521#undef SETBUILTIN
Guido van Rossum3f5da241990-12-20 15:06:42 +00002522}