blob: b0be6715e7c03c45a61f8557d2fc23fd160a461c [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
Martin v. Löwisbd928fe2011-10-14 10:20:37 +020035_Py_IDENTIFIER(fileno);
36_Py_IDENTIFIER(flush);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +020037
Guido van Rossum79f25d91997-04-29 20:08:16 +000038static PyObject *
Guido van Rossum52cc1d82007-03-18 15:41:51 +000039builtin___build_class__(PyObject *self, PyObject *args, PyObject *kwds)
40{
Nick Coghlande31b192011-10-23 22:04:16 +100041 PyObject *func, *name, *bases, *mkw, *meta, *winner, *prep, *ns, *cell;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000042 PyObject *cls = NULL;
Florent Xicluna4d46c2a2011-10-28 15:00:50 +020043 Py_ssize_t nargs;
Nick Coghlande31b192011-10-23 22:04:16 +100044 int isclass;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +020045 _Py_IDENTIFIER(__prepare__);
Guido van Rossum52cc1d82007-03-18 15:41:51 +000046
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000047 assert(args != NULL);
48 if (!PyTuple_Check(args)) {
49 PyErr_SetString(PyExc_TypeError,
50 "__build_class__: args is not a tuple");
51 return NULL;
52 }
53 nargs = PyTuple_GET_SIZE(args);
54 if (nargs < 2) {
55 PyErr_SetString(PyExc_TypeError,
56 "__build_class__: not enough arguments");
57 return NULL;
58 }
59 func = PyTuple_GET_ITEM(args, 0); /* Better be callable */
Benjamin Petersone8e14592013-05-16 14:37:25 -050060 if (!PyFunction_Check(func)) {
61 PyErr_SetString(PyExc_TypeError,
62 "__build__class__: func must be a function");
63 return NULL;
64 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000065 name = PyTuple_GET_ITEM(args, 1);
66 if (!PyUnicode_Check(name)) {
67 PyErr_SetString(PyExc_TypeError,
68 "__build_class__: name is not a string");
69 return NULL;
70 }
71 bases = PyTuple_GetSlice(args, 2, nargs);
72 if (bases == NULL)
73 return NULL;
Guido van Rossum52cc1d82007-03-18 15:41:51 +000074
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000075 if (kwds == NULL) {
76 meta = NULL;
77 mkw = NULL;
78 }
79 else {
80 mkw = PyDict_Copy(kwds); /* Don't modify kwds passed in! */
81 if (mkw == NULL) {
82 Py_DECREF(bases);
83 return NULL;
Guido van Rossum52cc1d82007-03-18 15:41:51 +000084 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000085 meta = PyDict_GetItemString(mkw, "metaclass");
86 if (meta != NULL) {
87 Py_INCREF(meta);
88 if (PyDict_DelItemString(mkw, "metaclass") < 0) {
89 Py_DECREF(meta);
90 Py_DECREF(mkw);
91 Py_DECREF(bases);
92 return NULL;
93 }
Nick Coghlande31b192011-10-23 22:04:16 +100094 /* metaclass is explicitly given, check if it's indeed a class */
95 isclass = PyType_Check(meta);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000096 }
97 }
98 if (meta == NULL) {
Nick Coghlande31b192011-10-23 22:04:16 +100099 /* if there are no bases, use type: */
100 if (PyTuple_GET_SIZE(bases) == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000101 meta = (PyObject *) (&PyType_Type);
Nick Coghlande31b192011-10-23 22:04:16 +1000102 }
103 /* else get the type of the first base */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000104 else {
105 PyObject *base0 = PyTuple_GET_ITEM(bases, 0);
106 meta = (PyObject *) (base0->ob_type);
107 }
108 Py_INCREF(meta);
Nick Coghlande31b192011-10-23 22:04:16 +1000109 isclass = 1; /* meta is really a class */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000110 }
Nick Coghlan9715d262011-10-23 22:36:42 +1000111
Nick Coghlande31b192011-10-23 22:04:16 +1000112 if (isclass) {
113 /* meta is really a class, so check for a more derived
114 metaclass, or possible metaclass conflicts: */
115 winner = (PyObject *)_PyType_CalculateMetaclass((PyTypeObject *)meta,
116 bases);
117 if (winner == NULL) {
118 Py_DECREF(meta);
119 Py_XDECREF(mkw);
120 Py_DECREF(bases);
121 return NULL;
122 }
123 if (winner != meta) {
124 Py_DECREF(meta);
125 meta = winner;
126 Py_INCREF(meta);
127 }
128 }
129 /* else: meta is not a class, so we cannot do the metaclass
130 calculation, so we will use the explicitly given object as it is */
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +0200131 prep = _PyObject_GetAttrId(meta, &PyId___prepare__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000132 if (prep == NULL) {
133 if (PyErr_ExceptionMatches(PyExc_AttributeError)) {
134 PyErr_Clear();
135 ns = PyDict_New();
136 }
137 else {
138 Py_DECREF(meta);
139 Py_XDECREF(mkw);
140 Py_DECREF(bases);
141 return NULL;
142 }
143 }
144 else {
145 PyObject *pargs = PyTuple_Pack(2, name, bases);
146 if (pargs == NULL) {
147 Py_DECREF(prep);
148 Py_DECREF(meta);
149 Py_XDECREF(mkw);
150 Py_DECREF(bases);
151 return NULL;
152 }
153 ns = PyEval_CallObjectWithKeywords(prep, pargs, mkw);
154 Py_DECREF(pargs);
155 Py_DECREF(prep);
156 }
157 if (ns == NULL) {
158 Py_DECREF(meta);
159 Py_XDECREF(mkw);
160 Py_DECREF(bases);
161 return NULL;
162 }
Benjamin Petersone8e14592013-05-16 14:37:25 -0500163 cell = PyEval_EvalCodeEx(PyFunction_GET_CODE(func), PyFunction_GET_GLOBALS(func), ns,
164 NULL, 0, NULL, 0, NULL, 0, NULL,
165 PyFunction_GET_CLOSURE(func));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000166 if (cell != NULL) {
167 PyObject *margs;
168 margs = PyTuple_Pack(3, name, bases, ns);
169 if (margs != NULL) {
170 cls = PyEval_CallObjectWithKeywords(meta, margs, mkw);
171 Py_DECREF(margs);
172 }
Benjamin Peterson8e8fbea2012-06-01 23:57:36 -0700173 if (cls != NULL && PyCell_Check(cell))
174 PyCell_Set(cell, cls);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000175 Py_DECREF(cell);
176 }
177 Py_DECREF(ns);
178 Py_DECREF(meta);
179 Py_XDECREF(mkw);
180 Py_DECREF(bases);
181 return cls;
Guido van Rossum52cc1d82007-03-18 15:41:51 +0000182}
183
184PyDoc_STRVAR(build_class_doc,
185"__build_class__(func, name, *bases, metaclass=None, **kwds) -> class\n\
186\n\
187Internal helper function used by the class statement.");
188
189static PyObject *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000190builtin___import__(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000191{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000192 static char *kwlist[] = {"name", "globals", "locals", "fromlist",
193 "level", 0};
Victor Stinnerfe93faf2011-03-14 15:54:52 -0400194 PyObject *name, *globals = NULL, *locals = NULL, *fromlist = NULL;
Brett Cannonfd074152012-04-14 14:10:13 -0400195 int level = 0;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000196
Victor Stinnerfe93faf2011-03-14 15:54:52 -0400197 if (!PyArg_ParseTupleAndKeywords(args, kwds, "U|OOOi:__import__",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000198 kwlist, &name, &globals, &locals, &fromlist, &level))
199 return NULL;
Victor Stinnerfe93faf2011-03-14 15:54:52 -0400200 return PyImport_ImportModuleLevelObject(name, globals, locals,
201 fromlist, level);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000202}
203
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000204PyDoc_STRVAR(import_doc,
Brett Cannoncb4996a2012-08-06 16:34:44 -0400205"__import__(name, globals=None, locals=None, fromlist=(), level=0) -> module\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000206\n\
Brett Cannon5305a992010-09-27 21:08:38 +0000207Import a module. Because this function is meant for use by the Python\n\
208interpreter and not for general use it is better to use\n\
209importlib.import_module() to programmatically import a module.\n\
210\n\
211The globals argument is only used to determine the context;\n\
212they are not modified. The locals argument is unused. The fromlist\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000213should be a list of names to emulate ``from name import ...'', or an\n\
214empty list to emulate ``import name''.\n\
215When importing a module from a package, note that __import__('A.B', ...)\n\
216returns package A when fromlist is empty, but its submodule B when\n\
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000217fromlist is not empty. Level is used to determine whether to perform \n\
Brett Cannon722d3ae2012-07-30 17:45:54 -0400218absolute or relative imports. 0 is absolute while a positive number\n\
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000219is the number of parent directories to search relative to the current module.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000220
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000221
Guido van Rossum79f25d91997-04-29 20:08:16 +0000222static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000223builtin_abs(PyObject *self, PyObject *v)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000224{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000225 return PyNumber_Absolute(v);
Guido van Rossum3f5da241990-12-20 15:06:42 +0000226}
227
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000228PyDoc_STRVAR(abs_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000229"abs(number) -> number\n\
230\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000231Return the absolute value of the argument.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000232
Raymond Hettinger96229b12005-03-11 06:49:40 +0000233static PyObject *
234builtin_all(PyObject *self, PyObject *v)
235{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000236 PyObject *it, *item;
237 PyObject *(*iternext)(PyObject *);
238 int cmp;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000239
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000240 it = PyObject_GetIter(v);
241 if (it == NULL)
242 return NULL;
243 iternext = *Py_TYPE(it)->tp_iternext;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000244
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000245 for (;;) {
246 item = iternext(it);
247 if (item == NULL)
248 break;
249 cmp = PyObject_IsTrue(item);
250 Py_DECREF(item);
251 if (cmp < 0) {
252 Py_DECREF(it);
253 return NULL;
254 }
255 if (cmp == 0) {
256 Py_DECREF(it);
257 Py_RETURN_FALSE;
258 }
259 }
260 Py_DECREF(it);
261 if (PyErr_Occurred()) {
262 if (PyErr_ExceptionMatches(PyExc_StopIteration))
263 PyErr_Clear();
264 else
265 return NULL;
266 }
267 Py_RETURN_TRUE;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000268}
269
270PyDoc_STRVAR(all_doc,
271"all(iterable) -> bool\n\
272\n\
Ezio Melottib19ed572013-02-15 23:35:14 +0200273Return True if bool(x) is True for all values x in the iterable.\n\
274If the iterable is empty, return True.");
Raymond Hettinger96229b12005-03-11 06:49:40 +0000275
276static PyObject *
277builtin_any(PyObject *self, PyObject *v)
278{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000279 PyObject *it, *item;
280 PyObject *(*iternext)(PyObject *);
281 int cmp;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000282
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000283 it = PyObject_GetIter(v);
284 if (it == NULL)
285 return NULL;
286 iternext = *Py_TYPE(it)->tp_iternext;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000287
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000288 for (;;) {
289 item = iternext(it);
290 if (item == NULL)
291 break;
292 cmp = PyObject_IsTrue(item);
293 Py_DECREF(item);
294 if (cmp < 0) {
295 Py_DECREF(it);
296 return NULL;
297 }
298 if (cmp == 1) {
299 Py_DECREF(it);
300 Py_RETURN_TRUE;
301 }
302 }
303 Py_DECREF(it);
304 if (PyErr_Occurred()) {
305 if (PyErr_ExceptionMatches(PyExc_StopIteration))
306 PyErr_Clear();
307 else
308 return NULL;
309 }
310 Py_RETURN_FALSE;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000311}
312
313PyDoc_STRVAR(any_doc,
314"any(iterable) -> bool\n\
315\n\
Ezio Melottib19ed572013-02-15 23:35:14 +0200316Return True if bool(x) is True for any x in the iterable.\n\
317If the iterable is empty, return False.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000318
Georg Brandl559e5d72008-06-11 18:37:52 +0000319static PyObject *
320builtin_ascii(PyObject *self, PyObject *v)
321{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000322 return PyObject_ASCII(v);
Georg Brandl559e5d72008-06-11 18:37:52 +0000323}
324
325PyDoc_STRVAR(ascii_doc,
326"ascii(object) -> string\n\
327\n\
328As repr(), return a string containing a printable representation of an\n\
329object, but escape the non-ASCII characters in the string returned by\n\
330repr() using \\x, \\u or \\U escapes. This generates a string similar\n\
331to that returned by repr() in Python 2.");
332
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000333
Guido van Rossum79f25d91997-04-29 20:08:16 +0000334static PyObject *
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000335builtin_bin(PyObject *self, PyObject *v)
336{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000337 return PyNumber_ToBase(v, 2);
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000338}
339
340PyDoc_STRVAR(bin_doc,
341"bin(number) -> string\n\
342\n\
Alexander Belopolsky12338ab2011-04-07 00:15:33 -0400343Return the binary representation of an integer.");
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000344
345
Antoine Pitroue71362d2010-11-27 22:00:11 +0000346static PyObject *
347builtin_callable(PyObject *self, PyObject *v)
348{
349 return PyBool_FromLong((long)PyCallable_Check(v));
350}
351
352PyDoc_STRVAR(callable_doc,
353"callable(object) -> bool\n\
354\n\
355Return whether the object is callable (i.e., some kind of function).\n\
356Note that classes are callable, as are instances of classes with a\n\
357__call__() method.");
358
359
Raymond Hettinger17301e92008-03-13 00:19:26 +0000360typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000361 PyObject_HEAD
362 PyObject *func;
363 PyObject *it;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000364} filterobject;
365
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000366static PyObject *
Raymond Hettinger17301e92008-03-13 00:19:26 +0000367filter_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
Guido van Rossum12d12c51993-10-26 17:58:25 +0000368{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000369 PyObject *func, *seq;
370 PyObject *it;
371 filterobject *lz;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000372
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000373 if (type == &PyFilter_Type && !_PyArg_NoKeywords("filter()", kwds))
374 return NULL;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000375
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000376 if (!PyArg_UnpackTuple(args, "filter", 2, 2, &func, &seq))
377 return NULL;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000378
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000379 /* Get iterator. */
380 it = PyObject_GetIter(seq);
381 if (it == NULL)
382 return NULL;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000383
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000384 /* create filterobject structure */
385 lz = (filterobject *)type->tp_alloc(type, 0);
386 if (lz == NULL) {
387 Py_DECREF(it);
388 return NULL;
389 }
390 Py_INCREF(func);
391 lz->func = func;
392 lz->it = it;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000393
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000394 return (PyObject *)lz;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000395}
396
397static void
398filter_dealloc(filterobject *lz)
399{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000400 PyObject_GC_UnTrack(lz);
401 Py_XDECREF(lz->func);
402 Py_XDECREF(lz->it);
403 Py_TYPE(lz)->tp_free(lz);
Raymond Hettinger17301e92008-03-13 00:19:26 +0000404}
405
406static int
407filter_traverse(filterobject *lz, visitproc visit, void *arg)
408{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000409 Py_VISIT(lz->it);
410 Py_VISIT(lz->func);
411 return 0;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000412}
413
414static PyObject *
415filter_next(filterobject *lz)
416{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000417 PyObject *item;
418 PyObject *it = lz->it;
419 long ok;
420 PyObject *(*iternext)(PyObject *);
Raymond Hettinger17301e92008-03-13 00:19:26 +0000421
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000422 iternext = *Py_TYPE(it)->tp_iternext;
423 for (;;) {
424 item = iternext(it);
425 if (item == NULL)
426 return NULL;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000427
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000428 if (lz->func == Py_None || lz->func == (PyObject *)&PyBool_Type) {
429 ok = PyObject_IsTrue(item);
430 } else {
431 PyObject *good;
432 good = PyObject_CallFunctionObjArgs(lz->func,
433 item, NULL);
434 if (good == NULL) {
435 Py_DECREF(item);
436 return NULL;
437 }
438 ok = PyObject_IsTrue(good);
439 Py_DECREF(good);
440 }
Antoine Pitrou6f430e42012-08-15 23:18:25 +0200441 if (ok > 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000442 return item;
443 Py_DECREF(item);
Antoine Pitrou6f430e42012-08-15 23:18:25 +0200444 if (ok < 0)
445 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000446 }
Guido van Rossum12d12c51993-10-26 17:58:25 +0000447}
448
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +0000449static PyObject *
450filter_reduce(filterobject *lz)
451{
452 return Py_BuildValue("O(OO)", Py_TYPE(lz), lz->func, lz->it);
453}
454
455PyDoc_STRVAR(reduce_doc, "Return state information for pickling.");
456
457static PyMethodDef filter_methods[] = {
458 {"__reduce__", (PyCFunction)filter_reduce, METH_NOARGS, reduce_doc},
459 {NULL, NULL} /* sentinel */
460};
461
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000462PyDoc_STRVAR(filter_doc,
Georg Brandld11ae5d2008-05-16 13:27:32 +0000463"filter(function or None, iterable) --> filter object\n\
Guido van Rossumc1f779c2007-07-03 08:25:58 +0000464\n\
Georg Brandld11ae5d2008-05-16 13:27:32 +0000465Return an iterator yielding those items of iterable for which function(item)\n\
Raymond Hettinger17301e92008-03-13 00:19:26 +0000466is true. If function is None, return the items that are true.");
467
468PyTypeObject PyFilter_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000469 PyVarObject_HEAD_INIT(&PyType_Type, 0)
470 "filter", /* tp_name */
471 sizeof(filterobject), /* tp_basicsize */
472 0, /* tp_itemsize */
473 /* methods */
474 (destructor)filter_dealloc, /* tp_dealloc */
475 0, /* tp_print */
476 0, /* tp_getattr */
477 0, /* tp_setattr */
478 0, /* tp_reserved */
479 0, /* tp_repr */
480 0, /* tp_as_number */
481 0, /* tp_as_sequence */
482 0, /* tp_as_mapping */
483 0, /* tp_hash */
484 0, /* tp_call */
485 0, /* tp_str */
486 PyObject_GenericGetAttr, /* tp_getattro */
487 0, /* tp_setattro */
488 0, /* tp_as_buffer */
489 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
490 Py_TPFLAGS_BASETYPE, /* tp_flags */
491 filter_doc, /* tp_doc */
492 (traverseproc)filter_traverse, /* tp_traverse */
493 0, /* tp_clear */
494 0, /* tp_richcompare */
495 0, /* tp_weaklistoffset */
496 PyObject_SelfIter, /* tp_iter */
497 (iternextfunc)filter_next, /* tp_iternext */
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +0000498 filter_methods, /* tp_methods */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000499 0, /* tp_members */
500 0, /* tp_getset */
501 0, /* tp_base */
502 0, /* tp_dict */
503 0, /* tp_descr_get */
504 0, /* tp_descr_set */
505 0, /* tp_dictoffset */
506 0, /* tp_init */
507 PyType_GenericAlloc, /* tp_alloc */
508 filter_new, /* tp_new */
509 PyObject_GC_Del, /* tp_free */
Raymond Hettinger17301e92008-03-13 00:19:26 +0000510};
511
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000512
Eric Smith8c663262007-08-25 02:26:07 +0000513static PyObject *
514builtin_format(PyObject *self, PyObject *args)
515{
Christian Heimes94b7d3d2007-12-11 20:20:39 +0000516 PyObject *value;
Eric Smith8fd3eba2008-02-17 19:48:00 +0000517 PyObject *format_spec = NULL;
Eric Smith8c663262007-08-25 02:26:07 +0000518
Eric Smith8fd3eba2008-02-17 19:48:00 +0000519 if (!PyArg_ParseTuple(args, "O|U:format", &value, &format_spec))
Benjamin Petersona12d5c62012-01-03 16:47:22 -0600520 return NULL;
Eric Smith8c663262007-08-25 02:26:07 +0000521
Eric Smith8fd3eba2008-02-17 19:48:00 +0000522 return PyObject_Format(value, format_spec);
Eric Smith8c663262007-08-25 02:26:07 +0000523}
524
Eric Smith8c663262007-08-25 02:26:07 +0000525PyDoc_STRVAR(format_doc,
Eric Smith81936692007-08-31 01:14:01 +0000526"format(value[, format_spec]) -> string\n\
Eric Smith8c663262007-08-25 02:26:07 +0000527\n\
Eric Smith81936692007-08-31 01:14:01 +0000528Returns value.__format__(format_spec)\n\
529format_spec defaults to \"\"");
530
Guido van Rossum7fcf2242007-05-04 17:43:11 +0000531static PyObject *
Walter Dörwalde7efd592007-06-05 20:07:21 +0000532builtin_chr(PyObject *self, PyObject *args)
Guido van Rossum09095f32000-03-10 23:00:52 +0000533{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000534 int x;
Guido van Rossum09095f32000-03-10 23:00:52 +0000535
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000536 if (!PyArg_ParseTuple(args, "i:chr", &x))
537 return NULL;
Fredrik Lundh0dcf67e2001-06-26 20:01:56 +0000538
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000539 return PyUnicode_FromOrdinal(x);
Guido van Rossum09095f32000-03-10 23:00:52 +0000540}
541
Victor Stinner63ab8752011-11-22 03:31:20 +0100542PyDoc_STRVAR(chr_doc,
Guido van Rossum84fc66d2007-05-03 17:18:26 +0000543"chr(i) -> Unicode character\n\
Guido van Rossum09095f32000-03-10 23:00:52 +0000544\n\
Victor Stinner63ab8752011-11-22 03:31:20 +0100545Return a Unicode string of one character with ordinal i; 0 <= i <= 0x10ffff.");
Guido van Rossum09095f32000-03-10 23:00:52 +0000546
547
Guido van Rossumf15a29f2007-05-04 00:41:39 +0000548static char *
Benjamin Petersonf5b52242009-03-02 23:31:26 +0000549source_as_string(PyObject *cmd, char *funcname, char *what, PyCompilerFlags *cf)
Guido van Rossumf15a29f2007-05-04 00:41:39 +0000550{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000551 char *str;
552 Py_ssize_t size;
Guido van Rossumf15a29f2007-05-04 00:41:39 +0000553
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000554 if (PyUnicode_Check(cmd)) {
555 cf->cf_flags |= PyCF_IGNORE_COOKIE;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200556 str = PyUnicode_AsUTF8AndSize(cmd, &size);
557 if (str == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000558 return NULL;
559 }
560 else if (!PyObject_CheckReadBuffer(cmd)) {
561 PyErr_Format(PyExc_TypeError,
562 "%s() arg 1 must be a %s object",
563 funcname, what);
564 return NULL;
565 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200566 else if (PyObject_AsReadBuffer(cmd, (const void **)&str, &size) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000567 return NULL;
568 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200569
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000570 if (strlen(str) != size) {
571 PyErr_SetString(PyExc_TypeError,
572 "source code string cannot contain null bytes");
573 return NULL;
574 }
575 return str;
Guido van Rossumf15a29f2007-05-04 00:41:39 +0000576}
577
Guido van Rossum79f25d91997-04-29 20:08:16 +0000578static PyObject *
Guido van Rossumd8faa362007-04-27 19:54:29 +0000579builtin_compile(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum5b722181993-03-30 17:46:03 +0000580{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000581 char *str;
Victor Stinner14e461d2013-08-26 22:28:21 +0200582 PyObject *filename;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000583 char *startstr;
584 int mode = -1;
585 int dont_inherit = 0;
586 int supplied_flags = 0;
Georg Brandl8334fd92010-12-04 10:26:46 +0000587 int optimize = -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000588 int is_ast;
589 PyCompilerFlags cf;
590 PyObject *cmd;
591 static char *kwlist[] = {"source", "filename", "mode", "flags",
Georg Brandl8334fd92010-12-04 10:26:46 +0000592 "dont_inherit", "optimize", NULL};
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000593 int start[] = {Py_file_input, Py_eval_input, Py_single_input};
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000594 PyObject *result;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000595
Georg Brandl8334fd92010-12-04 10:26:46 +0000596 if (!PyArg_ParseTupleAndKeywords(args, kwds, "OO&s|iii:compile", kwlist,
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000597 &cmd,
Victor Stinner14e461d2013-08-26 22:28:21 +0200598 PyUnicode_FSDecoder, &filename,
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000599 &startstr, &supplied_flags,
Georg Brandl8334fd92010-12-04 10:26:46 +0000600 &dont_inherit, &optimize))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000601 return NULL;
Tim Peters6cd6a822001-08-17 22:11:27 +0000602
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000603 cf.cf_flags = supplied_flags | PyCF_SOURCE_IS_UTF8;
Just van Rossum3aaf42c2003-02-10 08:21:10 +0000604
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000605 if (supplied_flags &
606 ~(PyCF_MASK | PyCF_MASK_OBSOLETE | PyCF_DONT_IMPLY_DEDENT | PyCF_ONLY_AST))
607 {
608 PyErr_SetString(PyExc_ValueError,
609 "compile(): unrecognised flags");
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000610 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000611 }
612 /* XXX Warn if (supplied_flags & PyCF_MASK_OBSOLETE) != 0? */
Tim Peters6cd6a822001-08-17 22:11:27 +0000613
Georg Brandl8334fd92010-12-04 10:26:46 +0000614 if (optimize < -1 || optimize > 2) {
615 PyErr_SetString(PyExc_ValueError,
616 "compile(): invalid optimize value");
617 goto error;
618 }
619
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000620 if (!dont_inherit) {
621 PyEval_MergeCompilerFlags(&cf);
622 }
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000623
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000624 if (strcmp(startstr, "exec") == 0)
625 mode = 0;
626 else if (strcmp(startstr, "eval") == 0)
627 mode = 1;
628 else if (strcmp(startstr, "single") == 0)
629 mode = 2;
630 else {
631 PyErr_SetString(PyExc_ValueError,
632 "compile() arg 3 must be 'exec', 'eval' or 'single'");
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000633 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000634 }
Neal Norwitzdb4115f2008-03-31 04:20:05 +0000635
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000636 is_ast = PyAST_Check(cmd);
637 if (is_ast == -1)
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000638 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000639 if (is_ast) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000640 if (supplied_flags & PyCF_ONLY_AST) {
641 Py_INCREF(cmd);
642 result = cmd;
643 }
644 else {
645 PyArena *arena;
646 mod_ty mod;
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000647
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000648 arena = PyArena_New();
Stefan Krah07795df2012-08-20 17:19:50 +0200649 if (arena == NULL)
650 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000651 mod = PyAST_obj2mod(cmd, arena, mode);
652 if (mod == NULL) {
653 PyArena_Free(arena);
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000654 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000655 }
Benjamin Peterson832bfe22011-08-09 16:15:04 -0500656 if (!PyAST_Validate(mod)) {
657 PyArena_Free(arena);
658 goto error;
659 }
Victor Stinner14e461d2013-08-26 22:28:21 +0200660 result = (PyObject*)PyAST_CompileObject(mod, filename,
661 &cf, optimize, arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000662 PyArena_Free(arena);
663 }
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000664 goto finally;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000665 }
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000666
Philip Jenveyf76f0ee2012-12-13 15:44:18 -0800667 str = source_as_string(cmd, "compile", "string, bytes or AST", &cf);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000668 if (str == NULL)
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000669 goto error;
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000670
Victor Stinner14e461d2013-08-26 22:28:21 +0200671 result = Py_CompileStringObject(str, filename, start[mode], &cf, optimize);
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000672 goto finally;
673
674error:
675 result = NULL;
676finally:
Victor Stinner14e461d2013-08-26 22:28:21 +0200677 Py_DECREF(filename);
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000678 return result;
Guido van Rossum5b722181993-03-30 17:46:03 +0000679}
680
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000681PyDoc_STRVAR(compile_doc,
Tim Peters6cd6a822001-08-17 22:11:27 +0000682"compile(source, filename, mode[, flags[, dont_inherit]]) -> code object\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000683\n\
684Compile the source string (a Python module, statement or expression)\n\
Georg Brandl7cae87c2006-09-06 06:51:57 +0000685into a code object that can be executed by exec() or eval().\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000686The filename will be used for run-time error messages.\n\
687The mode must be 'exec' to compile a module, 'single' to compile a\n\
Tim Peters6cd6a822001-08-17 22:11:27 +0000688single (interactive) statement, or 'eval' to compile an expression.\n\
689The flags argument, if present, controls which future statements influence\n\
690the compilation of the code.\n\
691The dont_inherit argument, if non-zero, stops the compilation inheriting\n\
692the effects of any future statements in effect in the code calling\n\
693compile; if absent or zero these statements do influence the compilation,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000694in addition to any features explicitly specified.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000695
Guido van Rossum79f25d91997-04-29 20:08:16 +0000696static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000697builtin_dir(PyObject *self, PyObject *args)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000698{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000699 PyObject *arg = NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000700
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000701 if (!PyArg_UnpackTuple(args, "dir", 0, 1, &arg))
702 return NULL;
703 return PyObject_Dir(arg);
Guido van Rossum3f5da241990-12-20 15:06:42 +0000704}
705
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000706PyDoc_STRVAR(dir_doc,
Tim Peters5d2b77c2001-09-03 05:47:38 +0000707"dir([object]) -> list of strings\n"
708"\n"
Georg Brandle32b4222007-03-10 22:13:27 +0000709"If called without an argument, return the names in the current scope.\n"
710"Else, return an alphabetized list of names comprising (some of) the attributes\n"
711"of the given object, and of attributes reachable from it.\n"
712"If the object supplies a method named __dir__, it will be used; otherwise\n"
713"the default dir() logic is used and returns:\n"
714" for a module object: the module's attributes.\n"
715" for a class object: its attributes, and recursively the attributes\n"
716" of its bases.\n"
Guido van Rossumd8faa362007-04-27 19:54:29 +0000717" for any other object: its attributes, its class's attributes, and\n"
Georg Brandle32b4222007-03-10 22:13:27 +0000718" recursively the attributes of its class's base classes.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000719
Guido van Rossum79f25d91997-04-29 20:08:16 +0000720static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000721builtin_divmod(PyObject *self, PyObject *args)
Guido van Rossum6a00cd81995-01-07 12:39:01 +0000722{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000723 PyObject *v, *w;
Guido van Rossum6a00cd81995-01-07 12:39:01 +0000724
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000725 if (!PyArg_UnpackTuple(args, "divmod", 2, 2, &v, &w))
726 return NULL;
727 return PyNumber_Divmod(v, w);
Guido van Rossum3f5da241990-12-20 15:06:42 +0000728}
729
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000730PyDoc_STRVAR(divmod_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000731"divmod(x, y) -> (div, mod)\n\
732\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000733Return the tuple ((x-x%y)/y, x%y). Invariant: div*y + mod == x.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000734
735
Guido van Rossum79f25d91997-04-29 20:08:16 +0000736static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000737builtin_eval(PyObject *self, PyObject *args)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000738{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000739 PyObject *cmd, *result, *tmp = NULL;
740 PyObject *globals = Py_None, *locals = Py_None;
741 char *str;
742 PyCompilerFlags cf;
Guido van Rossum590baa41993-11-30 13:40:46 +0000743
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000744 if (!PyArg_UnpackTuple(args, "eval", 1, 3, &cmd, &globals, &locals))
745 return NULL;
746 if (locals != Py_None && !PyMapping_Check(locals)) {
747 PyErr_SetString(PyExc_TypeError, "locals must be a mapping");
748 return NULL;
749 }
750 if (globals != Py_None && !PyDict_Check(globals)) {
751 PyErr_SetString(PyExc_TypeError, PyMapping_Check(globals) ?
752 "globals must be a real dict; try eval(expr, {}, mapping)"
753 : "globals must be a dict");
754 return NULL;
755 }
756 if (globals == Py_None) {
757 globals = PyEval_GetGlobals();
Victor Stinner41bb43a2013-10-29 01:19:37 +0100758 if (locals == Py_None) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000759 locals = PyEval_GetLocals();
Victor Stinner41bb43a2013-10-29 01:19:37 +0100760 if (locals == NULL)
761 return NULL;
762 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000763 }
764 else if (locals == Py_None)
765 locals = globals;
Tim Peters9fa96be2001-08-17 23:04:59 +0000766
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000767 if (globals == NULL || locals == NULL) {
768 PyErr_SetString(PyExc_TypeError,
769 "eval must be given globals and locals "
770 "when called without a frame");
771 return NULL;
772 }
Georg Brandl77c85e62005-09-15 10:46:13 +0000773
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000774 if (PyDict_GetItemString(globals, "__builtins__") == NULL) {
775 if (PyDict_SetItemString(globals, "__builtins__",
776 PyEval_GetBuiltins()) != 0)
777 return NULL;
778 }
Tim Peters9fa96be2001-08-17 23:04:59 +0000779
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000780 if (PyCode_Check(cmd)) {
781 if (PyCode_GetNumFree((PyCodeObject *)cmd) > 0) {
782 PyErr_SetString(PyExc_TypeError,
783 "code object passed to eval() may not contain free variables");
784 return NULL;
785 }
Martin v. Löwis4d0d4712010-12-03 20:14:31 +0000786 return PyEval_EvalCode(cmd, globals, locals);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000787 }
Tim Peters9fa96be2001-08-17 23:04:59 +0000788
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000789 cf.cf_flags = PyCF_SOURCE_IS_UTF8;
790 str = source_as_string(cmd, "eval", "string, bytes or code", &cf);
791 if (str == NULL)
792 return NULL;
Just van Rossum3aaf42c2003-02-10 08:21:10 +0000793
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000794 while (*str == ' ' || *str == '\t')
795 str++;
Tim Peters9fa96be2001-08-17 23:04:59 +0000796
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000797 (void)PyEval_MergeCompilerFlags(&cf);
798 result = PyRun_StringFlags(str, Py_eval_input, globals, locals, &cf);
799 Py_XDECREF(tmp);
800 return result;
Guido van Rossum3f5da241990-12-20 15:06:42 +0000801}
802
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000803PyDoc_STRVAR(eval_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000804"eval(source[, globals[, locals]]) -> value\n\
805\n\
806Evaluate the source in the context of globals and locals.\n\
807The source may be a string representing a Python expression\n\
808or a code object as returned by compile().\n\
Thomas Wouters89f507f2006-12-13 04:49:30 +0000809The globals must be a dictionary and locals can be any mapping,\n\
Raymond Hettinger214b1c32004-07-02 06:41:07 +0000810defaulting to the current globals and locals.\n\
811If only globals is given, locals defaults to it.\n");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000812
Georg Brandl7cae87c2006-09-06 06:51:57 +0000813static PyObject *
814builtin_exec(PyObject *self, PyObject *args)
815{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000816 PyObject *v;
817 PyObject *prog, *globals = Py_None, *locals = Py_None;
Georg Brandl7cae87c2006-09-06 06:51:57 +0000818
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000819 if (!PyArg_UnpackTuple(args, "exec", 1, 3, &prog, &globals, &locals))
820 return NULL;
Georg Brandl2cabc562008-08-28 07:57:16 +0000821
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000822 if (globals == Py_None) {
823 globals = PyEval_GetGlobals();
824 if (locals == Py_None) {
825 locals = PyEval_GetLocals();
Victor Stinner41bb43a2013-10-29 01:19:37 +0100826 if (locals == NULL)
827 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000828 }
829 if (!globals || !locals) {
830 PyErr_SetString(PyExc_SystemError,
831 "globals and locals cannot be NULL");
832 return NULL;
833 }
834 }
835 else if (locals == Py_None)
836 locals = globals;
Georg Brandl7cae87c2006-09-06 06:51:57 +0000837
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000838 if (!PyDict_Check(globals)) {
839 PyErr_Format(PyExc_TypeError, "exec() arg 2 must be a dict, not %.100s",
840 globals->ob_type->tp_name);
841 return NULL;
842 }
843 if (!PyMapping_Check(locals)) {
844 PyErr_Format(PyExc_TypeError,
845 "arg 3 must be a mapping or None, not %.100s",
846 locals->ob_type->tp_name);
847 return NULL;
848 }
849 if (PyDict_GetItemString(globals, "__builtins__") == NULL) {
850 if (PyDict_SetItemString(globals, "__builtins__",
851 PyEval_GetBuiltins()) != 0)
852 return NULL;
853 }
854
855 if (PyCode_Check(prog)) {
856 if (PyCode_GetNumFree((PyCodeObject *)prog) > 0) {
857 PyErr_SetString(PyExc_TypeError,
858 "code object passed to exec() may not "
859 "contain free variables");
860 return NULL;
861 }
Martin v. Löwis4d0d4712010-12-03 20:14:31 +0000862 v = PyEval_EvalCode(prog, globals, locals);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000863 }
864 else {
865 char *str;
866 PyCompilerFlags cf;
867 cf.cf_flags = PyCF_SOURCE_IS_UTF8;
868 str = source_as_string(prog, "exec",
869 "string, bytes or code", &cf);
870 if (str == NULL)
871 return NULL;
872 if (PyEval_MergeCompilerFlags(&cf))
873 v = PyRun_StringFlags(str, Py_file_input, globals,
874 locals, &cf);
875 else
876 v = PyRun_String(str, Py_file_input, globals, locals);
877 }
878 if (v == NULL)
879 return NULL;
880 Py_DECREF(v);
881 Py_RETURN_NONE;
Georg Brandl7cae87c2006-09-06 06:51:57 +0000882}
883
884PyDoc_STRVAR(exec_doc,
885"exec(object[, globals[, locals]])\n\
886\n\
Mark Dickinson480e8e32009-12-19 21:19:35 +0000887Read and execute code from an object, which can be a string or a code\n\
Benjamin Peterson38090262009-01-04 15:30:39 +0000888object.\n\
Georg Brandl7cae87c2006-09-06 06:51:57 +0000889The globals and locals are dictionaries, defaulting to the current\n\
890globals and locals. If only globals is given, locals defaults to it.");
891
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000892
Guido van Rossum79f25d91997-04-29 20:08:16 +0000893static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000894builtin_getattr(PyObject *self, PyObject *args)
Guido van Rossum33894be1992-01-27 16:53:09 +0000895{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000896 PyObject *v, *result, *dflt = NULL;
897 PyObject *name;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000898
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000899 if (!PyArg_UnpackTuple(args, "getattr", 2, 3, &v, &name, &dflt))
900 return NULL;
Martin v. Löwis5b222132007-06-10 09:51:05 +0000901
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000902 if (!PyUnicode_Check(name)) {
903 PyErr_SetString(PyExc_TypeError,
904 "getattr(): attribute name must be string");
905 return NULL;
906 }
907 result = PyObject_GetAttr(v, name);
908 if (result == NULL && dflt != NULL &&
909 PyErr_ExceptionMatches(PyExc_AttributeError))
910 {
911 PyErr_Clear();
912 Py_INCREF(dflt);
913 result = dflt;
914 }
915 return result;
Guido van Rossum9bfef441993-03-29 10:43:31 +0000916}
917
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000918PyDoc_STRVAR(getattr_doc,
Guido van Rossum950ff291998-06-29 13:38:57 +0000919"getattr(object, name[, default]) -> value\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000920\n\
Guido van Rossum950ff291998-06-29 13:38:57 +0000921Get a named attribute from an object; getattr(x, 'y') is equivalent to x.y.\n\
922When a default argument is given, it is returned when the attribute doesn't\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000923exist; without it, an exception is raised in that case.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000924
925
Guido van Rossum79f25d91997-04-29 20:08:16 +0000926static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000927builtin_globals(PyObject *self)
Guido van Rossum872537c1995-07-07 22:43:42 +0000928{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000929 PyObject *d;
Guido van Rossum872537c1995-07-07 22:43:42 +0000930
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000931 d = PyEval_GetGlobals();
932 Py_XINCREF(d);
933 return d;
Guido van Rossum872537c1995-07-07 22:43:42 +0000934}
935
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000936PyDoc_STRVAR(globals_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000937"globals() -> dictionary\n\
938\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000939Return the dictionary containing the current scope's global variables.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000940
941
Guido van Rossum79f25d91997-04-29 20:08:16 +0000942static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000943builtin_hasattr(PyObject *self, PyObject *args)
Guido van Rossum9bfef441993-03-29 10:43:31 +0000944{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000945 PyObject *v;
946 PyObject *name;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000947
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000948 if (!PyArg_UnpackTuple(args, "hasattr", 2, 2, &v, &name))
949 return NULL;
950 if (!PyUnicode_Check(name)) {
951 PyErr_SetString(PyExc_TypeError,
952 "hasattr(): attribute name must be string");
953 return NULL;
954 }
955 v = PyObject_GetAttr(v, name);
956 if (v == NULL) {
Benjamin Peterson17689992010-08-24 03:26:23 +0000957 if (PyErr_ExceptionMatches(PyExc_AttributeError)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000958 PyErr_Clear();
Benjamin Peterson17689992010-08-24 03:26:23 +0000959 Py_RETURN_FALSE;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000960 }
Benjamin Peterson17689992010-08-24 03:26:23 +0000961 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000962 }
963 Py_DECREF(v);
Benjamin Peterson17689992010-08-24 03:26:23 +0000964 Py_RETURN_TRUE;
Guido van Rossum33894be1992-01-27 16:53:09 +0000965}
966
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000967PyDoc_STRVAR(hasattr_doc,
Guido van Rossum77f6a652002-04-03 22:41:51 +0000968"hasattr(object, name) -> bool\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000969\n\
970Return whether the object has an attribute with the given name.\n\
Benjamin Peterson17689992010-08-24 03:26:23 +0000971(This is done by calling getattr(object, name) and catching AttributeError.)");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000972
973
Guido van Rossum79f25d91997-04-29 20:08:16 +0000974static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000975builtin_id(PyObject *self, PyObject *v)
Guido van Rossum5b722181993-03-30 17:46:03 +0000976{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000977 return PyLong_FromVoidPtr(v);
Guido van Rossum5b722181993-03-30 17:46:03 +0000978}
979
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000980PyDoc_STRVAR(id_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000981"id(object) -> integer\n\
982\n\
983Return the identity of an object. This is guaranteed to be unique among\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000984simultaneously existing objects. (Hint: it's the object's memory address.)");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000985
986
Raymond Hettingera6c60372008-03-13 01:26:19 +0000987/* map object ************************************************************/
988
989typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000990 PyObject_HEAD
991 PyObject *iters;
992 PyObject *func;
Raymond Hettingera6c60372008-03-13 01:26:19 +0000993} mapobject;
994
Guido van Rossum79f25d91997-04-29 20:08:16 +0000995static PyObject *
Raymond Hettingera6c60372008-03-13 01:26:19 +0000996map_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
Guido van Rossum12d12c51993-10-26 17:58:25 +0000997{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000998 PyObject *it, *iters, *func;
999 mapobject *lz;
1000 Py_ssize_t numargs, i;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001001
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001002 if (type == &PyMap_Type && !_PyArg_NoKeywords("map()", kwds))
1003 return NULL;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001004
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001005 numargs = PyTuple_Size(args);
1006 if (numargs < 2) {
1007 PyErr_SetString(PyExc_TypeError,
1008 "map() must have at least two arguments.");
1009 return NULL;
1010 }
Raymond Hettingera6c60372008-03-13 01:26:19 +00001011
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001012 iters = PyTuple_New(numargs-1);
1013 if (iters == NULL)
1014 return NULL;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001015
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001016 for (i=1 ; i<numargs ; i++) {
1017 /* Get iterator. */
1018 it = PyObject_GetIter(PyTuple_GET_ITEM(args, i));
1019 if (it == NULL) {
1020 Py_DECREF(iters);
1021 return NULL;
1022 }
1023 PyTuple_SET_ITEM(iters, i-1, it);
1024 }
Raymond Hettingera6c60372008-03-13 01:26:19 +00001025
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001026 /* create mapobject structure */
1027 lz = (mapobject *)type->tp_alloc(type, 0);
1028 if (lz == NULL) {
1029 Py_DECREF(iters);
1030 return NULL;
1031 }
1032 lz->iters = iters;
1033 func = PyTuple_GET_ITEM(args, 0);
1034 Py_INCREF(func);
1035 lz->func = func;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001036
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001037 return (PyObject *)lz;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001038}
1039
1040static void
1041map_dealloc(mapobject *lz)
1042{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001043 PyObject_GC_UnTrack(lz);
1044 Py_XDECREF(lz->iters);
1045 Py_XDECREF(lz->func);
1046 Py_TYPE(lz)->tp_free(lz);
Raymond Hettingera6c60372008-03-13 01:26:19 +00001047}
1048
1049static int
1050map_traverse(mapobject *lz, visitproc visit, void *arg)
1051{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001052 Py_VISIT(lz->iters);
1053 Py_VISIT(lz->func);
1054 return 0;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001055}
1056
1057static PyObject *
1058map_next(mapobject *lz)
1059{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001060 PyObject *val;
1061 PyObject *argtuple;
1062 PyObject *result;
1063 Py_ssize_t numargs, i;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001064
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001065 numargs = PyTuple_Size(lz->iters);
1066 argtuple = PyTuple_New(numargs);
1067 if (argtuple == NULL)
1068 return NULL;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001069
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001070 for (i=0 ; i<numargs ; i++) {
1071 val = PyIter_Next(PyTuple_GET_ITEM(lz->iters, i));
1072 if (val == NULL) {
1073 Py_DECREF(argtuple);
1074 return NULL;
1075 }
1076 PyTuple_SET_ITEM(argtuple, i, val);
1077 }
1078 result = PyObject_Call(lz->func, argtuple, NULL);
1079 Py_DECREF(argtuple);
1080 return result;
Guido van Rossum12d12c51993-10-26 17:58:25 +00001081}
1082
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001083static PyObject *
1084map_reduce(mapobject *lz)
1085{
1086 Py_ssize_t numargs = PyTuple_GET_SIZE(lz->iters);
1087 PyObject *args = PyTuple_New(numargs+1);
1088 Py_ssize_t i;
1089 if (args == NULL)
1090 return NULL;
1091 Py_INCREF(lz->func);
1092 PyTuple_SET_ITEM(args, 0, lz->func);
1093 for (i = 0; i<numargs; i++){
1094 PyObject *it = PyTuple_GET_ITEM(lz->iters, i);
1095 Py_INCREF(it);
1096 PyTuple_SET_ITEM(args, i+1, it);
1097 }
1098
1099 return Py_BuildValue("ON", Py_TYPE(lz), args);
1100}
1101
1102static PyMethodDef map_methods[] = {
1103 {"__reduce__", (PyCFunction)map_reduce, METH_NOARGS, reduce_doc},
1104 {NULL, NULL} /* sentinel */
1105};
1106
1107
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001108PyDoc_STRVAR(map_doc,
Raymond Hettingera6c60372008-03-13 01:26:19 +00001109"map(func, *iterables) --> map object\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001110\n\
Raymond Hettingera6c60372008-03-13 01:26:19 +00001111Make an iterator that computes the function using arguments from\n\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001112each of the iterables. Stops when the shortest iterable is exhausted.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001113
Raymond Hettingera6c60372008-03-13 01:26:19 +00001114PyTypeObject PyMap_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001115 PyVarObject_HEAD_INIT(&PyType_Type, 0)
1116 "map", /* tp_name */
1117 sizeof(mapobject), /* tp_basicsize */
1118 0, /* tp_itemsize */
1119 /* methods */
1120 (destructor)map_dealloc, /* tp_dealloc */
1121 0, /* tp_print */
1122 0, /* tp_getattr */
1123 0, /* tp_setattr */
1124 0, /* tp_reserved */
1125 0, /* tp_repr */
1126 0, /* tp_as_number */
1127 0, /* tp_as_sequence */
1128 0, /* tp_as_mapping */
1129 0, /* tp_hash */
1130 0, /* tp_call */
1131 0, /* tp_str */
1132 PyObject_GenericGetAttr, /* tp_getattro */
1133 0, /* tp_setattro */
1134 0, /* tp_as_buffer */
1135 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
1136 Py_TPFLAGS_BASETYPE, /* tp_flags */
1137 map_doc, /* tp_doc */
1138 (traverseproc)map_traverse, /* tp_traverse */
1139 0, /* tp_clear */
1140 0, /* tp_richcompare */
1141 0, /* tp_weaklistoffset */
1142 PyObject_SelfIter, /* tp_iter */
1143 (iternextfunc)map_next, /* tp_iternext */
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001144 map_methods, /* tp_methods */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001145 0, /* tp_members */
1146 0, /* tp_getset */
1147 0, /* tp_base */
1148 0, /* tp_dict */
1149 0, /* tp_descr_get */
1150 0, /* tp_descr_set */
1151 0, /* tp_dictoffset */
1152 0, /* tp_init */
1153 PyType_GenericAlloc, /* tp_alloc */
1154 map_new, /* tp_new */
1155 PyObject_GC_Del, /* tp_free */
Raymond Hettingera6c60372008-03-13 01:26:19 +00001156};
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001157
Guido van Rossum79f25d91997-04-29 20:08:16 +00001158static PyObject *
Georg Brandla18af4e2007-04-21 15:47:16 +00001159builtin_next(PyObject *self, PyObject *args)
1160{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001161 PyObject *it, *res;
1162 PyObject *def = NULL;
Georg Brandla18af4e2007-04-21 15:47:16 +00001163
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001164 if (!PyArg_UnpackTuple(args, "next", 1, 2, &it, &def))
1165 return NULL;
1166 if (!PyIter_Check(it)) {
1167 PyErr_Format(PyExc_TypeError,
Philip Jenvey50add042011-11-06 16:37:52 -08001168 "'%.200s' object is not an iterator",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001169 it->ob_type->tp_name);
1170 return NULL;
1171 }
1172
1173 res = (*it->ob_type->tp_iternext)(it);
1174 if (res != NULL) {
1175 return res;
1176 } else if (def != NULL) {
1177 if (PyErr_Occurred()) {
1178 if(!PyErr_ExceptionMatches(PyExc_StopIteration))
1179 return NULL;
1180 PyErr_Clear();
1181 }
1182 Py_INCREF(def);
1183 return def;
1184 } else if (PyErr_Occurred()) {
1185 return NULL;
1186 } else {
1187 PyErr_SetNone(PyExc_StopIteration);
1188 return NULL;
1189 }
Georg Brandla18af4e2007-04-21 15:47:16 +00001190}
1191
1192PyDoc_STRVAR(next_doc,
1193"next(iterator[, default])\n\
1194\n\
1195Return the next item from the iterator. If default is given and the iterator\n\
1196is exhausted, it is returned instead of raising StopIteration.");
1197
1198
1199static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001200builtin_setattr(PyObject *self, PyObject *args)
Guido van Rossum33894be1992-01-27 16:53:09 +00001201{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001202 PyObject *v;
1203 PyObject *name;
1204 PyObject *value;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001205
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001206 if (!PyArg_UnpackTuple(args, "setattr", 3, 3, &v, &name, &value))
1207 return NULL;
1208 if (PyObject_SetAttr(v, name, value) != 0)
1209 return NULL;
1210 Py_INCREF(Py_None);
1211 return Py_None;
Guido van Rossum33894be1992-01-27 16:53:09 +00001212}
1213
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001214PyDoc_STRVAR(setattr_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001215"setattr(object, name, value)\n\
1216\n\
1217Set a named attribute on an object; setattr(x, 'y', v) is equivalent to\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001218``x.y = v''.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001219
1220
Guido van Rossum79f25d91997-04-29 20:08:16 +00001221static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001222builtin_delattr(PyObject *self, PyObject *args)
Guido van Rossum14144fc1994-08-29 12:53:40 +00001223{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001224 PyObject *v;
1225 PyObject *name;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001226
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001227 if (!PyArg_UnpackTuple(args, "delattr", 2, 2, &v, &name))
1228 return NULL;
1229 if (PyObject_SetAttr(v, name, (PyObject *)NULL) != 0)
1230 return NULL;
1231 Py_INCREF(Py_None);
1232 return Py_None;
Guido van Rossum14144fc1994-08-29 12:53:40 +00001233}
1234
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001235PyDoc_STRVAR(delattr_doc,
Guido van Rossumdf12a591998-11-23 22:13:04 +00001236"delattr(object, name)\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001237\n\
1238Delete a named attribute on an object; delattr(x, 'y') is equivalent to\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001239``del x.y''.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001240
1241
Guido van Rossum79f25d91997-04-29 20:08:16 +00001242static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001243builtin_hash(PyObject *self, PyObject *v)
Guido van Rossum9bfef441993-03-29 10:43:31 +00001244{
Benjamin Peterson8f67d082010-10-17 20:54:53 +00001245 Py_hash_t x;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001246
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001247 x = PyObject_Hash(v);
1248 if (x == -1)
1249 return NULL;
Benjamin Peterson8f67d082010-10-17 20:54:53 +00001250 return PyLong_FromSsize_t(x);
Guido van Rossum9bfef441993-03-29 10:43:31 +00001251}
1252
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001253PyDoc_STRVAR(hash_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001254"hash(object) -> integer\n\
1255\n\
1256Return a hash value for the object. Two objects with the same value have\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001257the same hash value. The reverse is not necessarily true, but likely.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001258
1259
Guido van Rossum79f25d91997-04-29 20:08:16 +00001260static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001261builtin_hex(PyObject *self, PyObject *v)
Guido van Rossum006bcd41991-10-24 14:54:44 +00001262{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001263 return PyNumber_ToBase(v, 16);
Guido van Rossum006bcd41991-10-24 14:54:44 +00001264}
1265
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001266PyDoc_STRVAR(hex_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001267"hex(number) -> string\n\
1268\n\
Alexander Belopolsky12338ab2011-04-07 00:15:33 -04001269Return the hexadecimal representation of an integer.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001270
1271
Guido van Rossum79f25d91997-04-29 20:08:16 +00001272static PyObject *
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001273builtin_iter(PyObject *self, PyObject *args)
1274{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001275 PyObject *v, *w = NULL;
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001276
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001277 if (!PyArg_UnpackTuple(args, "iter", 1, 2, &v, &w))
1278 return NULL;
1279 if (w == NULL)
1280 return PyObject_GetIter(v);
1281 if (!PyCallable_Check(v)) {
1282 PyErr_SetString(PyExc_TypeError,
1283 "iter(v, w): v must be callable");
1284 return NULL;
1285 }
1286 return PyCallIter_New(v, w);
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001287}
1288
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001289PyDoc_STRVAR(iter_doc,
Georg Brandld11ae5d2008-05-16 13:27:32 +00001290"iter(iterable) -> iterator\n\
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001291iter(callable, sentinel) -> iterator\n\
1292\n\
1293Get an iterator from an object. In the first form, the argument must\n\
1294supply its own iterator, or be a sequence.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001295In the second form, the callable is called until it returns the sentinel.");
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001296
1297
1298static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001299builtin_len(PyObject *self, PyObject *v)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001300{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001301 Py_ssize_t res;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001302
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001303 res = PyObject_Size(v);
1304 if (res < 0 && PyErr_Occurred())
1305 return NULL;
1306 return PyLong_FromSsize_t(res);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001307}
1308
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001309PyDoc_STRVAR(len_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001310"len(object) -> integer\n\
1311\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001312Return the number of items of a sequence or mapping.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001313
1314
Guido van Rossum79f25d91997-04-29 20:08:16 +00001315static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001316builtin_locals(PyObject *self)
Guido van Rossum872537c1995-07-07 22:43:42 +00001317{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001318 PyObject *d;
Guido van Rossum872537c1995-07-07 22:43:42 +00001319
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001320 d = PyEval_GetLocals();
1321 Py_XINCREF(d);
1322 return d;
Guido van Rossum872537c1995-07-07 22:43:42 +00001323}
1324
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001325PyDoc_STRVAR(locals_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001326"locals() -> dictionary\n\
1327\n\
Raymond Hettinger69bf8f32003-01-04 02:16:22 +00001328Update and return a dictionary containing the current scope's local variables.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001329
1330
Guido van Rossum79f25d91997-04-29 20:08:16 +00001331static PyObject *
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001332min_max(PyObject *args, PyObject *kwds, int op)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001333{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001334 PyObject *v, *it, *item, *val, *maxitem, *maxval, *keyfunc=NULL;
Raymond Hettinger4d6018f2013-06-24 22:43:02 -07001335 PyObject *emptytuple, *defaultval = NULL;
1336 static char *kwlist[] = {"key", "default", NULL};
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001337 const char *name = op == Py_LT ? "min" : "max";
Raymond Hettinger4d6018f2013-06-24 22:43:02 -07001338 const int positional = PyTuple_Size(args) > 1;
1339 int ret;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001340
Raymond Hettinger4d6018f2013-06-24 22:43:02 -07001341 if (positional)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001342 v = args;
Serhiy Storchakac6792272013-10-19 21:03:34 +03001343 else if (!PyArg_UnpackTuple(args, name, 1, 1, &v))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001344 return NULL;
Tim Peters67d687a2002-04-29 21:27:32 +00001345
Raymond Hettinger4d6018f2013-06-24 22:43:02 -07001346 emptytuple = PyTuple_New(0);
1347 if (emptytuple == NULL)
1348 return NULL;
1349 ret = PyArg_ParseTupleAndKeywords(emptytuple, kwds, "|$OO", kwlist,
1350 &keyfunc, &defaultval);
1351 Py_DECREF(emptytuple);
1352 if (!ret)
1353 return NULL;
1354
1355 if (positional && defaultval != NULL) {
1356 PyErr_Format(PyExc_TypeError,
1357 "Cannot specify a default for %s() with multiple "
1358 "positional arguments", name);
1359 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001360 }
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001361
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001362 it = PyObject_GetIter(v);
1363 if (it == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001364 return NULL;
1365 }
Tim Petersc3074532001-05-03 07:00:32 +00001366
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001367 maxitem = NULL; /* the result */
1368 maxval = NULL; /* the value associated with the result */
1369 while (( item = PyIter_Next(it) )) {
1370 /* get the value from the key function */
1371 if (keyfunc != NULL) {
1372 val = PyObject_CallFunctionObjArgs(keyfunc, item, NULL);
1373 if (val == NULL)
1374 goto Fail_it_item;
1375 }
1376 /* no key function; the value is the item */
1377 else {
1378 val = item;
1379 Py_INCREF(val);
1380 }
Tim Petersc3074532001-05-03 07:00:32 +00001381
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001382 /* maximum value and item are unset; set them */
1383 if (maxval == NULL) {
1384 maxitem = item;
1385 maxval = val;
1386 }
1387 /* maximum value and item are set; update them as necessary */
1388 else {
1389 int cmp = PyObject_RichCompareBool(val, maxval, op);
1390 if (cmp < 0)
1391 goto Fail_it_item_and_val;
1392 else if (cmp > 0) {
1393 Py_DECREF(maxval);
1394 Py_DECREF(maxitem);
1395 maxval = val;
1396 maxitem = item;
1397 }
1398 else {
1399 Py_DECREF(item);
1400 Py_DECREF(val);
1401 }
1402 }
1403 }
1404 if (PyErr_Occurred())
1405 goto Fail_it;
1406 if (maxval == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001407 assert(maxitem == NULL);
Raymond Hettinger4d6018f2013-06-24 22:43:02 -07001408 if (defaultval != NULL) {
1409 Py_INCREF(defaultval);
1410 maxitem = defaultval;
1411 } else {
1412 PyErr_Format(PyExc_ValueError,
1413 "%s() arg is an empty sequence", name);
1414 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001415 }
1416 else
1417 Py_DECREF(maxval);
1418 Py_DECREF(it);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001419 return maxitem;
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001420
1421Fail_it_item_and_val:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001422 Py_DECREF(val);
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001423Fail_it_item:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001424 Py_DECREF(item);
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001425Fail_it:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001426 Py_XDECREF(maxval);
1427 Py_XDECREF(maxitem);
1428 Py_DECREF(it);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001429 return NULL;
Guido van Rossum3f5da241990-12-20 15:06:42 +00001430}
1431
Guido van Rossum79f25d91997-04-29 20:08:16 +00001432static PyObject *
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001433builtin_min(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001434{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001435 return min_max(args, kwds, Py_LT);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001436}
1437
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001438PyDoc_STRVAR(min_doc,
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001439"min(iterable[, key=func]) -> value\n\
1440min(a, b, c, ...[, key=func]) -> value\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001441\n\
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001442With a single iterable argument, return its smallest item.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001443With two or more arguments, return the smallest argument.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001444
1445
Guido van Rossum79f25d91997-04-29 20:08:16 +00001446static PyObject *
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001447builtin_max(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001448{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001449 return min_max(args, kwds, Py_GT);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001450}
1451
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001452PyDoc_STRVAR(max_doc,
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001453"max(iterable[, key=func]) -> value\n\
1454max(a, b, c, ...[, key=func]) -> value\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001455\n\
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001456With a single iterable argument, return its largest item.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001457With two or more arguments, return the largest argument.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001458
1459
Guido van Rossum79f25d91997-04-29 20:08:16 +00001460static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001461builtin_oct(PyObject *self, PyObject *v)
Guido van Rossum006bcd41991-10-24 14:54:44 +00001462{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001463 return PyNumber_ToBase(v, 8);
Guido van Rossum006bcd41991-10-24 14:54:44 +00001464}
1465
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001466PyDoc_STRVAR(oct_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001467"oct(number) -> string\n\
1468\n\
Alexander Belopolsky12338ab2011-04-07 00:15:33 -04001469Return the octal representation of an integer.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001470
1471
Guido van Rossum79f25d91997-04-29 20:08:16 +00001472static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001473builtin_ord(PyObject *self, PyObject* obj)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001474{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001475 long ord;
1476 Py_ssize_t size;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001477
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001478 if (PyBytes_Check(obj)) {
1479 size = PyBytes_GET_SIZE(obj);
1480 if (size == 1) {
1481 ord = (long)((unsigned char)*PyBytes_AS_STRING(obj));
1482 return PyLong_FromLong(ord);
1483 }
1484 }
1485 else if (PyUnicode_Check(obj)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001486 if (PyUnicode_READY(obj) == -1)
1487 return NULL;
1488 size = PyUnicode_GET_LENGTH(obj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001489 if (size == 1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001490 ord = (long)PyUnicode_READ_CHAR(obj, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001491 return PyLong_FromLong(ord);
1492 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001493 }
1494 else if (PyByteArray_Check(obj)) {
1495 /* XXX Hopefully this is temporary */
1496 size = PyByteArray_GET_SIZE(obj);
1497 if (size == 1) {
1498 ord = (long)((unsigned char)*PyByteArray_AS_STRING(obj));
1499 return PyLong_FromLong(ord);
1500 }
1501 }
1502 else {
1503 PyErr_Format(PyExc_TypeError,
1504 "ord() expected string of length 1, but " \
1505 "%.200s found", obj->ob_type->tp_name);
1506 return NULL;
1507 }
Guido van Rossum09095f32000-03-10 23:00:52 +00001508
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001509 PyErr_Format(PyExc_TypeError,
1510 "ord() expected a character, "
1511 "but string of length %zd found",
1512 size);
1513 return NULL;
Guido van Rossum3f5da241990-12-20 15:06:42 +00001514}
1515
Guido van Rossum307fa8c2007-07-16 20:46:27 +00001516PyDoc_VAR(ord_doc) = PyDoc_STR(
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001517"ord(c) -> integer\n\
1518\n\
Guido van Rossum8ac004e2007-07-15 13:00:05 +00001519Return the integer ordinal of a one-character string."
Antoine Pitrouedc60182012-06-23 14:19:58 +02001520);
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001521
1522
Guido van Rossum79f25d91997-04-29 20:08:16 +00001523static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001524builtin_pow(PyObject *self, PyObject *args)
Guido van Rossum6a00cd81995-01-07 12:39:01 +00001525{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001526 PyObject *v, *w, *z = Py_None;
Guido van Rossum6a00cd81995-01-07 12:39:01 +00001527
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001528 if (!PyArg_UnpackTuple(args, "pow", 2, 3, &v, &w, &z))
1529 return NULL;
1530 return PyNumber_Power(v, w, z);
Guido van Rossumd4905451991-05-05 20:00:36 +00001531}
1532
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001533PyDoc_STRVAR(pow_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001534"pow(x, y[, z]) -> number\n\
1535\n\
1536With two arguments, equivalent to x**y. With three arguments,\n\
Serhiy Storchaka95949422013-08-27 19:40:23 +03001537equivalent to (x**y) % z, but may be more efficient (e.g. for ints).");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001538
1539
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001540
Guido van Rossum34343512006-11-30 22:13:52 +00001541static PyObject *
1542builtin_print(PyObject *self, PyObject *args, PyObject *kwds)
1543{
Georg Brandlbc3b6822012-01-13 19:41:25 +01001544 static char *kwlist[] = {"sep", "end", "file", "flush", 0};
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001545 static PyObject *dummy_args;
Georg Brandlbc3b6822012-01-13 19:41:25 +01001546 PyObject *sep = NULL, *end = NULL, *file = NULL, *flush = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001547 int i, err;
Guido van Rossum34343512006-11-30 22:13:52 +00001548
Benjamin Peterson00102562012-01-11 21:00:16 -05001549 if (dummy_args == NULL && !(dummy_args = PyTuple_New(0)))
Georg Brandlbc3b6822012-01-13 19:41:25 +01001550 return NULL;
1551 if (!PyArg_ParseTupleAndKeywords(dummy_args, kwds, "|OOOO:print",
1552 kwlist, &sep, &end, &file, &flush))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001553 return NULL;
1554 if (file == NULL || file == Py_None) {
1555 file = PySys_GetObject("stdout");
Victor Stinner1e53bba2013-07-16 22:26:05 +02001556 if (file == NULL) {
1557 PyErr_SetString(PyExc_RuntimeError, "lost sys.stdout");
1558 return NULL;
1559 }
1560
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001561 /* sys.stdout may be None when FILE* stdout isn't connected */
1562 if (file == Py_None)
1563 Py_RETURN_NONE;
1564 }
Guido van Rossum34343512006-11-30 22:13:52 +00001565
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001566 if (sep == Py_None) {
1567 sep = NULL;
1568 }
1569 else if (sep && !PyUnicode_Check(sep)) {
1570 PyErr_Format(PyExc_TypeError,
1571 "sep must be None or a string, not %.200s",
1572 sep->ob_type->tp_name);
1573 return NULL;
1574 }
1575 if (end == Py_None) {
1576 end = NULL;
1577 }
1578 else if (end && !PyUnicode_Check(end)) {
1579 PyErr_Format(PyExc_TypeError,
1580 "end must be None or a string, not %.200s",
1581 end->ob_type->tp_name);
1582 return NULL;
1583 }
Guido van Rossum34343512006-11-30 22:13:52 +00001584
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001585 for (i = 0; i < PyTuple_Size(args); i++) {
1586 if (i > 0) {
1587 if (sep == NULL)
1588 err = PyFile_WriteString(" ", file);
1589 else
1590 err = PyFile_WriteObject(sep, file,
1591 Py_PRINT_RAW);
1592 if (err)
1593 return NULL;
1594 }
1595 err = PyFile_WriteObject(PyTuple_GetItem(args, i), file,
1596 Py_PRINT_RAW);
1597 if (err)
1598 return NULL;
1599 }
Guido van Rossum34343512006-11-30 22:13:52 +00001600
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001601 if (end == NULL)
1602 err = PyFile_WriteString("\n", file);
1603 else
1604 err = PyFile_WriteObject(end, file, Py_PRINT_RAW);
1605 if (err)
1606 return NULL;
Guido van Rossum34343512006-11-30 22:13:52 +00001607
Georg Brandlbc3b6822012-01-13 19:41:25 +01001608 if (flush != NULL) {
1609 PyObject *tmp;
1610 int do_flush = PyObject_IsTrue(flush);
1611 if (do_flush == -1)
1612 return NULL;
1613 else if (do_flush) {
1614 tmp = PyObject_CallMethod(file, "flush", "");
1615 if (tmp == NULL)
1616 return NULL;
1617 else
1618 Py_DECREF(tmp);
1619 }
1620 }
1621
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001622 Py_RETURN_NONE;
Guido van Rossum34343512006-11-30 22:13:52 +00001623}
1624
1625PyDoc_STRVAR(print_doc,
Senthil Kumarane9175bd2012-08-10 13:53:45 -07001626"print(value, ..., sep=' ', end='\\n', file=sys.stdout, flush=False)\n\
Guido van Rossum34343512006-11-30 22:13:52 +00001627\n\
1628Prints the values to a stream, or to sys.stdout by default.\n\
1629Optional keyword arguments:\n\
Senthil Kumarane9175bd2012-08-10 13:53:45 -07001630file: a file-like object (stream); defaults to the current sys.stdout.\n\
1631sep: string inserted between values, default a space.\n\
1632end: string appended after the last value, default a newline.\n\
1633flush: whether to forcibly flush the stream.");
Guido van Rossum34343512006-11-30 22:13:52 +00001634
1635
Guido van Rossuma88a0332007-02-26 16:59:55 +00001636static PyObject *
1637builtin_input(PyObject *self, PyObject *args)
1638{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001639 PyObject *promptarg = NULL;
1640 PyObject *fin = PySys_GetObject("stdin");
1641 PyObject *fout = PySys_GetObject("stdout");
1642 PyObject *ferr = PySys_GetObject("stderr");
1643 PyObject *tmp;
1644 long fd;
1645 int tty;
Guido van Rossuma88a0332007-02-26 16:59:55 +00001646
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001647 /* Parse arguments */
1648 if (!PyArg_UnpackTuple(args, "input", 0, 1, &promptarg))
1649 return NULL;
Guido van Rossuma88a0332007-02-26 16:59:55 +00001650
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001651 /* Check that stdin/out/err are intact */
1652 if (fin == NULL || fin == Py_None) {
1653 PyErr_SetString(PyExc_RuntimeError,
1654 "input(): lost sys.stdin");
1655 return NULL;
1656 }
1657 if (fout == NULL || fout == Py_None) {
1658 PyErr_SetString(PyExc_RuntimeError,
1659 "input(): lost sys.stdout");
1660 return NULL;
1661 }
1662 if (ferr == NULL || ferr == Py_None) {
1663 PyErr_SetString(PyExc_RuntimeError,
1664 "input(): lost sys.stderr");
1665 return NULL;
1666 }
Guido van Rossumeba76962007-05-27 09:13:28 +00001667
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001668 /* First of all, flush stderr */
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001669 tmp = _PyObject_CallMethodId(ferr, &PyId_flush, "");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001670 if (tmp == NULL)
1671 PyErr_Clear();
1672 else
1673 Py_DECREF(tmp);
Guido van Rossumeba76962007-05-27 09:13:28 +00001674
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001675 /* We should only use (GNU) readline if Python's sys.stdin and
1676 sys.stdout are the same as C's stdin and stdout, because we
1677 need to pass it those. */
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001678 tmp = _PyObject_CallMethodId(fin, &PyId_fileno, "");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001679 if (tmp == NULL) {
1680 PyErr_Clear();
1681 tty = 0;
1682 }
1683 else {
1684 fd = PyLong_AsLong(tmp);
1685 Py_DECREF(tmp);
1686 if (fd < 0 && PyErr_Occurred())
1687 return NULL;
1688 tty = fd == fileno(stdin) && isatty(fd);
1689 }
1690 if (tty) {
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001691 tmp = _PyObject_CallMethodId(fout, &PyId_fileno, "");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001692 if (tmp == NULL)
1693 PyErr_Clear();
1694 else {
1695 fd = PyLong_AsLong(tmp);
1696 Py_DECREF(tmp);
1697 if (fd < 0 && PyErr_Occurred())
1698 return NULL;
1699 tty = fd == fileno(stdout) && isatty(fd);
1700 }
1701 }
Guido van Rossumeba76962007-05-27 09:13:28 +00001702
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001703 /* If we're interactive, use (GNU) readline */
1704 if (tty) {
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001705 PyObject *po = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001706 char *prompt;
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001707 char *s = NULL;
1708 PyObject *stdin_encoding = NULL, *stdin_errors = NULL;
1709 PyObject *stdout_encoding = NULL, *stdout_errors = NULL;
1710 char *stdin_encoding_str, *stdin_errors_str;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001711 PyObject *result;
Victor Stinnerc0f1a1a2011-02-23 12:07:37 +00001712 size_t len;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02001713 _Py_IDENTIFIER(encoding);
Antoine Pitrou5ee9d8a2011-11-06 00:38:45 +01001714 _Py_IDENTIFIER(errors);
Martin v. Löwis4a7b5d52007-09-04 05:24:49 +00001715
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02001716 stdin_encoding = _PyObject_GetAttrId(fin, &PyId_encoding);
Antoine Pitrou5ee9d8a2011-11-06 00:38:45 +01001717 stdin_errors = _PyObject_GetAttrId(fin, &PyId_errors);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001718 if (!stdin_encoding || !stdin_errors)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001719 /* stdin is a text stream, so it must have an
1720 encoding. */
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001721 goto _readline_errors;
Victor Stinner306f0102010-05-19 01:06:22 +00001722 stdin_encoding_str = _PyUnicode_AsString(stdin_encoding);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001723 stdin_errors_str = _PyUnicode_AsString(stdin_errors);
1724 if (!stdin_encoding_str || !stdin_errors_str)
1725 goto _readline_errors;
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001726 tmp = _PyObject_CallMethodId(fout, &PyId_flush, "");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001727 if (tmp == NULL)
1728 PyErr_Clear();
1729 else
1730 Py_DECREF(tmp);
1731 if (promptarg != NULL) {
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001732 /* We have a prompt, encode it as stdout would */
1733 char *stdout_encoding_str, *stdout_errors_str;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001734 PyObject *stringpo;
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02001735 stdout_encoding = _PyObject_GetAttrId(fout, &PyId_encoding);
Antoine Pitrou5ee9d8a2011-11-06 00:38:45 +01001736 stdout_errors = _PyObject_GetAttrId(fout, &PyId_errors);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001737 if (!stdout_encoding || !stdout_errors)
1738 goto _readline_errors;
Victor Stinner306f0102010-05-19 01:06:22 +00001739 stdout_encoding_str = _PyUnicode_AsString(stdout_encoding);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001740 stdout_errors_str = _PyUnicode_AsString(stdout_errors);
1741 if (!stdout_encoding_str || !stdout_errors_str)
1742 goto _readline_errors;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001743 stringpo = PyObject_Str(promptarg);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001744 if (stringpo == NULL)
1745 goto _readline_errors;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001746 po = PyUnicode_AsEncodedString(stringpo,
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001747 stdout_encoding_str, stdout_errors_str);
1748 Py_CLEAR(stdout_encoding);
1749 Py_CLEAR(stdout_errors);
1750 Py_CLEAR(stringpo);
1751 if (po == NULL)
1752 goto _readline_errors;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001753 prompt = PyBytes_AsString(po);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001754 if (prompt == NULL)
1755 goto _readline_errors;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001756 }
1757 else {
1758 po = NULL;
1759 prompt = "";
1760 }
1761 s = PyOS_Readline(stdin, stdout, prompt);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001762 if (s == NULL) {
Richard Oudkerk614c5782013-04-03 13:44:50 +01001763 PyErr_CheckSignals();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001764 if (!PyErr_Occurred())
1765 PyErr_SetNone(PyExc_KeyboardInterrupt);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001766 goto _readline_errors;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001767 }
Victor Stinnerc0f1a1a2011-02-23 12:07:37 +00001768
1769 len = strlen(s);
1770 if (len == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001771 PyErr_SetNone(PyExc_EOFError);
1772 result = NULL;
1773 }
Victor Stinnerc0f1a1a2011-02-23 12:07:37 +00001774 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001775 if (len > PY_SSIZE_T_MAX) {
1776 PyErr_SetString(PyExc_OverflowError,
1777 "input: input too long");
1778 result = NULL;
1779 }
1780 else {
Victor Stinnerc0f1a1a2011-02-23 12:07:37 +00001781 len--; /* strip trailing '\n' */
1782 if (len != 0 && s[len-1] == '\r')
1783 len--; /* strip trailing '\r' */
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001784 result = PyUnicode_Decode(s, len, stdin_encoding_str,
1785 stdin_errors_str);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001786 }
1787 }
1788 Py_DECREF(stdin_encoding);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001789 Py_DECREF(stdin_errors);
1790 Py_XDECREF(po);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001791 PyMem_FREE(s);
1792 return result;
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001793 _readline_errors:
1794 Py_XDECREF(stdin_encoding);
1795 Py_XDECREF(stdout_encoding);
1796 Py_XDECREF(stdin_errors);
1797 Py_XDECREF(stdout_errors);
1798 Py_XDECREF(po);
1799 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001800 }
Guido van Rossumeba76962007-05-27 09:13:28 +00001801
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001802 /* Fallback if we're not interactive */
1803 if (promptarg != NULL) {
1804 if (PyFile_WriteObject(promptarg, fout, Py_PRINT_RAW) != 0)
1805 return NULL;
1806 }
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001807 tmp = _PyObject_CallMethodId(fout, &PyId_flush, "");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001808 if (tmp == NULL)
1809 PyErr_Clear();
1810 else
1811 Py_DECREF(tmp);
1812 return PyFile_GetLine(fin, -1);
Guido van Rossuma88a0332007-02-26 16:59:55 +00001813}
1814
1815PyDoc_STRVAR(input_doc,
1816"input([prompt]) -> string\n\
1817\n\
1818Read a string from standard input. The trailing newline is stripped.\n\
1819If the user hits EOF (Unix: Ctl-D, Windows: Ctl-Z+Return), raise EOFError.\n\
1820On Unix, GNU readline is used if enabled. The prompt string, if given,\n\
1821is printed without a trailing newline before reading.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001822
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001823
Guido van Rossum79f25d91997-04-29 20:08:16 +00001824static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001825builtin_repr(PyObject *self, PyObject *v)
Guido van Rossumc89705d1992-11-26 08:54:07 +00001826{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001827 return PyObject_Repr(v);
Guido van Rossumc89705d1992-11-26 08:54:07 +00001828}
1829
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001830PyDoc_STRVAR(repr_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001831"repr(object) -> string\n\
1832\n\
1833Return the canonical string representation of the object.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001834For most object types, eval(repr(object)) == object.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001835
1836
Guido van Rossum79f25d91997-04-29 20:08:16 +00001837static PyObject *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001838builtin_round(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum9e51f9b1993-02-12 16:29:05 +00001839{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001840 PyObject *ndigits = NULL;
1841 static char *kwlist[] = {"number", "ndigits", 0};
Benjamin Peterson214a7d22013-04-13 17:19:01 -04001842 PyObject *number, *round, *result;
1843 _Py_IDENTIFIER(__round__);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001844
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001845 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|O:round",
1846 kwlist, &number, &ndigits))
1847 return NULL;
Alex Martelliae211f92007-08-22 23:21:33 +00001848
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001849 if (Py_TYPE(number)->tp_dict == NULL) {
1850 if (PyType_Ready(Py_TYPE(number)) < 0)
1851 return NULL;
1852 }
Guido van Rossum15d3d042007-08-24 02:02:45 +00001853
Benjamin Peterson214a7d22013-04-13 17:19:01 -04001854 round = _PyObject_LookupSpecial(number, &PyId___round__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001855 if (round == NULL) {
Benjamin Peterson214a7d22013-04-13 17:19:01 -04001856 if (!PyErr_Occurred())
1857 PyErr_Format(PyExc_TypeError,
1858 "type %.100s doesn't define __round__ method",
1859 Py_TYPE(number)->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001860 return NULL;
1861 }
Alex Martelliae211f92007-08-22 23:21:33 +00001862
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001863 if (ndigits == NULL)
Benjamin Peterson214a7d22013-04-13 17:19:01 -04001864 result = PyObject_CallFunctionObjArgs(round, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001865 else
Benjamin Peterson214a7d22013-04-13 17:19:01 -04001866 result = PyObject_CallFunctionObjArgs(round, ndigits, NULL);
1867 Py_DECREF(round);
1868 return result;
Guido van Rossum9e51f9b1993-02-12 16:29:05 +00001869}
1870
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001871PyDoc_STRVAR(round_doc,
Mark Dickinson1124e712009-01-28 21:25:58 +00001872"round(number[, ndigits]) -> number\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001873\n\
1874Round a number to a given precision in decimal digits (default 0 digits).\n\
Mark Dickinson0d748c22008-07-05 11:29:03 +00001875This returns an int when called with one argument, otherwise the\n\
Georg Brandl809ddaa2008-07-01 20:39:59 +00001876same type as the number. ndigits may be negative.");
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001877
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001878
Raymond Hettinger64958a12003-12-17 20:43:33 +00001879static PyObject *
1880builtin_sorted(PyObject *self, PyObject *args, PyObject *kwds)
1881{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001882 PyObject *newlist, *v, *seq, *keyfunc=NULL, *newargs;
1883 PyObject *callable;
1884 static char *kwlist[] = {"iterable", "key", "reverse", 0};
1885 int reverse;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02001886 _Py_IDENTIFIER(sort);
Raymond Hettinger64958a12003-12-17 20:43:33 +00001887
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001888 /* args 1-3 should match listsort in Objects/listobject.c */
1889 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|Oi:sorted",
1890 kwlist, &seq, &keyfunc, &reverse))
1891 return NULL;
Raymond Hettinger64958a12003-12-17 20:43:33 +00001892
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001893 newlist = PySequence_List(seq);
1894 if (newlist == NULL)
1895 return NULL;
Raymond Hettinger64958a12003-12-17 20:43:33 +00001896
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02001897 callable = _PyObject_GetAttrId(newlist, &PyId_sort);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001898 if (callable == NULL) {
1899 Py_DECREF(newlist);
1900 return NULL;
1901 }
Georg Brandl99d7e4e2005-08-31 22:21:15 +00001902
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001903 newargs = PyTuple_GetSlice(args, 1, 4);
1904 if (newargs == NULL) {
1905 Py_DECREF(newlist);
1906 Py_DECREF(callable);
1907 return NULL;
1908 }
Raymond Hettinger64958a12003-12-17 20:43:33 +00001909
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001910 v = PyObject_Call(callable, newargs, kwds);
1911 Py_DECREF(newargs);
1912 Py_DECREF(callable);
1913 if (v == NULL) {
1914 Py_DECREF(newlist);
1915 return NULL;
1916 }
1917 Py_DECREF(v);
1918 return newlist;
Raymond Hettinger64958a12003-12-17 20:43:33 +00001919}
1920
1921PyDoc_STRVAR(sorted_doc,
Raymond Hettinger70b64fc2008-01-30 20:15:17 +00001922"sorted(iterable, key=None, reverse=False) --> new sorted list");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001923
Guido van Rossum79f25d91997-04-29 20:08:16 +00001924static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001925builtin_vars(PyObject *self, PyObject *args)
Guido van Rossum2d951851994-08-29 12:52:16 +00001926{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001927 PyObject *v = NULL;
1928 PyObject *d;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001929
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001930 if (!PyArg_UnpackTuple(args, "vars", 0, 1, &v))
1931 return NULL;
1932 if (v == NULL) {
1933 d = PyEval_GetLocals();
Victor Stinner41bb43a2013-10-29 01:19:37 +01001934 if (d == NULL)
1935 return NULL;
1936 Py_INCREF(d);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001937 }
1938 else {
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02001939 _Py_IDENTIFIER(__dict__);
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02001940 d = _PyObject_GetAttrId(v, &PyId___dict__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001941 if (d == NULL) {
1942 PyErr_SetString(PyExc_TypeError,
1943 "vars() argument must have __dict__ attribute");
1944 return NULL;
1945 }
1946 }
1947 return d;
Guido van Rossum2d951851994-08-29 12:52:16 +00001948}
1949
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001950PyDoc_STRVAR(vars_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001951"vars([object]) -> dictionary\n\
1952\n\
1953Without arguments, equivalent to locals().\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001954With an argument, equivalent to object.__dict__.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001955
Alex Martellia70b1912003-04-22 08:12:33 +00001956static PyObject*
1957builtin_sum(PyObject *self, PyObject *args)
1958{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001959 PyObject *seq;
1960 PyObject *result = NULL;
1961 PyObject *temp, *item, *iter;
Alex Martellia70b1912003-04-22 08:12:33 +00001962
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001963 if (!PyArg_UnpackTuple(args, "sum", 1, 2, &seq, &result))
1964 return NULL;
Alex Martellia70b1912003-04-22 08:12:33 +00001965
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001966 iter = PyObject_GetIter(seq);
1967 if (iter == NULL)
1968 return NULL;
Alex Martellia70b1912003-04-22 08:12:33 +00001969
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001970 if (result == NULL) {
1971 result = PyLong_FromLong(0);
1972 if (result == NULL) {
1973 Py_DECREF(iter);
1974 return NULL;
1975 }
1976 } else {
1977 /* reject string values for 'start' parameter */
1978 if (PyUnicode_Check(result)) {
1979 PyErr_SetString(PyExc_TypeError,
1980 "sum() can't sum strings [use ''.join(seq) instead]");
1981 Py_DECREF(iter);
1982 return NULL;
1983 }
Benjamin Petersonce071ca2011-07-29 14:23:47 -05001984 if (PyBytes_Check(result)) {
1985 PyErr_SetString(PyExc_TypeError,
1986 "sum() can't sum bytes [use b''.join(seq) instead]");
Benjamin Peterson405f32c2011-07-29 22:43:45 -05001987 Py_DECREF(iter);
Benjamin Petersonce071ca2011-07-29 14:23:47 -05001988 return NULL;
1989 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001990 if (PyByteArray_Check(result)) {
1991 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson4f921c22011-07-29 14:24:29 -05001992 "sum() can't sum bytearray [use b''.join(seq) instead]");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001993 Py_DECREF(iter);
1994 return NULL;
1995 }
Guido van Rossum3172c5d2007-10-16 18:12:55 +00001996
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001997 Py_INCREF(result);
1998 }
Alex Martellia70b1912003-04-22 08:12:33 +00001999
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002000#ifndef SLOW_SUM
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002001 /* Fast addition by keeping temporary sums in C instead of new Python objects.
2002 Assumes all inputs are the same type. If the assumption fails, default
2003 to the more general routine.
2004 */
2005 if (PyLong_CheckExact(result)) {
2006 int overflow;
2007 long i_result = PyLong_AsLongAndOverflow(result, &overflow);
2008 /* If this already overflowed, don't even enter the loop. */
2009 if (overflow == 0) {
2010 Py_DECREF(result);
2011 result = NULL;
2012 }
2013 while(result == NULL) {
2014 item = PyIter_Next(iter);
2015 if (item == NULL) {
2016 Py_DECREF(iter);
2017 if (PyErr_Occurred())
2018 return NULL;
2019 return PyLong_FromLong(i_result);
2020 }
2021 if (PyLong_CheckExact(item)) {
2022 long b = PyLong_AsLongAndOverflow(item, &overflow);
2023 long x = i_result + b;
2024 if (overflow == 0 && ((x^i_result) >= 0 || (x^b) >= 0)) {
2025 i_result = x;
2026 Py_DECREF(item);
2027 continue;
2028 }
2029 }
2030 /* Either overflowed or is not an int. Restore real objects and process normally */
2031 result = PyLong_FromLong(i_result);
Christian Heimes704e2d32013-07-26 22:49:26 +02002032 if (result == NULL) {
2033 Py_DECREF(item);
2034 Py_DECREF(iter);
2035 return NULL;
2036 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002037 temp = PyNumber_Add(result, item);
2038 Py_DECREF(result);
2039 Py_DECREF(item);
2040 result = temp;
2041 if (result == NULL) {
2042 Py_DECREF(iter);
2043 return NULL;
2044 }
2045 }
2046 }
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002047
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002048 if (PyFloat_CheckExact(result)) {
2049 double f_result = PyFloat_AS_DOUBLE(result);
2050 Py_DECREF(result);
2051 result = NULL;
2052 while(result == NULL) {
2053 item = PyIter_Next(iter);
2054 if (item == NULL) {
2055 Py_DECREF(iter);
2056 if (PyErr_Occurred())
2057 return NULL;
2058 return PyFloat_FromDouble(f_result);
2059 }
2060 if (PyFloat_CheckExact(item)) {
2061 PyFPE_START_PROTECT("add", Py_DECREF(item); Py_DECREF(iter); return 0)
2062 f_result += PyFloat_AS_DOUBLE(item);
2063 PyFPE_END_PROTECT(f_result)
2064 Py_DECREF(item);
2065 continue;
2066 }
2067 if (PyLong_CheckExact(item)) {
2068 long value;
2069 int overflow;
2070 value = PyLong_AsLongAndOverflow(item, &overflow);
2071 if (!overflow) {
2072 PyFPE_START_PROTECT("add", Py_DECREF(item); Py_DECREF(iter); return 0)
2073 f_result += (double)value;
2074 PyFPE_END_PROTECT(f_result)
2075 Py_DECREF(item);
2076 continue;
2077 }
2078 }
2079 result = PyFloat_FromDouble(f_result);
2080 temp = PyNumber_Add(result, item);
2081 Py_DECREF(result);
2082 Py_DECREF(item);
2083 result = temp;
2084 if (result == NULL) {
2085 Py_DECREF(iter);
2086 return NULL;
2087 }
2088 }
2089 }
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002090#endif
2091
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002092 for(;;) {
2093 item = PyIter_Next(iter);
2094 if (item == NULL) {
2095 /* error, or end-of-sequence */
2096 if (PyErr_Occurred()) {
2097 Py_DECREF(result);
2098 result = NULL;
2099 }
2100 break;
2101 }
2102 /* It's tempting to use PyNumber_InPlaceAdd instead of
2103 PyNumber_Add here, to avoid quadratic running time
2104 when doing 'sum(list_of_lists, [])'. However, this
2105 would produce a change in behaviour: a snippet like
Mark Dickinson9acadc52009-10-26 14:19:42 +00002106
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002107 empty = []
2108 sum([[x] for x in range(10)], empty)
Mark Dickinson9acadc52009-10-26 14:19:42 +00002109
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002110 would change the value of empty. */
2111 temp = PyNumber_Add(result, item);
2112 Py_DECREF(result);
2113 Py_DECREF(item);
2114 result = temp;
2115 if (result == NULL)
2116 break;
2117 }
2118 Py_DECREF(iter);
2119 return result;
Alex Martellia70b1912003-04-22 08:12:33 +00002120}
2121
2122PyDoc_STRVAR(sum_doc,
Georg Brandld11ae5d2008-05-16 13:27:32 +00002123"sum(iterable[, start]) -> value\n\
Alex Martellia70b1912003-04-22 08:12:33 +00002124\n\
R David Murray87ead112013-07-10 16:22:14 -04002125Return the sum of an iterable of numbers (NOT strings) plus the value\n\
Georg Brandld11ae5d2008-05-16 13:27:32 +00002126of parameter 'start' (which defaults to 0). When the iterable is\n\
R David Murray87ead112013-07-10 16:22:14 -04002127empty, return start.");
Alex Martellia70b1912003-04-22 08:12:33 +00002128
2129
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002130static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002131builtin_isinstance(PyObject *self, PyObject *args)
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002132{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002133 PyObject *inst;
2134 PyObject *cls;
2135 int retval;
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002136
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002137 if (!PyArg_UnpackTuple(args, "isinstance", 2, 2, &inst, &cls))
2138 return NULL;
Guido van Rossumf5dd9141997-12-02 19:11:45 +00002139
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002140 retval = PyObject_IsInstance(inst, cls);
2141 if (retval < 0)
2142 return NULL;
2143 return PyBool_FromLong(retval);
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002144}
2145
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002146PyDoc_STRVAR(isinstance_doc,
Guido van Rossum77f6a652002-04-03 22:41:51 +00002147"isinstance(object, class-or-type-or-tuple) -> bool\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002148\n\
2149Return whether an object is an instance of a class or of a subclass thereof.\n\
Guido van Rossum03290ec2001-10-07 20:54:12 +00002150With a type as second argument, return whether that is the object's type.\n\
2151The form using a tuple, isinstance(x, (A, B, ...)), is a shortcut for\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002152isinstance(x, A) or isinstance(x, B) or ... (etc.).");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002153
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002154
2155static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002156builtin_issubclass(PyObject *self, PyObject *args)
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002157{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002158 PyObject *derived;
2159 PyObject *cls;
2160 int retval;
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002161
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002162 if (!PyArg_UnpackTuple(args, "issubclass", 2, 2, &derived, &cls))
2163 return NULL;
Guido van Rossum668213d1999-06-16 17:28:37 +00002164
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002165 retval = PyObject_IsSubclass(derived, cls);
2166 if (retval < 0)
2167 return NULL;
2168 return PyBool_FromLong(retval);
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002169}
2170
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002171PyDoc_STRVAR(issubclass_doc,
Guido van Rossum77f6a652002-04-03 22:41:51 +00002172"issubclass(C, B) -> bool\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002173\n\
Walter Dörwaldd9a6ad32002-12-12 16:41:44 +00002174Return whether class C is a subclass (i.e., a derived class) of class B.\n\
2175When using a tuple as the second argument issubclass(X, (A, B, ...)),\n\
2176is a shortcut for issubclass(X, A) or issubclass(X, B) or ... (etc.).");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002177
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002178
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002179typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002180 PyObject_HEAD
2181 Py_ssize_t tuplesize;
2182 PyObject *ittuple; /* tuple of iterators */
2183 PyObject *result;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002184} zipobject;
2185
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002186static PyObject *
2187zip_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
Barry Warsawbd599b52000-08-03 15:45:29 +00002188{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002189 zipobject *lz;
2190 Py_ssize_t i;
2191 PyObject *ittuple; /* tuple of iterators */
2192 PyObject *result;
2193 Py_ssize_t tuplesize = PySequence_Length(args);
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002194
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002195 if (type == &PyZip_Type && !_PyArg_NoKeywords("zip()", kwds))
2196 return NULL;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002197
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002198 /* args must be a tuple */
2199 assert(PyTuple_Check(args));
Barry Warsawbd599b52000-08-03 15:45:29 +00002200
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002201 /* obtain iterators */
2202 ittuple = PyTuple_New(tuplesize);
2203 if (ittuple == NULL)
2204 return NULL;
2205 for (i=0; i < tuplesize; ++i) {
2206 PyObject *item = PyTuple_GET_ITEM(args, i);
2207 PyObject *it = PyObject_GetIter(item);
2208 if (it == NULL) {
2209 if (PyErr_ExceptionMatches(PyExc_TypeError))
2210 PyErr_Format(PyExc_TypeError,
2211 "zip argument #%zd must support iteration",
2212 i+1);
2213 Py_DECREF(ittuple);
2214 return NULL;
2215 }
2216 PyTuple_SET_ITEM(ittuple, i, it);
2217 }
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002218
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002219 /* create a result holder */
2220 result = PyTuple_New(tuplesize);
2221 if (result == NULL) {
2222 Py_DECREF(ittuple);
2223 return NULL;
2224 }
2225 for (i=0 ; i < tuplesize ; i++) {
2226 Py_INCREF(Py_None);
2227 PyTuple_SET_ITEM(result, i, Py_None);
2228 }
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002229
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002230 /* create zipobject structure */
2231 lz = (zipobject *)type->tp_alloc(type, 0);
2232 if (lz == NULL) {
2233 Py_DECREF(ittuple);
2234 Py_DECREF(result);
2235 return NULL;
2236 }
2237 lz->ittuple = ittuple;
2238 lz->tuplesize = tuplesize;
2239 lz->result = result;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002240
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002241 return (PyObject *)lz;
Barry Warsawbd599b52000-08-03 15:45:29 +00002242}
2243
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002244static void
2245zip_dealloc(zipobject *lz)
2246{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002247 PyObject_GC_UnTrack(lz);
2248 Py_XDECREF(lz->ittuple);
2249 Py_XDECREF(lz->result);
2250 Py_TYPE(lz)->tp_free(lz);
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002251}
2252
2253static int
2254zip_traverse(zipobject *lz, visitproc visit, void *arg)
2255{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002256 Py_VISIT(lz->ittuple);
2257 Py_VISIT(lz->result);
2258 return 0;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002259}
2260
2261static PyObject *
2262zip_next(zipobject *lz)
2263{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002264 Py_ssize_t i;
2265 Py_ssize_t tuplesize = lz->tuplesize;
2266 PyObject *result = lz->result;
2267 PyObject *it;
2268 PyObject *item;
2269 PyObject *olditem;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002270
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002271 if (tuplesize == 0)
2272 return NULL;
2273 if (Py_REFCNT(result) == 1) {
2274 Py_INCREF(result);
2275 for (i=0 ; i < tuplesize ; i++) {
2276 it = PyTuple_GET_ITEM(lz->ittuple, i);
2277 item = (*Py_TYPE(it)->tp_iternext)(it);
Serhiy Storchaka278d03b2013-04-06 22:52:34 +03002278 if (item == NULL) {
2279 Py_DECREF(result);
2280 return NULL;
2281 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002282 olditem = PyTuple_GET_ITEM(result, i);
2283 PyTuple_SET_ITEM(result, i, item);
2284 Py_DECREF(olditem);
2285 }
2286 } else {
2287 result = PyTuple_New(tuplesize);
2288 if (result == NULL)
Serhiy Storchaka278d03b2013-04-06 22:52:34 +03002289 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002290 for (i=0 ; i < tuplesize ; i++) {
2291 it = PyTuple_GET_ITEM(lz->ittuple, i);
2292 item = (*Py_TYPE(it)->tp_iternext)(it);
Serhiy Storchaka278d03b2013-04-06 22:52:34 +03002293 if (item == NULL) {
2294 Py_DECREF(result);
2295 return NULL;
2296 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002297 PyTuple_SET_ITEM(result, i, item);
2298 }
2299 }
2300 return result;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002301}
Barry Warsawbd599b52000-08-03 15:45:29 +00002302
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002303static PyObject *
2304zip_reduce(zipobject *lz)
2305{
2306 /* Just recreate the zip with the internal iterator tuple */
2307 return Py_BuildValue("OO", Py_TYPE(lz), lz->ittuple);
2308}
2309
2310static PyMethodDef zip_methods[] = {
2311 {"__reduce__", (PyCFunction)zip_reduce, METH_NOARGS, reduce_doc},
2312 {NULL, NULL} /* sentinel */
2313};
2314
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002315PyDoc_STRVAR(zip_doc,
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002316"zip(iter1 [,iter2 [...]]) --> zip object\n\
Barry Warsawbd599b52000-08-03 15:45:29 +00002317\n\
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002318Return a zip object whose .__next__() method returns a tuple where\n\
2319the i-th element comes from the i-th iterable argument. The .__next__()\n\
2320method continues until the shortest iterable in the argument sequence\n\
Georg Brandlced51db2008-12-04 18:28:38 +00002321is exhausted and then it raises StopIteration.");
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002322
2323PyTypeObject PyZip_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002324 PyVarObject_HEAD_INIT(&PyType_Type, 0)
2325 "zip", /* tp_name */
2326 sizeof(zipobject), /* tp_basicsize */
2327 0, /* tp_itemsize */
2328 /* methods */
2329 (destructor)zip_dealloc, /* tp_dealloc */
2330 0, /* tp_print */
2331 0, /* tp_getattr */
2332 0, /* tp_setattr */
2333 0, /* tp_reserved */
2334 0, /* tp_repr */
2335 0, /* tp_as_number */
2336 0, /* tp_as_sequence */
2337 0, /* tp_as_mapping */
2338 0, /* tp_hash */
2339 0, /* tp_call */
2340 0, /* tp_str */
2341 PyObject_GenericGetAttr, /* tp_getattro */
2342 0, /* tp_setattro */
2343 0, /* tp_as_buffer */
2344 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
2345 Py_TPFLAGS_BASETYPE, /* tp_flags */
2346 zip_doc, /* tp_doc */
2347 (traverseproc)zip_traverse, /* tp_traverse */
2348 0, /* tp_clear */
2349 0, /* tp_richcompare */
2350 0, /* tp_weaklistoffset */
2351 PyObject_SelfIter, /* tp_iter */
2352 (iternextfunc)zip_next, /* tp_iternext */
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002353 zip_methods, /* tp_methods */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002354 0, /* tp_members */
2355 0, /* tp_getset */
2356 0, /* tp_base */
2357 0, /* tp_dict */
2358 0, /* tp_descr_get */
2359 0, /* tp_descr_set */
2360 0, /* tp_dictoffset */
2361 0, /* tp_init */
2362 PyType_GenericAlloc, /* tp_alloc */
2363 zip_new, /* tp_new */
2364 PyObject_GC_Del, /* tp_free */
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002365};
Barry Warsawbd599b52000-08-03 15:45:29 +00002366
2367
Guido van Rossum79f25d91997-04-29 20:08:16 +00002368static PyMethodDef builtin_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002369 {"__build_class__", (PyCFunction)builtin___build_class__,
2370 METH_VARARGS | METH_KEYWORDS, build_class_doc},
2371 {"__import__", (PyCFunction)builtin___import__, METH_VARARGS | METH_KEYWORDS, import_doc},
2372 {"abs", builtin_abs, METH_O, abs_doc},
2373 {"all", builtin_all, METH_O, all_doc},
2374 {"any", builtin_any, METH_O, any_doc},
2375 {"ascii", builtin_ascii, METH_O, ascii_doc},
2376 {"bin", builtin_bin, METH_O, bin_doc},
Antoine Pitroue71362d2010-11-27 22:00:11 +00002377 {"callable", builtin_callable, METH_O, callable_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002378 {"chr", builtin_chr, METH_VARARGS, chr_doc},
2379 {"compile", (PyCFunction)builtin_compile, METH_VARARGS | METH_KEYWORDS, compile_doc},
2380 {"delattr", builtin_delattr, METH_VARARGS, delattr_doc},
2381 {"dir", builtin_dir, METH_VARARGS, dir_doc},
2382 {"divmod", builtin_divmod, METH_VARARGS, divmod_doc},
2383 {"eval", builtin_eval, METH_VARARGS, eval_doc},
2384 {"exec", builtin_exec, METH_VARARGS, exec_doc},
2385 {"format", builtin_format, METH_VARARGS, format_doc},
2386 {"getattr", builtin_getattr, METH_VARARGS, getattr_doc},
2387 {"globals", (PyCFunction)builtin_globals, METH_NOARGS, globals_doc},
2388 {"hasattr", builtin_hasattr, METH_VARARGS, hasattr_doc},
2389 {"hash", builtin_hash, METH_O, hash_doc},
2390 {"hex", builtin_hex, METH_O, hex_doc},
2391 {"id", builtin_id, METH_O, id_doc},
2392 {"input", builtin_input, METH_VARARGS, input_doc},
2393 {"isinstance", builtin_isinstance, METH_VARARGS, isinstance_doc},
2394 {"issubclass", builtin_issubclass, METH_VARARGS, issubclass_doc},
2395 {"iter", builtin_iter, METH_VARARGS, iter_doc},
2396 {"len", builtin_len, METH_O, len_doc},
2397 {"locals", (PyCFunction)builtin_locals, METH_NOARGS, locals_doc},
2398 {"max", (PyCFunction)builtin_max, METH_VARARGS | METH_KEYWORDS, max_doc},
2399 {"min", (PyCFunction)builtin_min, METH_VARARGS | METH_KEYWORDS, min_doc},
2400 {"next", (PyCFunction)builtin_next, METH_VARARGS, next_doc},
2401 {"oct", builtin_oct, METH_O, oct_doc},
2402 {"ord", builtin_ord, METH_O, ord_doc},
2403 {"pow", builtin_pow, METH_VARARGS, pow_doc},
2404 {"print", (PyCFunction)builtin_print, METH_VARARGS | METH_KEYWORDS, print_doc},
2405 {"repr", builtin_repr, METH_O, repr_doc},
2406 {"round", (PyCFunction)builtin_round, METH_VARARGS | METH_KEYWORDS, round_doc},
2407 {"setattr", builtin_setattr, METH_VARARGS, setattr_doc},
2408 {"sorted", (PyCFunction)builtin_sorted, METH_VARARGS | METH_KEYWORDS, sorted_doc},
2409 {"sum", builtin_sum, METH_VARARGS, sum_doc},
2410 {"vars", builtin_vars, METH_VARARGS, vars_doc},
2411 {NULL, NULL},
Guido van Rossum3f5da241990-12-20 15:06:42 +00002412};
2413
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002414PyDoc_STRVAR(builtin_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002415"Built-in functions, exceptions, and other objects.\n\
2416\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002417Noteworthy: None is the `nil' object; Ellipsis represents `...' in slices.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002418
Martin v. Löwis1a214512008-06-11 05:26:20 +00002419static struct PyModuleDef builtinsmodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002420 PyModuleDef_HEAD_INIT,
2421 "builtins",
2422 builtin_doc,
2423 -1, /* multiple "initialization" just copies the module dict. */
2424 builtin_methods,
2425 NULL,
2426 NULL,
2427 NULL,
2428 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00002429};
2430
2431
Guido van Rossum25ce5661997-08-02 03:10:38 +00002432PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002433_PyBuiltin_Init(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +00002434{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002435 PyObject *mod, *dict, *debug;
Benjamin Peterson42124a72012-10-30 23:41:54 -04002436
2437 if (PyType_Ready(&PyFilter_Type) < 0 ||
2438 PyType_Ready(&PyMap_Type) < 0 ||
2439 PyType_Ready(&PyZip_Type) < 0)
2440 return NULL;
2441
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002442 mod = PyModule_Create(&builtinsmodule);
2443 if (mod == NULL)
2444 return NULL;
2445 dict = PyModule_GetDict(mod);
Tim Peters4b7625e2001-09-13 21:37:17 +00002446
Tim Peters7571a0f2003-03-23 17:52:28 +00002447#ifdef Py_TRACE_REFS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002448 /* "builtins" exposes a number of statically allocated objects
2449 * that, before this code was added in 2.3, never showed up in
2450 * the list of "all objects" maintained by Py_TRACE_REFS. As a
2451 * result, programs leaking references to None and False (etc)
2452 * couldn't be diagnosed by examining sys.getobjects(0).
2453 */
Tim Peters7571a0f2003-03-23 17:52:28 +00002454#define ADD_TO_ALL(OBJECT) _Py_AddToAllObjects((PyObject *)(OBJECT), 0)
2455#else
2456#define ADD_TO_ALL(OBJECT) (void)0
2457#endif
2458
Tim Peters4b7625e2001-09-13 21:37:17 +00002459#define SETBUILTIN(NAME, OBJECT) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002460 if (PyDict_SetItemString(dict, NAME, (PyObject *)OBJECT) < 0) \
2461 return NULL; \
2462 ADD_TO_ALL(OBJECT)
Tim Peters4b7625e2001-09-13 21:37:17 +00002463
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002464 SETBUILTIN("None", Py_None);
2465 SETBUILTIN("Ellipsis", Py_Ellipsis);
2466 SETBUILTIN("NotImplemented", Py_NotImplemented);
2467 SETBUILTIN("False", Py_False);
2468 SETBUILTIN("True", Py_True);
2469 SETBUILTIN("bool", &PyBool_Type);
2470 SETBUILTIN("memoryview", &PyMemoryView_Type);
2471 SETBUILTIN("bytearray", &PyByteArray_Type);
2472 SETBUILTIN("bytes", &PyBytes_Type);
2473 SETBUILTIN("classmethod", &PyClassMethod_Type);
2474 SETBUILTIN("complex", &PyComplex_Type);
2475 SETBUILTIN("dict", &PyDict_Type);
2476 SETBUILTIN("enumerate", &PyEnum_Type);
2477 SETBUILTIN("filter", &PyFilter_Type);
2478 SETBUILTIN("float", &PyFloat_Type);
2479 SETBUILTIN("frozenset", &PyFrozenSet_Type);
2480 SETBUILTIN("property", &PyProperty_Type);
2481 SETBUILTIN("int", &PyLong_Type);
2482 SETBUILTIN("list", &PyList_Type);
2483 SETBUILTIN("map", &PyMap_Type);
2484 SETBUILTIN("object", &PyBaseObject_Type);
2485 SETBUILTIN("range", &PyRange_Type);
2486 SETBUILTIN("reversed", &PyReversed_Type);
2487 SETBUILTIN("set", &PySet_Type);
2488 SETBUILTIN("slice", &PySlice_Type);
2489 SETBUILTIN("staticmethod", &PyStaticMethod_Type);
2490 SETBUILTIN("str", &PyUnicode_Type);
2491 SETBUILTIN("super", &PySuper_Type);
2492 SETBUILTIN("tuple", &PyTuple_Type);
2493 SETBUILTIN("type", &PyType_Type);
2494 SETBUILTIN("zip", &PyZip_Type);
2495 debug = PyBool_FromLong(Py_OptimizeFlag == 0);
2496 if (PyDict_SetItemString(dict, "__debug__", debug) < 0) {
2497 Py_XDECREF(debug);
2498 return NULL;
2499 }
2500 Py_XDECREF(debug);
Barry Warsaw757af0e1997-08-29 22:13:51 +00002501
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002502 return mod;
Tim Peters7571a0f2003-03-23 17:52:28 +00002503#undef ADD_TO_ALL
Tim Peters4b7625e2001-09-13 21:37:17 +00002504#undef SETBUILTIN
Guido van Rossum3f5da241990-12-20 15:06:42 +00002505}