blob: 96ccd6422d29e6f215faf23bff093ea050142d2f [file] [log] [blame]
Guido van Rossum3f5da241990-12-20 15:06:42 +00001/* Built-in functions */
2
Guido van Rossum79f25d91997-04-29 20:08:16 +00003#include "Python.h"
Martin v. Löwis618dc5e2008-03-30 20:03:44 +00004#include "Python-ast.h"
Guido van Rossum3f5da241990-12-20 15:06:42 +00005
6#include "node.h"
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00007#include "code.h"
Guido van Rossum3f5da241990-12-20 15:06:42 +00008
Benjamin Petersonea281a52011-08-12 23:10:50 -05009#include "asdl.h"
10#include "ast.h"
11
Guido van Rossum6bf62da1997-04-11 20:37:35 +000012#include <ctype.h>
13
Victor Stinnerb744ba12010-05-15 12:27:16 +000014#ifdef HAVE_LANGINFO_H
15#include <langinfo.h> /* CODESET */
16#endif
17
Mark Hammond26cffde42001-05-14 12:17:34 +000018/* The default encoding used by the platform file system APIs
19 Can remain NULL for all platforms that don't have such a concept
Guido van Rossum00bc0e02007-10-15 02:52:41 +000020
21 Don't forget to modify PyUnicode_DecodeFSDefault() if you touch any of the
22 values for Py_FileSystemDefaultEncoding!
Mark Hammond26cffde42001-05-14 12:17:34 +000023*/
Victor Stinner99b95382011-07-04 14:23:54 +020024#ifdef HAVE_MBCS
Mark Hammond26cffde42001-05-14 12:17:34 +000025const char *Py_FileSystemDefaultEncoding = "mbcs";
Martin v. Löwis04dc25c2008-10-03 16:09:28 +000026int Py_HasFileSystemDefaultEncoding = 1;
Just van Rossumb9b8e9c2003-02-10 09:22:01 +000027#elif defined(__APPLE__)
28const char *Py_FileSystemDefaultEncoding = "utf-8";
Martin v. Löwis04dc25c2008-10-03 16:09:28 +000029int Py_HasFileSystemDefaultEncoding = 1;
Victor Stinnerd64e8a72011-07-04 13:48:30 +020030#else
Victor Stinnerb744ba12010-05-15 12:27:16 +000031const char *Py_FileSystemDefaultEncoding = NULL; /* set by initfsencoding() */
Martin v. Löwis04dc25c2008-10-03 16:09:28 +000032int Py_HasFileSystemDefaultEncoding = 0;
Mark Hammond26cffde42001-05-14 12:17:34 +000033#endif
Mark Hammondef8b6542001-05-13 08:04:26 +000034
Victor Stinnerbd303c12013-11-07 23:07:29 +010035_Py_IDENTIFIER(__builtins__);
36_Py_IDENTIFIER(__dict__);
37_Py_IDENTIFIER(__prepare__);
38_Py_IDENTIFIER(__round__);
39_Py_IDENTIFIER(encoding);
40_Py_IDENTIFIER(errors);
Martin v. Löwisbd928fe2011-10-14 10:20:37 +020041_Py_IDENTIFIER(fileno);
42_Py_IDENTIFIER(flush);
Victor Stinnerbd303c12013-11-07 23:07:29 +010043_Py_IDENTIFIER(metaclass);
44_Py_IDENTIFIER(sort);
45_Py_IDENTIFIER(stdin);
46_Py_IDENTIFIER(stdout);
47_Py_IDENTIFIER(stderr);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +020048
Guido van Rossum79f25d91997-04-29 20:08:16 +000049static PyObject *
Guido van Rossum52cc1d82007-03-18 15:41:51 +000050builtin___build_class__(PyObject *self, PyObject *args, PyObject *kwds)
51{
Nick Coghlande31b192011-10-23 22:04:16 +100052 PyObject *func, *name, *bases, *mkw, *meta, *winner, *prep, *ns, *cell;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000053 PyObject *cls = NULL;
Florent Xicluna4d46c2a2011-10-28 15:00:50 +020054 Py_ssize_t nargs;
Nick Coghlande31b192011-10-23 22:04:16 +100055 int isclass;
Guido van Rossum52cc1d82007-03-18 15:41:51 +000056
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000057 assert(args != NULL);
58 if (!PyTuple_Check(args)) {
59 PyErr_SetString(PyExc_TypeError,
60 "__build_class__: args is not a tuple");
61 return NULL;
62 }
63 nargs = PyTuple_GET_SIZE(args);
64 if (nargs < 2) {
65 PyErr_SetString(PyExc_TypeError,
66 "__build_class__: not enough arguments");
67 return NULL;
68 }
69 func = PyTuple_GET_ITEM(args, 0); /* Better be callable */
Benjamin Petersone8e14592013-05-16 14:37:25 -050070 if (!PyFunction_Check(func)) {
71 PyErr_SetString(PyExc_TypeError,
72 "__build__class__: func must be a function");
73 return NULL;
74 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000075 name = PyTuple_GET_ITEM(args, 1);
76 if (!PyUnicode_Check(name)) {
77 PyErr_SetString(PyExc_TypeError,
78 "__build_class__: name is not a string");
79 return NULL;
80 }
81 bases = PyTuple_GetSlice(args, 2, nargs);
82 if (bases == NULL)
83 return NULL;
Guido van Rossum52cc1d82007-03-18 15:41:51 +000084
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000085 if (kwds == NULL) {
86 meta = NULL;
87 mkw = NULL;
88 }
89 else {
90 mkw = PyDict_Copy(kwds); /* Don't modify kwds passed in! */
91 if (mkw == NULL) {
92 Py_DECREF(bases);
93 return NULL;
Guido van Rossum52cc1d82007-03-18 15:41:51 +000094 }
Victor Stinnerae9f1612013-11-06 22:46:51 +010095 meta = _PyDict_GetItemId(mkw, &PyId_metaclass);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000096 if (meta != NULL) {
97 Py_INCREF(meta);
Victor Stinnerae9f1612013-11-06 22:46:51 +010098 if (_PyDict_DelItemId(mkw, &PyId_metaclass) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000099 Py_DECREF(meta);
100 Py_DECREF(mkw);
101 Py_DECREF(bases);
102 return NULL;
103 }
Nick Coghlande31b192011-10-23 22:04:16 +1000104 /* metaclass is explicitly given, check if it's indeed a class */
105 isclass = PyType_Check(meta);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000106 }
107 }
108 if (meta == NULL) {
Nick Coghlande31b192011-10-23 22:04:16 +1000109 /* if there are no bases, use type: */
110 if (PyTuple_GET_SIZE(bases) == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000111 meta = (PyObject *) (&PyType_Type);
Nick Coghlande31b192011-10-23 22:04:16 +1000112 }
113 /* else get the type of the first base */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000114 else {
115 PyObject *base0 = PyTuple_GET_ITEM(bases, 0);
116 meta = (PyObject *) (base0->ob_type);
117 }
118 Py_INCREF(meta);
Nick Coghlande31b192011-10-23 22:04:16 +1000119 isclass = 1; /* meta is really a class */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000120 }
Nick Coghlan9715d262011-10-23 22:36:42 +1000121
Nick Coghlande31b192011-10-23 22:04:16 +1000122 if (isclass) {
123 /* meta is really a class, so check for a more derived
124 metaclass, or possible metaclass conflicts: */
125 winner = (PyObject *)_PyType_CalculateMetaclass((PyTypeObject *)meta,
126 bases);
127 if (winner == NULL) {
128 Py_DECREF(meta);
129 Py_XDECREF(mkw);
130 Py_DECREF(bases);
131 return NULL;
132 }
133 if (winner != meta) {
134 Py_DECREF(meta);
135 meta = winner;
136 Py_INCREF(meta);
137 }
138 }
139 /* else: meta is not a class, so we cannot do the metaclass
140 calculation, so we will use the explicitly given object as it is */
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +0200141 prep = _PyObject_GetAttrId(meta, &PyId___prepare__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000142 if (prep == NULL) {
143 if (PyErr_ExceptionMatches(PyExc_AttributeError)) {
144 PyErr_Clear();
145 ns = PyDict_New();
146 }
147 else {
148 Py_DECREF(meta);
149 Py_XDECREF(mkw);
150 Py_DECREF(bases);
151 return NULL;
152 }
153 }
154 else {
155 PyObject *pargs = PyTuple_Pack(2, name, bases);
156 if (pargs == NULL) {
157 Py_DECREF(prep);
158 Py_DECREF(meta);
159 Py_XDECREF(mkw);
160 Py_DECREF(bases);
161 return NULL;
162 }
163 ns = PyEval_CallObjectWithKeywords(prep, pargs, mkw);
164 Py_DECREF(pargs);
165 Py_DECREF(prep);
166 }
167 if (ns == NULL) {
168 Py_DECREF(meta);
169 Py_XDECREF(mkw);
170 Py_DECREF(bases);
171 return NULL;
172 }
Benjamin Petersone8e14592013-05-16 14:37:25 -0500173 cell = PyEval_EvalCodeEx(PyFunction_GET_CODE(func), PyFunction_GET_GLOBALS(func), ns,
174 NULL, 0, NULL, 0, NULL, 0, NULL,
175 PyFunction_GET_CLOSURE(func));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000176 if (cell != NULL) {
177 PyObject *margs;
178 margs = PyTuple_Pack(3, name, bases, ns);
179 if (margs != NULL) {
180 cls = PyEval_CallObjectWithKeywords(meta, margs, mkw);
181 Py_DECREF(margs);
182 }
Benjamin Peterson8e8fbea2012-06-01 23:57:36 -0700183 if (cls != NULL && PyCell_Check(cell))
184 PyCell_Set(cell, cls);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000185 Py_DECREF(cell);
186 }
187 Py_DECREF(ns);
188 Py_DECREF(meta);
189 Py_XDECREF(mkw);
190 Py_DECREF(bases);
191 return cls;
Guido van Rossum52cc1d82007-03-18 15:41:51 +0000192}
193
194PyDoc_STRVAR(build_class_doc,
195"__build_class__(func, name, *bases, metaclass=None, **kwds) -> class\n\
196\n\
197Internal helper function used by the class statement.");
198
199static PyObject *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000200builtin___import__(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000201{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000202 static char *kwlist[] = {"name", "globals", "locals", "fromlist",
203 "level", 0};
Victor Stinnerfe93faf2011-03-14 15:54:52 -0400204 PyObject *name, *globals = NULL, *locals = NULL, *fromlist = NULL;
Brett Cannonfd074152012-04-14 14:10:13 -0400205 int level = 0;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000206
Victor Stinnerfe93faf2011-03-14 15:54:52 -0400207 if (!PyArg_ParseTupleAndKeywords(args, kwds, "U|OOOi:__import__",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000208 kwlist, &name, &globals, &locals, &fromlist, &level))
209 return NULL;
Victor Stinnerfe93faf2011-03-14 15:54:52 -0400210 return PyImport_ImportModuleLevelObject(name, globals, locals,
211 fromlist, level);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000212}
213
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000214PyDoc_STRVAR(import_doc,
Brett Cannoncb4996a2012-08-06 16:34:44 -0400215"__import__(name, globals=None, locals=None, fromlist=(), level=0) -> module\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000216\n\
Brett Cannon5305a992010-09-27 21:08:38 +0000217Import a module. Because this function is meant for use by the Python\n\
218interpreter and not for general use it is better to use\n\
219importlib.import_module() to programmatically import a module.\n\
220\n\
221The globals argument is only used to determine the context;\n\
222they are not modified. The locals argument is unused. The fromlist\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000223should be a list of names to emulate ``from name import ...'', or an\n\
224empty list to emulate ``import name''.\n\
225When importing a module from a package, note that __import__('A.B', ...)\n\
226returns package A when fromlist is empty, but its submodule B when\n\
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000227fromlist is not empty. Level is used to determine whether to perform \n\
Brett Cannon722d3ae2012-07-30 17:45:54 -0400228absolute or relative imports. 0 is absolute while a positive number\n\
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000229is the number of parent directories to search relative to the current module.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000230
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000231
Guido van Rossum79f25d91997-04-29 20:08:16 +0000232static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000233builtin_abs(PyObject *self, PyObject *v)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000234{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000235 return PyNumber_Absolute(v);
Guido van Rossum3f5da241990-12-20 15:06:42 +0000236}
237
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000238PyDoc_STRVAR(abs_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000239"abs(number) -> number\n\
240\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000241Return the absolute value of the argument.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000242
Raymond Hettinger96229b12005-03-11 06:49:40 +0000243static PyObject *
244builtin_all(PyObject *self, PyObject *v)
245{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000246 PyObject *it, *item;
247 PyObject *(*iternext)(PyObject *);
248 int cmp;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000249
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000250 it = PyObject_GetIter(v);
251 if (it == NULL)
252 return NULL;
253 iternext = *Py_TYPE(it)->tp_iternext;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000254
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000255 for (;;) {
256 item = iternext(it);
257 if (item == NULL)
258 break;
259 cmp = PyObject_IsTrue(item);
260 Py_DECREF(item);
261 if (cmp < 0) {
262 Py_DECREF(it);
263 return NULL;
264 }
265 if (cmp == 0) {
266 Py_DECREF(it);
267 Py_RETURN_FALSE;
268 }
269 }
270 Py_DECREF(it);
271 if (PyErr_Occurred()) {
272 if (PyErr_ExceptionMatches(PyExc_StopIteration))
273 PyErr_Clear();
274 else
275 return NULL;
276 }
277 Py_RETURN_TRUE;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000278}
279
280PyDoc_STRVAR(all_doc,
281"all(iterable) -> bool\n\
282\n\
Ezio Melottib19ed572013-02-15 23:35:14 +0200283Return True if bool(x) is True for all values x in the iterable.\n\
284If the iterable is empty, return True.");
Raymond Hettinger96229b12005-03-11 06:49:40 +0000285
286static PyObject *
287builtin_any(PyObject *self, PyObject *v)
288{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000289 PyObject *it, *item;
290 PyObject *(*iternext)(PyObject *);
291 int cmp;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000292
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000293 it = PyObject_GetIter(v);
294 if (it == NULL)
295 return NULL;
296 iternext = *Py_TYPE(it)->tp_iternext;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000297
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000298 for (;;) {
299 item = iternext(it);
300 if (item == NULL)
301 break;
302 cmp = PyObject_IsTrue(item);
303 Py_DECREF(item);
304 if (cmp < 0) {
305 Py_DECREF(it);
306 return NULL;
307 }
308 if (cmp == 1) {
309 Py_DECREF(it);
310 Py_RETURN_TRUE;
311 }
312 }
313 Py_DECREF(it);
314 if (PyErr_Occurred()) {
315 if (PyErr_ExceptionMatches(PyExc_StopIteration))
316 PyErr_Clear();
317 else
318 return NULL;
319 }
320 Py_RETURN_FALSE;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000321}
322
323PyDoc_STRVAR(any_doc,
324"any(iterable) -> bool\n\
325\n\
Ezio Melottib19ed572013-02-15 23:35:14 +0200326Return True if bool(x) is True for any x in the iterable.\n\
327If the iterable is empty, return False.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000328
Georg Brandl559e5d72008-06-11 18:37:52 +0000329static PyObject *
330builtin_ascii(PyObject *self, PyObject *v)
331{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000332 return PyObject_ASCII(v);
Georg Brandl559e5d72008-06-11 18:37:52 +0000333}
334
335PyDoc_STRVAR(ascii_doc,
336"ascii(object) -> string\n\
337\n\
338As repr(), return a string containing a printable representation of an\n\
339object, but escape the non-ASCII characters in the string returned by\n\
340repr() using \\x, \\u or \\U escapes. This generates a string similar\n\
341to that returned by repr() in Python 2.");
342
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000343
Guido van Rossum79f25d91997-04-29 20:08:16 +0000344static PyObject *
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000345builtin_bin(PyObject *self, PyObject *v)
346{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000347 return PyNumber_ToBase(v, 2);
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000348}
349
350PyDoc_STRVAR(bin_doc,
351"bin(number) -> string\n\
352\n\
Alexander Belopolsky12338ab2011-04-07 00:15:33 -0400353Return the binary representation of an integer.");
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000354
355
Antoine Pitroue71362d2010-11-27 22:00:11 +0000356static PyObject *
357builtin_callable(PyObject *self, PyObject *v)
358{
359 return PyBool_FromLong((long)PyCallable_Check(v));
360}
361
362PyDoc_STRVAR(callable_doc,
363"callable(object) -> bool\n\
364\n\
365Return whether the object is callable (i.e., some kind of function).\n\
366Note that classes are callable, as are instances of classes with a\n\
367__call__() method.");
368
369
Raymond Hettinger17301e92008-03-13 00:19:26 +0000370typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000371 PyObject_HEAD
372 PyObject *func;
373 PyObject *it;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000374} filterobject;
375
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000376static PyObject *
Raymond Hettinger17301e92008-03-13 00:19:26 +0000377filter_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
Guido van Rossum12d12c51993-10-26 17:58:25 +0000378{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000379 PyObject *func, *seq;
380 PyObject *it;
381 filterobject *lz;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000382
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000383 if (type == &PyFilter_Type && !_PyArg_NoKeywords("filter()", kwds))
384 return NULL;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000385
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000386 if (!PyArg_UnpackTuple(args, "filter", 2, 2, &func, &seq))
387 return NULL;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000388
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000389 /* Get iterator. */
390 it = PyObject_GetIter(seq);
391 if (it == NULL)
392 return NULL;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000393
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000394 /* create filterobject structure */
395 lz = (filterobject *)type->tp_alloc(type, 0);
396 if (lz == NULL) {
397 Py_DECREF(it);
398 return NULL;
399 }
400 Py_INCREF(func);
401 lz->func = func;
402 lz->it = it;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000403
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000404 return (PyObject *)lz;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000405}
406
407static void
408filter_dealloc(filterobject *lz)
409{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000410 PyObject_GC_UnTrack(lz);
411 Py_XDECREF(lz->func);
412 Py_XDECREF(lz->it);
413 Py_TYPE(lz)->tp_free(lz);
Raymond Hettinger17301e92008-03-13 00:19:26 +0000414}
415
416static int
417filter_traverse(filterobject *lz, visitproc visit, void *arg)
418{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000419 Py_VISIT(lz->it);
420 Py_VISIT(lz->func);
421 return 0;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000422}
423
424static PyObject *
425filter_next(filterobject *lz)
426{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000427 PyObject *item;
428 PyObject *it = lz->it;
429 long ok;
430 PyObject *(*iternext)(PyObject *);
Raymond Hettinger17301e92008-03-13 00:19:26 +0000431
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000432 iternext = *Py_TYPE(it)->tp_iternext;
433 for (;;) {
434 item = iternext(it);
435 if (item == NULL)
436 return NULL;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000437
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000438 if (lz->func == Py_None || lz->func == (PyObject *)&PyBool_Type) {
439 ok = PyObject_IsTrue(item);
440 } else {
441 PyObject *good;
442 good = PyObject_CallFunctionObjArgs(lz->func,
443 item, NULL);
444 if (good == NULL) {
445 Py_DECREF(item);
446 return NULL;
447 }
448 ok = PyObject_IsTrue(good);
449 Py_DECREF(good);
450 }
Antoine Pitrou6f430e42012-08-15 23:18:25 +0200451 if (ok > 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000452 return item;
453 Py_DECREF(item);
Antoine Pitrou6f430e42012-08-15 23:18:25 +0200454 if (ok < 0)
455 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000456 }
Guido van Rossum12d12c51993-10-26 17:58:25 +0000457}
458
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +0000459static PyObject *
460filter_reduce(filterobject *lz)
461{
462 return Py_BuildValue("O(OO)", Py_TYPE(lz), lz->func, lz->it);
463}
464
465PyDoc_STRVAR(reduce_doc, "Return state information for pickling.");
466
467static PyMethodDef filter_methods[] = {
468 {"__reduce__", (PyCFunction)filter_reduce, METH_NOARGS, reduce_doc},
469 {NULL, NULL} /* sentinel */
470};
471
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000472PyDoc_STRVAR(filter_doc,
Georg Brandld11ae5d2008-05-16 13:27:32 +0000473"filter(function or None, iterable) --> filter object\n\
Guido van Rossumc1f779c2007-07-03 08:25:58 +0000474\n\
Georg Brandld11ae5d2008-05-16 13:27:32 +0000475Return an iterator yielding those items of iterable for which function(item)\n\
Raymond Hettinger17301e92008-03-13 00:19:26 +0000476is true. If function is None, return the items that are true.");
477
478PyTypeObject PyFilter_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000479 PyVarObject_HEAD_INIT(&PyType_Type, 0)
480 "filter", /* tp_name */
481 sizeof(filterobject), /* tp_basicsize */
482 0, /* tp_itemsize */
483 /* methods */
484 (destructor)filter_dealloc, /* tp_dealloc */
485 0, /* tp_print */
486 0, /* tp_getattr */
487 0, /* tp_setattr */
488 0, /* tp_reserved */
489 0, /* tp_repr */
490 0, /* tp_as_number */
491 0, /* tp_as_sequence */
492 0, /* tp_as_mapping */
493 0, /* tp_hash */
494 0, /* tp_call */
495 0, /* tp_str */
496 PyObject_GenericGetAttr, /* tp_getattro */
497 0, /* tp_setattro */
498 0, /* tp_as_buffer */
499 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
500 Py_TPFLAGS_BASETYPE, /* tp_flags */
501 filter_doc, /* tp_doc */
502 (traverseproc)filter_traverse, /* tp_traverse */
503 0, /* tp_clear */
504 0, /* tp_richcompare */
505 0, /* tp_weaklistoffset */
506 PyObject_SelfIter, /* tp_iter */
507 (iternextfunc)filter_next, /* tp_iternext */
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +0000508 filter_methods, /* tp_methods */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000509 0, /* tp_members */
510 0, /* tp_getset */
511 0, /* tp_base */
512 0, /* tp_dict */
513 0, /* tp_descr_get */
514 0, /* tp_descr_set */
515 0, /* tp_dictoffset */
516 0, /* tp_init */
517 PyType_GenericAlloc, /* tp_alloc */
518 filter_new, /* tp_new */
519 PyObject_GC_Del, /* tp_free */
Raymond Hettinger17301e92008-03-13 00:19:26 +0000520};
521
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000522
Eric Smith8c663262007-08-25 02:26:07 +0000523static PyObject *
524builtin_format(PyObject *self, PyObject *args)
525{
Christian Heimes94b7d3d2007-12-11 20:20:39 +0000526 PyObject *value;
Eric Smith8fd3eba2008-02-17 19:48:00 +0000527 PyObject *format_spec = NULL;
Eric Smith8c663262007-08-25 02:26:07 +0000528
Eric Smith8fd3eba2008-02-17 19:48:00 +0000529 if (!PyArg_ParseTuple(args, "O|U:format", &value, &format_spec))
Benjamin Petersona12d5c62012-01-03 16:47:22 -0600530 return NULL;
Eric Smith8c663262007-08-25 02:26:07 +0000531
Eric Smith8fd3eba2008-02-17 19:48:00 +0000532 return PyObject_Format(value, format_spec);
Eric Smith8c663262007-08-25 02:26:07 +0000533}
534
Eric Smith8c663262007-08-25 02:26:07 +0000535PyDoc_STRVAR(format_doc,
Eric Smith81936692007-08-31 01:14:01 +0000536"format(value[, format_spec]) -> string\n\
Eric Smith8c663262007-08-25 02:26:07 +0000537\n\
Eric Smith81936692007-08-31 01:14:01 +0000538Returns value.__format__(format_spec)\n\
539format_spec defaults to \"\"");
540
Guido van Rossum7fcf2242007-05-04 17:43:11 +0000541static PyObject *
Walter Dörwalde7efd592007-06-05 20:07:21 +0000542builtin_chr(PyObject *self, PyObject *args)
Guido van Rossum09095f32000-03-10 23:00:52 +0000543{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000544 int x;
Guido van Rossum09095f32000-03-10 23:00:52 +0000545
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000546 if (!PyArg_ParseTuple(args, "i:chr", &x))
547 return NULL;
Fredrik Lundh0dcf67e2001-06-26 20:01:56 +0000548
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000549 return PyUnicode_FromOrdinal(x);
Guido van Rossum09095f32000-03-10 23:00:52 +0000550}
551
Victor Stinner63ab8752011-11-22 03:31:20 +0100552PyDoc_STRVAR(chr_doc,
Guido van Rossum84fc66d2007-05-03 17:18:26 +0000553"chr(i) -> Unicode character\n\
Guido van Rossum09095f32000-03-10 23:00:52 +0000554\n\
Victor Stinner63ab8752011-11-22 03:31:20 +0100555Return a Unicode string of one character with ordinal i; 0 <= i <= 0x10ffff.");
Guido van Rossum09095f32000-03-10 23:00:52 +0000556
557
Guido van Rossumf15a29f2007-05-04 00:41:39 +0000558static char *
Benjamin Petersonf5b52242009-03-02 23:31:26 +0000559source_as_string(PyObject *cmd, char *funcname, char *what, PyCompilerFlags *cf)
Guido van Rossumf15a29f2007-05-04 00:41:39 +0000560{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000561 char *str;
562 Py_ssize_t size;
Guido van Rossumf15a29f2007-05-04 00:41:39 +0000563
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000564 if (PyUnicode_Check(cmd)) {
565 cf->cf_flags |= PyCF_IGNORE_COOKIE;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200566 str = PyUnicode_AsUTF8AndSize(cmd, &size);
567 if (str == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000568 return NULL;
569 }
570 else if (!PyObject_CheckReadBuffer(cmd)) {
571 PyErr_Format(PyExc_TypeError,
572 "%s() arg 1 must be a %s object",
573 funcname, what);
574 return NULL;
575 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200576 else if (PyObject_AsReadBuffer(cmd, (const void **)&str, &size) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000577 return NULL;
578 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200579
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000580 if (strlen(str) != size) {
581 PyErr_SetString(PyExc_TypeError,
582 "source code string cannot contain null bytes");
583 return NULL;
584 }
585 return str;
Guido van Rossumf15a29f2007-05-04 00:41:39 +0000586}
587
Guido van Rossum79f25d91997-04-29 20:08:16 +0000588static PyObject *
Guido van Rossumd8faa362007-04-27 19:54:29 +0000589builtin_compile(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum5b722181993-03-30 17:46:03 +0000590{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000591 char *str;
Victor Stinner14e461d2013-08-26 22:28:21 +0200592 PyObject *filename;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000593 char *startstr;
594 int mode = -1;
595 int dont_inherit = 0;
596 int supplied_flags = 0;
Georg Brandl8334fd92010-12-04 10:26:46 +0000597 int optimize = -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000598 int is_ast;
599 PyCompilerFlags cf;
600 PyObject *cmd;
601 static char *kwlist[] = {"source", "filename", "mode", "flags",
Georg Brandl8334fd92010-12-04 10:26:46 +0000602 "dont_inherit", "optimize", NULL};
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000603 int start[] = {Py_file_input, Py_eval_input, Py_single_input};
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000604 PyObject *result;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000605
Georg Brandl8334fd92010-12-04 10:26:46 +0000606 if (!PyArg_ParseTupleAndKeywords(args, kwds, "OO&s|iii:compile", kwlist,
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000607 &cmd,
Victor Stinner14e461d2013-08-26 22:28:21 +0200608 PyUnicode_FSDecoder, &filename,
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000609 &startstr, &supplied_flags,
Georg Brandl8334fd92010-12-04 10:26:46 +0000610 &dont_inherit, &optimize))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000611 return NULL;
Tim Peters6cd6a822001-08-17 22:11:27 +0000612
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000613 cf.cf_flags = supplied_flags | PyCF_SOURCE_IS_UTF8;
Just van Rossum3aaf42c2003-02-10 08:21:10 +0000614
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000615 if (supplied_flags &
616 ~(PyCF_MASK | PyCF_MASK_OBSOLETE | PyCF_DONT_IMPLY_DEDENT | PyCF_ONLY_AST))
617 {
618 PyErr_SetString(PyExc_ValueError,
619 "compile(): unrecognised flags");
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000620 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000621 }
622 /* XXX Warn if (supplied_flags & PyCF_MASK_OBSOLETE) != 0? */
Tim Peters6cd6a822001-08-17 22:11:27 +0000623
Georg Brandl8334fd92010-12-04 10:26:46 +0000624 if (optimize < -1 || optimize > 2) {
625 PyErr_SetString(PyExc_ValueError,
626 "compile(): invalid optimize value");
627 goto error;
628 }
629
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000630 if (!dont_inherit) {
631 PyEval_MergeCompilerFlags(&cf);
632 }
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000633
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000634 if (strcmp(startstr, "exec") == 0)
635 mode = 0;
636 else if (strcmp(startstr, "eval") == 0)
637 mode = 1;
638 else if (strcmp(startstr, "single") == 0)
639 mode = 2;
640 else {
641 PyErr_SetString(PyExc_ValueError,
642 "compile() arg 3 must be 'exec', 'eval' or 'single'");
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000643 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000644 }
Neal Norwitzdb4115f2008-03-31 04:20:05 +0000645
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000646 is_ast = PyAST_Check(cmd);
647 if (is_ast == -1)
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000648 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000649 if (is_ast) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000650 if (supplied_flags & PyCF_ONLY_AST) {
651 Py_INCREF(cmd);
652 result = cmd;
653 }
654 else {
655 PyArena *arena;
656 mod_ty mod;
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000657
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000658 arena = PyArena_New();
Stefan Krah07795df2012-08-20 17:19:50 +0200659 if (arena == NULL)
660 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000661 mod = PyAST_obj2mod(cmd, arena, mode);
662 if (mod == NULL) {
663 PyArena_Free(arena);
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000664 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000665 }
Benjamin Peterson832bfe22011-08-09 16:15:04 -0500666 if (!PyAST_Validate(mod)) {
667 PyArena_Free(arena);
668 goto error;
669 }
Victor Stinner14e461d2013-08-26 22:28:21 +0200670 result = (PyObject*)PyAST_CompileObject(mod, filename,
671 &cf, optimize, arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000672 PyArena_Free(arena);
673 }
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000674 goto finally;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000675 }
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000676
Philip Jenveyf76f0ee2012-12-13 15:44:18 -0800677 str = source_as_string(cmd, "compile", "string, bytes or AST", &cf);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000678 if (str == NULL)
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000679 goto error;
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000680
Victor Stinner14e461d2013-08-26 22:28:21 +0200681 result = Py_CompileStringObject(str, filename, start[mode], &cf, optimize);
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000682 goto finally;
683
684error:
685 result = NULL;
686finally:
Victor Stinner14e461d2013-08-26 22:28:21 +0200687 Py_DECREF(filename);
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000688 return result;
Guido van Rossum5b722181993-03-30 17:46:03 +0000689}
690
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000691PyDoc_STRVAR(compile_doc,
Tim Peters6cd6a822001-08-17 22:11:27 +0000692"compile(source, filename, mode[, flags[, dont_inherit]]) -> code object\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000693\n\
694Compile the source string (a Python module, statement or expression)\n\
Georg Brandl7cae87c2006-09-06 06:51:57 +0000695into a code object that can be executed by exec() or eval().\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000696The filename will be used for run-time error messages.\n\
697The mode must be 'exec' to compile a module, 'single' to compile a\n\
Tim Peters6cd6a822001-08-17 22:11:27 +0000698single (interactive) statement, or 'eval' to compile an expression.\n\
699The flags argument, if present, controls which future statements influence\n\
700the compilation of the code.\n\
701The dont_inherit argument, if non-zero, stops the compilation inheriting\n\
702the effects of any future statements in effect in the code calling\n\
703compile; if absent or zero these statements do influence the compilation,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000704in addition to any features explicitly specified.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000705
Guido van Rossum79f25d91997-04-29 20:08:16 +0000706static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000707builtin_dir(PyObject *self, PyObject *args)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000708{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000709 PyObject *arg = NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000710
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000711 if (!PyArg_UnpackTuple(args, "dir", 0, 1, &arg))
712 return NULL;
713 return PyObject_Dir(arg);
Guido van Rossum3f5da241990-12-20 15:06:42 +0000714}
715
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000716PyDoc_STRVAR(dir_doc,
Tim Peters5d2b77c2001-09-03 05:47:38 +0000717"dir([object]) -> list of strings\n"
718"\n"
Georg Brandle32b4222007-03-10 22:13:27 +0000719"If called without an argument, return the names in the current scope.\n"
720"Else, return an alphabetized list of names comprising (some of) the attributes\n"
721"of the given object, and of attributes reachable from it.\n"
722"If the object supplies a method named __dir__, it will be used; otherwise\n"
723"the default dir() logic is used and returns:\n"
724" for a module object: the module's attributes.\n"
725" for a class object: its attributes, and recursively the attributes\n"
726" of its bases.\n"
Guido van Rossumd8faa362007-04-27 19:54:29 +0000727" for any other object: its attributes, its class's attributes, and\n"
Georg Brandle32b4222007-03-10 22:13:27 +0000728" recursively the attributes of its class's base classes.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000729
Guido van Rossum79f25d91997-04-29 20:08:16 +0000730static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000731builtin_divmod(PyObject *self, PyObject *args)
Guido van Rossum6a00cd81995-01-07 12:39:01 +0000732{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000733 PyObject *v, *w;
Guido van Rossum6a00cd81995-01-07 12:39:01 +0000734
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000735 if (!PyArg_UnpackTuple(args, "divmod", 2, 2, &v, &w))
736 return NULL;
737 return PyNumber_Divmod(v, w);
Guido van Rossum3f5da241990-12-20 15:06:42 +0000738}
739
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000740PyDoc_STRVAR(divmod_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000741"divmod(x, y) -> (div, mod)\n\
742\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000743Return the tuple ((x-x%y)/y, x%y). Invariant: div*y + mod == x.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000744
745
Guido van Rossum79f25d91997-04-29 20:08:16 +0000746static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000747builtin_eval(PyObject *self, PyObject *args)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000748{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000749 PyObject *cmd, *result, *tmp = NULL;
750 PyObject *globals = Py_None, *locals = Py_None;
751 char *str;
752 PyCompilerFlags cf;
Guido van Rossum590baa41993-11-30 13:40:46 +0000753
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000754 if (!PyArg_UnpackTuple(args, "eval", 1, 3, &cmd, &globals, &locals))
755 return NULL;
756 if (locals != Py_None && !PyMapping_Check(locals)) {
757 PyErr_SetString(PyExc_TypeError, "locals must be a mapping");
758 return NULL;
759 }
760 if (globals != Py_None && !PyDict_Check(globals)) {
761 PyErr_SetString(PyExc_TypeError, PyMapping_Check(globals) ?
762 "globals must be a real dict; try eval(expr, {}, mapping)"
763 : "globals must be a dict");
764 return NULL;
765 }
766 if (globals == Py_None) {
767 globals = PyEval_GetGlobals();
Victor Stinner41bb43a2013-10-29 01:19:37 +0100768 if (locals == Py_None) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000769 locals = PyEval_GetLocals();
Victor Stinner41bb43a2013-10-29 01:19:37 +0100770 if (locals == NULL)
771 return NULL;
772 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000773 }
774 else if (locals == Py_None)
775 locals = globals;
Tim Peters9fa96be2001-08-17 23:04:59 +0000776
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000777 if (globals == NULL || locals == NULL) {
778 PyErr_SetString(PyExc_TypeError,
779 "eval must be given globals and locals "
780 "when called without a frame");
781 return NULL;
782 }
Georg Brandl77c85e62005-09-15 10:46:13 +0000783
Victor Stinnerb44562b2013-11-06 19:03:11 +0100784 if (_PyDict_GetItemId(globals, &PyId___builtins__) == NULL) {
785 if (_PyDict_SetItemId(globals, &PyId___builtins__,
786 PyEval_GetBuiltins()) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000787 return NULL;
788 }
Tim Peters9fa96be2001-08-17 23:04:59 +0000789
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000790 if (PyCode_Check(cmd)) {
791 if (PyCode_GetNumFree((PyCodeObject *)cmd) > 0) {
792 PyErr_SetString(PyExc_TypeError,
793 "code object passed to eval() may not contain free variables");
794 return NULL;
795 }
Martin v. Löwis4d0d4712010-12-03 20:14:31 +0000796 return PyEval_EvalCode(cmd, globals, locals);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000797 }
Tim Peters9fa96be2001-08-17 23:04:59 +0000798
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000799 cf.cf_flags = PyCF_SOURCE_IS_UTF8;
800 str = source_as_string(cmd, "eval", "string, bytes or code", &cf);
801 if (str == NULL)
802 return NULL;
Just van Rossum3aaf42c2003-02-10 08:21:10 +0000803
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000804 while (*str == ' ' || *str == '\t')
805 str++;
Tim Peters9fa96be2001-08-17 23:04:59 +0000806
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000807 (void)PyEval_MergeCompilerFlags(&cf);
808 result = PyRun_StringFlags(str, Py_eval_input, globals, locals, &cf);
809 Py_XDECREF(tmp);
810 return result;
Guido van Rossum3f5da241990-12-20 15:06:42 +0000811}
812
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000813PyDoc_STRVAR(eval_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000814"eval(source[, globals[, locals]]) -> value\n\
815\n\
816Evaluate the source in the context of globals and locals.\n\
817The source may be a string representing a Python expression\n\
818or a code object as returned by compile().\n\
Thomas Wouters89f507f2006-12-13 04:49:30 +0000819The globals must be a dictionary and locals can be any mapping,\n\
Raymond Hettinger214b1c32004-07-02 06:41:07 +0000820defaulting to the current globals and locals.\n\
821If only globals is given, locals defaults to it.\n");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000822
Georg Brandl7cae87c2006-09-06 06:51:57 +0000823static PyObject *
824builtin_exec(PyObject *self, PyObject *args)
825{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000826 PyObject *v;
827 PyObject *prog, *globals = Py_None, *locals = Py_None;
Georg Brandl7cae87c2006-09-06 06:51:57 +0000828
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000829 if (!PyArg_UnpackTuple(args, "exec", 1, 3, &prog, &globals, &locals))
830 return NULL;
Georg Brandl2cabc562008-08-28 07:57:16 +0000831
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000832 if (globals == Py_None) {
833 globals = PyEval_GetGlobals();
834 if (locals == Py_None) {
835 locals = PyEval_GetLocals();
Victor Stinner41bb43a2013-10-29 01:19:37 +0100836 if (locals == NULL)
837 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000838 }
839 if (!globals || !locals) {
840 PyErr_SetString(PyExc_SystemError,
841 "globals and locals cannot be NULL");
842 return NULL;
843 }
844 }
845 else if (locals == Py_None)
846 locals = globals;
Georg Brandl7cae87c2006-09-06 06:51:57 +0000847
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000848 if (!PyDict_Check(globals)) {
849 PyErr_Format(PyExc_TypeError, "exec() arg 2 must be a dict, not %.100s",
850 globals->ob_type->tp_name);
851 return NULL;
852 }
853 if (!PyMapping_Check(locals)) {
854 PyErr_Format(PyExc_TypeError,
855 "arg 3 must be a mapping or None, not %.100s",
856 locals->ob_type->tp_name);
857 return NULL;
858 }
Victor Stinnerb44562b2013-11-06 19:03:11 +0100859 if (_PyDict_GetItemId(globals, &PyId___builtins__) == NULL) {
860 if (_PyDict_SetItemId(globals, &PyId___builtins__,
861 PyEval_GetBuiltins()) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000862 return NULL;
863 }
864
865 if (PyCode_Check(prog)) {
866 if (PyCode_GetNumFree((PyCodeObject *)prog) > 0) {
867 PyErr_SetString(PyExc_TypeError,
868 "code object passed to exec() may not "
869 "contain free variables");
870 return NULL;
871 }
Martin v. Löwis4d0d4712010-12-03 20:14:31 +0000872 v = PyEval_EvalCode(prog, globals, locals);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000873 }
874 else {
875 char *str;
876 PyCompilerFlags cf;
877 cf.cf_flags = PyCF_SOURCE_IS_UTF8;
878 str = source_as_string(prog, "exec",
879 "string, bytes or code", &cf);
880 if (str == NULL)
881 return NULL;
882 if (PyEval_MergeCompilerFlags(&cf))
883 v = PyRun_StringFlags(str, Py_file_input, globals,
884 locals, &cf);
885 else
886 v = PyRun_String(str, Py_file_input, globals, locals);
887 }
888 if (v == NULL)
889 return NULL;
890 Py_DECREF(v);
891 Py_RETURN_NONE;
Georg Brandl7cae87c2006-09-06 06:51:57 +0000892}
893
894PyDoc_STRVAR(exec_doc,
895"exec(object[, globals[, locals]])\n\
896\n\
Mark Dickinson480e8e32009-12-19 21:19:35 +0000897Read and execute code from an object, which can be a string or a code\n\
Benjamin Peterson38090262009-01-04 15:30:39 +0000898object.\n\
Georg Brandl7cae87c2006-09-06 06:51:57 +0000899The globals and locals are dictionaries, defaulting to the current\n\
900globals and locals. If only globals is given, locals defaults to it.");
901
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000902
Guido van Rossum79f25d91997-04-29 20:08:16 +0000903static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000904builtin_getattr(PyObject *self, PyObject *args)
Guido van Rossum33894be1992-01-27 16:53:09 +0000905{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000906 PyObject *v, *result, *dflt = NULL;
907 PyObject *name;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000908
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000909 if (!PyArg_UnpackTuple(args, "getattr", 2, 3, &v, &name, &dflt))
910 return NULL;
Martin v. Löwis5b222132007-06-10 09:51:05 +0000911
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000912 if (!PyUnicode_Check(name)) {
913 PyErr_SetString(PyExc_TypeError,
914 "getattr(): attribute name must be string");
915 return NULL;
916 }
917 result = PyObject_GetAttr(v, name);
918 if (result == NULL && dflt != NULL &&
919 PyErr_ExceptionMatches(PyExc_AttributeError))
920 {
921 PyErr_Clear();
922 Py_INCREF(dflt);
923 result = dflt;
924 }
925 return result;
Guido van Rossum9bfef441993-03-29 10:43:31 +0000926}
927
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000928PyDoc_STRVAR(getattr_doc,
Guido van Rossum950ff291998-06-29 13:38:57 +0000929"getattr(object, name[, default]) -> value\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000930\n\
Guido van Rossum950ff291998-06-29 13:38:57 +0000931Get a named attribute from an object; getattr(x, 'y') is equivalent to x.y.\n\
932When a default argument is given, it is returned when the attribute doesn't\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000933exist; without it, an exception is raised in that case.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000934
935
Guido van Rossum79f25d91997-04-29 20:08:16 +0000936static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000937builtin_globals(PyObject *self)
Guido van Rossum872537c1995-07-07 22:43:42 +0000938{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000939 PyObject *d;
Guido van Rossum872537c1995-07-07 22:43:42 +0000940
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000941 d = PyEval_GetGlobals();
942 Py_XINCREF(d);
943 return d;
Guido van Rossum872537c1995-07-07 22:43:42 +0000944}
945
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000946PyDoc_STRVAR(globals_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000947"globals() -> dictionary\n\
948\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000949Return the dictionary containing the current scope's global variables.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000950
951
Guido van Rossum79f25d91997-04-29 20:08:16 +0000952static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000953builtin_hasattr(PyObject *self, PyObject *args)
Guido van Rossum9bfef441993-03-29 10:43:31 +0000954{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000955 PyObject *v;
956 PyObject *name;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000957
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000958 if (!PyArg_UnpackTuple(args, "hasattr", 2, 2, &v, &name))
959 return NULL;
960 if (!PyUnicode_Check(name)) {
961 PyErr_SetString(PyExc_TypeError,
962 "hasattr(): attribute name must be string");
963 return NULL;
964 }
965 v = PyObject_GetAttr(v, name);
966 if (v == NULL) {
Benjamin Peterson17689992010-08-24 03:26:23 +0000967 if (PyErr_ExceptionMatches(PyExc_AttributeError)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000968 PyErr_Clear();
Benjamin Peterson17689992010-08-24 03:26:23 +0000969 Py_RETURN_FALSE;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000970 }
Benjamin Peterson17689992010-08-24 03:26:23 +0000971 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000972 }
973 Py_DECREF(v);
Benjamin Peterson17689992010-08-24 03:26:23 +0000974 Py_RETURN_TRUE;
Guido van Rossum33894be1992-01-27 16:53:09 +0000975}
976
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000977PyDoc_STRVAR(hasattr_doc,
Guido van Rossum77f6a652002-04-03 22:41:51 +0000978"hasattr(object, name) -> bool\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000979\n\
980Return whether the object has an attribute with the given name.\n\
Benjamin Peterson17689992010-08-24 03:26:23 +0000981(This is done by calling getattr(object, name) and catching AttributeError.)");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000982
983
Guido van Rossum79f25d91997-04-29 20:08:16 +0000984static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000985builtin_id(PyObject *self, PyObject *v)
Guido van Rossum5b722181993-03-30 17:46:03 +0000986{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000987 return PyLong_FromVoidPtr(v);
Guido van Rossum5b722181993-03-30 17:46:03 +0000988}
989
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000990PyDoc_STRVAR(id_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000991"id(object) -> integer\n\
992\n\
993Return the identity of an object. This is guaranteed to be unique among\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000994simultaneously existing objects. (Hint: it's the object's memory address.)");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000995
996
Raymond Hettingera6c60372008-03-13 01:26:19 +0000997/* map object ************************************************************/
998
999typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001000 PyObject_HEAD
1001 PyObject *iters;
1002 PyObject *func;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001003} mapobject;
1004
Guido van Rossum79f25d91997-04-29 20:08:16 +00001005static PyObject *
Raymond Hettingera6c60372008-03-13 01:26:19 +00001006map_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
Guido van Rossum12d12c51993-10-26 17:58:25 +00001007{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001008 PyObject *it, *iters, *func;
1009 mapobject *lz;
1010 Py_ssize_t numargs, i;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001011
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001012 if (type == &PyMap_Type && !_PyArg_NoKeywords("map()", kwds))
1013 return NULL;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001014
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001015 numargs = PyTuple_Size(args);
1016 if (numargs < 2) {
1017 PyErr_SetString(PyExc_TypeError,
1018 "map() must have at least two arguments.");
1019 return NULL;
1020 }
Raymond Hettingera6c60372008-03-13 01:26:19 +00001021
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001022 iters = PyTuple_New(numargs-1);
1023 if (iters == NULL)
1024 return NULL;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001025
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001026 for (i=1 ; i<numargs ; i++) {
1027 /* Get iterator. */
1028 it = PyObject_GetIter(PyTuple_GET_ITEM(args, i));
1029 if (it == NULL) {
1030 Py_DECREF(iters);
1031 return NULL;
1032 }
1033 PyTuple_SET_ITEM(iters, i-1, it);
1034 }
Raymond Hettingera6c60372008-03-13 01:26:19 +00001035
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001036 /* create mapobject structure */
1037 lz = (mapobject *)type->tp_alloc(type, 0);
1038 if (lz == NULL) {
1039 Py_DECREF(iters);
1040 return NULL;
1041 }
1042 lz->iters = iters;
1043 func = PyTuple_GET_ITEM(args, 0);
1044 Py_INCREF(func);
1045 lz->func = func;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001046
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001047 return (PyObject *)lz;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001048}
1049
1050static void
1051map_dealloc(mapobject *lz)
1052{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001053 PyObject_GC_UnTrack(lz);
1054 Py_XDECREF(lz->iters);
1055 Py_XDECREF(lz->func);
1056 Py_TYPE(lz)->tp_free(lz);
Raymond Hettingera6c60372008-03-13 01:26:19 +00001057}
1058
1059static int
1060map_traverse(mapobject *lz, visitproc visit, void *arg)
1061{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001062 Py_VISIT(lz->iters);
1063 Py_VISIT(lz->func);
1064 return 0;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001065}
1066
1067static PyObject *
1068map_next(mapobject *lz)
1069{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001070 PyObject *val;
1071 PyObject *argtuple;
1072 PyObject *result;
1073 Py_ssize_t numargs, i;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001074
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001075 numargs = PyTuple_Size(lz->iters);
1076 argtuple = PyTuple_New(numargs);
1077 if (argtuple == NULL)
1078 return NULL;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001079
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001080 for (i=0 ; i<numargs ; i++) {
1081 val = PyIter_Next(PyTuple_GET_ITEM(lz->iters, i));
1082 if (val == NULL) {
1083 Py_DECREF(argtuple);
1084 return NULL;
1085 }
1086 PyTuple_SET_ITEM(argtuple, i, val);
1087 }
1088 result = PyObject_Call(lz->func, argtuple, NULL);
1089 Py_DECREF(argtuple);
1090 return result;
Guido van Rossum12d12c51993-10-26 17:58:25 +00001091}
1092
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001093static PyObject *
1094map_reduce(mapobject *lz)
1095{
1096 Py_ssize_t numargs = PyTuple_GET_SIZE(lz->iters);
1097 PyObject *args = PyTuple_New(numargs+1);
1098 Py_ssize_t i;
1099 if (args == NULL)
1100 return NULL;
1101 Py_INCREF(lz->func);
1102 PyTuple_SET_ITEM(args, 0, lz->func);
1103 for (i = 0; i<numargs; i++){
1104 PyObject *it = PyTuple_GET_ITEM(lz->iters, i);
1105 Py_INCREF(it);
1106 PyTuple_SET_ITEM(args, i+1, it);
1107 }
1108
1109 return Py_BuildValue("ON", Py_TYPE(lz), args);
1110}
1111
1112static PyMethodDef map_methods[] = {
1113 {"__reduce__", (PyCFunction)map_reduce, METH_NOARGS, reduce_doc},
1114 {NULL, NULL} /* sentinel */
1115};
1116
1117
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001118PyDoc_STRVAR(map_doc,
Raymond Hettingera6c60372008-03-13 01:26:19 +00001119"map(func, *iterables) --> map object\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001120\n\
Raymond Hettingera6c60372008-03-13 01:26:19 +00001121Make an iterator that computes the function using arguments from\n\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001122each of the iterables. Stops when the shortest iterable is exhausted.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001123
Raymond Hettingera6c60372008-03-13 01:26:19 +00001124PyTypeObject PyMap_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001125 PyVarObject_HEAD_INIT(&PyType_Type, 0)
1126 "map", /* tp_name */
1127 sizeof(mapobject), /* tp_basicsize */
1128 0, /* tp_itemsize */
1129 /* methods */
1130 (destructor)map_dealloc, /* tp_dealloc */
1131 0, /* tp_print */
1132 0, /* tp_getattr */
1133 0, /* tp_setattr */
1134 0, /* tp_reserved */
1135 0, /* tp_repr */
1136 0, /* tp_as_number */
1137 0, /* tp_as_sequence */
1138 0, /* tp_as_mapping */
1139 0, /* tp_hash */
1140 0, /* tp_call */
1141 0, /* tp_str */
1142 PyObject_GenericGetAttr, /* tp_getattro */
1143 0, /* tp_setattro */
1144 0, /* tp_as_buffer */
1145 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
1146 Py_TPFLAGS_BASETYPE, /* tp_flags */
1147 map_doc, /* tp_doc */
1148 (traverseproc)map_traverse, /* tp_traverse */
1149 0, /* tp_clear */
1150 0, /* tp_richcompare */
1151 0, /* tp_weaklistoffset */
1152 PyObject_SelfIter, /* tp_iter */
1153 (iternextfunc)map_next, /* tp_iternext */
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001154 map_methods, /* tp_methods */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001155 0, /* tp_members */
1156 0, /* tp_getset */
1157 0, /* tp_base */
1158 0, /* tp_dict */
1159 0, /* tp_descr_get */
1160 0, /* tp_descr_set */
1161 0, /* tp_dictoffset */
1162 0, /* tp_init */
1163 PyType_GenericAlloc, /* tp_alloc */
1164 map_new, /* tp_new */
1165 PyObject_GC_Del, /* tp_free */
Raymond Hettingera6c60372008-03-13 01:26:19 +00001166};
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001167
Guido van Rossum79f25d91997-04-29 20:08:16 +00001168static PyObject *
Georg Brandla18af4e2007-04-21 15:47:16 +00001169builtin_next(PyObject *self, PyObject *args)
1170{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001171 PyObject *it, *res;
1172 PyObject *def = NULL;
Georg Brandla18af4e2007-04-21 15:47:16 +00001173
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001174 if (!PyArg_UnpackTuple(args, "next", 1, 2, &it, &def))
1175 return NULL;
1176 if (!PyIter_Check(it)) {
1177 PyErr_Format(PyExc_TypeError,
Philip Jenvey50add042011-11-06 16:37:52 -08001178 "'%.200s' object is not an iterator",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001179 it->ob_type->tp_name);
1180 return NULL;
1181 }
1182
1183 res = (*it->ob_type->tp_iternext)(it);
1184 if (res != NULL) {
1185 return res;
1186 } else if (def != NULL) {
1187 if (PyErr_Occurred()) {
1188 if(!PyErr_ExceptionMatches(PyExc_StopIteration))
1189 return NULL;
1190 PyErr_Clear();
1191 }
1192 Py_INCREF(def);
1193 return def;
1194 } else if (PyErr_Occurred()) {
1195 return NULL;
1196 } else {
1197 PyErr_SetNone(PyExc_StopIteration);
1198 return NULL;
1199 }
Georg Brandla18af4e2007-04-21 15:47:16 +00001200}
1201
1202PyDoc_STRVAR(next_doc,
1203"next(iterator[, default])\n\
1204\n\
1205Return the next item from the iterator. If default is given and the iterator\n\
1206is exhausted, it is returned instead of raising StopIteration.");
1207
1208
1209static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001210builtin_setattr(PyObject *self, PyObject *args)
Guido van Rossum33894be1992-01-27 16:53:09 +00001211{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001212 PyObject *v;
1213 PyObject *name;
1214 PyObject *value;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001215
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001216 if (!PyArg_UnpackTuple(args, "setattr", 3, 3, &v, &name, &value))
1217 return NULL;
1218 if (PyObject_SetAttr(v, name, value) != 0)
1219 return NULL;
1220 Py_INCREF(Py_None);
1221 return Py_None;
Guido van Rossum33894be1992-01-27 16:53:09 +00001222}
1223
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001224PyDoc_STRVAR(setattr_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001225"setattr(object, name, value)\n\
1226\n\
1227Set a named attribute on an object; setattr(x, 'y', v) is equivalent to\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001228``x.y = v''.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001229
1230
Guido van Rossum79f25d91997-04-29 20:08:16 +00001231static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001232builtin_delattr(PyObject *self, PyObject *args)
Guido van Rossum14144fc1994-08-29 12:53:40 +00001233{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001234 PyObject *v;
1235 PyObject *name;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001236
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001237 if (!PyArg_UnpackTuple(args, "delattr", 2, 2, &v, &name))
1238 return NULL;
1239 if (PyObject_SetAttr(v, name, (PyObject *)NULL) != 0)
1240 return NULL;
1241 Py_INCREF(Py_None);
1242 return Py_None;
Guido van Rossum14144fc1994-08-29 12:53:40 +00001243}
1244
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001245PyDoc_STRVAR(delattr_doc,
Guido van Rossumdf12a591998-11-23 22:13:04 +00001246"delattr(object, name)\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001247\n\
1248Delete a named attribute on an object; delattr(x, 'y') is equivalent to\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001249``del x.y''.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001250
1251
Guido van Rossum79f25d91997-04-29 20:08:16 +00001252static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001253builtin_hash(PyObject *self, PyObject *v)
Guido van Rossum9bfef441993-03-29 10:43:31 +00001254{
Benjamin Peterson8f67d082010-10-17 20:54:53 +00001255 Py_hash_t x;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001256
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001257 x = PyObject_Hash(v);
1258 if (x == -1)
1259 return NULL;
Benjamin Peterson8f67d082010-10-17 20:54:53 +00001260 return PyLong_FromSsize_t(x);
Guido van Rossum9bfef441993-03-29 10:43:31 +00001261}
1262
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001263PyDoc_STRVAR(hash_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001264"hash(object) -> integer\n\
1265\n\
1266Return a hash value for the object. Two objects with the same value have\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001267the same hash value. The reverse is not necessarily true, but likely.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001268
1269
Guido van Rossum79f25d91997-04-29 20:08:16 +00001270static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001271builtin_hex(PyObject *self, PyObject *v)
Guido van Rossum006bcd41991-10-24 14:54:44 +00001272{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001273 return PyNumber_ToBase(v, 16);
Guido van Rossum006bcd41991-10-24 14:54:44 +00001274}
1275
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001276PyDoc_STRVAR(hex_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001277"hex(number) -> string\n\
1278\n\
Alexander Belopolsky12338ab2011-04-07 00:15:33 -04001279Return the hexadecimal representation of an integer.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001280
1281
Guido van Rossum79f25d91997-04-29 20:08:16 +00001282static PyObject *
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001283builtin_iter(PyObject *self, PyObject *args)
1284{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001285 PyObject *v, *w = NULL;
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001286
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001287 if (!PyArg_UnpackTuple(args, "iter", 1, 2, &v, &w))
1288 return NULL;
1289 if (w == NULL)
1290 return PyObject_GetIter(v);
1291 if (!PyCallable_Check(v)) {
1292 PyErr_SetString(PyExc_TypeError,
1293 "iter(v, w): v must be callable");
1294 return NULL;
1295 }
1296 return PyCallIter_New(v, w);
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001297}
1298
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001299PyDoc_STRVAR(iter_doc,
Georg Brandld11ae5d2008-05-16 13:27:32 +00001300"iter(iterable) -> iterator\n\
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001301iter(callable, sentinel) -> iterator\n\
1302\n\
1303Get an iterator from an object. In the first form, the argument must\n\
1304supply its own iterator, or be a sequence.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001305In the second form, the callable is called until it returns the sentinel.");
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001306
1307
1308static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001309builtin_len(PyObject *self, PyObject *v)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001310{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001311 Py_ssize_t res;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001312
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001313 res = PyObject_Size(v);
1314 if (res < 0 && PyErr_Occurred())
1315 return NULL;
1316 return PyLong_FromSsize_t(res);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001317}
1318
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001319PyDoc_STRVAR(len_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001320"len(object) -> integer\n\
1321\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001322Return the number of items of a sequence or mapping.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001323
1324
Guido van Rossum79f25d91997-04-29 20:08:16 +00001325static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001326builtin_locals(PyObject *self)
Guido van Rossum872537c1995-07-07 22:43:42 +00001327{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001328 PyObject *d;
Guido van Rossum872537c1995-07-07 22:43:42 +00001329
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001330 d = PyEval_GetLocals();
1331 Py_XINCREF(d);
1332 return d;
Guido van Rossum872537c1995-07-07 22:43:42 +00001333}
1334
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001335PyDoc_STRVAR(locals_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001336"locals() -> dictionary\n\
1337\n\
Raymond Hettinger69bf8f32003-01-04 02:16:22 +00001338Update and return a dictionary containing the current scope's local variables.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001339
1340
Guido van Rossum79f25d91997-04-29 20:08:16 +00001341static PyObject *
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001342min_max(PyObject *args, PyObject *kwds, int op)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001343{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001344 PyObject *v, *it, *item, *val, *maxitem, *maxval, *keyfunc=NULL;
Raymond Hettinger4d6018f2013-06-24 22:43:02 -07001345 PyObject *emptytuple, *defaultval = NULL;
1346 static char *kwlist[] = {"key", "default", NULL};
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001347 const char *name = op == Py_LT ? "min" : "max";
Raymond Hettinger4d6018f2013-06-24 22:43:02 -07001348 const int positional = PyTuple_Size(args) > 1;
1349 int ret;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001350
Raymond Hettinger4d6018f2013-06-24 22:43:02 -07001351 if (positional)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001352 v = args;
Serhiy Storchakac6792272013-10-19 21:03:34 +03001353 else if (!PyArg_UnpackTuple(args, name, 1, 1, &v))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001354 return NULL;
Tim Peters67d687a2002-04-29 21:27:32 +00001355
Raymond Hettinger4d6018f2013-06-24 22:43:02 -07001356 emptytuple = PyTuple_New(0);
1357 if (emptytuple == NULL)
1358 return NULL;
1359 ret = PyArg_ParseTupleAndKeywords(emptytuple, kwds, "|$OO", kwlist,
1360 &keyfunc, &defaultval);
1361 Py_DECREF(emptytuple);
1362 if (!ret)
1363 return NULL;
1364
1365 if (positional && defaultval != NULL) {
1366 PyErr_Format(PyExc_TypeError,
1367 "Cannot specify a default for %s() with multiple "
1368 "positional arguments", name);
1369 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001370 }
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001371
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001372 it = PyObject_GetIter(v);
1373 if (it == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001374 return NULL;
1375 }
Tim Petersc3074532001-05-03 07:00:32 +00001376
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001377 maxitem = NULL; /* the result */
1378 maxval = NULL; /* the value associated with the result */
1379 while (( item = PyIter_Next(it) )) {
1380 /* get the value from the key function */
1381 if (keyfunc != NULL) {
1382 val = PyObject_CallFunctionObjArgs(keyfunc, item, NULL);
1383 if (val == NULL)
1384 goto Fail_it_item;
1385 }
1386 /* no key function; the value is the item */
1387 else {
1388 val = item;
1389 Py_INCREF(val);
1390 }
Tim Petersc3074532001-05-03 07:00:32 +00001391
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001392 /* maximum value and item are unset; set them */
1393 if (maxval == NULL) {
1394 maxitem = item;
1395 maxval = val;
1396 }
1397 /* maximum value and item are set; update them as necessary */
1398 else {
1399 int cmp = PyObject_RichCompareBool(val, maxval, op);
1400 if (cmp < 0)
1401 goto Fail_it_item_and_val;
1402 else if (cmp > 0) {
1403 Py_DECREF(maxval);
1404 Py_DECREF(maxitem);
1405 maxval = val;
1406 maxitem = item;
1407 }
1408 else {
1409 Py_DECREF(item);
1410 Py_DECREF(val);
1411 }
1412 }
1413 }
1414 if (PyErr_Occurred())
1415 goto Fail_it;
1416 if (maxval == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001417 assert(maxitem == NULL);
Raymond Hettinger4d6018f2013-06-24 22:43:02 -07001418 if (defaultval != NULL) {
1419 Py_INCREF(defaultval);
1420 maxitem = defaultval;
1421 } else {
1422 PyErr_Format(PyExc_ValueError,
1423 "%s() arg is an empty sequence", name);
1424 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001425 }
1426 else
1427 Py_DECREF(maxval);
1428 Py_DECREF(it);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001429 return maxitem;
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001430
1431Fail_it_item_and_val:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001432 Py_DECREF(val);
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001433Fail_it_item:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001434 Py_DECREF(item);
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001435Fail_it:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001436 Py_XDECREF(maxval);
1437 Py_XDECREF(maxitem);
1438 Py_DECREF(it);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001439 return NULL;
Guido van Rossum3f5da241990-12-20 15:06:42 +00001440}
1441
Guido van Rossum79f25d91997-04-29 20:08:16 +00001442static PyObject *
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001443builtin_min(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001444{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001445 return min_max(args, kwds, Py_LT);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001446}
1447
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001448PyDoc_STRVAR(min_doc,
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001449"min(iterable[, key=func]) -> value\n\
1450min(a, b, c, ...[, key=func]) -> value\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001451\n\
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001452With a single iterable argument, return its smallest item.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001453With two or more arguments, return the smallest argument.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001454
1455
Guido van Rossum79f25d91997-04-29 20:08:16 +00001456static PyObject *
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001457builtin_max(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001458{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001459 return min_max(args, kwds, Py_GT);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001460}
1461
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001462PyDoc_STRVAR(max_doc,
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001463"max(iterable[, key=func]) -> value\n\
1464max(a, b, c, ...[, key=func]) -> value\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001465\n\
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001466With a single iterable argument, return its largest item.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001467With two or more arguments, return the largest argument.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001468
1469
Guido van Rossum79f25d91997-04-29 20:08:16 +00001470static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001471builtin_oct(PyObject *self, PyObject *v)
Guido van Rossum006bcd41991-10-24 14:54:44 +00001472{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001473 return PyNumber_ToBase(v, 8);
Guido van Rossum006bcd41991-10-24 14:54:44 +00001474}
1475
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001476PyDoc_STRVAR(oct_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001477"oct(number) -> string\n\
1478\n\
Alexander Belopolsky12338ab2011-04-07 00:15:33 -04001479Return the octal representation of an integer.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001480
1481
Guido van Rossum79f25d91997-04-29 20:08:16 +00001482static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001483builtin_ord(PyObject *self, PyObject* obj)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001484{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001485 long ord;
1486 Py_ssize_t size;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001487
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001488 if (PyBytes_Check(obj)) {
1489 size = PyBytes_GET_SIZE(obj);
1490 if (size == 1) {
1491 ord = (long)((unsigned char)*PyBytes_AS_STRING(obj));
1492 return PyLong_FromLong(ord);
1493 }
1494 }
1495 else if (PyUnicode_Check(obj)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001496 if (PyUnicode_READY(obj) == -1)
1497 return NULL;
1498 size = PyUnicode_GET_LENGTH(obj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001499 if (size == 1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001500 ord = (long)PyUnicode_READ_CHAR(obj, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001501 return PyLong_FromLong(ord);
1502 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001503 }
1504 else if (PyByteArray_Check(obj)) {
1505 /* XXX Hopefully this is temporary */
1506 size = PyByteArray_GET_SIZE(obj);
1507 if (size == 1) {
1508 ord = (long)((unsigned char)*PyByteArray_AS_STRING(obj));
1509 return PyLong_FromLong(ord);
1510 }
1511 }
1512 else {
1513 PyErr_Format(PyExc_TypeError,
1514 "ord() expected string of length 1, but " \
1515 "%.200s found", obj->ob_type->tp_name);
1516 return NULL;
1517 }
Guido van Rossum09095f32000-03-10 23:00:52 +00001518
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001519 PyErr_Format(PyExc_TypeError,
1520 "ord() expected a character, "
1521 "but string of length %zd found",
1522 size);
1523 return NULL;
Guido van Rossum3f5da241990-12-20 15:06:42 +00001524}
1525
Guido van Rossum307fa8c2007-07-16 20:46:27 +00001526PyDoc_VAR(ord_doc) = PyDoc_STR(
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001527"ord(c) -> integer\n\
1528\n\
Guido van Rossum8ac004e2007-07-15 13:00:05 +00001529Return the integer ordinal of a one-character string."
Antoine Pitrouedc60182012-06-23 14:19:58 +02001530);
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001531
1532
Guido van Rossum79f25d91997-04-29 20:08:16 +00001533static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001534builtin_pow(PyObject *self, PyObject *args)
Guido van Rossum6a00cd81995-01-07 12:39:01 +00001535{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001536 PyObject *v, *w, *z = Py_None;
Guido van Rossum6a00cd81995-01-07 12:39:01 +00001537
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001538 if (!PyArg_UnpackTuple(args, "pow", 2, 3, &v, &w, &z))
1539 return NULL;
1540 return PyNumber_Power(v, w, z);
Guido van Rossumd4905451991-05-05 20:00:36 +00001541}
1542
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001543PyDoc_STRVAR(pow_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001544"pow(x, y[, z]) -> number\n\
1545\n\
1546With two arguments, equivalent to x**y. With three arguments,\n\
Serhiy Storchaka95949422013-08-27 19:40:23 +03001547equivalent to (x**y) % z, but may be more efficient (e.g. for ints).");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001548
1549
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001550
Guido van Rossum34343512006-11-30 22:13:52 +00001551static PyObject *
1552builtin_print(PyObject *self, PyObject *args, PyObject *kwds)
1553{
Georg Brandlbc3b6822012-01-13 19:41:25 +01001554 static char *kwlist[] = {"sep", "end", "file", "flush", 0};
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001555 static PyObject *dummy_args;
Georg Brandlbc3b6822012-01-13 19:41:25 +01001556 PyObject *sep = NULL, *end = NULL, *file = NULL, *flush = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001557 int i, err;
Guido van Rossum34343512006-11-30 22:13:52 +00001558
Benjamin Peterson00102562012-01-11 21:00:16 -05001559 if (dummy_args == NULL && !(dummy_args = PyTuple_New(0)))
Georg Brandlbc3b6822012-01-13 19:41:25 +01001560 return NULL;
1561 if (!PyArg_ParseTupleAndKeywords(dummy_args, kwds, "|OOOO:print",
1562 kwlist, &sep, &end, &file, &flush))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001563 return NULL;
1564 if (file == NULL || file == Py_None) {
Victor Stinnerbd303c12013-11-07 23:07:29 +01001565 file = _PySys_GetObjectId(&PyId_stdout);
Victor Stinner1e53bba2013-07-16 22:26:05 +02001566 if (file == NULL) {
1567 PyErr_SetString(PyExc_RuntimeError, "lost sys.stdout");
1568 return NULL;
1569 }
1570
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001571 /* sys.stdout may be None when FILE* stdout isn't connected */
1572 if (file == Py_None)
1573 Py_RETURN_NONE;
1574 }
Guido van Rossum34343512006-11-30 22:13:52 +00001575
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001576 if (sep == Py_None) {
1577 sep = NULL;
1578 }
1579 else if (sep && !PyUnicode_Check(sep)) {
1580 PyErr_Format(PyExc_TypeError,
1581 "sep must be None or a string, not %.200s",
1582 sep->ob_type->tp_name);
1583 return NULL;
1584 }
1585 if (end == Py_None) {
1586 end = NULL;
1587 }
1588 else if (end && !PyUnicode_Check(end)) {
1589 PyErr_Format(PyExc_TypeError,
1590 "end must be None or a string, not %.200s",
1591 end->ob_type->tp_name);
1592 return NULL;
1593 }
Guido van Rossum34343512006-11-30 22:13:52 +00001594
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001595 for (i = 0; i < PyTuple_Size(args); i++) {
1596 if (i > 0) {
1597 if (sep == NULL)
1598 err = PyFile_WriteString(" ", file);
1599 else
1600 err = PyFile_WriteObject(sep, file,
1601 Py_PRINT_RAW);
1602 if (err)
1603 return NULL;
1604 }
1605 err = PyFile_WriteObject(PyTuple_GetItem(args, i), file,
1606 Py_PRINT_RAW);
1607 if (err)
1608 return NULL;
1609 }
Guido van Rossum34343512006-11-30 22:13:52 +00001610
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001611 if (end == NULL)
1612 err = PyFile_WriteString("\n", file);
1613 else
1614 err = PyFile_WriteObject(end, file, Py_PRINT_RAW);
1615 if (err)
1616 return NULL;
Guido van Rossum34343512006-11-30 22:13:52 +00001617
Georg Brandlbc3b6822012-01-13 19:41:25 +01001618 if (flush != NULL) {
1619 PyObject *tmp;
1620 int do_flush = PyObject_IsTrue(flush);
1621 if (do_flush == -1)
1622 return NULL;
1623 else if (do_flush) {
Victor Stinnereaa28832013-11-07 00:01:51 +01001624 tmp = _PyObject_CallMethodId(file, &PyId_flush, "");
Georg Brandlbc3b6822012-01-13 19:41:25 +01001625 if (tmp == NULL)
1626 return NULL;
1627 else
1628 Py_DECREF(tmp);
1629 }
1630 }
1631
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001632 Py_RETURN_NONE;
Guido van Rossum34343512006-11-30 22:13:52 +00001633}
1634
1635PyDoc_STRVAR(print_doc,
Senthil Kumarane9175bd2012-08-10 13:53:45 -07001636"print(value, ..., sep=' ', end='\\n', file=sys.stdout, flush=False)\n\
Guido van Rossum34343512006-11-30 22:13:52 +00001637\n\
1638Prints the values to a stream, or to sys.stdout by default.\n\
1639Optional keyword arguments:\n\
Senthil Kumarane9175bd2012-08-10 13:53:45 -07001640file: a file-like object (stream); defaults to the current sys.stdout.\n\
1641sep: string inserted between values, default a space.\n\
1642end: string appended after the last value, default a newline.\n\
1643flush: whether to forcibly flush the stream.");
Guido van Rossum34343512006-11-30 22:13:52 +00001644
1645
Guido van Rossuma88a0332007-02-26 16:59:55 +00001646static PyObject *
1647builtin_input(PyObject *self, PyObject *args)
1648{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001649 PyObject *promptarg = NULL;
Victor Stinnerbd303c12013-11-07 23:07:29 +01001650 PyObject *fin = _PySys_GetObjectId(&PyId_stdin);
1651 PyObject *fout = _PySys_GetObjectId(&PyId_stdout);
1652 PyObject *ferr = _PySys_GetObjectId(&PyId_stderr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001653 PyObject *tmp;
1654 long fd;
1655 int tty;
Guido van Rossuma88a0332007-02-26 16:59:55 +00001656
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001657 /* Parse arguments */
1658 if (!PyArg_UnpackTuple(args, "input", 0, 1, &promptarg))
1659 return NULL;
Guido van Rossuma88a0332007-02-26 16:59:55 +00001660
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001661 /* Check that stdin/out/err are intact */
1662 if (fin == NULL || fin == Py_None) {
1663 PyErr_SetString(PyExc_RuntimeError,
1664 "input(): lost sys.stdin");
1665 return NULL;
1666 }
1667 if (fout == NULL || fout == Py_None) {
1668 PyErr_SetString(PyExc_RuntimeError,
1669 "input(): lost sys.stdout");
1670 return NULL;
1671 }
1672 if (ferr == NULL || ferr == Py_None) {
1673 PyErr_SetString(PyExc_RuntimeError,
1674 "input(): lost sys.stderr");
1675 return NULL;
1676 }
Guido van Rossumeba76962007-05-27 09:13:28 +00001677
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001678 /* First of all, flush stderr */
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001679 tmp = _PyObject_CallMethodId(ferr, &PyId_flush, "");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001680 if (tmp == NULL)
1681 PyErr_Clear();
1682 else
1683 Py_DECREF(tmp);
Guido van Rossumeba76962007-05-27 09:13:28 +00001684
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001685 /* We should only use (GNU) readline if Python's sys.stdin and
1686 sys.stdout are the same as C's stdin and stdout, because we
1687 need to pass it those. */
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001688 tmp = _PyObject_CallMethodId(fin, &PyId_fileno, "");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001689 if (tmp == NULL) {
1690 PyErr_Clear();
1691 tty = 0;
1692 }
1693 else {
1694 fd = PyLong_AsLong(tmp);
1695 Py_DECREF(tmp);
1696 if (fd < 0 && PyErr_Occurred())
1697 return NULL;
1698 tty = fd == fileno(stdin) && isatty(fd);
1699 }
1700 if (tty) {
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001701 tmp = _PyObject_CallMethodId(fout, &PyId_fileno, "");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001702 if (tmp == NULL)
1703 PyErr_Clear();
1704 else {
1705 fd = PyLong_AsLong(tmp);
1706 Py_DECREF(tmp);
1707 if (fd < 0 && PyErr_Occurred())
1708 return NULL;
1709 tty = fd == fileno(stdout) && isatty(fd);
1710 }
1711 }
Guido van Rossumeba76962007-05-27 09:13:28 +00001712
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001713 /* If we're interactive, use (GNU) readline */
1714 if (tty) {
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001715 PyObject *po = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001716 char *prompt;
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001717 char *s = NULL;
1718 PyObject *stdin_encoding = NULL, *stdin_errors = NULL;
1719 PyObject *stdout_encoding = NULL, *stdout_errors = NULL;
1720 char *stdin_encoding_str, *stdin_errors_str;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001721 PyObject *result;
Victor Stinnerc0f1a1a2011-02-23 12:07:37 +00001722 size_t len;
Martin v. Löwis4a7b5d52007-09-04 05:24:49 +00001723
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02001724 stdin_encoding = _PyObject_GetAttrId(fin, &PyId_encoding);
Antoine Pitrou5ee9d8a2011-11-06 00:38:45 +01001725 stdin_errors = _PyObject_GetAttrId(fin, &PyId_errors);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001726 if (!stdin_encoding || !stdin_errors)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001727 /* stdin is a text stream, so it must have an
1728 encoding. */
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001729 goto _readline_errors;
Victor Stinner306f0102010-05-19 01:06:22 +00001730 stdin_encoding_str = _PyUnicode_AsString(stdin_encoding);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001731 stdin_errors_str = _PyUnicode_AsString(stdin_errors);
1732 if (!stdin_encoding_str || !stdin_errors_str)
1733 goto _readline_errors;
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001734 tmp = _PyObject_CallMethodId(fout, &PyId_flush, "");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001735 if (tmp == NULL)
1736 PyErr_Clear();
1737 else
1738 Py_DECREF(tmp);
1739 if (promptarg != NULL) {
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001740 /* We have a prompt, encode it as stdout would */
1741 char *stdout_encoding_str, *stdout_errors_str;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001742 PyObject *stringpo;
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02001743 stdout_encoding = _PyObject_GetAttrId(fout, &PyId_encoding);
Antoine Pitrou5ee9d8a2011-11-06 00:38:45 +01001744 stdout_errors = _PyObject_GetAttrId(fout, &PyId_errors);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001745 if (!stdout_encoding || !stdout_errors)
1746 goto _readline_errors;
Victor Stinner306f0102010-05-19 01:06:22 +00001747 stdout_encoding_str = _PyUnicode_AsString(stdout_encoding);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001748 stdout_errors_str = _PyUnicode_AsString(stdout_errors);
1749 if (!stdout_encoding_str || !stdout_errors_str)
1750 goto _readline_errors;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001751 stringpo = PyObject_Str(promptarg);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001752 if (stringpo == NULL)
1753 goto _readline_errors;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001754 po = PyUnicode_AsEncodedString(stringpo,
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001755 stdout_encoding_str, stdout_errors_str);
1756 Py_CLEAR(stdout_encoding);
1757 Py_CLEAR(stdout_errors);
1758 Py_CLEAR(stringpo);
1759 if (po == NULL)
1760 goto _readline_errors;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001761 prompt = PyBytes_AsString(po);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001762 if (prompt == NULL)
1763 goto _readline_errors;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001764 }
1765 else {
1766 po = NULL;
1767 prompt = "";
1768 }
1769 s = PyOS_Readline(stdin, stdout, prompt);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001770 if (s == NULL) {
Richard Oudkerk614c5782013-04-03 13:44:50 +01001771 PyErr_CheckSignals();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001772 if (!PyErr_Occurred())
1773 PyErr_SetNone(PyExc_KeyboardInterrupt);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001774 goto _readline_errors;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001775 }
Victor Stinnerc0f1a1a2011-02-23 12:07:37 +00001776
1777 len = strlen(s);
1778 if (len == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001779 PyErr_SetNone(PyExc_EOFError);
1780 result = NULL;
1781 }
Victor Stinnerc0f1a1a2011-02-23 12:07:37 +00001782 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001783 if (len > PY_SSIZE_T_MAX) {
1784 PyErr_SetString(PyExc_OverflowError,
1785 "input: input too long");
1786 result = NULL;
1787 }
1788 else {
Victor Stinnerc0f1a1a2011-02-23 12:07:37 +00001789 len--; /* strip trailing '\n' */
1790 if (len != 0 && s[len-1] == '\r')
1791 len--; /* strip trailing '\r' */
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001792 result = PyUnicode_Decode(s, len, stdin_encoding_str,
1793 stdin_errors_str);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001794 }
1795 }
1796 Py_DECREF(stdin_encoding);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001797 Py_DECREF(stdin_errors);
1798 Py_XDECREF(po);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001799 PyMem_FREE(s);
1800 return result;
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001801 _readline_errors:
1802 Py_XDECREF(stdin_encoding);
1803 Py_XDECREF(stdout_encoding);
1804 Py_XDECREF(stdin_errors);
1805 Py_XDECREF(stdout_errors);
1806 Py_XDECREF(po);
1807 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001808 }
Guido van Rossumeba76962007-05-27 09:13:28 +00001809
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001810 /* Fallback if we're not interactive */
1811 if (promptarg != NULL) {
1812 if (PyFile_WriteObject(promptarg, fout, Py_PRINT_RAW) != 0)
1813 return NULL;
1814 }
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001815 tmp = _PyObject_CallMethodId(fout, &PyId_flush, "");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001816 if (tmp == NULL)
1817 PyErr_Clear();
1818 else
1819 Py_DECREF(tmp);
1820 return PyFile_GetLine(fin, -1);
Guido van Rossuma88a0332007-02-26 16:59:55 +00001821}
1822
1823PyDoc_STRVAR(input_doc,
1824"input([prompt]) -> string\n\
1825\n\
1826Read a string from standard input. The trailing newline is stripped.\n\
1827If the user hits EOF (Unix: Ctl-D, Windows: Ctl-Z+Return), raise EOFError.\n\
1828On Unix, GNU readline is used if enabled. The prompt string, if given,\n\
1829is printed without a trailing newline before reading.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001830
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001831
Guido van Rossum79f25d91997-04-29 20:08:16 +00001832static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001833builtin_repr(PyObject *self, PyObject *v)
Guido van Rossumc89705d1992-11-26 08:54:07 +00001834{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001835 return PyObject_Repr(v);
Guido van Rossumc89705d1992-11-26 08:54:07 +00001836}
1837
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001838PyDoc_STRVAR(repr_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001839"repr(object) -> string\n\
1840\n\
1841Return the canonical string representation of the object.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001842For most object types, eval(repr(object)) == object.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001843
1844
Guido van Rossum79f25d91997-04-29 20:08:16 +00001845static PyObject *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001846builtin_round(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum9e51f9b1993-02-12 16:29:05 +00001847{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001848 PyObject *ndigits = NULL;
1849 static char *kwlist[] = {"number", "ndigits", 0};
Benjamin Peterson214a7d22013-04-13 17:19:01 -04001850 PyObject *number, *round, *result;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001851
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001852 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|O:round",
1853 kwlist, &number, &ndigits))
1854 return NULL;
Alex Martelliae211f92007-08-22 23:21:33 +00001855
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001856 if (Py_TYPE(number)->tp_dict == NULL) {
1857 if (PyType_Ready(Py_TYPE(number)) < 0)
1858 return NULL;
1859 }
Guido van Rossum15d3d042007-08-24 02:02:45 +00001860
Benjamin Peterson214a7d22013-04-13 17:19:01 -04001861 round = _PyObject_LookupSpecial(number, &PyId___round__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001862 if (round == NULL) {
Benjamin Peterson214a7d22013-04-13 17:19:01 -04001863 if (!PyErr_Occurred())
1864 PyErr_Format(PyExc_TypeError,
1865 "type %.100s doesn't define __round__ method",
1866 Py_TYPE(number)->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001867 return NULL;
1868 }
Alex Martelliae211f92007-08-22 23:21:33 +00001869
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001870 if (ndigits == NULL)
Benjamin Peterson214a7d22013-04-13 17:19:01 -04001871 result = PyObject_CallFunctionObjArgs(round, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001872 else
Benjamin Peterson214a7d22013-04-13 17:19:01 -04001873 result = PyObject_CallFunctionObjArgs(round, ndigits, NULL);
1874 Py_DECREF(round);
1875 return result;
Guido van Rossum9e51f9b1993-02-12 16:29:05 +00001876}
1877
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001878PyDoc_STRVAR(round_doc,
Mark Dickinson1124e712009-01-28 21:25:58 +00001879"round(number[, ndigits]) -> number\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001880\n\
1881Round a number to a given precision in decimal digits (default 0 digits).\n\
Mark Dickinson0d748c22008-07-05 11:29:03 +00001882This returns an int when called with one argument, otherwise the\n\
Georg Brandl809ddaa2008-07-01 20:39:59 +00001883same type as the number. ndigits may be negative.");
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001884
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001885
Raymond Hettinger64958a12003-12-17 20:43:33 +00001886static PyObject *
1887builtin_sorted(PyObject *self, PyObject *args, PyObject *kwds)
1888{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001889 PyObject *newlist, *v, *seq, *keyfunc=NULL, *newargs;
1890 PyObject *callable;
1891 static char *kwlist[] = {"iterable", "key", "reverse", 0};
1892 int reverse;
Raymond Hettinger64958a12003-12-17 20:43:33 +00001893
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001894 /* args 1-3 should match listsort in Objects/listobject.c */
1895 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|Oi:sorted",
1896 kwlist, &seq, &keyfunc, &reverse))
1897 return NULL;
Raymond Hettinger64958a12003-12-17 20:43:33 +00001898
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001899 newlist = PySequence_List(seq);
1900 if (newlist == NULL)
1901 return NULL;
Raymond Hettinger64958a12003-12-17 20:43:33 +00001902
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02001903 callable = _PyObject_GetAttrId(newlist, &PyId_sort);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001904 if (callable == NULL) {
1905 Py_DECREF(newlist);
1906 return NULL;
1907 }
Georg Brandl99d7e4e2005-08-31 22:21:15 +00001908
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001909 newargs = PyTuple_GetSlice(args, 1, 4);
1910 if (newargs == NULL) {
1911 Py_DECREF(newlist);
1912 Py_DECREF(callable);
1913 return NULL;
1914 }
Raymond Hettinger64958a12003-12-17 20:43:33 +00001915
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001916 v = PyObject_Call(callable, newargs, kwds);
1917 Py_DECREF(newargs);
1918 Py_DECREF(callable);
1919 if (v == NULL) {
1920 Py_DECREF(newlist);
1921 return NULL;
1922 }
1923 Py_DECREF(v);
1924 return newlist;
Raymond Hettinger64958a12003-12-17 20:43:33 +00001925}
1926
1927PyDoc_STRVAR(sorted_doc,
Raymond Hettinger70b64fc2008-01-30 20:15:17 +00001928"sorted(iterable, key=None, reverse=False) --> new sorted list");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001929
Guido van Rossum79f25d91997-04-29 20:08:16 +00001930static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001931builtin_vars(PyObject *self, PyObject *args)
Guido van Rossum2d951851994-08-29 12:52:16 +00001932{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001933 PyObject *v = NULL;
1934 PyObject *d;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001935
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001936 if (!PyArg_UnpackTuple(args, "vars", 0, 1, &v))
1937 return NULL;
1938 if (v == NULL) {
1939 d = PyEval_GetLocals();
Victor Stinner41bb43a2013-10-29 01:19:37 +01001940 if (d == NULL)
1941 return NULL;
1942 Py_INCREF(d);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001943 }
1944 else {
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02001945 d = _PyObject_GetAttrId(v, &PyId___dict__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001946 if (d == NULL) {
1947 PyErr_SetString(PyExc_TypeError,
1948 "vars() argument must have __dict__ attribute");
1949 return NULL;
1950 }
1951 }
1952 return d;
Guido van Rossum2d951851994-08-29 12:52:16 +00001953}
1954
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001955PyDoc_STRVAR(vars_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001956"vars([object]) -> dictionary\n\
1957\n\
1958Without arguments, equivalent to locals().\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001959With an argument, equivalent to object.__dict__.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001960
Alex Martellia70b1912003-04-22 08:12:33 +00001961static PyObject*
1962builtin_sum(PyObject *self, PyObject *args)
1963{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001964 PyObject *seq;
1965 PyObject *result = NULL;
1966 PyObject *temp, *item, *iter;
Alex Martellia70b1912003-04-22 08:12:33 +00001967
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001968 if (!PyArg_UnpackTuple(args, "sum", 1, 2, &seq, &result))
1969 return NULL;
Alex Martellia70b1912003-04-22 08:12:33 +00001970
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001971 iter = PyObject_GetIter(seq);
1972 if (iter == NULL)
1973 return NULL;
Alex Martellia70b1912003-04-22 08:12:33 +00001974
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001975 if (result == NULL) {
1976 result = PyLong_FromLong(0);
1977 if (result == NULL) {
1978 Py_DECREF(iter);
1979 return NULL;
1980 }
1981 } else {
1982 /* reject string values for 'start' parameter */
1983 if (PyUnicode_Check(result)) {
1984 PyErr_SetString(PyExc_TypeError,
1985 "sum() can't sum strings [use ''.join(seq) instead]");
1986 Py_DECREF(iter);
1987 return NULL;
1988 }
Benjamin Petersonce071ca2011-07-29 14:23:47 -05001989 if (PyBytes_Check(result)) {
1990 PyErr_SetString(PyExc_TypeError,
1991 "sum() can't sum bytes [use b''.join(seq) instead]");
Benjamin Peterson405f32c2011-07-29 22:43:45 -05001992 Py_DECREF(iter);
Benjamin Petersonce071ca2011-07-29 14:23:47 -05001993 return NULL;
1994 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001995 if (PyByteArray_Check(result)) {
1996 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson4f921c22011-07-29 14:24:29 -05001997 "sum() can't sum bytearray [use b''.join(seq) instead]");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001998 Py_DECREF(iter);
1999 return NULL;
2000 }
Guido van Rossum3172c5d2007-10-16 18:12:55 +00002001
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002002 Py_INCREF(result);
2003 }
Alex Martellia70b1912003-04-22 08:12:33 +00002004
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002005#ifndef SLOW_SUM
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002006 /* Fast addition by keeping temporary sums in C instead of new Python objects.
2007 Assumes all inputs are the same type. If the assumption fails, default
2008 to the more general routine.
2009 */
2010 if (PyLong_CheckExact(result)) {
2011 int overflow;
2012 long i_result = PyLong_AsLongAndOverflow(result, &overflow);
2013 /* If this already overflowed, don't even enter the loop. */
2014 if (overflow == 0) {
2015 Py_DECREF(result);
2016 result = NULL;
2017 }
2018 while(result == NULL) {
2019 item = PyIter_Next(iter);
2020 if (item == NULL) {
2021 Py_DECREF(iter);
2022 if (PyErr_Occurred())
2023 return NULL;
2024 return PyLong_FromLong(i_result);
2025 }
2026 if (PyLong_CheckExact(item)) {
2027 long b = PyLong_AsLongAndOverflow(item, &overflow);
2028 long x = i_result + b;
2029 if (overflow == 0 && ((x^i_result) >= 0 || (x^b) >= 0)) {
2030 i_result = x;
2031 Py_DECREF(item);
2032 continue;
2033 }
2034 }
2035 /* Either overflowed or is not an int. Restore real objects and process normally */
2036 result = PyLong_FromLong(i_result);
Christian Heimes704e2d32013-07-26 22:49:26 +02002037 if (result == NULL) {
2038 Py_DECREF(item);
2039 Py_DECREF(iter);
2040 return NULL;
2041 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002042 temp = PyNumber_Add(result, item);
2043 Py_DECREF(result);
2044 Py_DECREF(item);
2045 result = temp;
2046 if (result == NULL) {
2047 Py_DECREF(iter);
2048 return NULL;
2049 }
2050 }
2051 }
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002052
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002053 if (PyFloat_CheckExact(result)) {
2054 double f_result = PyFloat_AS_DOUBLE(result);
2055 Py_DECREF(result);
2056 result = NULL;
2057 while(result == NULL) {
2058 item = PyIter_Next(iter);
2059 if (item == NULL) {
2060 Py_DECREF(iter);
2061 if (PyErr_Occurred())
2062 return NULL;
2063 return PyFloat_FromDouble(f_result);
2064 }
2065 if (PyFloat_CheckExact(item)) {
2066 PyFPE_START_PROTECT("add", Py_DECREF(item); Py_DECREF(iter); return 0)
2067 f_result += PyFloat_AS_DOUBLE(item);
2068 PyFPE_END_PROTECT(f_result)
2069 Py_DECREF(item);
2070 continue;
2071 }
2072 if (PyLong_CheckExact(item)) {
2073 long value;
2074 int overflow;
2075 value = PyLong_AsLongAndOverflow(item, &overflow);
2076 if (!overflow) {
2077 PyFPE_START_PROTECT("add", Py_DECREF(item); Py_DECREF(iter); return 0)
2078 f_result += (double)value;
2079 PyFPE_END_PROTECT(f_result)
2080 Py_DECREF(item);
2081 continue;
2082 }
2083 }
2084 result = PyFloat_FromDouble(f_result);
2085 temp = PyNumber_Add(result, item);
2086 Py_DECREF(result);
2087 Py_DECREF(item);
2088 result = temp;
2089 if (result == NULL) {
2090 Py_DECREF(iter);
2091 return NULL;
2092 }
2093 }
2094 }
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002095#endif
2096
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002097 for(;;) {
2098 item = PyIter_Next(iter);
2099 if (item == NULL) {
2100 /* error, or end-of-sequence */
2101 if (PyErr_Occurred()) {
2102 Py_DECREF(result);
2103 result = NULL;
2104 }
2105 break;
2106 }
2107 /* It's tempting to use PyNumber_InPlaceAdd instead of
2108 PyNumber_Add here, to avoid quadratic running time
2109 when doing 'sum(list_of_lists, [])'. However, this
2110 would produce a change in behaviour: a snippet like
Mark Dickinson9acadc52009-10-26 14:19:42 +00002111
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002112 empty = []
2113 sum([[x] for x in range(10)], empty)
Mark Dickinson9acadc52009-10-26 14:19:42 +00002114
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002115 would change the value of empty. */
2116 temp = PyNumber_Add(result, item);
2117 Py_DECREF(result);
2118 Py_DECREF(item);
2119 result = temp;
2120 if (result == NULL)
2121 break;
2122 }
2123 Py_DECREF(iter);
2124 return result;
Alex Martellia70b1912003-04-22 08:12:33 +00002125}
2126
2127PyDoc_STRVAR(sum_doc,
Georg Brandld11ae5d2008-05-16 13:27:32 +00002128"sum(iterable[, start]) -> value\n\
Alex Martellia70b1912003-04-22 08:12:33 +00002129\n\
R David Murray87ead112013-07-10 16:22:14 -04002130Return the sum of an iterable of numbers (NOT strings) plus the value\n\
Georg Brandld11ae5d2008-05-16 13:27:32 +00002131of parameter 'start' (which defaults to 0). When the iterable is\n\
R David Murray87ead112013-07-10 16:22:14 -04002132empty, return start.");
Alex Martellia70b1912003-04-22 08:12:33 +00002133
2134
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002135static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002136builtin_isinstance(PyObject *self, PyObject *args)
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002137{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002138 PyObject *inst;
2139 PyObject *cls;
2140 int retval;
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002141
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002142 if (!PyArg_UnpackTuple(args, "isinstance", 2, 2, &inst, &cls))
2143 return NULL;
Guido van Rossumf5dd9141997-12-02 19:11:45 +00002144
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002145 retval = PyObject_IsInstance(inst, cls);
2146 if (retval < 0)
2147 return NULL;
2148 return PyBool_FromLong(retval);
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002149}
2150
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002151PyDoc_STRVAR(isinstance_doc,
Guido van Rossum77f6a652002-04-03 22:41:51 +00002152"isinstance(object, class-or-type-or-tuple) -> bool\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002153\n\
2154Return whether an object is an instance of a class or of a subclass thereof.\n\
Guido van Rossum03290ec2001-10-07 20:54:12 +00002155With a type as second argument, return whether that is the object's type.\n\
2156The form using a tuple, isinstance(x, (A, B, ...)), is a shortcut for\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002157isinstance(x, A) or isinstance(x, B) or ... (etc.).");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002158
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002159
2160static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002161builtin_issubclass(PyObject *self, PyObject *args)
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002162{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002163 PyObject *derived;
2164 PyObject *cls;
2165 int retval;
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002166
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002167 if (!PyArg_UnpackTuple(args, "issubclass", 2, 2, &derived, &cls))
2168 return NULL;
Guido van Rossum668213d1999-06-16 17:28:37 +00002169
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002170 retval = PyObject_IsSubclass(derived, cls);
2171 if (retval < 0)
2172 return NULL;
2173 return PyBool_FromLong(retval);
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002174}
2175
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002176PyDoc_STRVAR(issubclass_doc,
Guido van Rossum77f6a652002-04-03 22:41:51 +00002177"issubclass(C, B) -> bool\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002178\n\
Walter Dörwaldd9a6ad32002-12-12 16:41:44 +00002179Return whether class C is a subclass (i.e., a derived class) of class B.\n\
2180When using a tuple as the second argument issubclass(X, (A, B, ...)),\n\
2181is a shortcut for issubclass(X, A) or issubclass(X, B) or ... (etc.).");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002182
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002183
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002184typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002185 PyObject_HEAD
2186 Py_ssize_t tuplesize;
2187 PyObject *ittuple; /* tuple of iterators */
2188 PyObject *result;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002189} zipobject;
2190
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002191static PyObject *
2192zip_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
Barry Warsawbd599b52000-08-03 15:45:29 +00002193{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002194 zipobject *lz;
2195 Py_ssize_t i;
2196 PyObject *ittuple; /* tuple of iterators */
2197 PyObject *result;
2198 Py_ssize_t tuplesize = PySequence_Length(args);
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002199
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002200 if (type == &PyZip_Type && !_PyArg_NoKeywords("zip()", kwds))
2201 return NULL;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002202
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002203 /* args must be a tuple */
2204 assert(PyTuple_Check(args));
Barry Warsawbd599b52000-08-03 15:45:29 +00002205
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002206 /* obtain iterators */
2207 ittuple = PyTuple_New(tuplesize);
2208 if (ittuple == NULL)
2209 return NULL;
2210 for (i=0; i < tuplesize; ++i) {
2211 PyObject *item = PyTuple_GET_ITEM(args, i);
2212 PyObject *it = PyObject_GetIter(item);
2213 if (it == NULL) {
2214 if (PyErr_ExceptionMatches(PyExc_TypeError))
2215 PyErr_Format(PyExc_TypeError,
2216 "zip argument #%zd must support iteration",
2217 i+1);
2218 Py_DECREF(ittuple);
2219 return NULL;
2220 }
2221 PyTuple_SET_ITEM(ittuple, i, it);
2222 }
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002223
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002224 /* create a result holder */
2225 result = PyTuple_New(tuplesize);
2226 if (result == NULL) {
2227 Py_DECREF(ittuple);
2228 return NULL;
2229 }
2230 for (i=0 ; i < tuplesize ; i++) {
2231 Py_INCREF(Py_None);
2232 PyTuple_SET_ITEM(result, i, Py_None);
2233 }
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002234
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002235 /* create zipobject structure */
2236 lz = (zipobject *)type->tp_alloc(type, 0);
2237 if (lz == NULL) {
2238 Py_DECREF(ittuple);
2239 Py_DECREF(result);
2240 return NULL;
2241 }
2242 lz->ittuple = ittuple;
2243 lz->tuplesize = tuplesize;
2244 lz->result = result;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002245
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002246 return (PyObject *)lz;
Barry Warsawbd599b52000-08-03 15:45:29 +00002247}
2248
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002249static void
2250zip_dealloc(zipobject *lz)
2251{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002252 PyObject_GC_UnTrack(lz);
2253 Py_XDECREF(lz->ittuple);
2254 Py_XDECREF(lz->result);
2255 Py_TYPE(lz)->tp_free(lz);
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002256}
2257
2258static int
2259zip_traverse(zipobject *lz, visitproc visit, void *arg)
2260{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002261 Py_VISIT(lz->ittuple);
2262 Py_VISIT(lz->result);
2263 return 0;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002264}
2265
2266static PyObject *
2267zip_next(zipobject *lz)
2268{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002269 Py_ssize_t i;
2270 Py_ssize_t tuplesize = lz->tuplesize;
2271 PyObject *result = lz->result;
2272 PyObject *it;
2273 PyObject *item;
2274 PyObject *olditem;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002275
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002276 if (tuplesize == 0)
2277 return NULL;
2278 if (Py_REFCNT(result) == 1) {
2279 Py_INCREF(result);
2280 for (i=0 ; i < tuplesize ; i++) {
2281 it = PyTuple_GET_ITEM(lz->ittuple, i);
2282 item = (*Py_TYPE(it)->tp_iternext)(it);
Serhiy Storchaka278d03b2013-04-06 22:52:34 +03002283 if (item == NULL) {
2284 Py_DECREF(result);
2285 return NULL;
2286 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002287 olditem = PyTuple_GET_ITEM(result, i);
2288 PyTuple_SET_ITEM(result, i, item);
2289 Py_DECREF(olditem);
2290 }
2291 } else {
2292 result = PyTuple_New(tuplesize);
2293 if (result == NULL)
Serhiy Storchaka278d03b2013-04-06 22:52:34 +03002294 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002295 for (i=0 ; i < tuplesize ; i++) {
2296 it = PyTuple_GET_ITEM(lz->ittuple, i);
2297 item = (*Py_TYPE(it)->tp_iternext)(it);
Serhiy Storchaka278d03b2013-04-06 22:52:34 +03002298 if (item == NULL) {
2299 Py_DECREF(result);
2300 return NULL;
2301 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002302 PyTuple_SET_ITEM(result, i, item);
2303 }
2304 }
2305 return result;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002306}
Barry Warsawbd599b52000-08-03 15:45:29 +00002307
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002308static PyObject *
2309zip_reduce(zipobject *lz)
2310{
2311 /* Just recreate the zip with the internal iterator tuple */
2312 return Py_BuildValue("OO", Py_TYPE(lz), lz->ittuple);
2313}
2314
2315static PyMethodDef zip_methods[] = {
2316 {"__reduce__", (PyCFunction)zip_reduce, METH_NOARGS, reduce_doc},
2317 {NULL, NULL} /* sentinel */
2318};
2319
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002320PyDoc_STRVAR(zip_doc,
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002321"zip(iter1 [,iter2 [...]]) --> zip object\n\
Barry Warsawbd599b52000-08-03 15:45:29 +00002322\n\
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002323Return a zip object whose .__next__() method returns a tuple where\n\
2324the i-th element comes from the i-th iterable argument. The .__next__()\n\
2325method continues until the shortest iterable in the argument sequence\n\
Georg Brandlced51db2008-12-04 18:28:38 +00002326is exhausted and then it raises StopIteration.");
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002327
2328PyTypeObject PyZip_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002329 PyVarObject_HEAD_INIT(&PyType_Type, 0)
2330 "zip", /* tp_name */
2331 sizeof(zipobject), /* tp_basicsize */
2332 0, /* tp_itemsize */
2333 /* methods */
2334 (destructor)zip_dealloc, /* tp_dealloc */
2335 0, /* tp_print */
2336 0, /* tp_getattr */
2337 0, /* tp_setattr */
2338 0, /* tp_reserved */
2339 0, /* tp_repr */
2340 0, /* tp_as_number */
2341 0, /* tp_as_sequence */
2342 0, /* tp_as_mapping */
2343 0, /* tp_hash */
2344 0, /* tp_call */
2345 0, /* tp_str */
2346 PyObject_GenericGetAttr, /* tp_getattro */
2347 0, /* tp_setattro */
2348 0, /* tp_as_buffer */
2349 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
2350 Py_TPFLAGS_BASETYPE, /* tp_flags */
2351 zip_doc, /* tp_doc */
2352 (traverseproc)zip_traverse, /* tp_traverse */
2353 0, /* tp_clear */
2354 0, /* tp_richcompare */
2355 0, /* tp_weaklistoffset */
2356 PyObject_SelfIter, /* tp_iter */
2357 (iternextfunc)zip_next, /* tp_iternext */
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002358 zip_methods, /* tp_methods */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002359 0, /* tp_members */
2360 0, /* tp_getset */
2361 0, /* tp_base */
2362 0, /* tp_dict */
2363 0, /* tp_descr_get */
2364 0, /* tp_descr_set */
2365 0, /* tp_dictoffset */
2366 0, /* tp_init */
2367 PyType_GenericAlloc, /* tp_alloc */
2368 zip_new, /* tp_new */
2369 PyObject_GC_Del, /* tp_free */
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002370};
Barry Warsawbd599b52000-08-03 15:45:29 +00002371
2372
Guido van Rossum79f25d91997-04-29 20:08:16 +00002373static PyMethodDef builtin_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002374 {"__build_class__", (PyCFunction)builtin___build_class__,
2375 METH_VARARGS | METH_KEYWORDS, build_class_doc},
2376 {"__import__", (PyCFunction)builtin___import__, METH_VARARGS | METH_KEYWORDS, import_doc},
2377 {"abs", builtin_abs, METH_O, abs_doc},
2378 {"all", builtin_all, METH_O, all_doc},
2379 {"any", builtin_any, METH_O, any_doc},
2380 {"ascii", builtin_ascii, METH_O, ascii_doc},
2381 {"bin", builtin_bin, METH_O, bin_doc},
Antoine Pitroue71362d2010-11-27 22:00:11 +00002382 {"callable", builtin_callable, METH_O, callable_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002383 {"chr", builtin_chr, METH_VARARGS, chr_doc},
2384 {"compile", (PyCFunction)builtin_compile, METH_VARARGS | METH_KEYWORDS, compile_doc},
2385 {"delattr", builtin_delattr, METH_VARARGS, delattr_doc},
2386 {"dir", builtin_dir, METH_VARARGS, dir_doc},
2387 {"divmod", builtin_divmod, METH_VARARGS, divmod_doc},
2388 {"eval", builtin_eval, METH_VARARGS, eval_doc},
2389 {"exec", builtin_exec, METH_VARARGS, exec_doc},
2390 {"format", builtin_format, METH_VARARGS, format_doc},
2391 {"getattr", builtin_getattr, METH_VARARGS, getattr_doc},
2392 {"globals", (PyCFunction)builtin_globals, METH_NOARGS, globals_doc},
2393 {"hasattr", builtin_hasattr, METH_VARARGS, hasattr_doc},
2394 {"hash", builtin_hash, METH_O, hash_doc},
2395 {"hex", builtin_hex, METH_O, hex_doc},
2396 {"id", builtin_id, METH_O, id_doc},
2397 {"input", builtin_input, METH_VARARGS, input_doc},
2398 {"isinstance", builtin_isinstance, METH_VARARGS, isinstance_doc},
2399 {"issubclass", builtin_issubclass, METH_VARARGS, issubclass_doc},
2400 {"iter", builtin_iter, METH_VARARGS, iter_doc},
2401 {"len", builtin_len, METH_O, len_doc},
2402 {"locals", (PyCFunction)builtin_locals, METH_NOARGS, locals_doc},
2403 {"max", (PyCFunction)builtin_max, METH_VARARGS | METH_KEYWORDS, max_doc},
2404 {"min", (PyCFunction)builtin_min, METH_VARARGS | METH_KEYWORDS, min_doc},
2405 {"next", (PyCFunction)builtin_next, METH_VARARGS, next_doc},
2406 {"oct", builtin_oct, METH_O, oct_doc},
2407 {"ord", builtin_ord, METH_O, ord_doc},
2408 {"pow", builtin_pow, METH_VARARGS, pow_doc},
2409 {"print", (PyCFunction)builtin_print, METH_VARARGS | METH_KEYWORDS, print_doc},
2410 {"repr", builtin_repr, METH_O, repr_doc},
2411 {"round", (PyCFunction)builtin_round, METH_VARARGS | METH_KEYWORDS, round_doc},
2412 {"setattr", builtin_setattr, METH_VARARGS, setattr_doc},
2413 {"sorted", (PyCFunction)builtin_sorted, METH_VARARGS | METH_KEYWORDS, sorted_doc},
2414 {"sum", builtin_sum, METH_VARARGS, sum_doc},
2415 {"vars", builtin_vars, METH_VARARGS, vars_doc},
2416 {NULL, NULL},
Guido van Rossum3f5da241990-12-20 15:06:42 +00002417};
2418
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002419PyDoc_STRVAR(builtin_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002420"Built-in functions, exceptions, and other objects.\n\
2421\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002422Noteworthy: None is the `nil' object; Ellipsis represents `...' in slices.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002423
Martin v. Löwis1a214512008-06-11 05:26:20 +00002424static struct PyModuleDef builtinsmodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002425 PyModuleDef_HEAD_INIT,
2426 "builtins",
2427 builtin_doc,
2428 -1, /* multiple "initialization" just copies the module dict. */
2429 builtin_methods,
2430 NULL,
2431 NULL,
2432 NULL,
2433 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00002434};
2435
2436
Guido van Rossum25ce5661997-08-02 03:10:38 +00002437PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002438_PyBuiltin_Init(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +00002439{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002440 PyObject *mod, *dict, *debug;
Benjamin Peterson42124a72012-10-30 23:41:54 -04002441
2442 if (PyType_Ready(&PyFilter_Type) < 0 ||
2443 PyType_Ready(&PyMap_Type) < 0 ||
2444 PyType_Ready(&PyZip_Type) < 0)
2445 return NULL;
2446
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002447 mod = PyModule_Create(&builtinsmodule);
2448 if (mod == NULL)
2449 return NULL;
2450 dict = PyModule_GetDict(mod);
Tim Peters4b7625e2001-09-13 21:37:17 +00002451
Tim Peters7571a0f2003-03-23 17:52:28 +00002452#ifdef Py_TRACE_REFS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002453 /* "builtins" exposes a number of statically allocated objects
2454 * that, before this code was added in 2.3, never showed up in
2455 * the list of "all objects" maintained by Py_TRACE_REFS. As a
2456 * result, programs leaking references to None and False (etc)
2457 * couldn't be diagnosed by examining sys.getobjects(0).
2458 */
Tim Peters7571a0f2003-03-23 17:52:28 +00002459#define ADD_TO_ALL(OBJECT) _Py_AddToAllObjects((PyObject *)(OBJECT), 0)
2460#else
2461#define ADD_TO_ALL(OBJECT) (void)0
2462#endif
2463
Tim Peters4b7625e2001-09-13 21:37:17 +00002464#define SETBUILTIN(NAME, OBJECT) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002465 if (PyDict_SetItemString(dict, NAME, (PyObject *)OBJECT) < 0) \
2466 return NULL; \
2467 ADD_TO_ALL(OBJECT)
Tim Peters4b7625e2001-09-13 21:37:17 +00002468
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002469 SETBUILTIN("None", Py_None);
2470 SETBUILTIN("Ellipsis", Py_Ellipsis);
2471 SETBUILTIN("NotImplemented", Py_NotImplemented);
2472 SETBUILTIN("False", Py_False);
2473 SETBUILTIN("True", Py_True);
2474 SETBUILTIN("bool", &PyBool_Type);
2475 SETBUILTIN("memoryview", &PyMemoryView_Type);
2476 SETBUILTIN("bytearray", &PyByteArray_Type);
2477 SETBUILTIN("bytes", &PyBytes_Type);
2478 SETBUILTIN("classmethod", &PyClassMethod_Type);
2479 SETBUILTIN("complex", &PyComplex_Type);
2480 SETBUILTIN("dict", &PyDict_Type);
2481 SETBUILTIN("enumerate", &PyEnum_Type);
2482 SETBUILTIN("filter", &PyFilter_Type);
2483 SETBUILTIN("float", &PyFloat_Type);
2484 SETBUILTIN("frozenset", &PyFrozenSet_Type);
2485 SETBUILTIN("property", &PyProperty_Type);
2486 SETBUILTIN("int", &PyLong_Type);
2487 SETBUILTIN("list", &PyList_Type);
2488 SETBUILTIN("map", &PyMap_Type);
2489 SETBUILTIN("object", &PyBaseObject_Type);
2490 SETBUILTIN("range", &PyRange_Type);
2491 SETBUILTIN("reversed", &PyReversed_Type);
2492 SETBUILTIN("set", &PySet_Type);
2493 SETBUILTIN("slice", &PySlice_Type);
2494 SETBUILTIN("staticmethod", &PyStaticMethod_Type);
2495 SETBUILTIN("str", &PyUnicode_Type);
2496 SETBUILTIN("super", &PySuper_Type);
2497 SETBUILTIN("tuple", &PyTuple_Type);
2498 SETBUILTIN("type", &PyType_Type);
2499 SETBUILTIN("zip", &PyZip_Type);
2500 debug = PyBool_FromLong(Py_OptimizeFlag == 0);
2501 if (PyDict_SetItemString(dict, "__debug__", debug) < 0) {
2502 Py_XDECREF(debug);
2503 return NULL;
2504 }
2505 Py_XDECREF(debug);
Barry Warsaw757af0e1997-08-29 22:13:51 +00002506
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002507 return mod;
Tim Peters7571a0f2003-03-23 17:52:28 +00002508#undef ADD_TO_ALL
Tim Peters4b7625e2001-09-13 21:37:17 +00002509#undef SETBUILTIN
Guido van Rossum3f5da241990-12-20 15:06:42 +00002510}