blob: 4b4f979169bf4454522b8fa01d66e584908a76d8 [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,
Zachary Ware9b338722014-08-05 14:01:10 -050072 "__build_class__: func must be a function");
Benjamin Petersone8e14592013-05-16 14:37:25 -050073 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
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +0200562static const char *
563source_as_string(PyObject *cmd, const char *funcname, const char *what, PyCompilerFlags *cf, Py_buffer *view)
Guido van Rossumf15a29f2007-05-04 00:41:39 +0000564{
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +0200565 const char *str;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000566 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 }
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +0200574 else if (PyObject_GetBuffer(cmd, view, PyBUF_SIMPLE) == 0) {
575 str = (const char *)view->buf;
576 size = view->len;
577 }
578 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000579 PyErr_Format(PyExc_TypeError,
580 "%s() arg 1 must be a %s object",
581 funcname, what);
582 return NULL;
583 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200584
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000585 if (strlen(str) != size) {
586 PyErr_SetString(PyExc_TypeError,
587 "source code string cannot contain null bytes");
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +0200588 PyBuffer_Release(view);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000589 return NULL;
590 }
591 return str;
Guido van Rossumf15a29f2007-05-04 00:41:39 +0000592}
593
Guido van Rossum79f25d91997-04-29 20:08:16 +0000594static PyObject *
Guido van Rossumd8faa362007-04-27 19:54:29 +0000595builtin_compile(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum5b722181993-03-30 17:46:03 +0000596{
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +0200597 Py_buffer view = {NULL, NULL};
598 const char *str;
Victor Stinner14e461d2013-08-26 22:28:21 +0200599 PyObject *filename;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000600 char *startstr;
601 int mode = -1;
602 int dont_inherit = 0;
603 int supplied_flags = 0;
Georg Brandl8334fd92010-12-04 10:26:46 +0000604 int optimize = -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000605 int is_ast;
606 PyCompilerFlags cf;
607 PyObject *cmd;
608 static char *kwlist[] = {"source", "filename", "mode", "flags",
Georg Brandl8334fd92010-12-04 10:26:46 +0000609 "dont_inherit", "optimize", NULL};
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000610 int start[] = {Py_file_input, Py_eval_input, Py_single_input};
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000611 PyObject *result;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000612
Georg Brandl8334fd92010-12-04 10:26:46 +0000613 if (!PyArg_ParseTupleAndKeywords(args, kwds, "OO&s|iii:compile", kwlist,
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000614 &cmd,
Victor Stinner14e461d2013-08-26 22:28:21 +0200615 PyUnicode_FSDecoder, &filename,
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000616 &startstr, &supplied_flags,
Georg Brandl8334fd92010-12-04 10:26:46 +0000617 &dont_inherit, &optimize))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000618 return NULL;
Tim Peters6cd6a822001-08-17 22:11:27 +0000619
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000620 cf.cf_flags = supplied_flags | PyCF_SOURCE_IS_UTF8;
Just van Rossum3aaf42c2003-02-10 08:21:10 +0000621
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000622 if (supplied_flags &
623 ~(PyCF_MASK | PyCF_MASK_OBSOLETE | PyCF_DONT_IMPLY_DEDENT | PyCF_ONLY_AST))
624 {
625 PyErr_SetString(PyExc_ValueError,
626 "compile(): unrecognised flags");
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000627 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000628 }
629 /* XXX Warn if (supplied_flags & PyCF_MASK_OBSOLETE) != 0? */
Tim Peters6cd6a822001-08-17 22:11:27 +0000630
Georg Brandl8334fd92010-12-04 10:26:46 +0000631 if (optimize < -1 || optimize > 2) {
632 PyErr_SetString(PyExc_ValueError,
633 "compile(): invalid optimize value");
634 goto error;
635 }
636
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000637 if (!dont_inherit) {
638 PyEval_MergeCompilerFlags(&cf);
639 }
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000640
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000641 if (strcmp(startstr, "exec") == 0)
642 mode = 0;
643 else if (strcmp(startstr, "eval") == 0)
644 mode = 1;
645 else if (strcmp(startstr, "single") == 0)
646 mode = 2;
647 else {
648 PyErr_SetString(PyExc_ValueError,
649 "compile() arg 3 must be 'exec', 'eval' or 'single'");
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000650 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000651 }
Neal Norwitzdb4115f2008-03-31 04:20:05 +0000652
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000653 is_ast = PyAST_Check(cmd);
654 if (is_ast == -1)
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000655 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000656 if (is_ast) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000657 if (supplied_flags & PyCF_ONLY_AST) {
658 Py_INCREF(cmd);
659 result = cmd;
660 }
661 else {
662 PyArena *arena;
663 mod_ty mod;
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000664
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000665 arena = PyArena_New();
Stefan Krah07795df2012-08-20 17:19:50 +0200666 if (arena == NULL)
667 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000668 mod = PyAST_obj2mod(cmd, arena, mode);
669 if (mod == NULL) {
670 PyArena_Free(arena);
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000671 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000672 }
Benjamin Peterson832bfe22011-08-09 16:15:04 -0500673 if (!PyAST_Validate(mod)) {
674 PyArena_Free(arena);
675 goto error;
676 }
Victor Stinner14e461d2013-08-26 22:28:21 +0200677 result = (PyObject*)PyAST_CompileObject(mod, filename,
678 &cf, optimize, arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000679 PyArena_Free(arena);
680 }
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000681 goto finally;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000682 }
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000683
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +0200684 str = source_as_string(cmd, "compile", "string, bytes or AST", &cf, &view);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000685 if (str == NULL)
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000686 goto error;
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000687
Victor Stinner14e461d2013-08-26 22:28:21 +0200688 result = Py_CompileStringObject(str, filename, start[mode], &cf, optimize);
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +0200689 PyBuffer_Release(&view);
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000690 goto finally;
691
692error:
693 result = NULL;
694finally:
Victor Stinner14e461d2013-08-26 22:28:21 +0200695 Py_DECREF(filename);
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000696 return result;
Guido van Rossum5b722181993-03-30 17:46:03 +0000697}
698
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000699PyDoc_STRVAR(compile_doc,
Tim Peters6cd6a822001-08-17 22:11:27 +0000700"compile(source, filename, mode[, flags[, dont_inherit]]) -> code object\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000701\n\
Benjamin Peterson933142a2013-12-06 20:12:39 -0500702Compile the source (a Python module, statement or expression)\n\
Georg Brandl7cae87c2006-09-06 06:51:57 +0000703into a code object that can be executed by exec() or eval().\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000704The filename will be used for run-time error messages.\n\
705The mode must be 'exec' to compile a module, 'single' to compile a\n\
Tim Peters6cd6a822001-08-17 22:11:27 +0000706single (interactive) statement, or 'eval' to compile an expression.\n\
707The flags argument, if present, controls which future statements influence\n\
708the compilation of the code.\n\
709The dont_inherit argument, if non-zero, stops the compilation inheriting\n\
710the effects of any future statements in effect in the code calling\n\
711compile; if absent or zero these statements do influence the compilation,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000712in addition to any features explicitly specified.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000713
Guido van Rossum79f25d91997-04-29 20:08:16 +0000714static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000715builtin_dir(PyObject *self, PyObject *args)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000716{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000717 PyObject *arg = NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000718
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000719 if (!PyArg_UnpackTuple(args, "dir", 0, 1, &arg))
720 return NULL;
721 return PyObject_Dir(arg);
Guido van Rossum3f5da241990-12-20 15:06:42 +0000722}
723
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000724PyDoc_STRVAR(dir_doc,
Tim Peters5d2b77c2001-09-03 05:47:38 +0000725"dir([object]) -> list of strings\n"
726"\n"
Georg Brandle32b4222007-03-10 22:13:27 +0000727"If called without an argument, return the names in the current scope.\n"
728"Else, return an alphabetized list of names comprising (some of) the attributes\n"
729"of the given object, and of attributes reachable from it.\n"
730"If the object supplies a method named __dir__, it will be used; otherwise\n"
731"the default dir() logic is used and returns:\n"
732" for a module object: the module's attributes.\n"
733" for a class object: its attributes, and recursively the attributes\n"
734" of its bases.\n"
Guido van Rossumd8faa362007-04-27 19:54:29 +0000735" for any other object: its attributes, its class's attributes, and\n"
Georg Brandle32b4222007-03-10 22:13:27 +0000736" recursively the attributes of its class's base classes.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000737
Guido van Rossum79f25d91997-04-29 20:08:16 +0000738static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000739builtin_divmod(PyObject *self, PyObject *args)
Guido van Rossum6a00cd81995-01-07 12:39:01 +0000740{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000741 PyObject *v, *w;
Guido van Rossum6a00cd81995-01-07 12:39:01 +0000742
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000743 if (!PyArg_UnpackTuple(args, "divmod", 2, 2, &v, &w))
744 return NULL;
745 return PyNumber_Divmod(v, w);
Guido van Rossum3f5da241990-12-20 15:06:42 +0000746}
747
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000748PyDoc_STRVAR(divmod_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000749"divmod(x, y) -> (div, mod)\n\
750\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000751Return the tuple ((x-x%y)/y, x%y). Invariant: div*y + mod == x.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000752
753
Guido van Rossum79f25d91997-04-29 20:08:16 +0000754static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000755builtin_eval(PyObject *self, PyObject *args)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000756{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000757 PyObject *cmd, *result, *tmp = NULL;
758 PyObject *globals = Py_None, *locals = Py_None;
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +0200759 Py_buffer view = {NULL, NULL};
760 const char *str;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000761 PyCompilerFlags cf;
Guido van Rossum590baa41993-11-30 13:40:46 +0000762
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000763 if (!PyArg_UnpackTuple(args, "eval", 1, 3, &cmd, &globals, &locals))
764 return NULL;
765 if (locals != Py_None && !PyMapping_Check(locals)) {
766 PyErr_SetString(PyExc_TypeError, "locals must be a mapping");
767 return NULL;
768 }
769 if (globals != Py_None && !PyDict_Check(globals)) {
770 PyErr_SetString(PyExc_TypeError, PyMapping_Check(globals) ?
771 "globals must be a real dict; try eval(expr, {}, mapping)"
772 : "globals must be a dict");
773 return NULL;
774 }
775 if (globals == Py_None) {
776 globals = PyEval_GetGlobals();
Victor Stinner41bb43a2013-10-29 01:19:37 +0100777 if (locals == Py_None) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000778 locals = PyEval_GetLocals();
Victor Stinner41bb43a2013-10-29 01:19:37 +0100779 if (locals == NULL)
780 return NULL;
781 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000782 }
783 else if (locals == Py_None)
784 locals = globals;
Tim Peters9fa96be2001-08-17 23:04:59 +0000785
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000786 if (globals == NULL || locals == NULL) {
787 PyErr_SetString(PyExc_TypeError,
788 "eval must be given globals and locals "
789 "when called without a frame");
790 return NULL;
791 }
Georg Brandl77c85e62005-09-15 10:46:13 +0000792
Victor Stinnerb44562b2013-11-06 19:03:11 +0100793 if (_PyDict_GetItemId(globals, &PyId___builtins__) == NULL) {
794 if (_PyDict_SetItemId(globals, &PyId___builtins__,
795 PyEval_GetBuiltins()) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000796 return NULL;
797 }
Tim Peters9fa96be2001-08-17 23:04:59 +0000798
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000799 if (PyCode_Check(cmd)) {
800 if (PyCode_GetNumFree((PyCodeObject *)cmd) > 0) {
801 PyErr_SetString(PyExc_TypeError,
802 "code object passed to eval() may not contain free variables");
803 return NULL;
804 }
Martin v. Löwis4d0d4712010-12-03 20:14:31 +0000805 return PyEval_EvalCode(cmd, globals, locals);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000806 }
Tim Peters9fa96be2001-08-17 23:04:59 +0000807
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000808 cf.cf_flags = PyCF_SOURCE_IS_UTF8;
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +0200809 str = source_as_string(cmd, "eval", "string, bytes or code", &cf, &view);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000810 if (str == NULL)
811 return NULL;
Just van Rossum3aaf42c2003-02-10 08:21:10 +0000812
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000813 while (*str == ' ' || *str == '\t')
814 str++;
Tim Peters9fa96be2001-08-17 23:04:59 +0000815
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000816 (void)PyEval_MergeCompilerFlags(&cf);
817 result = PyRun_StringFlags(str, Py_eval_input, globals, locals, &cf);
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +0200818 PyBuffer_Release(&view);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000819 Py_XDECREF(tmp);
820 return result;
Guido van Rossum3f5da241990-12-20 15:06:42 +0000821}
822
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000823PyDoc_STRVAR(eval_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000824"eval(source[, globals[, locals]]) -> value\n\
825\n\
826Evaluate the source in the context of globals and locals.\n\
827The source may be a string representing a Python expression\n\
828or a code object as returned by compile().\n\
Thomas Wouters89f507f2006-12-13 04:49:30 +0000829The globals must be a dictionary and locals can be any mapping,\n\
Raymond Hettinger214b1c32004-07-02 06:41:07 +0000830defaulting to the current globals and locals.\n\
831If only globals is given, locals defaults to it.\n");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000832
Georg Brandl7cae87c2006-09-06 06:51:57 +0000833static PyObject *
834builtin_exec(PyObject *self, PyObject *args)
835{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000836 PyObject *v;
837 PyObject *prog, *globals = Py_None, *locals = Py_None;
Georg Brandl7cae87c2006-09-06 06:51:57 +0000838
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000839 if (!PyArg_UnpackTuple(args, "exec", 1, 3, &prog, &globals, &locals))
840 return NULL;
Georg Brandl2cabc562008-08-28 07:57:16 +0000841
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000842 if (globals == Py_None) {
843 globals = PyEval_GetGlobals();
844 if (locals == Py_None) {
845 locals = PyEval_GetLocals();
Victor Stinner41bb43a2013-10-29 01:19:37 +0100846 if (locals == NULL)
847 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000848 }
849 if (!globals || !locals) {
850 PyErr_SetString(PyExc_SystemError,
851 "globals and locals cannot be NULL");
852 return NULL;
853 }
854 }
855 else if (locals == Py_None)
856 locals = globals;
Georg Brandl7cae87c2006-09-06 06:51:57 +0000857
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000858 if (!PyDict_Check(globals)) {
859 PyErr_Format(PyExc_TypeError, "exec() arg 2 must be a dict, not %.100s",
860 globals->ob_type->tp_name);
861 return NULL;
862 }
863 if (!PyMapping_Check(locals)) {
864 PyErr_Format(PyExc_TypeError,
865 "arg 3 must be a mapping or None, not %.100s",
866 locals->ob_type->tp_name);
867 return NULL;
868 }
Victor Stinnerb44562b2013-11-06 19:03:11 +0100869 if (_PyDict_GetItemId(globals, &PyId___builtins__) == NULL) {
870 if (_PyDict_SetItemId(globals, &PyId___builtins__,
871 PyEval_GetBuiltins()) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000872 return NULL;
873 }
874
875 if (PyCode_Check(prog)) {
876 if (PyCode_GetNumFree((PyCodeObject *)prog) > 0) {
877 PyErr_SetString(PyExc_TypeError,
878 "code object passed to exec() may not "
879 "contain free variables");
880 return NULL;
881 }
Martin v. Löwis4d0d4712010-12-03 20:14:31 +0000882 v = PyEval_EvalCode(prog, globals, locals);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000883 }
884 else {
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +0200885 Py_buffer view = {NULL, NULL};
886 const char *str;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000887 PyCompilerFlags cf;
888 cf.cf_flags = PyCF_SOURCE_IS_UTF8;
889 str = source_as_string(prog, "exec",
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +0200890 "string, bytes or code", &cf, &view);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000891 if (str == NULL)
892 return NULL;
893 if (PyEval_MergeCompilerFlags(&cf))
894 v = PyRun_StringFlags(str, Py_file_input, globals,
895 locals, &cf);
896 else
897 v = PyRun_String(str, Py_file_input, globals, locals);
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +0200898 PyBuffer_Release(&view);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000899 }
900 if (v == NULL)
901 return NULL;
902 Py_DECREF(v);
903 Py_RETURN_NONE;
Georg Brandl7cae87c2006-09-06 06:51:57 +0000904}
905
906PyDoc_STRVAR(exec_doc,
907"exec(object[, globals[, locals]])\n\
908\n\
Mark Dickinson480e8e32009-12-19 21:19:35 +0000909Read and execute code from an object, which can be a string or a code\n\
Benjamin Peterson38090262009-01-04 15:30:39 +0000910object.\n\
Georg Brandl7cae87c2006-09-06 06:51:57 +0000911The globals and locals are dictionaries, defaulting to the current\n\
912globals and locals. If only globals is given, locals defaults to it.");
913
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000914
Guido van Rossum79f25d91997-04-29 20:08:16 +0000915static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000916builtin_getattr(PyObject *self, PyObject *args)
Guido van Rossum33894be1992-01-27 16:53:09 +0000917{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000918 PyObject *v, *result, *dflt = NULL;
919 PyObject *name;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000920
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000921 if (!PyArg_UnpackTuple(args, "getattr", 2, 3, &v, &name, &dflt))
922 return NULL;
Martin v. Löwis5b222132007-06-10 09:51:05 +0000923
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000924 if (!PyUnicode_Check(name)) {
925 PyErr_SetString(PyExc_TypeError,
926 "getattr(): attribute name must be string");
927 return NULL;
928 }
929 result = PyObject_GetAttr(v, name);
930 if (result == NULL && dflt != NULL &&
931 PyErr_ExceptionMatches(PyExc_AttributeError))
932 {
933 PyErr_Clear();
934 Py_INCREF(dflt);
935 result = dflt;
936 }
937 return result;
Guido van Rossum9bfef441993-03-29 10:43:31 +0000938}
939
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000940PyDoc_STRVAR(getattr_doc,
Guido van Rossum950ff291998-06-29 13:38:57 +0000941"getattr(object, name[, default]) -> value\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000942\n\
Guido van Rossum950ff291998-06-29 13:38:57 +0000943Get a named attribute from an object; getattr(x, 'y') is equivalent to x.y.\n\
944When a default argument is given, it is returned when the attribute doesn't\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000945exist; without it, an exception is raised in that case.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000946
947
Guido van Rossum79f25d91997-04-29 20:08:16 +0000948static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000949builtin_globals(PyObject *self)
Guido van Rossum872537c1995-07-07 22:43:42 +0000950{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000951 PyObject *d;
Guido van Rossum872537c1995-07-07 22:43:42 +0000952
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000953 d = PyEval_GetGlobals();
954 Py_XINCREF(d);
955 return d;
Guido van Rossum872537c1995-07-07 22:43:42 +0000956}
957
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000958PyDoc_STRVAR(globals_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000959"globals() -> dictionary\n\
960\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000961Return the dictionary containing the current scope's global variables.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000962
963
Guido van Rossum79f25d91997-04-29 20:08:16 +0000964static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000965builtin_hasattr(PyObject *self, PyObject *args)
Guido van Rossum9bfef441993-03-29 10:43:31 +0000966{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000967 PyObject *v;
968 PyObject *name;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000969
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000970 if (!PyArg_UnpackTuple(args, "hasattr", 2, 2, &v, &name))
971 return NULL;
972 if (!PyUnicode_Check(name)) {
973 PyErr_SetString(PyExc_TypeError,
974 "hasattr(): attribute name must be string");
975 return NULL;
976 }
977 v = PyObject_GetAttr(v, name);
978 if (v == NULL) {
Benjamin Peterson17689992010-08-24 03:26:23 +0000979 if (PyErr_ExceptionMatches(PyExc_AttributeError)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000980 PyErr_Clear();
Benjamin Peterson17689992010-08-24 03:26:23 +0000981 Py_RETURN_FALSE;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000982 }
Benjamin Peterson17689992010-08-24 03:26:23 +0000983 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000984 }
985 Py_DECREF(v);
Benjamin Peterson17689992010-08-24 03:26:23 +0000986 Py_RETURN_TRUE;
Guido van Rossum33894be1992-01-27 16:53:09 +0000987}
988
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000989PyDoc_STRVAR(hasattr_doc,
Guido van Rossum77f6a652002-04-03 22:41:51 +0000990"hasattr(object, name) -> bool\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000991\n\
992Return whether the object has an attribute with the given name.\n\
Benjamin Peterson17689992010-08-24 03:26:23 +0000993(This is done by calling getattr(object, name) and catching AttributeError.)");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000994
995
Guido van Rossum79f25d91997-04-29 20:08:16 +0000996static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000997builtin_id(PyObject *self, PyObject *v)
Guido van Rossum5b722181993-03-30 17:46:03 +0000998{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000999 return PyLong_FromVoidPtr(v);
Guido van Rossum5b722181993-03-30 17:46:03 +00001000}
1001
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001002PyDoc_STRVAR(id_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001003"id(object) -> integer\n\
1004\n\
1005Return the identity of an object. This is guaranteed to be unique among\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001006simultaneously existing objects. (Hint: it's the object's memory address.)");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001007
1008
Raymond Hettingera6c60372008-03-13 01:26:19 +00001009/* map object ************************************************************/
1010
1011typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001012 PyObject_HEAD
1013 PyObject *iters;
1014 PyObject *func;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001015} mapobject;
1016
Guido van Rossum79f25d91997-04-29 20:08:16 +00001017static PyObject *
Raymond Hettingera6c60372008-03-13 01:26:19 +00001018map_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
Guido van Rossum12d12c51993-10-26 17:58:25 +00001019{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001020 PyObject *it, *iters, *func;
1021 mapobject *lz;
1022 Py_ssize_t numargs, i;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001023
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001024 if (type == &PyMap_Type && !_PyArg_NoKeywords("map()", kwds))
1025 return NULL;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001026
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001027 numargs = PyTuple_Size(args);
1028 if (numargs < 2) {
1029 PyErr_SetString(PyExc_TypeError,
1030 "map() must have at least two arguments.");
1031 return NULL;
1032 }
Raymond Hettingera6c60372008-03-13 01:26:19 +00001033
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001034 iters = PyTuple_New(numargs-1);
1035 if (iters == NULL)
1036 return NULL;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001037
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001038 for (i=1 ; i<numargs ; i++) {
1039 /* Get iterator. */
1040 it = PyObject_GetIter(PyTuple_GET_ITEM(args, i));
1041 if (it == NULL) {
1042 Py_DECREF(iters);
1043 return NULL;
1044 }
1045 PyTuple_SET_ITEM(iters, i-1, it);
1046 }
Raymond Hettingera6c60372008-03-13 01:26:19 +00001047
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001048 /* create mapobject structure */
1049 lz = (mapobject *)type->tp_alloc(type, 0);
1050 if (lz == NULL) {
1051 Py_DECREF(iters);
1052 return NULL;
1053 }
1054 lz->iters = iters;
1055 func = PyTuple_GET_ITEM(args, 0);
1056 Py_INCREF(func);
1057 lz->func = func;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001058
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001059 return (PyObject *)lz;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001060}
1061
1062static void
1063map_dealloc(mapobject *lz)
1064{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001065 PyObject_GC_UnTrack(lz);
1066 Py_XDECREF(lz->iters);
1067 Py_XDECREF(lz->func);
1068 Py_TYPE(lz)->tp_free(lz);
Raymond Hettingera6c60372008-03-13 01:26:19 +00001069}
1070
1071static int
1072map_traverse(mapobject *lz, visitproc visit, void *arg)
1073{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001074 Py_VISIT(lz->iters);
1075 Py_VISIT(lz->func);
1076 return 0;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001077}
1078
1079static PyObject *
1080map_next(mapobject *lz)
1081{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001082 PyObject *val;
1083 PyObject *argtuple;
1084 PyObject *result;
1085 Py_ssize_t numargs, i;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001086
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001087 numargs = PyTuple_Size(lz->iters);
1088 argtuple = PyTuple_New(numargs);
1089 if (argtuple == NULL)
1090 return NULL;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001091
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001092 for (i=0 ; i<numargs ; i++) {
1093 val = PyIter_Next(PyTuple_GET_ITEM(lz->iters, i));
1094 if (val == NULL) {
1095 Py_DECREF(argtuple);
1096 return NULL;
1097 }
1098 PyTuple_SET_ITEM(argtuple, i, val);
1099 }
1100 result = PyObject_Call(lz->func, argtuple, NULL);
1101 Py_DECREF(argtuple);
1102 return result;
Guido van Rossum12d12c51993-10-26 17:58:25 +00001103}
1104
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001105static PyObject *
1106map_reduce(mapobject *lz)
1107{
1108 Py_ssize_t numargs = PyTuple_GET_SIZE(lz->iters);
1109 PyObject *args = PyTuple_New(numargs+1);
1110 Py_ssize_t i;
1111 if (args == NULL)
1112 return NULL;
1113 Py_INCREF(lz->func);
1114 PyTuple_SET_ITEM(args, 0, lz->func);
1115 for (i = 0; i<numargs; i++){
1116 PyObject *it = PyTuple_GET_ITEM(lz->iters, i);
1117 Py_INCREF(it);
1118 PyTuple_SET_ITEM(args, i+1, it);
1119 }
1120
1121 return Py_BuildValue("ON", Py_TYPE(lz), args);
1122}
1123
1124static PyMethodDef map_methods[] = {
1125 {"__reduce__", (PyCFunction)map_reduce, METH_NOARGS, reduce_doc},
1126 {NULL, NULL} /* sentinel */
1127};
1128
1129
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001130PyDoc_STRVAR(map_doc,
Raymond Hettingera6c60372008-03-13 01:26:19 +00001131"map(func, *iterables) --> map object\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001132\n\
Raymond Hettingera6c60372008-03-13 01:26:19 +00001133Make an iterator that computes the function using arguments from\n\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001134each of the iterables. Stops when the shortest iterable is exhausted.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001135
Raymond Hettingera6c60372008-03-13 01:26:19 +00001136PyTypeObject PyMap_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001137 PyVarObject_HEAD_INIT(&PyType_Type, 0)
1138 "map", /* tp_name */
1139 sizeof(mapobject), /* tp_basicsize */
1140 0, /* tp_itemsize */
1141 /* methods */
1142 (destructor)map_dealloc, /* tp_dealloc */
1143 0, /* tp_print */
1144 0, /* tp_getattr */
1145 0, /* tp_setattr */
1146 0, /* tp_reserved */
1147 0, /* tp_repr */
1148 0, /* tp_as_number */
1149 0, /* tp_as_sequence */
1150 0, /* tp_as_mapping */
1151 0, /* tp_hash */
1152 0, /* tp_call */
1153 0, /* tp_str */
1154 PyObject_GenericGetAttr, /* tp_getattro */
1155 0, /* tp_setattro */
1156 0, /* tp_as_buffer */
1157 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
1158 Py_TPFLAGS_BASETYPE, /* tp_flags */
1159 map_doc, /* tp_doc */
1160 (traverseproc)map_traverse, /* tp_traverse */
1161 0, /* tp_clear */
1162 0, /* tp_richcompare */
1163 0, /* tp_weaklistoffset */
1164 PyObject_SelfIter, /* tp_iter */
1165 (iternextfunc)map_next, /* tp_iternext */
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001166 map_methods, /* tp_methods */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001167 0, /* tp_members */
1168 0, /* tp_getset */
1169 0, /* tp_base */
1170 0, /* tp_dict */
1171 0, /* tp_descr_get */
1172 0, /* tp_descr_set */
1173 0, /* tp_dictoffset */
1174 0, /* tp_init */
1175 PyType_GenericAlloc, /* tp_alloc */
1176 map_new, /* tp_new */
1177 PyObject_GC_Del, /* tp_free */
Raymond Hettingera6c60372008-03-13 01:26:19 +00001178};
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001179
Guido van Rossum79f25d91997-04-29 20:08:16 +00001180static PyObject *
Georg Brandla18af4e2007-04-21 15:47:16 +00001181builtin_next(PyObject *self, PyObject *args)
1182{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001183 PyObject *it, *res;
1184 PyObject *def = NULL;
Georg Brandla18af4e2007-04-21 15:47:16 +00001185
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001186 if (!PyArg_UnpackTuple(args, "next", 1, 2, &it, &def))
1187 return NULL;
1188 if (!PyIter_Check(it)) {
1189 PyErr_Format(PyExc_TypeError,
Philip Jenvey50add042011-11-06 16:37:52 -08001190 "'%.200s' object is not an iterator",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001191 it->ob_type->tp_name);
1192 return NULL;
1193 }
1194
1195 res = (*it->ob_type->tp_iternext)(it);
1196 if (res != NULL) {
1197 return res;
1198 } else if (def != NULL) {
1199 if (PyErr_Occurred()) {
1200 if(!PyErr_ExceptionMatches(PyExc_StopIteration))
1201 return NULL;
1202 PyErr_Clear();
1203 }
1204 Py_INCREF(def);
1205 return def;
1206 } else if (PyErr_Occurred()) {
1207 return NULL;
1208 } else {
1209 PyErr_SetNone(PyExc_StopIteration);
1210 return NULL;
1211 }
Georg Brandla18af4e2007-04-21 15:47:16 +00001212}
1213
1214PyDoc_STRVAR(next_doc,
1215"next(iterator[, default])\n\
1216\n\
1217Return the next item from the iterator. If default is given and the iterator\n\
1218is exhausted, it is returned instead of raising StopIteration.");
1219
1220
1221static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001222builtin_setattr(PyObject *self, PyObject *args)
Guido van Rossum33894be1992-01-27 16:53:09 +00001223{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001224 PyObject *v;
1225 PyObject *name;
1226 PyObject *value;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001227
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001228 if (!PyArg_UnpackTuple(args, "setattr", 3, 3, &v, &name, &value))
1229 return NULL;
1230 if (PyObject_SetAttr(v, name, value) != 0)
1231 return NULL;
1232 Py_INCREF(Py_None);
1233 return Py_None;
Guido van Rossum33894be1992-01-27 16:53:09 +00001234}
1235
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001236PyDoc_STRVAR(setattr_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001237"setattr(object, name, value)\n\
1238\n\
1239Set a named attribute on an object; setattr(x, 'y', v) is equivalent to\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001240``x.y = v''.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001241
1242
Guido van Rossum79f25d91997-04-29 20:08:16 +00001243static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001244builtin_delattr(PyObject *self, PyObject *args)
Guido van Rossum14144fc1994-08-29 12:53:40 +00001245{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001246 PyObject *v;
1247 PyObject *name;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001248
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001249 if (!PyArg_UnpackTuple(args, "delattr", 2, 2, &v, &name))
1250 return NULL;
1251 if (PyObject_SetAttr(v, name, (PyObject *)NULL) != 0)
1252 return NULL;
1253 Py_INCREF(Py_None);
1254 return Py_None;
Guido van Rossum14144fc1994-08-29 12:53:40 +00001255}
1256
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001257PyDoc_STRVAR(delattr_doc,
Guido van Rossumdf12a591998-11-23 22:13:04 +00001258"delattr(object, name)\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001259\n\
1260Delete a named attribute on an object; delattr(x, 'y') is equivalent to\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001261``del x.y''.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001262
1263
Guido van Rossum79f25d91997-04-29 20:08:16 +00001264static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001265builtin_hash(PyObject *self, PyObject *v)
Guido van Rossum9bfef441993-03-29 10:43:31 +00001266{
Benjamin Peterson8f67d082010-10-17 20:54:53 +00001267 Py_hash_t x;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001268
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001269 x = PyObject_Hash(v);
1270 if (x == -1)
1271 return NULL;
Benjamin Peterson8f67d082010-10-17 20:54:53 +00001272 return PyLong_FromSsize_t(x);
Guido van Rossum9bfef441993-03-29 10:43:31 +00001273}
1274
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001275PyDoc_STRVAR(hash_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001276"hash(object) -> integer\n\
1277\n\
1278Return a hash value for the object. Two objects with the same value have\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001279the same hash value. The reverse is not necessarily true, but likely.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001280
1281
Guido van Rossum79f25d91997-04-29 20:08:16 +00001282static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001283builtin_hex(PyObject *self, PyObject *v)
Guido van Rossum006bcd41991-10-24 14:54:44 +00001284{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001285 return PyNumber_ToBase(v, 16);
Guido van Rossum006bcd41991-10-24 14:54:44 +00001286}
1287
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001288PyDoc_STRVAR(hex_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001289"hex(number) -> string\n\
1290\n\
Zachary Warea4b7a752013-11-24 01:19:09 -06001291Return the hexadecimal representation of an integer.\n\
1292\n\
1293 >>> hex(3735928559)\n\
1294 '0xdeadbeef'\n\
1295");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001296
1297
Guido van Rossum79f25d91997-04-29 20:08:16 +00001298static PyObject *
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001299builtin_iter(PyObject *self, PyObject *args)
1300{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001301 PyObject *v, *w = NULL;
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001302
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001303 if (!PyArg_UnpackTuple(args, "iter", 1, 2, &v, &w))
1304 return NULL;
1305 if (w == NULL)
1306 return PyObject_GetIter(v);
1307 if (!PyCallable_Check(v)) {
1308 PyErr_SetString(PyExc_TypeError,
1309 "iter(v, w): v must be callable");
1310 return NULL;
1311 }
1312 return PyCallIter_New(v, w);
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001313}
1314
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001315PyDoc_STRVAR(iter_doc,
Georg Brandld11ae5d2008-05-16 13:27:32 +00001316"iter(iterable) -> iterator\n\
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001317iter(callable, sentinel) -> iterator\n\
1318\n\
1319Get an iterator from an object. In the first form, the argument must\n\
1320supply its own iterator, or be a sequence.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001321In the second form, the callable is called until it returns the sentinel.");
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001322
1323
1324static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001325builtin_len(PyObject *self, PyObject *v)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001326{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001327 Py_ssize_t res;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001328
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001329 res = PyObject_Size(v);
1330 if (res < 0 && PyErr_Occurred())
1331 return NULL;
1332 return PyLong_FromSsize_t(res);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001333}
1334
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001335PyDoc_STRVAR(len_doc,
Benjamin Peterson5edbb7b2014-04-18 01:03:59 -04001336"len(object)\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001337\n\
Terry Jan Reedyf2fb73f2014-06-16 03:05:37 -04001338Return the number of items of a sequence or collection.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001339
1340
Guido van Rossum79f25d91997-04-29 20:08:16 +00001341static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001342builtin_locals(PyObject *self)
Guido van Rossum872537c1995-07-07 22:43:42 +00001343{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001344 PyObject *d;
Guido van Rossum872537c1995-07-07 22:43:42 +00001345
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001346 d = PyEval_GetLocals();
1347 Py_XINCREF(d);
1348 return d;
Guido van Rossum872537c1995-07-07 22:43:42 +00001349}
1350
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001351PyDoc_STRVAR(locals_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001352"locals() -> dictionary\n\
1353\n\
Raymond Hettinger69bf8f32003-01-04 02:16:22 +00001354Update and return a dictionary containing the current scope's local variables.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001355
1356
Guido van Rossum79f25d91997-04-29 20:08:16 +00001357static PyObject *
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001358min_max(PyObject *args, PyObject *kwds, int op)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001359{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001360 PyObject *v, *it, *item, *val, *maxitem, *maxval, *keyfunc=NULL;
Raymond Hettinger4d6018f2013-06-24 22:43:02 -07001361 PyObject *emptytuple, *defaultval = NULL;
1362 static char *kwlist[] = {"key", "default", NULL};
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001363 const char *name = op == Py_LT ? "min" : "max";
Raymond Hettinger4d6018f2013-06-24 22:43:02 -07001364 const int positional = PyTuple_Size(args) > 1;
1365 int ret;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001366
Raymond Hettinger4d6018f2013-06-24 22:43:02 -07001367 if (positional)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001368 v = args;
Serhiy Storchakac6792272013-10-19 21:03:34 +03001369 else if (!PyArg_UnpackTuple(args, name, 1, 1, &v))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001370 return NULL;
Tim Peters67d687a2002-04-29 21:27:32 +00001371
Raymond Hettinger4d6018f2013-06-24 22:43:02 -07001372 emptytuple = PyTuple_New(0);
1373 if (emptytuple == NULL)
1374 return NULL;
1375 ret = PyArg_ParseTupleAndKeywords(emptytuple, kwds, "|$OO", kwlist,
1376 &keyfunc, &defaultval);
1377 Py_DECREF(emptytuple);
1378 if (!ret)
1379 return NULL;
1380
1381 if (positional && defaultval != NULL) {
1382 PyErr_Format(PyExc_TypeError,
1383 "Cannot specify a default for %s() with multiple "
1384 "positional arguments", name);
1385 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001386 }
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001387
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001388 it = PyObject_GetIter(v);
1389 if (it == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001390 return NULL;
1391 }
Tim Petersc3074532001-05-03 07:00:32 +00001392
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001393 maxitem = NULL; /* the result */
1394 maxval = NULL; /* the value associated with the result */
1395 while (( item = PyIter_Next(it) )) {
1396 /* get the value from the key function */
1397 if (keyfunc != NULL) {
1398 val = PyObject_CallFunctionObjArgs(keyfunc, item, NULL);
1399 if (val == NULL)
1400 goto Fail_it_item;
1401 }
1402 /* no key function; the value is the item */
1403 else {
1404 val = item;
1405 Py_INCREF(val);
1406 }
Tim Petersc3074532001-05-03 07:00:32 +00001407
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001408 /* maximum value and item are unset; set them */
1409 if (maxval == NULL) {
1410 maxitem = item;
1411 maxval = val;
1412 }
1413 /* maximum value and item are set; update them as necessary */
1414 else {
1415 int cmp = PyObject_RichCompareBool(val, maxval, op);
1416 if (cmp < 0)
1417 goto Fail_it_item_and_val;
1418 else if (cmp > 0) {
1419 Py_DECREF(maxval);
1420 Py_DECREF(maxitem);
1421 maxval = val;
1422 maxitem = item;
1423 }
1424 else {
1425 Py_DECREF(item);
1426 Py_DECREF(val);
1427 }
1428 }
1429 }
1430 if (PyErr_Occurred())
1431 goto Fail_it;
1432 if (maxval == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001433 assert(maxitem == NULL);
Raymond Hettinger4d6018f2013-06-24 22:43:02 -07001434 if (defaultval != NULL) {
1435 Py_INCREF(defaultval);
1436 maxitem = defaultval;
1437 } else {
1438 PyErr_Format(PyExc_ValueError,
1439 "%s() arg is an empty sequence", name);
1440 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001441 }
1442 else
1443 Py_DECREF(maxval);
1444 Py_DECREF(it);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001445 return maxitem;
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001446
1447Fail_it_item_and_val:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001448 Py_DECREF(val);
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001449Fail_it_item:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001450 Py_DECREF(item);
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001451Fail_it:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001452 Py_XDECREF(maxval);
1453 Py_XDECREF(maxitem);
1454 Py_DECREF(it);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001455 return NULL;
Guido van Rossum3f5da241990-12-20 15:06:42 +00001456}
1457
Guido van Rossum79f25d91997-04-29 20:08:16 +00001458static PyObject *
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001459builtin_min(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001460{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001461 return min_max(args, kwds, Py_LT);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001462}
1463
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001464PyDoc_STRVAR(min_doc,
Raymond Hettinger2a545822014-05-19 22:20:52 +01001465"min(iterable, *[, default=obj, key=func]) -> value\n\
1466min(arg1, arg2, *args, *[, key=func]) -> value\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001467\n\
Raymond Hettinger2a545822014-05-19 22:20:52 +01001468With a single iterable argument, return its smallest item. The\n\
1469default keyword-only argument specifies an object to return if\n\
1470the provided iterable is empty.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001471With two or more arguments, return the smallest argument.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001472
1473
Guido van Rossum79f25d91997-04-29 20:08:16 +00001474static PyObject *
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001475builtin_max(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001476{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001477 return min_max(args, kwds, Py_GT);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001478}
1479
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001480PyDoc_STRVAR(max_doc,
Raymond Hettinger2a545822014-05-19 22:20:52 +01001481"max(iterable, *[, default=obj, key=func]) -> value\n\
1482max(arg1, arg2, *args, *[, key=func]) -> value\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001483\n\
Raymond Hettinger2a545822014-05-19 22:20:52 +01001484With a single iterable argument, return its biggest item. The\n\
1485default keyword-only argument specifies an object to return if\n\
1486the provided iterable is empty.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001487With two or more arguments, return the largest argument.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001488
1489
Guido van Rossum79f25d91997-04-29 20:08:16 +00001490static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001491builtin_oct(PyObject *self, PyObject *v)
Guido van Rossum006bcd41991-10-24 14:54:44 +00001492{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001493 return PyNumber_ToBase(v, 8);
Guido van Rossum006bcd41991-10-24 14:54:44 +00001494}
1495
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001496PyDoc_STRVAR(oct_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001497"oct(number) -> string\n\
1498\n\
Zachary Warea4b7a752013-11-24 01:19:09 -06001499Return the octal representation of an integer.\n\
1500\n\
1501 >>> oct(342391)\n\
1502 '0o1234567'\n\
1503");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001504
1505
Guido van Rossum79f25d91997-04-29 20:08:16 +00001506static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001507builtin_ord(PyObject *self, PyObject* obj)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001508{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001509 long ord;
1510 Py_ssize_t size;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001511
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001512 if (PyBytes_Check(obj)) {
1513 size = PyBytes_GET_SIZE(obj);
1514 if (size == 1) {
1515 ord = (long)((unsigned char)*PyBytes_AS_STRING(obj));
1516 return PyLong_FromLong(ord);
1517 }
1518 }
1519 else if (PyUnicode_Check(obj)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001520 if (PyUnicode_READY(obj) == -1)
1521 return NULL;
1522 size = PyUnicode_GET_LENGTH(obj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001523 if (size == 1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001524 ord = (long)PyUnicode_READ_CHAR(obj, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001525 return PyLong_FromLong(ord);
1526 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001527 }
1528 else if (PyByteArray_Check(obj)) {
1529 /* XXX Hopefully this is temporary */
1530 size = PyByteArray_GET_SIZE(obj);
1531 if (size == 1) {
1532 ord = (long)((unsigned char)*PyByteArray_AS_STRING(obj));
1533 return PyLong_FromLong(ord);
1534 }
1535 }
1536 else {
1537 PyErr_Format(PyExc_TypeError,
1538 "ord() expected string of length 1, but " \
1539 "%.200s found", obj->ob_type->tp_name);
1540 return NULL;
1541 }
Guido van Rossum09095f32000-03-10 23:00:52 +00001542
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001543 PyErr_Format(PyExc_TypeError,
1544 "ord() expected a character, "
1545 "but string of length %zd found",
1546 size);
1547 return NULL;
Guido van Rossum3f5da241990-12-20 15:06:42 +00001548}
1549
Guido van Rossum307fa8c2007-07-16 20:46:27 +00001550PyDoc_VAR(ord_doc) = PyDoc_STR(
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001551"ord(c) -> integer\n\
1552\n\
Guido van Rossum8ac004e2007-07-15 13:00:05 +00001553Return the integer ordinal of a one-character string."
Antoine Pitrouedc60182012-06-23 14:19:58 +02001554);
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001555
1556
Guido van Rossum79f25d91997-04-29 20:08:16 +00001557static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001558builtin_pow(PyObject *self, PyObject *args)
Guido van Rossum6a00cd81995-01-07 12:39:01 +00001559{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001560 PyObject *v, *w, *z = Py_None;
Guido van Rossum6a00cd81995-01-07 12:39:01 +00001561
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001562 if (!PyArg_UnpackTuple(args, "pow", 2, 3, &v, &w, &z))
1563 return NULL;
1564 return PyNumber_Power(v, w, z);
Guido van Rossumd4905451991-05-05 20:00:36 +00001565}
1566
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001567PyDoc_STRVAR(pow_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001568"pow(x, y[, z]) -> number\n\
1569\n\
1570With two arguments, equivalent to x**y. With three arguments,\n\
Serhiy Storchaka95949422013-08-27 19:40:23 +03001571equivalent to (x**y) % z, but may be more efficient (e.g. for ints).");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001572
1573
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001574
Guido van Rossum34343512006-11-30 22:13:52 +00001575static PyObject *
1576builtin_print(PyObject *self, PyObject *args, PyObject *kwds)
1577{
Georg Brandlbc3b6822012-01-13 19:41:25 +01001578 static char *kwlist[] = {"sep", "end", "file", "flush", 0};
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001579 static PyObject *dummy_args;
Georg Brandlbc3b6822012-01-13 19:41:25 +01001580 PyObject *sep = NULL, *end = NULL, *file = NULL, *flush = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001581 int i, err;
Guido van Rossum34343512006-11-30 22:13:52 +00001582
Benjamin Peterson00102562012-01-11 21:00:16 -05001583 if (dummy_args == NULL && !(dummy_args = PyTuple_New(0)))
Georg Brandlbc3b6822012-01-13 19:41:25 +01001584 return NULL;
1585 if (!PyArg_ParseTupleAndKeywords(dummy_args, kwds, "|OOOO:print",
1586 kwlist, &sep, &end, &file, &flush))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001587 return NULL;
1588 if (file == NULL || file == Py_None) {
Victor Stinnerbd303c12013-11-07 23:07:29 +01001589 file = _PySys_GetObjectId(&PyId_stdout);
Victor Stinner1e53bba2013-07-16 22:26:05 +02001590 if (file == NULL) {
1591 PyErr_SetString(PyExc_RuntimeError, "lost sys.stdout");
1592 return NULL;
1593 }
1594
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001595 /* sys.stdout may be None when FILE* stdout isn't connected */
1596 if (file == Py_None)
1597 Py_RETURN_NONE;
1598 }
Guido van Rossum34343512006-11-30 22:13:52 +00001599
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001600 if (sep == Py_None) {
1601 sep = NULL;
1602 }
1603 else if (sep && !PyUnicode_Check(sep)) {
1604 PyErr_Format(PyExc_TypeError,
1605 "sep must be None or a string, not %.200s",
1606 sep->ob_type->tp_name);
1607 return NULL;
1608 }
1609 if (end == Py_None) {
1610 end = NULL;
1611 }
1612 else if (end && !PyUnicode_Check(end)) {
1613 PyErr_Format(PyExc_TypeError,
1614 "end must be None or a string, not %.200s",
1615 end->ob_type->tp_name);
1616 return NULL;
1617 }
Guido van Rossum34343512006-11-30 22:13:52 +00001618
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001619 for (i = 0; i < PyTuple_Size(args); i++) {
1620 if (i > 0) {
1621 if (sep == NULL)
1622 err = PyFile_WriteString(" ", file);
1623 else
1624 err = PyFile_WriteObject(sep, file,
1625 Py_PRINT_RAW);
1626 if (err)
1627 return NULL;
1628 }
1629 err = PyFile_WriteObject(PyTuple_GetItem(args, i), file,
1630 Py_PRINT_RAW);
1631 if (err)
1632 return NULL;
1633 }
Guido van Rossum34343512006-11-30 22:13:52 +00001634
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001635 if (end == NULL)
1636 err = PyFile_WriteString("\n", file);
1637 else
1638 err = PyFile_WriteObject(end, file, Py_PRINT_RAW);
1639 if (err)
1640 return NULL;
Guido van Rossum34343512006-11-30 22:13:52 +00001641
Georg Brandlbc3b6822012-01-13 19:41:25 +01001642 if (flush != NULL) {
1643 PyObject *tmp;
1644 int do_flush = PyObject_IsTrue(flush);
1645 if (do_flush == -1)
1646 return NULL;
1647 else if (do_flush) {
Victor Stinnereaa28832013-11-07 00:01:51 +01001648 tmp = _PyObject_CallMethodId(file, &PyId_flush, "");
Georg Brandlbc3b6822012-01-13 19:41:25 +01001649 if (tmp == NULL)
1650 return NULL;
1651 else
1652 Py_DECREF(tmp);
1653 }
1654 }
1655
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001656 Py_RETURN_NONE;
Guido van Rossum34343512006-11-30 22:13:52 +00001657}
1658
1659PyDoc_STRVAR(print_doc,
Senthil Kumarane9175bd2012-08-10 13:53:45 -07001660"print(value, ..., sep=' ', end='\\n', file=sys.stdout, flush=False)\n\
Guido van Rossum34343512006-11-30 22:13:52 +00001661\n\
1662Prints the values to a stream, or to sys.stdout by default.\n\
1663Optional keyword arguments:\n\
Senthil Kumarane9175bd2012-08-10 13:53:45 -07001664file: a file-like object (stream); defaults to the current sys.stdout.\n\
1665sep: string inserted between values, default a space.\n\
1666end: string appended after the last value, default a newline.\n\
1667flush: whether to forcibly flush the stream.");
Guido van Rossum34343512006-11-30 22:13:52 +00001668
1669
Guido van Rossuma88a0332007-02-26 16:59:55 +00001670static PyObject *
1671builtin_input(PyObject *self, PyObject *args)
1672{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001673 PyObject *promptarg = NULL;
Victor Stinnerbd303c12013-11-07 23:07:29 +01001674 PyObject *fin = _PySys_GetObjectId(&PyId_stdin);
1675 PyObject *fout = _PySys_GetObjectId(&PyId_stdout);
1676 PyObject *ferr = _PySys_GetObjectId(&PyId_stderr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001677 PyObject *tmp;
1678 long fd;
1679 int tty;
Guido van Rossuma88a0332007-02-26 16:59:55 +00001680
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001681 /* Parse arguments */
1682 if (!PyArg_UnpackTuple(args, "input", 0, 1, &promptarg))
1683 return NULL;
Guido van Rossuma88a0332007-02-26 16:59:55 +00001684
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001685 /* Check that stdin/out/err are intact */
1686 if (fin == NULL || fin == Py_None) {
1687 PyErr_SetString(PyExc_RuntimeError,
1688 "input(): lost sys.stdin");
1689 return NULL;
1690 }
1691 if (fout == NULL || fout == Py_None) {
1692 PyErr_SetString(PyExc_RuntimeError,
1693 "input(): lost sys.stdout");
1694 return NULL;
1695 }
1696 if (ferr == NULL || ferr == Py_None) {
1697 PyErr_SetString(PyExc_RuntimeError,
1698 "input(): lost sys.stderr");
1699 return NULL;
1700 }
Guido van Rossumeba76962007-05-27 09:13:28 +00001701
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001702 /* First of all, flush stderr */
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001703 tmp = _PyObject_CallMethodId(ferr, &PyId_flush, "");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001704 if (tmp == NULL)
1705 PyErr_Clear();
1706 else
1707 Py_DECREF(tmp);
Guido van Rossumeba76962007-05-27 09:13:28 +00001708
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001709 /* We should only use (GNU) readline if Python's sys.stdin and
1710 sys.stdout are the same as C's stdin and stdout, because we
1711 need to pass it those. */
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001712 tmp = _PyObject_CallMethodId(fin, &PyId_fileno, "");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001713 if (tmp == NULL) {
1714 PyErr_Clear();
1715 tty = 0;
1716 }
1717 else {
1718 fd = PyLong_AsLong(tmp);
1719 Py_DECREF(tmp);
1720 if (fd < 0 && PyErr_Occurred())
1721 return NULL;
1722 tty = fd == fileno(stdin) && isatty(fd);
1723 }
1724 if (tty) {
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001725 tmp = _PyObject_CallMethodId(fout, &PyId_fileno, "");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001726 if (tmp == NULL)
1727 PyErr_Clear();
1728 else {
1729 fd = PyLong_AsLong(tmp);
1730 Py_DECREF(tmp);
1731 if (fd < 0 && PyErr_Occurred())
1732 return NULL;
1733 tty = fd == fileno(stdout) && isatty(fd);
1734 }
1735 }
Guido van Rossumeba76962007-05-27 09:13:28 +00001736
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001737 /* If we're interactive, use (GNU) readline */
1738 if (tty) {
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001739 PyObject *po = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001740 char *prompt;
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001741 char *s = NULL;
1742 PyObject *stdin_encoding = NULL, *stdin_errors = NULL;
1743 PyObject *stdout_encoding = NULL, *stdout_errors = NULL;
1744 char *stdin_encoding_str, *stdin_errors_str;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001745 PyObject *result;
Victor Stinnerc0f1a1a2011-02-23 12:07:37 +00001746 size_t len;
Martin v. Löwis4a7b5d52007-09-04 05:24:49 +00001747
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02001748 stdin_encoding = _PyObject_GetAttrId(fin, &PyId_encoding);
Antoine Pitrou5ee9d8a2011-11-06 00:38:45 +01001749 stdin_errors = _PyObject_GetAttrId(fin, &PyId_errors);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001750 if (!stdin_encoding || !stdin_errors)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001751 /* stdin is a text stream, so it must have an
1752 encoding. */
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001753 goto _readline_errors;
Victor Stinner306f0102010-05-19 01:06:22 +00001754 stdin_encoding_str = _PyUnicode_AsString(stdin_encoding);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001755 stdin_errors_str = _PyUnicode_AsString(stdin_errors);
1756 if (!stdin_encoding_str || !stdin_errors_str)
1757 goto _readline_errors;
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001758 tmp = _PyObject_CallMethodId(fout, &PyId_flush, "");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001759 if (tmp == NULL)
1760 PyErr_Clear();
1761 else
1762 Py_DECREF(tmp);
1763 if (promptarg != NULL) {
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001764 /* We have a prompt, encode it as stdout would */
1765 char *stdout_encoding_str, *stdout_errors_str;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001766 PyObject *stringpo;
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02001767 stdout_encoding = _PyObject_GetAttrId(fout, &PyId_encoding);
Antoine Pitrou5ee9d8a2011-11-06 00:38:45 +01001768 stdout_errors = _PyObject_GetAttrId(fout, &PyId_errors);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001769 if (!stdout_encoding || !stdout_errors)
1770 goto _readline_errors;
Victor Stinner306f0102010-05-19 01:06:22 +00001771 stdout_encoding_str = _PyUnicode_AsString(stdout_encoding);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001772 stdout_errors_str = _PyUnicode_AsString(stdout_errors);
1773 if (!stdout_encoding_str || !stdout_errors_str)
1774 goto _readline_errors;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001775 stringpo = PyObject_Str(promptarg);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001776 if (stringpo == NULL)
1777 goto _readline_errors;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001778 po = PyUnicode_AsEncodedString(stringpo,
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001779 stdout_encoding_str, stdout_errors_str);
1780 Py_CLEAR(stdout_encoding);
1781 Py_CLEAR(stdout_errors);
1782 Py_CLEAR(stringpo);
1783 if (po == NULL)
1784 goto _readline_errors;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001785 prompt = PyBytes_AsString(po);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001786 if (prompt == NULL)
1787 goto _readline_errors;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001788 }
1789 else {
1790 po = NULL;
1791 prompt = "";
1792 }
1793 s = PyOS_Readline(stdin, stdout, prompt);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001794 if (s == NULL) {
Richard Oudkerk614c5782013-04-03 13:44:50 +01001795 PyErr_CheckSignals();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001796 if (!PyErr_Occurred())
1797 PyErr_SetNone(PyExc_KeyboardInterrupt);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001798 goto _readline_errors;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001799 }
Victor Stinnerc0f1a1a2011-02-23 12:07:37 +00001800
1801 len = strlen(s);
1802 if (len == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001803 PyErr_SetNone(PyExc_EOFError);
1804 result = NULL;
1805 }
Victor Stinnerc0f1a1a2011-02-23 12:07:37 +00001806 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001807 if (len > PY_SSIZE_T_MAX) {
1808 PyErr_SetString(PyExc_OverflowError,
1809 "input: input too long");
1810 result = NULL;
1811 }
1812 else {
Victor Stinnerc0f1a1a2011-02-23 12:07:37 +00001813 len--; /* strip trailing '\n' */
1814 if (len != 0 && s[len-1] == '\r')
1815 len--; /* strip trailing '\r' */
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001816 result = PyUnicode_Decode(s, len, stdin_encoding_str,
1817 stdin_errors_str);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001818 }
1819 }
1820 Py_DECREF(stdin_encoding);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001821 Py_DECREF(stdin_errors);
1822 Py_XDECREF(po);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001823 PyMem_FREE(s);
1824 return result;
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001825 _readline_errors:
1826 Py_XDECREF(stdin_encoding);
1827 Py_XDECREF(stdout_encoding);
1828 Py_XDECREF(stdin_errors);
1829 Py_XDECREF(stdout_errors);
1830 Py_XDECREF(po);
1831 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001832 }
Guido van Rossumeba76962007-05-27 09:13:28 +00001833
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001834 /* Fallback if we're not interactive */
1835 if (promptarg != NULL) {
1836 if (PyFile_WriteObject(promptarg, fout, Py_PRINT_RAW) != 0)
1837 return NULL;
1838 }
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001839 tmp = _PyObject_CallMethodId(fout, &PyId_flush, "");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001840 if (tmp == NULL)
1841 PyErr_Clear();
1842 else
1843 Py_DECREF(tmp);
1844 return PyFile_GetLine(fin, -1);
Guido van Rossuma88a0332007-02-26 16:59:55 +00001845}
1846
1847PyDoc_STRVAR(input_doc,
1848"input([prompt]) -> string\n\
1849\n\
1850Read a string from standard input. The trailing newline is stripped.\n\
1851If the user hits EOF (Unix: Ctl-D, Windows: Ctl-Z+Return), raise EOFError.\n\
1852On Unix, GNU readline is used if enabled. The prompt string, if given,\n\
1853is printed without a trailing newline before reading.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001854
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001855
Guido van Rossum79f25d91997-04-29 20:08:16 +00001856static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001857builtin_repr(PyObject *self, PyObject *v)
Guido van Rossumc89705d1992-11-26 08:54:07 +00001858{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001859 return PyObject_Repr(v);
Guido van Rossumc89705d1992-11-26 08:54:07 +00001860}
1861
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001862PyDoc_STRVAR(repr_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001863"repr(object) -> string\n\
1864\n\
1865Return the canonical string representation of the object.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001866For most object types, eval(repr(object)) == object.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001867
1868
Guido van Rossum79f25d91997-04-29 20:08:16 +00001869static PyObject *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001870builtin_round(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum9e51f9b1993-02-12 16:29:05 +00001871{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001872 PyObject *ndigits = NULL;
1873 static char *kwlist[] = {"number", "ndigits", 0};
Benjamin Peterson214a7d22013-04-13 17:19:01 -04001874 PyObject *number, *round, *result;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001875
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001876 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|O:round",
1877 kwlist, &number, &ndigits))
1878 return NULL;
Alex Martelliae211f92007-08-22 23:21:33 +00001879
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001880 if (Py_TYPE(number)->tp_dict == NULL) {
1881 if (PyType_Ready(Py_TYPE(number)) < 0)
1882 return NULL;
1883 }
Guido van Rossum15d3d042007-08-24 02:02:45 +00001884
Benjamin Peterson214a7d22013-04-13 17:19:01 -04001885 round = _PyObject_LookupSpecial(number, &PyId___round__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001886 if (round == NULL) {
Benjamin Peterson214a7d22013-04-13 17:19:01 -04001887 if (!PyErr_Occurred())
1888 PyErr_Format(PyExc_TypeError,
1889 "type %.100s doesn't define __round__ method",
1890 Py_TYPE(number)->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001891 return NULL;
1892 }
Alex Martelliae211f92007-08-22 23:21:33 +00001893
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001894 if (ndigits == NULL)
Benjamin Peterson214a7d22013-04-13 17:19:01 -04001895 result = PyObject_CallFunctionObjArgs(round, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001896 else
Benjamin Peterson214a7d22013-04-13 17:19:01 -04001897 result = PyObject_CallFunctionObjArgs(round, ndigits, NULL);
1898 Py_DECREF(round);
1899 return result;
Guido van Rossum9e51f9b1993-02-12 16:29:05 +00001900}
1901
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001902PyDoc_STRVAR(round_doc,
Mark Dickinson1124e712009-01-28 21:25:58 +00001903"round(number[, ndigits]) -> number\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001904\n\
1905Round a number to a given precision in decimal digits (default 0 digits).\n\
Mark Dickinson0d748c22008-07-05 11:29:03 +00001906This returns an int when called with one argument, otherwise the\n\
Georg Brandl809ddaa2008-07-01 20:39:59 +00001907same type as the number. ndigits may be negative.");
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001908
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001909
Raymond Hettinger64958a12003-12-17 20:43:33 +00001910static PyObject *
1911builtin_sorted(PyObject *self, PyObject *args, PyObject *kwds)
1912{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001913 PyObject *newlist, *v, *seq, *keyfunc=NULL, *newargs;
1914 PyObject *callable;
1915 static char *kwlist[] = {"iterable", "key", "reverse", 0};
1916 int reverse;
Raymond Hettinger64958a12003-12-17 20:43:33 +00001917
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001918 /* args 1-3 should match listsort in Objects/listobject.c */
1919 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|Oi:sorted",
1920 kwlist, &seq, &keyfunc, &reverse))
1921 return NULL;
Raymond Hettinger64958a12003-12-17 20:43:33 +00001922
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001923 newlist = PySequence_List(seq);
1924 if (newlist == NULL)
1925 return NULL;
Raymond Hettinger64958a12003-12-17 20:43:33 +00001926
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02001927 callable = _PyObject_GetAttrId(newlist, &PyId_sort);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001928 if (callable == NULL) {
1929 Py_DECREF(newlist);
1930 return NULL;
1931 }
Georg Brandl99d7e4e2005-08-31 22:21:15 +00001932
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001933 newargs = PyTuple_GetSlice(args, 1, 4);
1934 if (newargs == NULL) {
1935 Py_DECREF(newlist);
1936 Py_DECREF(callable);
1937 return NULL;
1938 }
Raymond Hettinger64958a12003-12-17 20:43:33 +00001939
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001940 v = PyObject_Call(callable, newargs, kwds);
1941 Py_DECREF(newargs);
1942 Py_DECREF(callable);
1943 if (v == NULL) {
1944 Py_DECREF(newlist);
1945 return NULL;
1946 }
1947 Py_DECREF(v);
1948 return newlist;
Raymond Hettinger64958a12003-12-17 20:43:33 +00001949}
1950
1951PyDoc_STRVAR(sorted_doc,
Raymond Hettinger70b64fc2008-01-30 20:15:17 +00001952"sorted(iterable, key=None, reverse=False) --> new sorted list");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001953
Guido van Rossum79f25d91997-04-29 20:08:16 +00001954static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001955builtin_vars(PyObject *self, PyObject *args)
Guido van Rossum2d951851994-08-29 12:52:16 +00001956{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001957 PyObject *v = NULL;
1958 PyObject *d;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001959
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001960 if (!PyArg_UnpackTuple(args, "vars", 0, 1, &v))
1961 return NULL;
1962 if (v == NULL) {
1963 d = PyEval_GetLocals();
Victor Stinner41bb43a2013-10-29 01:19:37 +01001964 if (d == NULL)
1965 return NULL;
1966 Py_INCREF(d);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001967 }
1968 else {
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02001969 d = _PyObject_GetAttrId(v, &PyId___dict__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001970 if (d == NULL) {
1971 PyErr_SetString(PyExc_TypeError,
1972 "vars() argument must have __dict__ attribute");
1973 return NULL;
1974 }
1975 }
1976 return d;
Guido van Rossum2d951851994-08-29 12:52:16 +00001977}
1978
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001979PyDoc_STRVAR(vars_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001980"vars([object]) -> dictionary\n\
1981\n\
1982Without arguments, equivalent to locals().\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001983With an argument, equivalent to object.__dict__.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001984
Alex Martellia70b1912003-04-22 08:12:33 +00001985static PyObject*
1986builtin_sum(PyObject *self, PyObject *args)
1987{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001988 PyObject *seq;
1989 PyObject *result = NULL;
1990 PyObject *temp, *item, *iter;
Alex Martellia70b1912003-04-22 08:12:33 +00001991
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001992 if (!PyArg_UnpackTuple(args, "sum", 1, 2, &seq, &result))
1993 return NULL;
Alex Martellia70b1912003-04-22 08:12:33 +00001994
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001995 iter = PyObject_GetIter(seq);
1996 if (iter == NULL)
1997 return NULL;
Alex Martellia70b1912003-04-22 08:12:33 +00001998
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001999 if (result == NULL) {
2000 result = PyLong_FromLong(0);
2001 if (result == NULL) {
2002 Py_DECREF(iter);
2003 return NULL;
2004 }
2005 } else {
2006 /* reject string values for 'start' parameter */
2007 if (PyUnicode_Check(result)) {
2008 PyErr_SetString(PyExc_TypeError,
2009 "sum() can't sum strings [use ''.join(seq) instead]");
2010 Py_DECREF(iter);
2011 return NULL;
2012 }
Benjamin Petersonce071ca2011-07-29 14:23:47 -05002013 if (PyBytes_Check(result)) {
2014 PyErr_SetString(PyExc_TypeError,
2015 "sum() can't sum bytes [use b''.join(seq) instead]");
Benjamin Peterson405f32c2011-07-29 22:43:45 -05002016 Py_DECREF(iter);
Benjamin Petersonce071ca2011-07-29 14:23:47 -05002017 return NULL;
2018 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002019 if (PyByteArray_Check(result)) {
2020 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson4f921c22011-07-29 14:24:29 -05002021 "sum() can't sum bytearray [use b''.join(seq) instead]");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002022 Py_DECREF(iter);
2023 return NULL;
2024 }
Guido van Rossum3172c5d2007-10-16 18:12:55 +00002025
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002026 Py_INCREF(result);
2027 }
Alex Martellia70b1912003-04-22 08:12:33 +00002028
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002029#ifndef SLOW_SUM
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002030 /* Fast addition by keeping temporary sums in C instead of new Python objects.
2031 Assumes all inputs are the same type. If the assumption fails, default
2032 to the more general routine.
2033 */
2034 if (PyLong_CheckExact(result)) {
2035 int overflow;
2036 long i_result = PyLong_AsLongAndOverflow(result, &overflow);
2037 /* If this already overflowed, don't even enter the loop. */
2038 if (overflow == 0) {
2039 Py_DECREF(result);
2040 result = NULL;
2041 }
2042 while(result == NULL) {
2043 item = PyIter_Next(iter);
2044 if (item == NULL) {
2045 Py_DECREF(iter);
2046 if (PyErr_Occurred())
2047 return NULL;
2048 return PyLong_FromLong(i_result);
2049 }
2050 if (PyLong_CheckExact(item)) {
2051 long b = PyLong_AsLongAndOverflow(item, &overflow);
2052 long x = i_result + b;
2053 if (overflow == 0 && ((x^i_result) >= 0 || (x^b) >= 0)) {
2054 i_result = x;
2055 Py_DECREF(item);
2056 continue;
2057 }
2058 }
2059 /* Either overflowed or is not an int. Restore real objects and process normally */
2060 result = PyLong_FromLong(i_result);
Christian Heimes704e2d32013-07-26 22:49:26 +02002061 if (result == NULL) {
2062 Py_DECREF(item);
2063 Py_DECREF(iter);
2064 return NULL;
2065 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002066 temp = PyNumber_Add(result, item);
2067 Py_DECREF(result);
2068 Py_DECREF(item);
2069 result = temp;
2070 if (result == NULL) {
2071 Py_DECREF(iter);
2072 return NULL;
2073 }
2074 }
2075 }
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002076
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002077 if (PyFloat_CheckExact(result)) {
2078 double f_result = PyFloat_AS_DOUBLE(result);
2079 Py_DECREF(result);
2080 result = NULL;
2081 while(result == NULL) {
2082 item = PyIter_Next(iter);
2083 if (item == NULL) {
2084 Py_DECREF(iter);
2085 if (PyErr_Occurred())
2086 return NULL;
2087 return PyFloat_FromDouble(f_result);
2088 }
2089 if (PyFloat_CheckExact(item)) {
2090 PyFPE_START_PROTECT("add", Py_DECREF(item); Py_DECREF(iter); return 0)
2091 f_result += PyFloat_AS_DOUBLE(item);
2092 PyFPE_END_PROTECT(f_result)
2093 Py_DECREF(item);
2094 continue;
2095 }
2096 if (PyLong_CheckExact(item)) {
2097 long value;
2098 int overflow;
2099 value = PyLong_AsLongAndOverflow(item, &overflow);
2100 if (!overflow) {
2101 PyFPE_START_PROTECT("add", Py_DECREF(item); Py_DECREF(iter); return 0)
2102 f_result += (double)value;
2103 PyFPE_END_PROTECT(f_result)
2104 Py_DECREF(item);
2105 continue;
2106 }
2107 }
2108 result = PyFloat_FromDouble(f_result);
2109 temp = PyNumber_Add(result, item);
2110 Py_DECREF(result);
2111 Py_DECREF(item);
2112 result = temp;
2113 if (result == NULL) {
2114 Py_DECREF(iter);
2115 return NULL;
2116 }
2117 }
2118 }
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002119#endif
2120
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002121 for(;;) {
2122 item = PyIter_Next(iter);
2123 if (item == NULL) {
2124 /* error, or end-of-sequence */
2125 if (PyErr_Occurred()) {
2126 Py_DECREF(result);
2127 result = NULL;
2128 }
2129 break;
2130 }
2131 /* It's tempting to use PyNumber_InPlaceAdd instead of
2132 PyNumber_Add here, to avoid quadratic running time
2133 when doing 'sum(list_of_lists, [])'. However, this
2134 would produce a change in behaviour: a snippet like
Mark Dickinson9acadc52009-10-26 14:19:42 +00002135
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002136 empty = []
2137 sum([[x] for x in range(10)], empty)
Mark Dickinson9acadc52009-10-26 14:19:42 +00002138
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002139 would change the value of empty. */
2140 temp = PyNumber_Add(result, item);
2141 Py_DECREF(result);
2142 Py_DECREF(item);
2143 result = temp;
2144 if (result == NULL)
2145 break;
2146 }
2147 Py_DECREF(iter);
2148 return result;
Alex Martellia70b1912003-04-22 08:12:33 +00002149}
2150
2151PyDoc_STRVAR(sum_doc,
Georg Brandld11ae5d2008-05-16 13:27:32 +00002152"sum(iterable[, start]) -> value\n\
Alex Martellia70b1912003-04-22 08:12:33 +00002153\n\
R David Murray87ead112013-07-10 16:22:14 -04002154Return the sum of an iterable of numbers (NOT strings) plus the value\n\
Georg Brandld11ae5d2008-05-16 13:27:32 +00002155of parameter 'start' (which defaults to 0). When the iterable is\n\
R David Murray87ead112013-07-10 16:22:14 -04002156empty, return start.");
Alex Martellia70b1912003-04-22 08:12:33 +00002157
2158
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002159static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002160builtin_isinstance(PyObject *self, PyObject *args)
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002161{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002162 PyObject *inst;
2163 PyObject *cls;
2164 int retval;
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002165
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002166 if (!PyArg_UnpackTuple(args, "isinstance", 2, 2, &inst, &cls))
2167 return NULL;
Guido van Rossumf5dd9141997-12-02 19:11:45 +00002168
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002169 retval = PyObject_IsInstance(inst, cls);
2170 if (retval < 0)
2171 return NULL;
2172 return PyBool_FromLong(retval);
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002173}
2174
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002175PyDoc_STRVAR(isinstance_doc,
Guido van Rossum77f6a652002-04-03 22:41:51 +00002176"isinstance(object, class-or-type-or-tuple) -> bool\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002177\n\
2178Return whether an object is an instance of a class or of a subclass thereof.\n\
Guido van Rossum03290ec2001-10-07 20:54:12 +00002179With a type as second argument, return whether that is the object's type.\n\
2180The form using a tuple, isinstance(x, (A, B, ...)), is a shortcut for\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002181isinstance(x, A) or isinstance(x, B) or ... (etc.).");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002182
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002183
2184static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002185builtin_issubclass(PyObject *self, PyObject *args)
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002186{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002187 PyObject *derived;
2188 PyObject *cls;
2189 int retval;
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002190
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002191 if (!PyArg_UnpackTuple(args, "issubclass", 2, 2, &derived, &cls))
2192 return NULL;
Guido van Rossum668213d1999-06-16 17:28:37 +00002193
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002194 retval = PyObject_IsSubclass(derived, cls);
2195 if (retval < 0)
2196 return NULL;
2197 return PyBool_FromLong(retval);
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002198}
2199
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002200PyDoc_STRVAR(issubclass_doc,
Guido van Rossum77f6a652002-04-03 22:41:51 +00002201"issubclass(C, B) -> bool\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002202\n\
Walter Dörwaldd9a6ad32002-12-12 16:41:44 +00002203Return whether class C is a subclass (i.e., a derived class) of class B.\n\
2204When using a tuple as the second argument issubclass(X, (A, B, ...)),\n\
2205is a shortcut for issubclass(X, A) or issubclass(X, B) or ... (etc.).");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002206
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002207
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002208typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002209 PyObject_HEAD
2210 Py_ssize_t tuplesize;
2211 PyObject *ittuple; /* tuple of iterators */
2212 PyObject *result;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002213} zipobject;
2214
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002215static PyObject *
2216zip_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
Barry Warsawbd599b52000-08-03 15:45:29 +00002217{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002218 zipobject *lz;
2219 Py_ssize_t i;
2220 PyObject *ittuple; /* tuple of iterators */
2221 PyObject *result;
2222 Py_ssize_t tuplesize = PySequence_Length(args);
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002223
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002224 if (type == &PyZip_Type && !_PyArg_NoKeywords("zip()", kwds))
2225 return NULL;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002226
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002227 /* args must be a tuple */
2228 assert(PyTuple_Check(args));
Barry Warsawbd599b52000-08-03 15:45:29 +00002229
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002230 /* obtain iterators */
2231 ittuple = PyTuple_New(tuplesize);
2232 if (ittuple == NULL)
2233 return NULL;
2234 for (i=0; i < tuplesize; ++i) {
2235 PyObject *item = PyTuple_GET_ITEM(args, i);
2236 PyObject *it = PyObject_GetIter(item);
2237 if (it == NULL) {
2238 if (PyErr_ExceptionMatches(PyExc_TypeError))
2239 PyErr_Format(PyExc_TypeError,
2240 "zip argument #%zd must support iteration",
2241 i+1);
2242 Py_DECREF(ittuple);
2243 return NULL;
2244 }
2245 PyTuple_SET_ITEM(ittuple, i, it);
2246 }
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002247
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002248 /* create a result holder */
2249 result = PyTuple_New(tuplesize);
2250 if (result == NULL) {
2251 Py_DECREF(ittuple);
2252 return NULL;
2253 }
2254 for (i=0 ; i < tuplesize ; i++) {
2255 Py_INCREF(Py_None);
2256 PyTuple_SET_ITEM(result, i, Py_None);
2257 }
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002258
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002259 /* create zipobject structure */
2260 lz = (zipobject *)type->tp_alloc(type, 0);
2261 if (lz == NULL) {
2262 Py_DECREF(ittuple);
2263 Py_DECREF(result);
2264 return NULL;
2265 }
2266 lz->ittuple = ittuple;
2267 lz->tuplesize = tuplesize;
2268 lz->result = result;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002269
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002270 return (PyObject *)lz;
Barry Warsawbd599b52000-08-03 15:45:29 +00002271}
2272
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002273static void
2274zip_dealloc(zipobject *lz)
2275{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002276 PyObject_GC_UnTrack(lz);
2277 Py_XDECREF(lz->ittuple);
2278 Py_XDECREF(lz->result);
2279 Py_TYPE(lz)->tp_free(lz);
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002280}
2281
2282static int
2283zip_traverse(zipobject *lz, visitproc visit, void *arg)
2284{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002285 Py_VISIT(lz->ittuple);
2286 Py_VISIT(lz->result);
2287 return 0;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002288}
2289
2290static PyObject *
2291zip_next(zipobject *lz)
2292{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002293 Py_ssize_t i;
2294 Py_ssize_t tuplesize = lz->tuplesize;
2295 PyObject *result = lz->result;
2296 PyObject *it;
2297 PyObject *item;
2298 PyObject *olditem;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002299
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002300 if (tuplesize == 0)
2301 return NULL;
2302 if (Py_REFCNT(result) == 1) {
2303 Py_INCREF(result);
2304 for (i=0 ; i < tuplesize ; i++) {
2305 it = PyTuple_GET_ITEM(lz->ittuple, i);
2306 item = (*Py_TYPE(it)->tp_iternext)(it);
Serhiy Storchaka278d03b2013-04-06 22:52:34 +03002307 if (item == NULL) {
2308 Py_DECREF(result);
2309 return NULL;
2310 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002311 olditem = PyTuple_GET_ITEM(result, i);
2312 PyTuple_SET_ITEM(result, i, item);
2313 Py_DECREF(olditem);
2314 }
2315 } else {
2316 result = PyTuple_New(tuplesize);
2317 if (result == NULL)
Serhiy Storchaka278d03b2013-04-06 22:52:34 +03002318 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002319 for (i=0 ; i < tuplesize ; i++) {
2320 it = PyTuple_GET_ITEM(lz->ittuple, i);
2321 item = (*Py_TYPE(it)->tp_iternext)(it);
Serhiy Storchaka278d03b2013-04-06 22:52:34 +03002322 if (item == NULL) {
2323 Py_DECREF(result);
2324 return NULL;
2325 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002326 PyTuple_SET_ITEM(result, i, item);
2327 }
2328 }
2329 return result;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002330}
Barry Warsawbd599b52000-08-03 15:45:29 +00002331
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002332static PyObject *
2333zip_reduce(zipobject *lz)
2334{
2335 /* Just recreate the zip with the internal iterator tuple */
2336 return Py_BuildValue("OO", Py_TYPE(lz), lz->ittuple);
2337}
2338
2339static PyMethodDef zip_methods[] = {
2340 {"__reduce__", (PyCFunction)zip_reduce, METH_NOARGS, reduce_doc},
2341 {NULL, NULL} /* sentinel */
2342};
2343
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002344PyDoc_STRVAR(zip_doc,
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002345"zip(iter1 [,iter2 [...]]) --> zip object\n\
Barry Warsawbd599b52000-08-03 15:45:29 +00002346\n\
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002347Return a zip object whose .__next__() method returns a tuple where\n\
2348the i-th element comes from the i-th iterable argument. The .__next__()\n\
2349method continues until the shortest iterable in the argument sequence\n\
Georg Brandlced51db2008-12-04 18:28:38 +00002350is exhausted and then it raises StopIteration.");
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002351
2352PyTypeObject PyZip_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002353 PyVarObject_HEAD_INIT(&PyType_Type, 0)
2354 "zip", /* tp_name */
2355 sizeof(zipobject), /* tp_basicsize */
2356 0, /* tp_itemsize */
2357 /* methods */
2358 (destructor)zip_dealloc, /* tp_dealloc */
2359 0, /* tp_print */
2360 0, /* tp_getattr */
2361 0, /* tp_setattr */
2362 0, /* tp_reserved */
2363 0, /* tp_repr */
2364 0, /* tp_as_number */
2365 0, /* tp_as_sequence */
2366 0, /* tp_as_mapping */
2367 0, /* tp_hash */
2368 0, /* tp_call */
2369 0, /* tp_str */
2370 PyObject_GenericGetAttr, /* tp_getattro */
2371 0, /* tp_setattro */
2372 0, /* tp_as_buffer */
2373 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
2374 Py_TPFLAGS_BASETYPE, /* tp_flags */
2375 zip_doc, /* tp_doc */
2376 (traverseproc)zip_traverse, /* tp_traverse */
2377 0, /* tp_clear */
2378 0, /* tp_richcompare */
2379 0, /* tp_weaklistoffset */
2380 PyObject_SelfIter, /* tp_iter */
2381 (iternextfunc)zip_next, /* tp_iternext */
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002382 zip_methods, /* tp_methods */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002383 0, /* tp_members */
2384 0, /* tp_getset */
2385 0, /* tp_base */
2386 0, /* tp_dict */
2387 0, /* tp_descr_get */
2388 0, /* tp_descr_set */
2389 0, /* tp_dictoffset */
2390 0, /* tp_init */
2391 PyType_GenericAlloc, /* tp_alloc */
2392 zip_new, /* tp_new */
2393 PyObject_GC_Del, /* tp_free */
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002394};
Barry Warsawbd599b52000-08-03 15:45:29 +00002395
2396
Guido van Rossum79f25d91997-04-29 20:08:16 +00002397static PyMethodDef builtin_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002398 {"__build_class__", (PyCFunction)builtin___build_class__,
2399 METH_VARARGS | METH_KEYWORDS, build_class_doc},
2400 {"__import__", (PyCFunction)builtin___import__, METH_VARARGS | METH_KEYWORDS, import_doc},
2401 {"abs", builtin_abs, METH_O, abs_doc},
2402 {"all", builtin_all, METH_O, all_doc},
2403 {"any", builtin_any, METH_O, any_doc},
2404 {"ascii", builtin_ascii, METH_O, ascii_doc},
2405 {"bin", builtin_bin, METH_O, bin_doc},
Antoine Pitroue71362d2010-11-27 22:00:11 +00002406 {"callable", builtin_callable, METH_O, callable_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002407 {"chr", builtin_chr, METH_VARARGS, chr_doc},
2408 {"compile", (PyCFunction)builtin_compile, METH_VARARGS | METH_KEYWORDS, compile_doc},
2409 {"delattr", builtin_delattr, METH_VARARGS, delattr_doc},
2410 {"dir", builtin_dir, METH_VARARGS, dir_doc},
2411 {"divmod", builtin_divmod, METH_VARARGS, divmod_doc},
2412 {"eval", builtin_eval, METH_VARARGS, eval_doc},
2413 {"exec", builtin_exec, METH_VARARGS, exec_doc},
2414 {"format", builtin_format, METH_VARARGS, format_doc},
2415 {"getattr", builtin_getattr, METH_VARARGS, getattr_doc},
2416 {"globals", (PyCFunction)builtin_globals, METH_NOARGS, globals_doc},
2417 {"hasattr", builtin_hasattr, METH_VARARGS, hasattr_doc},
2418 {"hash", builtin_hash, METH_O, hash_doc},
2419 {"hex", builtin_hex, METH_O, hex_doc},
2420 {"id", builtin_id, METH_O, id_doc},
2421 {"input", builtin_input, METH_VARARGS, input_doc},
2422 {"isinstance", builtin_isinstance, METH_VARARGS, isinstance_doc},
2423 {"issubclass", builtin_issubclass, METH_VARARGS, issubclass_doc},
2424 {"iter", builtin_iter, METH_VARARGS, iter_doc},
2425 {"len", builtin_len, METH_O, len_doc},
2426 {"locals", (PyCFunction)builtin_locals, METH_NOARGS, locals_doc},
2427 {"max", (PyCFunction)builtin_max, METH_VARARGS | METH_KEYWORDS, max_doc},
2428 {"min", (PyCFunction)builtin_min, METH_VARARGS | METH_KEYWORDS, min_doc},
2429 {"next", (PyCFunction)builtin_next, METH_VARARGS, next_doc},
2430 {"oct", builtin_oct, METH_O, oct_doc},
2431 {"ord", builtin_ord, METH_O, ord_doc},
2432 {"pow", builtin_pow, METH_VARARGS, pow_doc},
2433 {"print", (PyCFunction)builtin_print, METH_VARARGS | METH_KEYWORDS, print_doc},
2434 {"repr", builtin_repr, METH_O, repr_doc},
2435 {"round", (PyCFunction)builtin_round, METH_VARARGS | METH_KEYWORDS, round_doc},
2436 {"setattr", builtin_setattr, METH_VARARGS, setattr_doc},
2437 {"sorted", (PyCFunction)builtin_sorted, METH_VARARGS | METH_KEYWORDS, sorted_doc},
2438 {"sum", builtin_sum, METH_VARARGS, sum_doc},
2439 {"vars", builtin_vars, METH_VARARGS, vars_doc},
2440 {NULL, NULL},
Guido van Rossum3f5da241990-12-20 15:06:42 +00002441};
2442
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002443PyDoc_STRVAR(builtin_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002444"Built-in functions, exceptions, and other objects.\n\
2445\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002446Noteworthy: None is the `nil' object; Ellipsis represents `...' in slices.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002447
Martin v. Löwis1a214512008-06-11 05:26:20 +00002448static struct PyModuleDef builtinsmodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002449 PyModuleDef_HEAD_INIT,
2450 "builtins",
2451 builtin_doc,
2452 -1, /* multiple "initialization" just copies the module dict. */
2453 builtin_methods,
2454 NULL,
2455 NULL,
2456 NULL,
2457 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00002458};
2459
2460
Guido van Rossum25ce5661997-08-02 03:10:38 +00002461PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002462_PyBuiltin_Init(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +00002463{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002464 PyObject *mod, *dict, *debug;
Benjamin Peterson42124a72012-10-30 23:41:54 -04002465
2466 if (PyType_Ready(&PyFilter_Type) < 0 ||
2467 PyType_Ready(&PyMap_Type) < 0 ||
2468 PyType_Ready(&PyZip_Type) < 0)
2469 return NULL;
2470
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002471 mod = PyModule_Create(&builtinsmodule);
2472 if (mod == NULL)
2473 return NULL;
2474 dict = PyModule_GetDict(mod);
Tim Peters4b7625e2001-09-13 21:37:17 +00002475
Tim Peters7571a0f2003-03-23 17:52:28 +00002476#ifdef Py_TRACE_REFS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002477 /* "builtins" exposes a number of statically allocated objects
2478 * that, before this code was added in 2.3, never showed up in
2479 * the list of "all objects" maintained by Py_TRACE_REFS. As a
2480 * result, programs leaking references to None and False (etc)
2481 * couldn't be diagnosed by examining sys.getobjects(0).
2482 */
Tim Peters7571a0f2003-03-23 17:52:28 +00002483#define ADD_TO_ALL(OBJECT) _Py_AddToAllObjects((PyObject *)(OBJECT), 0)
2484#else
2485#define ADD_TO_ALL(OBJECT) (void)0
2486#endif
2487
Tim Peters4b7625e2001-09-13 21:37:17 +00002488#define SETBUILTIN(NAME, OBJECT) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002489 if (PyDict_SetItemString(dict, NAME, (PyObject *)OBJECT) < 0) \
2490 return NULL; \
2491 ADD_TO_ALL(OBJECT)
Tim Peters4b7625e2001-09-13 21:37:17 +00002492
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002493 SETBUILTIN("None", Py_None);
2494 SETBUILTIN("Ellipsis", Py_Ellipsis);
2495 SETBUILTIN("NotImplemented", Py_NotImplemented);
2496 SETBUILTIN("False", Py_False);
2497 SETBUILTIN("True", Py_True);
2498 SETBUILTIN("bool", &PyBool_Type);
2499 SETBUILTIN("memoryview", &PyMemoryView_Type);
2500 SETBUILTIN("bytearray", &PyByteArray_Type);
2501 SETBUILTIN("bytes", &PyBytes_Type);
2502 SETBUILTIN("classmethod", &PyClassMethod_Type);
2503 SETBUILTIN("complex", &PyComplex_Type);
2504 SETBUILTIN("dict", &PyDict_Type);
2505 SETBUILTIN("enumerate", &PyEnum_Type);
2506 SETBUILTIN("filter", &PyFilter_Type);
2507 SETBUILTIN("float", &PyFloat_Type);
2508 SETBUILTIN("frozenset", &PyFrozenSet_Type);
2509 SETBUILTIN("property", &PyProperty_Type);
2510 SETBUILTIN("int", &PyLong_Type);
2511 SETBUILTIN("list", &PyList_Type);
2512 SETBUILTIN("map", &PyMap_Type);
2513 SETBUILTIN("object", &PyBaseObject_Type);
2514 SETBUILTIN("range", &PyRange_Type);
2515 SETBUILTIN("reversed", &PyReversed_Type);
2516 SETBUILTIN("set", &PySet_Type);
2517 SETBUILTIN("slice", &PySlice_Type);
2518 SETBUILTIN("staticmethod", &PyStaticMethod_Type);
2519 SETBUILTIN("str", &PyUnicode_Type);
2520 SETBUILTIN("super", &PySuper_Type);
2521 SETBUILTIN("tuple", &PyTuple_Type);
2522 SETBUILTIN("type", &PyType_Type);
2523 SETBUILTIN("zip", &PyZip_Type);
2524 debug = PyBool_FromLong(Py_OptimizeFlag == 0);
2525 if (PyDict_SetItemString(dict, "__debug__", debug) < 0) {
2526 Py_XDECREF(debug);
2527 return NULL;
2528 }
2529 Py_XDECREF(debug);
Barry Warsaw757af0e1997-08-29 22:13:51 +00002530
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002531 return mod;
Tim Peters7571a0f2003-03-23 17:52:28 +00002532#undef ADD_TO_ALL
Tim Peters4b7625e2001-09-13 21:37:17 +00002533#undef SETBUILTIN
Guido van Rossum3f5da241990-12-20 15:06:42 +00002534}