blob: d905ba2d949b96ea133c50ba49d9f9a8047daaa2 [file] [log] [blame]
Guido van Rossum3f5da241990-12-20 15:06:42 +00001/* Built-in functions */
2
Guido van Rossum79f25d91997-04-29 20:08:16 +00003#include "Python.h"
Martin v. Löwis618dc5e2008-03-30 20:03:44 +00004#include "Python-ast.h"
Guido van Rossum3f5da241990-12-20 15:06:42 +00005
6#include "node.h"
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00007#include "code.h"
Guido van Rossum3f5da241990-12-20 15:06:42 +00008
Benjamin Petersonea281a52011-08-12 23:10:50 -05009#include "asdl.h"
10#include "ast.h"
11
Guido van Rossum6bf62da1997-04-11 20:37:35 +000012#include <ctype.h>
13
Victor Stinnerb744ba12010-05-15 12:27:16 +000014#ifdef HAVE_LANGINFO_H
15#include <langinfo.h> /* CODESET */
16#endif
17
Mark Hammond26cffde42001-05-14 12:17:34 +000018/* The default encoding used by the platform file system APIs
19 Can remain NULL for all platforms that don't have such a concept
Guido van Rossum00bc0e02007-10-15 02:52:41 +000020
21 Don't forget to modify PyUnicode_DecodeFSDefault() if you touch any of the
22 values for Py_FileSystemDefaultEncoding!
Mark Hammond26cffde42001-05-14 12:17:34 +000023*/
Victor Stinner99b95382011-07-04 14:23:54 +020024#ifdef HAVE_MBCS
Mark Hammond26cffde42001-05-14 12:17:34 +000025const char *Py_FileSystemDefaultEncoding = "mbcs";
Martin v. Löwis04dc25c2008-10-03 16:09:28 +000026int Py_HasFileSystemDefaultEncoding = 1;
Just van Rossumb9b8e9c2003-02-10 09:22:01 +000027#elif defined(__APPLE__)
28const char *Py_FileSystemDefaultEncoding = "utf-8";
Martin v. Löwis04dc25c2008-10-03 16:09:28 +000029int Py_HasFileSystemDefaultEncoding = 1;
Victor Stinnerd64e8a72011-07-04 13:48:30 +020030#else
Victor Stinnerb744ba12010-05-15 12:27:16 +000031const char *Py_FileSystemDefaultEncoding = NULL; /* set by initfsencoding() */
Martin v. Löwis04dc25c2008-10-03 16:09:28 +000032int Py_HasFileSystemDefaultEncoding = 0;
Mark Hammond26cffde42001-05-14 12:17:34 +000033#endif
Mark Hammondef8b6542001-05-13 08:04:26 +000034
Victor Stinnerbd303c12013-11-07 23:07:29 +010035_Py_IDENTIFIER(__builtins__);
36_Py_IDENTIFIER(__dict__);
37_Py_IDENTIFIER(__prepare__);
38_Py_IDENTIFIER(__round__);
39_Py_IDENTIFIER(encoding);
40_Py_IDENTIFIER(errors);
Martin v. Löwisbd928fe2011-10-14 10:20:37 +020041_Py_IDENTIFIER(fileno);
42_Py_IDENTIFIER(flush);
Victor Stinnerbd303c12013-11-07 23:07:29 +010043_Py_IDENTIFIER(metaclass);
44_Py_IDENTIFIER(sort);
45_Py_IDENTIFIER(stdin);
46_Py_IDENTIFIER(stdout);
47_Py_IDENTIFIER(stderr);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +020048
Guido van Rossum79f25d91997-04-29 20:08:16 +000049static PyObject *
Guido van Rossum52cc1d82007-03-18 15:41:51 +000050builtin___build_class__(PyObject *self, PyObject *args, PyObject *kwds)
51{
Nick Coghlande31b192011-10-23 22:04:16 +100052 PyObject *func, *name, *bases, *mkw, *meta, *winner, *prep, *ns, *cell;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000053 PyObject *cls = NULL;
Florent Xicluna4d46c2a2011-10-28 15:00:50 +020054 Py_ssize_t nargs;
Nick Coghlande31b192011-10-23 22:04:16 +100055 int isclass;
Guido van Rossum52cc1d82007-03-18 15:41:51 +000056
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000057 assert(args != NULL);
58 if (!PyTuple_Check(args)) {
59 PyErr_SetString(PyExc_TypeError,
60 "__build_class__: args is not a tuple");
61 return NULL;
62 }
63 nargs = PyTuple_GET_SIZE(args);
64 if (nargs < 2) {
65 PyErr_SetString(PyExc_TypeError,
66 "__build_class__: not enough arguments");
67 return NULL;
68 }
69 func = PyTuple_GET_ITEM(args, 0); /* Better be callable */
Benjamin Petersone8e14592013-05-16 14:37:25 -050070 if (!PyFunction_Check(func)) {
71 PyErr_SetString(PyExc_TypeError,
Zachary Ware9b338722014-08-05 14:01:10 -050072 "__build_class__: func must be a function");
Benjamin Petersone8e14592013-05-16 14:37:25 -050073 return NULL;
74 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000075 name = PyTuple_GET_ITEM(args, 1);
76 if (!PyUnicode_Check(name)) {
77 PyErr_SetString(PyExc_TypeError,
78 "__build_class__: name is not a string");
79 return NULL;
80 }
81 bases = PyTuple_GetSlice(args, 2, nargs);
82 if (bases == NULL)
83 return NULL;
Guido van Rossum52cc1d82007-03-18 15:41:51 +000084
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000085 if (kwds == NULL) {
86 meta = NULL;
87 mkw = NULL;
88 }
89 else {
90 mkw = PyDict_Copy(kwds); /* Don't modify kwds passed in! */
91 if (mkw == NULL) {
92 Py_DECREF(bases);
93 return NULL;
Guido van Rossum52cc1d82007-03-18 15:41:51 +000094 }
Victor Stinnerae9f1612013-11-06 22:46:51 +010095 meta = _PyDict_GetItemId(mkw, &PyId_metaclass);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000096 if (meta != NULL) {
97 Py_INCREF(meta);
Victor Stinnerae9f1612013-11-06 22:46:51 +010098 if (_PyDict_DelItemId(mkw, &PyId_metaclass) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000099 Py_DECREF(meta);
100 Py_DECREF(mkw);
101 Py_DECREF(bases);
102 return NULL;
103 }
Nick Coghlande31b192011-10-23 22:04:16 +1000104 /* metaclass is explicitly given, check if it's indeed a class */
105 isclass = PyType_Check(meta);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000106 }
107 }
108 if (meta == NULL) {
Nick Coghlande31b192011-10-23 22:04:16 +1000109 /* if there are no bases, use type: */
110 if (PyTuple_GET_SIZE(bases) == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000111 meta = (PyObject *) (&PyType_Type);
Nick Coghlande31b192011-10-23 22:04:16 +1000112 }
113 /* else get the type of the first base */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000114 else {
115 PyObject *base0 = PyTuple_GET_ITEM(bases, 0);
116 meta = (PyObject *) (base0->ob_type);
117 }
118 Py_INCREF(meta);
Nick Coghlande31b192011-10-23 22:04:16 +1000119 isclass = 1; /* meta is really a class */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000120 }
Nick Coghlan9715d262011-10-23 22:36:42 +1000121
Nick Coghlande31b192011-10-23 22:04:16 +1000122 if (isclass) {
123 /* meta is really a class, so check for a more derived
124 metaclass, or possible metaclass conflicts: */
125 winner = (PyObject *)_PyType_CalculateMetaclass((PyTypeObject *)meta,
126 bases);
127 if (winner == NULL) {
128 Py_DECREF(meta);
129 Py_XDECREF(mkw);
130 Py_DECREF(bases);
131 return NULL;
132 }
133 if (winner != meta) {
134 Py_DECREF(meta);
135 meta = winner;
136 Py_INCREF(meta);
137 }
138 }
139 /* else: meta is not a class, so we cannot do the metaclass
140 calculation, so we will use the explicitly given object as it is */
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +0200141 prep = _PyObject_GetAttrId(meta, &PyId___prepare__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000142 if (prep == NULL) {
143 if (PyErr_ExceptionMatches(PyExc_AttributeError)) {
144 PyErr_Clear();
145 ns = PyDict_New();
146 }
147 else {
148 Py_DECREF(meta);
149 Py_XDECREF(mkw);
150 Py_DECREF(bases);
151 return NULL;
152 }
153 }
154 else {
155 PyObject *pargs = PyTuple_Pack(2, name, bases);
156 if (pargs == NULL) {
157 Py_DECREF(prep);
158 Py_DECREF(meta);
159 Py_XDECREF(mkw);
160 Py_DECREF(bases);
161 return NULL;
162 }
163 ns = PyEval_CallObjectWithKeywords(prep, pargs, mkw);
164 Py_DECREF(pargs);
165 Py_DECREF(prep);
166 }
167 if (ns == NULL) {
168 Py_DECREF(meta);
169 Py_XDECREF(mkw);
170 Py_DECREF(bases);
171 return NULL;
172 }
Benjamin Petersone8e14592013-05-16 14:37:25 -0500173 cell = PyEval_EvalCodeEx(PyFunction_GET_CODE(func), PyFunction_GET_GLOBALS(func), ns,
174 NULL, 0, NULL, 0, NULL, 0, NULL,
175 PyFunction_GET_CLOSURE(func));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000176 if (cell != NULL) {
177 PyObject *margs;
178 margs = PyTuple_Pack(3, name, bases, ns);
179 if (margs != NULL) {
180 cls = PyEval_CallObjectWithKeywords(meta, margs, mkw);
181 Py_DECREF(margs);
182 }
Benjamin Peterson8e8fbea2012-06-01 23:57:36 -0700183 if (cls != NULL && PyCell_Check(cell))
184 PyCell_Set(cell, cls);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000185 Py_DECREF(cell);
186 }
187 Py_DECREF(ns);
188 Py_DECREF(meta);
189 Py_XDECREF(mkw);
190 Py_DECREF(bases);
191 return cls;
Guido van Rossum52cc1d82007-03-18 15:41:51 +0000192}
193
194PyDoc_STRVAR(build_class_doc,
195"__build_class__(func, name, *bases, metaclass=None, **kwds) -> class\n\
196\n\
197Internal helper function used by the class statement.");
198
199static PyObject *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000200builtin___import__(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000201{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000202 static char *kwlist[] = {"name", "globals", "locals", "fromlist",
203 "level", 0};
Victor Stinnerfe93faf2011-03-14 15:54:52 -0400204 PyObject *name, *globals = NULL, *locals = NULL, *fromlist = NULL;
Brett Cannonfd074152012-04-14 14:10:13 -0400205 int level = 0;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000206
Victor Stinnerfe93faf2011-03-14 15:54:52 -0400207 if (!PyArg_ParseTupleAndKeywords(args, kwds, "U|OOOi:__import__",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000208 kwlist, &name, &globals, &locals, &fromlist, &level))
209 return NULL;
Victor Stinnerfe93faf2011-03-14 15:54:52 -0400210 return PyImport_ImportModuleLevelObject(name, globals, locals,
211 fromlist, level);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000212}
213
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000214PyDoc_STRVAR(import_doc,
Brett Cannoncb4996a2012-08-06 16:34:44 -0400215"__import__(name, globals=None, locals=None, fromlist=(), level=0) -> module\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000216\n\
Brett Cannon5305a992010-09-27 21:08:38 +0000217Import a module. Because this function is meant for use by the Python\n\
218interpreter and not for general use it is better to use\n\
219importlib.import_module() to programmatically import a module.\n\
220\n\
221The globals argument is only used to determine the context;\n\
222they are not modified. The locals argument is unused. The fromlist\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000223should be a list of names to emulate ``from name import ...'', or an\n\
224empty list to emulate ``import name''.\n\
225When importing a module from a package, note that __import__('A.B', ...)\n\
226returns package A when fromlist is empty, but its submodule B when\n\
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000227fromlist is not empty. Level is used to determine whether to perform \n\
Brett Cannon722d3ae2012-07-30 17:45:54 -0400228absolute or relative imports. 0 is absolute while a positive number\n\
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000229is the number of parent directories to search relative to the current module.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000230
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000231
Guido van Rossum79f25d91997-04-29 20:08:16 +0000232static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000233builtin_abs(PyObject *self, PyObject *v)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000234{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000235 return PyNumber_Absolute(v);
Guido van Rossum3f5da241990-12-20 15:06:42 +0000236}
237
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000238PyDoc_STRVAR(abs_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000239"abs(number) -> number\n\
240\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000241Return the absolute value of the argument.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000242
Raymond Hettinger96229b12005-03-11 06:49:40 +0000243static PyObject *
244builtin_all(PyObject *self, PyObject *v)
245{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000246 PyObject *it, *item;
247 PyObject *(*iternext)(PyObject *);
248 int cmp;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000249
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000250 it = PyObject_GetIter(v);
251 if (it == NULL)
252 return NULL;
253 iternext = *Py_TYPE(it)->tp_iternext;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000254
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000255 for (;;) {
256 item = iternext(it);
257 if (item == NULL)
258 break;
259 cmp = PyObject_IsTrue(item);
260 Py_DECREF(item);
261 if (cmp < 0) {
262 Py_DECREF(it);
263 return NULL;
264 }
265 if (cmp == 0) {
266 Py_DECREF(it);
267 Py_RETURN_FALSE;
268 }
269 }
270 Py_DECREF(it);
271 if (PyErr_Occurred()) {
272 if (PyErr_ExceptionMatches(PyExc_StopIteration))
273 PyErr_Clear();
274 else
275 return NULL;
276 }
277 Py_RETURN_TRUE;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000278}
279
280PyDoc_STRVAR(all_doc,
281"all(iterable) -> bool\n\
282\n\
Ezio Melottib19ed572013-02-15 23:35:14 +0200283Return True if bool(x) is True for all values x in the iterable.\n\
284If the iterable is empty, return True.");
Raymond Hettinger96229b12005-03-11 06:49:40 +0000285
286static PyObject *
287builtin_any(PyObject *self, PyObject *v)
288{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000289 PyObject *it, *item;
290 PyObject *(*iternext)(PyObject *);
291 int cmp;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000292
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000293 it = PyObject_GetIter(v);
294 if (it == NULL)
295 return NULL;
296 iternext = *Py_TYPE(it)->tp_iternext;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000297
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000298 for (;;) {
299 item = iternext(it);
300 if (item == NULL)
301 break;
302 cmp = PyObject_IsTrue(item);
303 Py_DECREF(item);
304 if (cmp < 0) {
305 Py_DECREF(it);
306 return NULL;
307 }
308 if (cmp == 1) {
309 Py_DECREF(it);
310 Py_RETURN_TRUE;
311 }
312 }
313 Py_DECREF(it);
314 if (PyErr_Occurred()) {
315 if (PyErr_ExceptionMatches(PyExc_StopIteration))
316 PyErr_Clear();
317 else
318 return NULL;
319 }
320 Py_RETURN_FALSE;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000321}
322
323PyDoc_STRVAR(any_doc,
324"any(iterable) -> bool\n\
325\n\
Ezio Melottib19ed572013-02-15 23:35:14 +0200326Return True if bool(x) is True for any x in the iterable.\n\
327If the iterable is empty, return False.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000328
Georg Brandl559e5d72008-06-11 18:37:52 +0000329static PyObject *
330builtin_ascii(PyObject *self, PyObject *v)
331{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000332 return PyObject_ASCII(v);
Georg Brandl559e5d72008-06-11 18:37:52 +0000333}
334
335PyDoc_STRVAR(ascii_doc,
336"ascii(object) -> string\n\
337\n\
338As repr(), return a string containing a printable representation of an\n\
339object, but escape the non-ASCII characters in the string returned by\n\
340repr() using \\x, \\u or \\U escapes. This generates a string similar\n\
341to that returned by repr() in Python 2.");
342
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000343
Guido van Rossum79f25d91997-04-29 20:08:16 +0000344static PyObject *
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000345builtin_bin(PyObject *self, PyObject *v)
346{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000347 return PyNumber_ToBase(v, 2);
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000348}
349
350PyDoc_STRVAR(bin_doc,
351"bin(number) -> string\n\
352\n\
Zachary Warea4b7a752013-11-24 01:19:09 -0600353Return the binary representation of an integer.\n\
354\n\
355 >>> bin(2796202)\n\
356 '0b1010101010101010101010'\n\
357");
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000358
359
Antoine Pitroue71362d2010-11-27 22:00:11 +0000360static PyObject *
361builtin_callable(PyObject *self, PyObject *v)
362{
363 return PyBool_FromLong((long)PyCallable_Check(v));
364}
365
366PyDoc_STRVAR(callable_doc,
367"callable(object) -> bool\n\
368\n\
369Return whether the object is callable (i.e., some kind of function).\n\
370Note that classes are callable, as are instances of classes with a\n\
371__call__() method.");
372
373
Raymond Hettinger17301e92008-03-13 00:19:26 +0000374typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000375 PyObject_HEAD
376 PyObject *func;
377 PyObject *it;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000378} filterobject;
379
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000380static PyObject *
Raymond Hettinger17301e92008-03-13 00:19:26 +0000381filter_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
Guido van Rossum12d12c51993-10-26 17:58:25 +0000382{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000383 PyObject *func, *seq;
384 PyObject *it;
385 filterobject *lz;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000386
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000387 if (type == &PyFilter_Type && !_PyArg_NoKeywords("filter()", kwds))
388 return NULL;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000389
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000390 if (!PyArg_UnpackTuple(args, "filter", 2, 2, &func, &seq))
391 return NULL;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000392
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000393 /* Get iterator. */
394 it = PyObject_GetIter(seq);
395 if (it == NULL)
396 return NULL;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000397
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000398 /* create filterobject structure */
399 lz = (filterobject *)type->tp_alloc(type, 0);
400 if (lz == NULL) {
401 Py_DECREF(it);
402 return NULL;
403 }
404 Py_INCREF(func);
405 lz->func = func;
406 lz->it = it;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000407
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000408 return (PyObject *)lz;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000409}
410
411static void
412filter_dealloc(filterobject *lz)
413{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000414 PyObject_GC_UnTrack(lz);
415 Py_XDECREF(lz->func);
416 Py_XDECREF(lz->it);
417 Py_TYPE(lz)->tp_free(lz);
Raymond Hettinger17301e92008-03-13 00:19:26 +0000418}
419
420static int
421filter_traverse(filterobject *lz, visitproc visit, void *arg)
422{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000423 Py_VISIT(lz->it);
424 Py_VISIT(lz->func);
425 return 0;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000426}
427
428static PyObject *
429filter_next(filterobject *lz)
430{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000431 PyObject *item;
432 PyObject *it = lz->it;
433 long ok;
434 PyObject *(*iternext)(PyObject *);
Raymond Hettinger17301e92008-03-13 00:19:26 +0000435
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000436 iternext = *Py_TYPE(it)->tp_iternext;
437 for (;;) {
438 item = iternext(it);
439 if (item == NULL)
440 return NULL;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000441
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000442 if (lz->func == Py_None || lz->func == (PyObject *)&PyBool_Type) {
443 ok = PyObject_IsTrue(item);
444 } else {
445 PyObject *good;
446 good = PyObject_CallFunctionObjArgs(lz->func,
447 item, NULL);
448 if (good == NULL) {
449 Py_DECREF(item);
450 return NULL;
451 }
452 ok = PyObject_IsTrue(good);
453 Py_DECREF(good);
454 }
Antoine Pitrou6f430e42012-08-15 23:18:25 +0200455 if (ok > 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000456 return item;
457 Py_DECREF(item);
Antoine Pitrou6f430e42012-08-15 23:18:25 +0200458 if (ok < 0)
459 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000460 }
Guido van Rossum12d12c51993-10-26 17:58:25 +0000461}
462
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +0000463static PyObject *
464filter_reduce(filterobject *lz)
465{
466 return Py_BuildValue("O(OO)", Py_TYPE(lz), lz->func, lz->it);
467}
468
469PyDoc_STRVAR(reduce_doc, "Return state information for pickling.");
470
471static PyMethodDef filter_methods[] = {
472 {"__reduce__", (PyCFunction)filter_reduce, METH_NOARGS, reduce_doc},
473 {NULL, NULL} /* sentinel */
474};
475
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000476PyDoc_STRVAR(filter_doc,
Georg Brandld11ae5d2008-05-16 13:27:32 +0000477"filter(function or None, iterable) --> filter object\n\
Guido van Rossumc1f779c2007-07-03 08:25:58 +0000478\n\
Georg Brandld11ae5d2008-05-16 13:27:32 +0000479Return an iterator yielding those items of iterable for which function(item)\n\
Raymond Hettinger17301e92008-03-13 00:19:26 +0000480is true. If function is None, return the items that are true.");
481
482PyTypeObject PyFilter_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000483 PyVarObject_HEAD_INIT(&PyType_Type, 0)
484 "filter", /* tp_name */
485 sizeof(filterobject), /* tp_basicsize */
486 0, /* tp_itemsize */
487 /* methods */
488 (destructor)filter_dealloc, /* tp_dealloc */
489 0, /* tp_print */
490 0, /* tp_getattr */
491 0, /* tp_setattr */
492 0, /* tp_reserved */
493 0, /* tp_repr */
494 0, /* tp_as_number */
495 0, /* tp_as_sequence */
496 0, /* tp_as_mapping */
497 0, /* tp_hash */
498 0, /* tp_call */
499 0, /* tp_str */
500 PyObject_GenericGetAttr, /* tp_getattro */
501 0, /* tp_setattro */
502 0, /* tp_as_buffer */
503 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
504 Py_TPFLAGS_BASETYPE, /* tp_flags */
505 filter_doc, /* tp_doc */
506 (traverseproc)filter_traverse, /* tp_traverse */
507 0, /* tp_clear */
508 0, /* tp_richcompare */
509 0, /* tp_weaklistoffset */
510 PyObject_SelfIter, /* tp_iter */
511 (iternextfunc)filter_next, /* tp_iternext */
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +0000512 filter_methods, /* tp_methods */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000513 0, /* tp_members */
514 0, /* tp_getset */
515 0, /* tp_base */
516 0, /* tp_dict */
517 0, /* tp_descr_get */
518 0, /* tp_descr_set */
519 0, /* tp_dictoffset */
520 0, /* tp_init */
521 PyType_GenericAlloc, /* tp_alloc */
522 filter_new, /* tp_new */
523 PyObject_GC_Del, /* tp_free */
Raymond Hettinger17301e92008-03-13 00:19:26 +0000524};
525
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000526
Eric Smith8c663262007-08-25 02:26:07 +0000527static PyObject *
528builtin_format(PyObject *self, PyObject *args)
529{
Christian Heimes94b7d3d2007-12-11 20:20:39 +0000530 PyObject *value;
Eric Smith8fd3eba2008-02-17 19:48:00 +0000531 PyObject *format_spec = NULL;
Eric Smith8c663262007-08-25 02:26:07 +0000532
Eric Smith8fd3eba2008-02-17 19:48:00 +0000533 if (!PyArg_ParseTuple(args, "O|U:format", &value, &format_spec))
Benjamin Petersona12d5c62012-01-03 16:47:22 -0600534 return NULL;
Eric Smith8c663262007-08-25 02:26:07 +0000535
Eric Smith8fd3eba2008-02-17 19:48:00 +0000536 return PyObject_Format(value, format_spec);
Eric Smith8c663262007-08-25 02:26:07 +0000537}
538
Eric Smith8c663262007-08-25 02:26:07 +0000539PyDoc_STRVAR(format_doc,
Eric Smith81936692007-08-31 01:14:01 +0000540"format(value[, format_spec]) -> string\n\
Eric Smith8c663262007-08-25 02:26:07 +0000541\n\
Eric Smith81936692007-08-31 01:14:01 +0000542Returns value.__format__(format_spec)\n\
543format_spec defaults to \"\"");
544
Guido van Rossum7fcf2242007-05-04 17:43:11 +0000545static PyObject *
Walter Dörwalde7efd592007-06-05 20:07:21 +0000546builtin_chr(PyObject *self, PyObject *args)
Guido van Rossum09095f32000-03-10 23:00:52 +0000547{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000548 int x;
Guido van Rossum09095f32000-03-10 23:00:52 +0000549
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000550 if (!PyArg_ParseTuple(args, "i:chr", &x))
551 return NULL;
Fredrik Lundh0dcf67e2001-06-26 20:01:56 +0000552
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000553 return PyUnicode_FromOrdinal(x);
Guido van Rossum09095f32000-03-10 23:00:52 +0000554}
555
Victor Stinner63ab8752011-11-22 03:31:20 +0100556PyDoc_STRVAR(chr_doc,
Guido van Rossum84fc66d2007-05-03 17:18:26 +0000557"chr(i) -> Unicode character\n\
Guido van Rossum09095f32000-03-10 23:00:52 +0000558\n\
Victor Stinner63ab8752011-11-22 03:31:20 +0100559Return a Unicode string of one character with ordinal i; 0 <= i <= 0x10ffff.");
Guido van Rossum09095f32000-03-10 23:00:52 +0000560
561
Guido van Rossumf15a29f2007-05-04 00:41:39 +0000562static char *
Benjamin Petersonf5b52242009-03-02 23:31:26 +0000563source_as_string(PyObject *cmd, char *funcname, char *what, PyCompilerFlags *cf)
Guido van Rossumf15a29f2007-05-04 00:41:39 +0000564{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000565 char *str;
566 Py_ssize_t size;
Guido van Rossumf15a29f2007-05-04 00:41:39 +0000567
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000568 if (PyUnicode_Check(cmd)) {
569 cf->cf_flags |= PyCF_IGNORE_COOKIE;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200570 str = PyUnicode_AsUTF8AndSize(cmd, &size);
571 if (str == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000572 return NULL;
573 }
574 else if (!PyObject_CheckReadBuffer(cmd)) {
575 PyErr_Format(PyExc_TypeError,
576 "%s() arg 1 must be a %s object",
577 funcname, what);
578 return NULL;
579 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200580 else if (PyObject_AsReadBuffer(cmd, (const void **)&str, &size) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000581 return NULL;
582 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200583
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000584 if (strlen(str) != size) {
585 PyErr_SetString(PyExc_TypeError,
586 "source code string cannot contain null bytes");
587 return NULL;
588 }
589 return str;
Guido van Rossumf15a29f2007-05-04 00:41:39 +0000590}
591
Guido van Rossum79f25d91997-04-29 20:08:16 +0000592static PyObject *
Guido van Rossumd8faa362007-04-27 19:54:29 +0000593builtin_compile(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum5b722181993-03-30 17:46:03 +0000594{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000595 char *str;
Victor Stinner14e461d2013-08-26 22:28:21 +0200596 PyObject *filename;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000597 char *startstr;
598 int mode = -1;
599 int dont_inherit = 0;
600 int supplied_flags = 0;
Georg Brandl8334fd92010-12-04 10:26:46 +0000601 int optimize = -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000602 int is_ast;
603 PyCompilerFlags cf;
604 PyObject *cmd;
605 static char *kwlist[] = {"source", "filename", "mode", "flags",
Georg Brandl8334fd92010-12-04 10:26:46 +0000606 "dont_inherit", "optimize", NULL};
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000607 int start[] = {Py_file_input, Py_eval_input, Py_single_input};
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000608 PyObject *result;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000609
Georg Brandl8334fd92010-12-04 10:26:46 +0000610 if (!PyArg_ParseTupleAndKeywords(args, kwds, "OO&s|iii:compile", kwlist,
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000611 &cmd,
Victor Stinner14e461d2013-08-26 22:28:21 +0200612 PyUnicode_FSDecoder, &filename,
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000613 &startstr, &supplied_flags,
Georg Brandl8334fd92010-12-04 10:26:46 +0000614 &dont_inherit, &optimize))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000615 return NULL;
Tim Peters6cd6a822001-08-17 22:11:27 +0000616
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000617 cf.cf_flags = supplied_flags | PyCF_SOURCE_IS_UTF8;
Just van Rossum3aaf42c2003-02-10 08:21:10 +0000618
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000619 if (supplied_flags &
620 ~(PyCF_MASK | PyCF_MASK_OBSOLETE | PyCF_DONT_IMPLY_DEDENT | PyCF_ONLY_AST))
621 {
622 PyErr_SetString(PyExc_ValueError,
623 "compile(): unrecognised flags");
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000624 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000625 }
626 /* XXX Warn if (supplied_flags & PyCF_MASK_OBSOLETE) != 0? */
Tim Peters6cd6a822001-08-17 22:11:27 +0000627
Georg Brandl8334fd92010-12-04 10:26:46 +0000628 if (optimize < -1 || optimize > 2) {
629 PyErr_SetString(PyExc_ValueError,
630 "compile(): invalid optimize value");
631 goto error;
632 }
633
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000634 if (!dont_inherit) {
635 PyEval_MergeCompilerFlags(&cf);
636 }
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000637
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000638 if (strcmp(startstr, "exec") == 0)
639 mode = 0;
640 else if (strcmp(startstr, "eval") == 0)
641 mode = 1;
642 else if (strcmp(startstr, "single") == 0)
643 mode = 2;
644 else {
645 PyErr_SetString(PyExc_ValueError,
646 "compile() arg 3 must be 'exec', 'eval' or 'single'");
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000647 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000648 }
Neal Norwitzdb4115f2008-03-31 04:20:05 +0000649
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000650 is_ast = PyAST_Check(cmd);
651 if (is_ast == -1)
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000652 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000653 if (is_ast) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000654 if (supplied_flags & PyCF_ONLY_AST) {
655 Py_INCREF(cmd);
656 result = cmd;
657 }
658 else {
659 PyArena *arena;
660 mod_ty mod;
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000661
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000662 arena = PyArena_New();
Stefan Krah07795df2012-08-20 17:19:50 +0200663 if (arena == NULL)
664 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000665 mod = PyAST_obj2mod(cmd, arena, mode);
666 if (mod == NULL) {
667 PyArena_Free(arena);
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000668 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000669 }
Benjamin Peterson832bfe22011-08-09 16:15:04 -0500670 if (!PyAST_Validate(mod)) {
671 PyArena_Free(arena);
672 goto error;
673 }
Victor Stinner14e461d2013-08-26 22:28:21 +0200674 result = (PyObject*)PyAST_CompileObject(mod, filename,
675 &cf, optimize, arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000676 PyArena_Free(arena);
677 }
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000678 goto finally;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000679 }
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000680
Philip Jenveyf76f0ee2012-12-13 15:44:18 -0800681 str = source_as_string(cmd, "compile", "string, bytes or AST", &cf);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000682 if (str == NULL)
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000683 goto error;
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000684
Victor Stinner14e461d2013-08-26 22:28:21 +0200685 result = Py_CompileStringObject(str, filename, start[mode], &cf, optimize);
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000686 goto finally;
687
688error:
689 result = NULL;
690finally:
Victor Stinner14e461d2013-08-26 22:28:21 +0200691 Py_DECREF(filename);
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000692 return result;
Guido van Rossum5b722181993-03-30 17:46:03 +0000693}
694
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000695PyDoc_STRVAR(compile_doc,
Tim Peters6cd6a822001-08-17 22:11:27 +0000696"compile(source, filename, mode[, flags[, dont_inherit]]) -> code object\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000697\n\
Benjamin Peterson933142a2013-12-06 20:12:39 -0500698Compile the source (a Python module, statement or expression)\n\
Georg Brandl7cae87c2006-09-06 06:51:57 +0000699into a code object that can be executed by exec() or eval().\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000700The filename will be used for run-time error messages.\n\
701The mode must be 'exec' to compile a module, 'single' to compile a\n\
Tim Peters6cd6a822001-08-17 22:11:27 +0000702single (interactive) statement, or 'eval' to compile an expression.\n\
703The flags argument, if present, controls which future statements influence\n\
704the compilation of the code.\n\
705The dont_inherit argument, if non-zero, stops the compilation inheriting\n\
706the effects of any future statements in effect in the code calling\n\
707compile; if absent or zero these statements do influence the compilation,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000708in addition to any features explicitly specified.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000709
Guido van Rossum79f25d91997-04-29 20:08:16 +0000710static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000711builtin_dir(PyObject *self, PyObject *args)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000712{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000713 PyObject *arg = NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000714
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000715 if (!PyArg_UnpackTuple(args, "dir", 0, 1, &arg))
716 return NULL;
717 return PyObject_Dir(arg);
Guido van Rossum3f5da241990-12-20 15:06:42 +0000718}
719
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000720PyDoc_STRVAR(dir_doc,
Tim Peters5d2b77c2001-09-03 05:47:38 +0000721"dir([object]) -> list of strings\n"
722"\n"
Georg Brandle32b4222007-03-10 22:13:27 +0000723"If called without an argument, return the names in the current scope.\n"
724"Else, return an alphabetized list of names comprising (some of) the attributes\n"
725"of the given object, and of attributes reachable from it.\n"
726"If the object supplies a method named __dir__, it will be used; otherwise\n"
727"the default dir() logic is used and returns:\n"
728" for a module object: the module's attributes.\n"
729" for a class object: its attributes, and recursively the attributes\n"
730" of its bases.\n"
Guido van Rossumd8faa362007-04-27 19:54:29 +0000731" for any other object: its attributes, its class's attributes, and\n"
Georg Brandle32b4222007-03-10 22:13:27 +0000732" recursively the attributes of its class's base classes.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000733
Guido van Rossum79f25d91997-04-29 20:08:16 +0000734static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000735builtin_divmod(PyObject *self, PyObject *args)
Guido van Rossum6a00cd81995-01-07 12:39:01 +0000736{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000737 PyObject *v, *w;
Guido van Rossum6a00cd81995-01-07 12:39:01 +0000738
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000739 if (!PyArg_UnpackTuple(args, "divmod", 2, 2, &v, &w))
740 return NULL;
741 return PyNumber_Divmod(v, w);
Guido van Rossum3f5da241990-12-20 15:06:42 +0000742}
743
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000744PyDoc_STRVAR(divmod_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000745"divmod(x, y) -> (div, mod)\n\
746\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000747Return the tuple ((x-x%y)/y, x%y). Invariant: div*y + mod == x.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000748
749
Guido van Rossum79f25d91997-04-29 20:08:16 +0000750static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000751builtin_eval(PyObject *self, PyObject *args)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000752{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000753 PyObject *cmd, *result, *tmp = NULL;
754 PyObject *globals = Py_None, *locals = Py_None;
755 char *str;
756 PyCompilerFlags cf;
Guido van Rossum590baa41993-11-30 13:40:46 +0000757
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000758 if (!PyArg_UnpackTuple(args, "eval", 1, 3, &cmd, &globals, &locals))
759 return NULL;
760 if (locals != Py_None && !PyMapping_Check(locals)) {
761 PyErr_SetString(PyExc_TypeError, "locals must be a mapping");
762 return NULL;
763 }
764 if (globals != Py_None && !PyDict_Check(globals)) {
765 PyErr_SetString(PyExc_TypeError, PyMapping_Check(globals) ?
766 "globals must be a real dict; try eval(expr, {}, mapping)"
767 : "globals must be a dict");
768 return NULL;
769 }
770 if (globals == Py_None) {
771 globals = PyEval_GetGlobals();
Victor Stinner41bb43a2013-10-29 01:19:37 +0100772 if (locals == Py_None) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000773 locals = PyEval_GetLocals();
Victor Stinner41bb43a2013-10-29 01:19:37 +0100774 if (locals == NULL)
775 return NULL;
776 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000777 }
778 else if (locals == Py_None)
779 locals = globals;
Tim Peters9fa96be2001-08-17 23:04:59 +0000780
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000781 if (globals == NULL || locals == NULL) {
782 PyErr_SetString(PyExc_TypeError,
783 "eval must be given globals and locals "
784 "when called without a frame");
785 return NULL;
786 }
Georg Brandl77c85e62005-09-15 10:46:13 +0000787
Victor Stinnerb44562b2013-11-06 19:03:11 +0100788 if (_PyDict_GetItemId(globals, &PyId___builtins__) == NULL) {
789 if (_PyDict_SetItemId(globals, &PyId___builtins__,
790 PyEval_GetBuiltins()) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000791 return NULL;
792 }
Tim Peters9fa96be2001-08-17 23:04:59 +0000793
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000794 if (PyCode_Check(cmd)) {
795 if (PyCode_GetNumFree((PyCodeObject *)cmd) > 0) {
796 PyErr_SetString(PyExc_TypeError,
797 "code object passed to eval() may not contain free variables");
798 return NULL;
799 }
Martin v. Löwis4d0d4712010-12-03 20:14:31 +0000800 return PyEval_EvalCode(cmd, globals, locals);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000801 }
Tim Peters9fa96be2001-08-17 23:04:59 +0000802
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000803 cf.cf_flags = PyCF_SOURCE_IS_UTF8;
804 str = source_as_string(cmd, "eval", "string, bytes or code", &cf);
805 if (str == NULL)
806 return NULL;
Just van Rossum3aaf42c2003-02-10 08:21:10 +0000807
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000808 while (*str == ' ' || *str == '\t')
809 str++;
Tim Peters9fa96be2001-08-17 23:04:59 +0000810
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000811 (void)PyEval_MergeCompilerFlags(&cf);
812 result = PyRun_StringFlags(str, Py_eval_input, globals, locals, &cf);
813 Py_XDECREF(tmp);
814 return result;
Guido van Rossum3f5da241990-12-20 15:06:42 +0000815}
816
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000817PyDoc_STRVAR(eval_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000818"eval(source[, globals[, locals]]) -> value\n\
819\n\
820Evaluate the source in the context of globals and locals.\n\
821The source may be a string representing a Python expression\n\
822or a code object as returned by compile().\n\
Thomas Wouters89f507f2006-12-13 04:49:30 +0000823The globals must be a dictionary and locals can be any mapping,\n\
Raymond Hettinger214b1c32004-07-02 06:41:07 +0000824defaulting to the current globals and locals.\n\
825If only globals is given, locals defaults to it.\n");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000826
Georg Brandl7cae87c2006-09-06 06:51:57 +0000827static PyObject *
828builtin_exec(PyObject *self, PyObject *args)
829{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000830 PyObject *v;
831 PyObject *prog, *globals = Py_None, *locals = Py_None;
Georg Brandl7cae87c2006-09-06 06:51:57 +0000832
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000833 if (!PyArg_UnpackTuple(args, "exec", 1, 3, &prog, &globals, &locals))
834 return NULL;
Georg Brandl2cabc562008-08-28 07:57:16 +0000835
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000836 if (globals == Py_None) {
837 globals = PyEval_GetGlobals();
838 if (locals == Py_None) {
839 locals = PyEval_GetLocals();
Victor Stinner41bb43a2013-10-29 01:19:37 +0100840 if (locals == NULL)
841 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000842 }
843 if (!globals || !locals) {
844 PyErr_SetString(PyExc_SystemError,
845 "globals and locals cannot be NULL");
846 return NULL;
847 }
848 }
849 else if (locals == Py_None)
850 locals = globals;
Georg Brandl7cae87c2006-09-06 06:51:57 +0000851
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000852 if (!PyDict_Check(globals)) {
853 PyErr_Format(PyExc_TypeError, "exec() arg 2 must be a dict, not %.100s",
854 globals->ob_type->tp_name);
855 return NULL;
856 }
857 if (!PyMapping_Check(locals)) {
858 PyErr_Format(PyExc_TypeError,
859 "arg 3 must be a mapping or None, not %.100s",
860 locals->ob_type->tp_name);
861 return NULL;
862 }
Victor Stinnerb44562b2013-11-06 19:03:11 +0100863 if (_PyDict_GetItemId(globals, &PyId___builtins__) == NULL) {
864 if (_PyDict_SetItemId(globals, &PyId___builtins__,
865 PyEval_GetBuiltins()) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000866 return NULL;
867 }
868
869 if (PyCode_Check(prog)) {
870 if (PyCode_GetNumFree((PyCodeObject *)prog) > 0) {
871 PyErr_SetString(PyExc_TypeError,
872 "code object passed to exec() may not "
873 "contain free variables");
874 return NULL;
875 }
Martin v. Löwis4d0d4712010-12-03 20:14:31 +0000876 v = PyEval_EvalCode(prog, globals, locals);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000877 }
878 else {
879 char *str;
880 PyCompilerFlags cf;
881 cf.cf_flags = PyCF_SOURCE_IS_UTF8;
882 str = source_as_string(prog, "exec",
883 "string, bytes or code", &cf);
884 if (str == NULL)
885 return NULL;
886 if (PyEval_MergeCompilerFlags(&cf))
887 v = PyRun_StringFlags(str, Py_file_input, globals,
888 locals, &cf);
889 else
890 v = PyRun_String(str, Py_file_input, globals, locals);
891 }
892 if (v == NULL)
893 return NULL;
894 Py_DECREF(v);
895 Py_RETURN_NONE;
Georg Brandl7cae87c2006-09-06 06:51:57 +0000896}
897
898PyDoc_STRVAR(exec_doc,
899"exec(object[, globals[, locals]])\n\
900\n\
Mark Dickinson480e8e32009-12-19 21:19:35 +0000901Read and execute code from an object, which can be a string or a code\n\
Benjamin Peterson38090262009-01-04 15:30:39 +0000902object.\n\
Georg Brandl7cae87c2006-09-06 06:51:57 +0000903The globals and locals are dictionaries, defaulting to the current\n\
904globals and locals. If only globals is given, locals defaults to it.");
905
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000906
Guido van Rossum79f25d91997-04-29 20:08:16 +0000907static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000908builtin_getattr(PyObject *self, PyObject *args)
Guido van Rossum33894be1992-01-27 16:53:09 +0000909{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000910 PyObject *v, *result, *dflt = NULL;
911 PyObject *name;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000912
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000913 if (!PyArg_UnpackTuple(args, "getattr", 2, 3, &v, &name, &dflt))
914 return NULL;
Martin v. Löwis5b222132007-06-10 09:51:05 +0000915
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000916 if (!PyUnicode_Check(name)) {
917 PyErr_SetString(PyExc_TypeError,
918 "getattr(): attribute name must be string");
919 return NULL;
920 }
921 result = PyObject_GetAttr(v, name);
922 if (result == NULL && dflt != NULL &&
923 PyErr_ExceptionMatches(PyExc_AttributeError))
924 {
925 PyErr_Clear();
926 Py_INCREF(dflt);
927 result = dflt;
928 }
929 return result;
Guido van Rossum9bfef441993-03-29 10:43:31 +0000930}
931
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000932PyDoc_STRVAR(getattr_doc,
Guido van Rossum950ff291998-06-29 13:38:57 +0000933"getattr(object, name[, default]) -> value\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000934\n\
Guido van Rossum950ff291998-06-29 13:38:57 +0000935Get a named attribute from an object; getattr(x, 'y') is equivalent to x.y.\n\
936When a default argument is given, it is returned when the attribute doesn't\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000937exist; without it, an exception is raised in that case.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000938
939
Guido van Rossum79f25d91997-04-29 20:08:16 +0000940static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000941builtin_globals(PyObject *self)
Guido van Rossum872537c1995-07-07 22:43:42 +0000942{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000943 PyObject *d;
Guido van Rossum872537c1995-07-07 22:43:42 +0000944
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000945 d = PyEval_GetGlobals();
946 Py_XINCREF(d);
947 return d;
Guido van Rossum872537c1995-07-07 22:43:42 +0000948}
949
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000950PyDoc_STRVAR(globals_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000951"globals() -> dictionary\n\
952\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000953Return the dictionary containing the current scope's global variables.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000954
955
Guido van Rossum79f25d91997-04-29 20:08:16 +0000956static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000957builtin_hasattr(PyObject *self, PyObject *args)
Guido van Rossum9bfef441993-03-29 10:43:31 +0000958{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000959 PyObject *v;
960 PyObject *name;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000961
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000962 if (!PyArg_UnpackTuple(args, "hasattr", 2, 2, &v, &name))
963 return NULL;
964 if (!PyUnicode_Check(name)) {
965 PyErr_SetString(PyExc_TypeError,
966 "hasattr(): attribute name must be string");
967 return NULL;
968 }
969 v = PyObject_GetAttr(v, name);
970 if (v == NULL) {
Benjamin Peterson17689992010-08-24 03:26:23 +0000971 if (PyErr_ExceptionMatches(PyExc_AttributeError)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000972 PyErr_Clear();
Benjamin Peterson17689992010-08-24 03:26:23 +0000973 Py_RETURN_FALSE;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000974 }
Benjamin Peterson17689992010-08-24 03:26:23 +0000975 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000976 }
977 Py_DECREF(v);
Benjamin Peterson17689992010-08-24 03:26:23 +0000978 Py_RETURN_TRUE;
Guido van Rossum33894be1992-01-27 16:53:09 +0000979}
980
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000981PyDoc_STRVAR(hasattr_doc,
Guido van Rossum77f6a652002-04-03 22:41:51 +0000982"hasattr(object, name) -> bool\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000983\n\
984Return whether the object has an attribute with the given name.\n\
Benjamin Peterson17689992010-08-24 03:26:23 +0000985(This is done by calling getattr(object, name) and catching AttributeError.)");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000986
987
Guido van Rossum79f25d91997-04-29 20:08:16 +0000988static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000989builtin_id(PyObject *self, PyObject *v)
Guido van Rossum5b722181993-03-30 17:46:03 +0000990{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000991 return PyLong_FromVoidPtr(v);
Guido van Rossum5b722181993-03-30 17:46:03 +0000992}
993
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000994PyDoc_STRVAR(id_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000995"id(object) -> integer\n\
996\n\
997Return the identity of an object. This is guaranteed to be unique among\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000998simultaneously existing objects. (Hint: it's the object's memory address.)");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000999
1000
Raymond Hettingera6c60372008-03-13 01:26:19 +00001001/* map object ************************************************************/
1002
1003typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001004 PyObject_HEAD
1005 PyObject *iters;
1006 PyObject *func;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001007} mapobject;
1008
Guido van Rossum79f25d91997-04-29 20:08:16 +00001009static PyObject *
Raymond Hettingera6c60372008-03-13 01:26:19 +00001010map_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
Guido van Rossum12d12c51993-10-26 17:58:25 +00001011{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001012 PyObject *it, *iters, *func;
1013 mapobject *lz;
1014 Py_ssize_t numargs, i;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001015
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001016 if (type == &PyMap_Type && !_PyArg_NoKeywords("map()", kwds))
1017 return NULL;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001018
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001019 numargs = PyTuple_Size(args);
1020 if (numargs < 2) {
1021 PyErr_SetString(PyExc_TypeError,
1022 "map() must have at least two arguments.");
1023 return NULL;
1024 }
Raymond Hettingera6c60372008-03-13 01:26:19 +00001025
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001026 iters = PyTuple_New(numargs-1);
1027 if (iters == NULL)
1028 return NULL;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001029
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001030 for (i=1 ; i<numargs ; i++) {
1031 /* Get iterator. */
1032 it = PyObject_GetIter(PyTuple_GET_ITEM(args, i));
1033 if (it == NULL) {
1034 Py_DECREF(iters);
1035 return NULL;
1036 }
1037 PyTuple_SET_ITEM(iters, i-1, it);
1038 }
Raymond Hettingera6c60372008-03-13 01:26:19 +00001039
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001040 /* create mapobject structure */
1041 lz = (mapobject *)type->tp_alloc(type, 0);
1042 if (lz == NULL) {
1043 Py_DECREF(iters);
1044 return NULL;
1045 }
1046 lz->iters = iters;
1047 func = PyTuple_GET_ITEM(args, 0);
1048 Py_INCREF(func);
1049 lz->func = func;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001050
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001051 return (PyObject *)lz;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001052}
1053
1054static void
1055map_dealloc(mapobject *lz)
1056{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001057 PyObject_GC_UnTrack(lz);
1058 Py_XDECREF(lz->iters);
1059 Py_XDECREF(lz->func);
1060 Py_TYPE(lz)->tp_free(lz);
Raymond Hettingera6c60372008-03-13 01:26:19 +00001061}
1062
1063static int
1064map_traverse(mapobject *lz, visitproc visit, void *arg)
1065{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001066 Py_VISIT(lz->iters);
1067 Py_VISIT(lz->func);
1068 return 0;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001069}
1070
1071static PyObject *
1072map_next(mapobject *lz)
1073{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001074 PyObject *val;
1075 PyObject *argtuple;
1076 PyObject *result;
1077 Py_ssize_t numargs, i;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001078
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001079 numargs = PyTuple_Size(lz->iters);
1080 argtuple = PyTuple_New(numargs);
1081 if (argtuple == NULL)
1082 return NULL;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001083
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001084 for (i=0 ; i<numargs ; i++) {
1085 val = PyIter_Next(PyTuple_GET_ITEM(lz->iters, i));
1086 if (val == NULL) {
1087 Py_DECREF(argtuple);
1088 return NULL;
1089 }
1090 PyTuple_SET_ITEM(argtuple, i, val);
1091 }
1092 result = PyObject_Call(lz->func, argtuple, NULL);
1093 Py_DECREF(argtuple);
1094 return result;
Guido van Rossum12d12c51993-10-26 17:58:25 +00001095}
1096
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001097static PyObject *
1098map_reduce(mapobject *lz)
1099{
1100 Py_ssize_t numargs = PyTuple_GET_SIZE(lz->iters);
1101 PyObject *args = PyTuple_New(numargs+1);
1102 Py_ssize_t i;
1103 if (args == NULL)
1104 return NULL;
1105 Py_INCREF(lz->func);
1106 PyTuple_SET_ITEM(args, 0, lz->func);
1107 for (i = 0; i<numargs; i++){
1108 PyObject *it = PyTuple_GET_ITEM(lz->iters, i);
1109 Py_INCREF(it);
1110 PyTuple_SET_ITEM(args, i+1, it);
1111 }
1112
1113 return Py_BuildValue("ON", Py_TYPE(lz), args);
1114}
1115
1116static PyMethodDef map_methods[] = {
1117 {"__reduce__", (PyCFunction)map_reduce, METH_NOARGS, reduce_doc},
1118 {NULL, NULL} /* sentinel */
1119};
1120
1121
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001122PyDoc_STRVAR(map_doc,
Raymond Hettingera6c60372008-03-13 01:26:19 +00001123"map(func, *iterables) --> map object\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001124\n\
Raymond Hettingera6c60372008-03-13 01:26:19 +00001125Make an iterator that computes the function using arguments from\n\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001126each of the iterables. Stops when the shortest iterable is exhausted.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001127
Raymond Hettingera6c60372008-03-13 01:26:19 +00001128PyTypeObject PyMap_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001129 PyVarObject_HEAD_INIT(&PyType_Type, 0)
1130 "map", /* tp_name */
1131 sizeof(mapobject), /* tp_basicsize */
1132 0, /* tp_itemsize */
1133 /* methods */
1134 (destructor)map_dealloc, /* tp_dealloc */
1135 0, /* tp_print */
1136 0, /* tp_getattr */
1137 0, /* tp_setattr */
1138 0, /* tp_reserved */
1139 0, /* tp_repr */
1140 0, /* tp_as_number */
1141 0, /* tp_as_sequence */
1142 0, /* tp_as_mapping */
1143 0, /* tp_hash */
1144 0, /* tp_call */
1145 0, /* tp_str */
1146 PyObject_GenericGetAttr, /* tp_getattro */
1147 0, /* tp_setattro */
1148 0, /* tp_as_buffer */
1149 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
1150 Py_TPFLAGS_BASETYPE, /* tp_flags */
1151 map_doc, /* tp_doc */
1152 (traverseproc)map_traverse, /* tp_traverse */
1153 0, /* tp_clear */
1154 0, /* tp_richcompare */
1155 0, /* tp_weaklistoffset */
1156 PyObject_SelfIter, /* tp_iter */
1157 (iternextfunc)map_next, /* tp_iternext */
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001158 map_methods, /* tp_methods */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001159 0, /* tp_members */
1160 0, /* tp_getset */
1161 0, /* tp_base */
1162 0, /* tp_dict */
1163 0, /* tp_descr_get */
1164 0, /* tp_descr_set */
1165 0, /* tp_dictoffset */
1166 0, /* tp_init */
1167 PyType_GenericAlloc, /* tp_alloc */
1168 map_new, /* tp_new */
1169 PyObject_GC_Del, /* tp_free */
Raymond Hettingera6c60372008-03-13 01:26:19 +00001170};
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001171
Guido van Rossum79f25d91997-04-29 20:08:16 +00001172static PyObject *
Georg Brandla18af4e2007-04-21 15:47:16 +00001173builtin_next(PyObject *self, PyObject *args)
1174{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001175 PyObject *it, *res;
1176 PyObject *def = NULL;
Georg Brandla18af4e2007-04-21 15:47:16 +00001177
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001178 if (!PyArg_UnpackTuple(args, "next", 1, 2, &it, &def))
1179 return NULL;
1180 if (!PyIter_Check(it)) {
1181 PyErr_Format(PyExc_TypeError,
Philip Jenvey50add042011-11-06 16:37:52 -08001182 "'%.200s' object is not an iterator",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001183 it->ob_type->tp_name);
1184 return NULL;
1185 }
1186
1187 res = (*it->ob_type->tp_iternext)(it);
1188 if (res != NULL) {
1189 return res;
1190 } else if (def != NULL) {
1191 if (PyErr_Occurred()) {
1192 if(!PyErr_ExceptionMatches(PyExc_StopIteration))
1193 return NULL;
1194 PyErr_Clear();
1195 }
1196 Py_INCREF(def);
1197 return def;
1198 } else if (PyErr_Occurred()) {
1199 return NULL;
1200 } else {
1201 PyErr_SetNone(PyExc_StopIteration);
1202 return NULL;
1203 }
Georg Brandla18af4e2007-04-21 15:47:16 +00001204}
1205
1206PyDoc_STRVAR(next_doc,
1207"next(iterator[, default])\n\
1208\n\
1209Return the next item from the iterator. If default is given and the iterator\n\
1210is exhausted, it is returned instead of raising StopIteration.");
1211
1212
1213static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001214builtin_setattr(PyObject *self, PyObject *args)
Guido van Rossum33894be1992-01-27 16:53:09 +00001215{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001216 PyObject *v;
1217 PyObject *name;
1218 PyObject *value;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001219
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001220 if (!PyArg_UnpackTuple(args, "setattr", 3, 3, &v, &name, &value))
1221 return NULL;
1222 if (PyObject_SetAttr(v, name, value) != 0)
1223 return NULL;
1224 Py_INCREF(Py_None);
1225 return Py_None;
Guido van Rossum33894be1992-01-27 16:53:09 +00001226}
1227
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001228PyDoc_STRVAR(setattr_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001229"setattr(object, name, value)\n\
1230\n\
1231Set a named attribute on an object; setattr(x, 'y', v) is equivalent to\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001232``x.y = v''.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001233
1234
Guido van Rossum79f25d91997-04-29 20:08:16 +00001235static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001236builtin_delattr(PyObject *self, PyObject *args)
Guido van Rossum14144fc1994-08-29 12:53:40 +00001237{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001238 PyObject *v;
1239 PyObject *name;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001240
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001241 if (!PyArg_UnpackTuple(args, "delattr", 2, 2, &v, &name))
1242 return NULL;
1243 if (PyObject_SetAttr(v, name, (PyObject *)NULL) != 0)
1244 return NULL;
1245 Py_INCREF(Py_None);
1246 return Py_None;
Guido van Rossum14144fc1994-08-29 12:53:40 +00001247}
1248
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001249PyDoc_STRVAR(delattr_doc,
Guido van Rossumdf12a591998-11-23 22:13:04 +00001250"delattr(object, name)\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001251\n\
1252Delete a named attribute on an object; delattr(x, 'y') is equivalent to\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001253``del x.y''.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001254
1255
Guido van Rossum79f25d91997-04-29 20:08:16 +00001256static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001257builtin_hash(PyObject *self, PyObject *v)
Guido van Rossum9bfef441993-03-29 10:43:31 +00001258{
Benjamin Peterson8f67d082010-10-17 20:54:53 +00001259 Py_hash_t x;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001260
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001261 x = PyObject_Hash(v);
1262 if (x == -1)
1263 return NULL;
Benjamin Peterson8f67d082010-10-17 20:54:53 +00001264 return PyLong_FromSsize_t(x);
Guido van Rossum9bfef441993-03-29 10:43:31 +00001265}
1266
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001267PyDoc_STRVAR(hash_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001268"hash(object) -> integer\n\
1269\n\
1270Return a hash value for the object. Two objects with the same value have\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001271the same hash value. The reverse is not necessarily true, but likely.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001272
1273
Guido van Rossum79f25d91997-04-29 20:08:16 +00001274static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001275builtin_hex(PyObject *self, PyObject *v)
Guido van Rossum006bcd41991-10-24 14:54:44 +00001276{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001277 return PyNumber_ToBase(v, 16);
Guido van Rossum006bcd41991-10-24 14:54:44 +00001278}
1279
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001280PyDoc_STRVAR(hex_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001281"hex(number) -> string\n\
1282\n\
Zachary Warea4b7a752013-11-24 01:19:09 -06001283Return the hexadecimal representation of an integer.\n\
1284\n\
1285 >>> hex(3735928559)\n\
1286 '0xdeadbeef'\n\
1287");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001288
1289
Guido van Rossum79f25d91997-04-29 20:08:16 +00001290static PyObject *
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001291builtin_iter(PyObject *self, PyObject *args)
1292{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001293 PyObject *v, *w = NULL;
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001294
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001295 if (!PyArg_UnpackTuple(args, "iter", 1, 2, &v, &w))
1296 return NULL;
1297 if (w == NULL)
1298 return PyObject_GetIter(v);
1299 if (!PyCallable_Check(v)) {
1300 PyErr_SetString(PyExc_TypeError,
1301 "iter(v, w): v must be callable");
1302 return NULL;
1303 }
1304 return PyCallIter_New(v, w);
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001305}
1306
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001307PyDoc_STRVAR(iter_doc,
Georg Brandld11ae5d2008-05-16 13:27:32 +00001308"iter(iterable) -> iterator\n\
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001309iter(callable, sentinel) -> iterator\n\
1310\n\
1311Get an iterator from an object. In the first form, the argument must\n\
1312supply its own iterator, or be a sequence.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001313In the second form, the callable is called until it returns the sentinel.");
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001314
1315
1316static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001317builtin_len(PyObject *self, PyObject *v)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001318{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001319 Py_ssize_t res;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001320
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001321 res = PyObject_Size(v);
1322 if (res < 0 && PyErr_Occurred())
1323 return NULL;
1324 return PyLong_FromSsize_t(res);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001325}
1326
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001327PyDoc_STRVAR(len_doc,
Benjamin Peterson5edbb7b2014-04-18 01:03:59 -04001328"len(object)\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001329\n\
Terry Jan Reedyf2fb73f2014-06-16 03:05:37 -04001330Return the number of items of a sequence or collection.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001331
1332
Guido van Rossum79f25d91997-04-29 20:08:16 +00001333static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001334builtin_locals(PyObject *self)
Guido van Rossum872537c1995-07-07 22:43:42 +00001335{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001336 PyObject *d;
Guido van Rossum872537c1995-07-07 22:43:42 +00001337
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001338 d = PyEval_GetLocals();
1339 Py_XINCREF(d);
1340 return d;
Guido van Rossum872537c1995-07-07 22:43:42 +00001341}
1342
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001343PyDoc_STRVAR(locals_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001344"locals() -> dictionary\n\
1345\n\
Raymond Hettinger69bf8f32003-01-04 02:16:22 +00001346Update and return a dictionary containing the current scope's local variables.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001347
1348
Guido van Rossum79f25d91997-04-29 20:08:16 +00001349static PyObject *
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001350min_max(PyObject *args, PyObject *kwds, int op)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001351{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001352 PyObject *v, *it, *item, *val, *maxitem, *maxval, *keyfunc=NULL;
Raymond Hettinger4d6018f2013-06-24 22:43:02 -07001353 PyObject *emptytuple, *defaultval = NULL;
1354 static char *kwlist[] = {"key", "default", NULL};
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001355 const char *name = op == Py_LT ? "min" : "max";
Raymond Hettinger4d6018f2013-06-24 22:43:02 -07001356 const int positional = PyTuple_Size(args) > 1;
1357 int ret;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001358
Raymond Hettinger4d6018f2013-06-24 22:43:02 -07001359 if (positional)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001360 v = args;
Serhiy Storchakac6792272013-10-19 21:03:34 +03001361 else if (!PyArg_UnpackTuple(args, name, 1, 1, &v))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001362 return NULL;
Tim Peters67d687a2002-04-29 21:27:32 +00001363
Raymond Hettinger4d6018f2013-06-24 22:43:02 -07001364 emptytuple = PyTuple_New(0);
1365 if (emptytuple == NULL)
1366 return NULL;
1367 ret = PyArg_ParseTupleAndKeywords(emptytuple, kwds, "|$OO", kwlist,
1368 &keyfunc, &defaultval);
1369 Py_DECREF(emptytuple);
1370 if (!ret)
1371 return NULL;
1372
1373 if (positional && defaultval != NULL) {
1374 PyErr_Format(PyExc_TypeError,
1375 "Cannot specify a default for %s() with multiple "
1376 "positional arguments", name);
1377 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001378 }
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001379
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001380 it = PyObject_GetIter(v);
1381 if (it == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001382 return NULL;
1383 }
Tim Petersc3074532001-05-03 07:00:32 +00001384
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001385 maxitem = NULL; /* the result */
1386 maxval = NULL; /* the value associated with the result */
1387 while (( item = PyIter_Next(it) )) {
1388 /* get the value from the key function */
1389 if (keyfunc != NULL) {
1390 val = PyObject_CallFunctionObjArgs(keyfunc, item, NULL);
1391 if (val == NULL)
1392 goto Fail_it_item;
1393 }
1394 /* no key function; the value is the item */
1395 else {
1396 val = item;
1397 Py_INCREF(val);
1398 }
Tim Petersc3074532001-05-03 07:00:32 +00001399
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001400 /* maximum value and item are unset; set them */
1401 if (maxval == NULL) {
1402 maxitem = item;
1403 maxval = val;
1404 }
1405 /* maximum value and item are set; update them as necessary */
1406 else {
1407 int cmp = PyObject_RichCompareBool(val, maxval, op);
1408 if (cmp < 0)
1409 goto Fail_it_item_and_val;
1410 else if (cmp > 0) {
1411 Py_DECREF(maxval);
1412 Py_DECREF(maxitem);
1413 maxval = val;
1414 maxitem = item;
1415 }
1416 else {
1417 Py_DECREF(item);
1418 Py_DECREF(val);
1419 }
1420 }
1421 }
1422 if (PyErr_Occurred())
1423 goto Fail_it;
1424 if (maxval == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001425 assert(maxitem == NULL);
Raymond Hettinger4d6018f2013-06-24 22:43:02 -07001426 if (defaultval != NULL) {
1427 Py_INCREF(defaultval);
1428 maxitem = defaultval;
1429 } else {
1430 PyErr_Format(PyExc_ValueError,
1431 "%s() arg is an empty sequence", name);
1432 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001433 }
1434 else
1435 Py_DECREF(maxval);
1436 Py_DECREF(it);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001437 return maxitem;
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001438
1439Fail_it_item_and_val:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001440 Py_DECREF(val);
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001441Fail_it_item:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001442 Py_DECREF(item);
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001443Fail_it:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001444 Py_XDECREF(maxval);
1445 Py_XDECREF(maxitem);
1446 Py_DECREF(it);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001447 return NULL;
Guido van Rossum3f5da241990-12-20 15:06:42 +00001448}
1449
Guido van Rossum79f25d91997-04-29 20:08:16 +00001450static PyObject *
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001451builtin_min(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001452{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001453 return min_max(args, kwds, Py_LT);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001454}
1455
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001456PyDoc_STRVAR(min_doc,
Raymond Hettinger2a545822014-05-19 22:20:52 +01001457"min(iterable, *[, default=obj, key=func]) -> value\n\
1458min(arg1, arg2, *args, *[, key=func]) -> value\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001459\n\
Raymond Hettinger2a545822014-05-19 22:20:52 +01001460With a single iterable argument, return its smallest item. The\n\
1461default keyword-only argument specifies an object to return if\n\
1462the provided iterable is empty.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001463With two or more arguments, return the smallest argument.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001464
1465
Guido van Rossum79f25d91997-04-29 20:08:16 +00001466static PyObject *
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001467builtin_max(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001468{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001469 return min_max(args, kwds, Py_GT);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001470}
1471
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001472PyDoc_STRVAR(max_doc,
Raymond Hettinger2a545822014-05-19 22:20:52 +01001473"max(iterable, *[, default=obj, key=func]) -> value\n\
1474max(arg1, arg2, *args, *[, key=func]) -> value\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001475\n\
Raymond Hettinger2a545822014-05-19 22:20:52 +01001476With a single iterable argument, return its biggest item. The\n\
1477default keyword-only argument specifies an object to return if\n\
1478the provided iterable is empty.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001479With two or more arguments, return the largest argument.");
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_oct(PyObject *self, PyObject *v)
Guido van Rossum006bcd41991-10-24 14:54:44 +00001484{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001485 return PyNumber_ToBase(v, 8);
Guido van Rossum006bcd41991-10-24 14:54:44 +00001486}
1487
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001488PyDoc_STRVAR(oct_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001489"oct(number) -> string\n\
1490\n\
Zachary Warea4b7a752013-11-24 01:19:09 -06001491Return the octal representation of an integer.\n\
1492\n\
1493 >>> oct(342391)\n\
1494 '0o1234567'\n\
1495");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001496
1497
Guido van Rossum79f25d91997-04-29 20:08:16 +00001498static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001499builtin_ord(PyObject *self, PyObject* obj)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001500{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001501 long ord;
1502 Py_ssize_t size;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001503
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001504 if (PyBytes_Check(obj)) {
1505 size = PyBytes_GET_SIZE(obj);
1506 if (size == 1) {
1507 ord = (long)((unsigned char)*PyBytes_AS_STRING(obj));
1508 return PyLong_FromLong(ord);
1509 }
1510 }
1511 else if (PyUnicode_Check(obj)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001512 if (PyUnicode_READY(obj) == -1)
1513 return NULL;
1514 size = PyUnicode_GET_LENGTH(obj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001515 if (size == 1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001516 ord = (long)PyUnicode_READ_CHAR(obj, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001517 return PyLong_FromLong(ord);
1518 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001519 }
1520 else if (PyByteArray_Check(obj)) {
1521 /* XXX Hopefully this is temporary */
1522 size = PyByteArray_GET_SIZE(obj);
1523 if (size == 1) {
1524 ord = (long)((unsigned char)*PyByteArray_AS_STRING(obj));
1525 return PyLong_FromLong(ord);
1526 }
1527 }
1528 else {
1529 PyErr_Format(PyExc_TypeError,
1530 "ord() expected string of length 1, but " \
1531 "%.200s found", obj->ob_type->tp_name);
1532 return NULL;
1533 }
Guido van Rossum09095f32000-03-10 23:00:52 +00001534
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001535 PyErr_Format(PyExc_TypeError,
1536 "ord() expected a character, "
1537 "but string of length %zd found",
1538 size);
1539 return NULL;
Guido van Rossum3f5da241990-12-20 15:06:42 +00001540}
1541
Guido van Rossum307fa8c2007-07-16 20:46:27 +00001542PyDoc_VAR(ord_doc) = PyDoc_STR(
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001543"ord(c) -> integer\n\
1544\n\
Guido van Rossum8ac004e2007-07-15 13:00:05 +00001545Return the integer ordinal of a one-character string."
Antoine Pitrouedc60182012-06-23 14:19:58 +02001546);
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001547
1548
Guido van Rossum79f25d91997-04-29 20:08:16 +00001549static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001550builtin_pow(PyObject *self, PyObject *args)
Guido van Rossum6a00cd81995-01-07 12:39:01 +00001551{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001552 PyObject *v, *w, *z = Py_None;
Guido van Rossum6a00cd81995-01-07 12:39:01 +00001553
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001554 if (!PyArg_UnpackTuple(args, "pow", 2, 3, &v, &w, &z))
1555 return NULL;
1556 return PyNumber_Power(v, w, z);
Guido van Rossumd4905451991-05-05 20:00:36 +00001557}
1558
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001559PyDoc_STRVAR(pow_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001560"pow(x, y[, z]) -> number\n\
1561\n\
1562With two arguments, equivalent to x**y. With three arguments,\n\
Serhiy Storchaka95949422013-08-27 19:40:23 +03001563equivalent to (x**y) % z, but may be more efficient (e.g. for ints).");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001564
1565
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001566
Guido van Rossum34343512006-11-30 22:13:52 +00001567static PyObject *
1568builtin_print(PyObject *self, PyObject *args, PyObject *kwds)
1569{
Georg Brandlbc3b6822012-01-13 19:41:25 +01001570 static char *kwlist[] = {"sep", "end", "file", "flush", 0};
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001571 static PyObject *dummy_args;
Georg Brandlbc3b6822012-01-13 19:41:25 +01001572 PyObject *sep = NULL, *end = NULL, *file = NULL, *flush = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001573 int i, err;
Guido van Rossum34343512006-11-30 22:13:52 +00001574
Benjamin Peterson00102562012-01-11 21:00:16 -05001575 if (dummy_args == NULL && !(dummy_args = PyTuple_New(0)))
Georg Brandlbc3b6822012-01-13 19:41:25 +01001576 return NULL;
1577 if (!PyArg_ParseTupleAndKeywords(dummy_args, kwds, "|OOOO:print",
1578 kwlist, &sep, &end, &file, &flush))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001579 return NULL;
1580 if (file == NULL || file == Py_None) {
Victor Stinnerbd303c12013-11-07 23:07:29 +01001581 file = _PySys_GetObjectId(&PyId_stdout);
Victor Stinner1e53bba2013-07-16 22:26:05 +02001582 if (file == NULL) {
1583 PyErr_SetString(PyExc_RuntimeError, "lost sys.stdout");
1584 return NULL;
1585 }
1586
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001587 /* sys.stdout may be None when FILE* stdout isn't connected */
1588 if (file == Py_None)
1589 Py_RETURN_NONE;
1590 }
Guido van Rossum34343512006-11-30 22:13:52 +00001591
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001592 if (sep == Py_None) {
1593 sep = NULL;
1594 }
1595 else if (sep && !PyUnicode_Check(sep)) {
1596 PyErr_Format(PyExc_TypeError,
1597 "sep must be None or a string, not %.200s",
1598 sep->ob_type->tp_name);
1599 return NULL;
1600 }
1601 if (end == Py_None) {
1602 end = NULL;
1603 }
1604 else if (end && !PyUnicode_Check(end)) {
1605 PyErr_Format(PyExc_TypeError,
1606 "end must be None or a string, not %.200s",
1607 end->ob_type->tp_name);
1608 return NULL;
1609 }
Guido van Rossum34343512006-11-30 22:13:52 +00001610
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001611 for (i = 0; i < PyTuple_Size(args); i++) {
1612 if (i > 0) {
1613 if (sep == NULL)
1614 err = PyFile_WriteString(" ", file);
1615 else
1616 err = PyFile_WriteObject(sep, file,
1617 Py_PRINT_RAW);
1618 if (err)
1619 return NULL;
1620 }
1621 err = PyFile_WriteObject(PyTuple_GetItem(args, i), file,
1622 Py_PRINT_RAW);
1623 if (err)
1624 return NULL;
1625 }
Guido van Rossum34343512006-11-30 22:13:52 +00001626
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001627 if (end == NULL)
1628 err = PyFile_WriteString("\n", file);
1629 else
1630 err = PyFile_WriteObject(end, file, Py_PRINT_RAW);
1631 if (err)
1632 return NULL;
Guido van Rossum34343512006-11-30 22:13:52 +00001633
Georg Brandlbc3b6822012-01-13 19:41:25 +01001634 if (flush != NULL) {
1635 PyObject *tmp;
1636 int do_flush = PyObject_IsTrue(flush);
1637 if (do_flush == -1)
1638 return NULL;
1639 else if (do_flush) {
Victor Stinnereaa28832013-11-07 00:01:51 +01001640 tmp = _PyObject_CallMethodId(file, &PyId_flush, "");
Georg Brandlbc3b6822012-01-13 19:41:25 +01001641 if (tmp == NULL)
1642 return NULL;
1643 else
1644 Py_DECREF(tmp);
1645 }
1646 }
1647
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001648 Py_RETURN_NONE;
Guido van Rossum34343512006-11-30 22:13:52 +00001649}
1650
1651PyDoc_STRVAR(print_doc,
Senthil Kumarane9175bd2012-08-10 13:53:45 -07001652"print(value, ..., sep=' ', end='\\n', file=sys.stdout, flush=False)\n\
Guido van Rossum34343512006-11-30 22:13:52 +00001653\n\
1654Prints the values to a stream, or to sys.stdout by default.\n\
1655Optional keyword arguments:\n\
Senthil Kumarane9175bd2012-08-10 13:53:45 -07001656file: a file-like object (stream); defaults to the current sys.stdout.\n\
1657sep: string inserted between values, default a space.\n\
1658end: string appended after the last value, default a newline.\n\
1659flush: whether to forcibly flush the stream.");
Guido van Rossum34343512006-11-30 22:13:52 +00001660
1661
Guido van Rossuma88a0332007-02-26 16:59:55 +00001662static PyObject *
1663builtin_input(PyObject *self, PyObject *args)
1664{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001665 PyObject *promptarg = NULL;
Victor Stinnerbd303c12013-11-07 23:07:29 +01001666 PyObject *fin = _PySys_GetObjectId(&PyId_stdin);
1667 PyObject *fout = _PySys_GetObjectId(&PyId_stdout);
1668 PyObject *ferr = _PySys_GetObjectId(&PyId_stderr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001669 PyObject *tmp;
1670 long fd;
1671 int tty;
Guido van Rossuma88a0332007-02-26 16:59:55 +00001672
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001673 /* Parse arguments */
1674 if (!PyArg_UnpackTuple(args, "input", 0, 1, &promptarg))
1675 return NULL;
Guido van Rossuma88a0332007-02-26 16:59:55 +00001676
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001677 /* Check that stdin/out/err are intact */
1678 if (fin == NULL || fin == Py_None) {
1679 PyErr_SetString(PyExc_RuntimeError,
1680 "input(): lost sys.stdin");
1681 return NULL;
1682 }
1683 if (fout == NULL || fout == Py_None) {
1684 PyErr_SetString(PyExc_RuntimeError,
1685 "input(): lost sys.stdout");
1686 return NULL;
1687 }
1688 if (ferr == NULL || ferr == Py_None) {
1689 PyErr_SetString(PyExc_RuntimeError,
1690 "input(): lost sys.stderr");
1691 return NULL;
1692 }
Guido van Rossumeba76962007-05-27 09:13:28 +00001693
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001694 /* First of all, flush stderr */
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001695 tmp = _PyObject_CallMethodId(ferr, &PyId_flush, "");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001696 if (tmp == NULL)
1697 PyErr_Clear();
1698 else
1699 Py_DECREF(tmp);
Guido van Rossumeba76962007-05-27 09:13:28 +00001700
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001701 /* We should only use (GNU) readline if Python's sys.stdin and
1702 sys.stdout are the same as C's stdin and stdout, because we
1703 need to pass it those. */
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001704 tmp = _PyObject_CallMethodId(fin, &PyId_fileno, "");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001705 if (tmp == NULL) {
1706 PyErr_Clear();
1707 tty = 0;
1708 }
1709 else {
1710 fd = PyLong_AsLong(tmp);
1711 Py_DECREF(tmp);
1712 if (fd < 0 && PyErr_Occurred())
1713 return NULL;
1714 tty = fd == fileno(stdin) && isatty(fd);
1715 }
1716 if (tty) {
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001717 tmp = _PyObject_CallMethodId(fout, &PyId_fileno, "");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001718 if (tmp == NULL)
1719 PyErr_Clear();
1720 else {
1721 fd = PyLong_AsLong(tmp);
1722 Py_DECREF(tmp);
1723 if (fd < 0 && PyErr_Occurred())
1724 return NULL;
1725 tty = fd == fileno(stdout) && isatty(fd);
1726 }
1727 }
Guido van Rossumeba76962007-05-27 09:13:28 +00001728
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001729 /* If we're interactive, use (GNU) readline */
1730 if (tty) {
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001731 PyObject *po = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001732 char *prompt;
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001733 char *s = NULL;
1734 PyObject *stdin_encoding = NULL, *stdin_errors = NULL;
1735 PyObject *stdout_encoding = NULL, *stdout_errors = NULL;
1736 char *stdin_encoding_str, *stdin_errors_str;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001737 PyObject *result;
Victor Stinnerc0f1a1a2011-02-23 12:07:37 +00001738 size_t len;
Martin v. Löwis4a7b5d52007-09-04 05:24:49 +00001739
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02001740 stdin_encoding = _PyObject_GetAttrId(fin, &PyId_encoding);
Antoine Pitrou5ee9d8a2011-11-06 00:38:45 +01001741 stdin_errors = _PyObject_GetAttrId(fin, &PyId_errors);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001742 if (!stdin_encoding || !stdin_errors)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001743 /* stdin is a text stream, so it must have an
1744 encoding. */
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001745 goto _readline_errors;
Victor Stinner306f0102010-05-19 01:06:22 +00001746 stdin_encoding_str = _PyUnicode_AsString(stdin_encoding);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001747 stdin_errors_str = _PyUnicode_AsString(stdin_errors);
1748 if (!stdin_encoding_str || !stdin_errors_str)
1749 goto _readline_errors;
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001750 tmp = _PyObject_CallMethodId(fout, &PyId_flush, "");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001751 if (tmp == NULL)
1752 PyErr_Clear();
1753 else
1754 Py_DECREF(tmp);
1755 if (promptarg != NULL) {
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001756 /* We have a prompt, encode it as stdout would */
1757 char *stdout_encoding_str, *stdout_errors_str;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001758 PyObject *stringpo;
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02001759 stdout_encoding = _PyObject_GetAttrId(fout, &PyId_encoding);
Antoine Pitrou5ee9d8a2011-11-06 00:38:45 +01001760 stdout_errors = _PyObject_GetAttrId(fout, &PyId_errors);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001761 if (!stdout_encoding || !stdout_errors)
1762 goto _readline_errors;
Victor Stinner306f0102010-05-19 01:06:22 +00001763 stdout_encoding_str = _PyUnicode_AsString(stdout_encoding);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001764 stdout_errors_str = _PyUnicode_AsString(stdout_errors);
1765 if (!stdout_encoding_str || !stdout_errors_str)
1766 goto _readline_errors;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001767 stringpo = PyObject_Str(promptarg);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001768 if (stringpo == NULL)
1769 goto _readline_errors;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001770 po = PyUnicode_AsEncodedString(stringpo,
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001771 stdout_encoding_str, stdout_errors_str);
1772 Py_CLEAR(stdout_encoding);
1773 Py_CLEAR(stdout_errors);
1774 Py_CLEAR(stringpo);
1775 if (po == NULL)
1776 goto _readline_errors;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001777 prompt = PyBytes_AsString(po);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001778 if (prompt == NULL)
1779 goto _readline_errors;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001780 }
1781 else {
1782 po = NULL;
1783 prompt = "";
1784 }
1785 s = PyOS_Readline(stdin, stdout, prompt);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001786 if (s == NULL) {
Richard Oudkerk614c5782013-04-03 13:44:50 +01001787 PyErr_CheckSignals();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001788 if (!PyErr_Occurred())
1789 PyErr_SetNone(PyExc_KeyboardInterrupt);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001790 goto _readline_errors;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001791 }
Victor Stinnerc0f1a1a2011-02-23 12:07:37 +00001792
1793 len = strlen(s);
1794 if (len == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001795 PyErr_SetNone(PyExc_EOFError);
1796 result = NULL;
1797 }
Victor Stinnerc0f1a1a2011-02-23 12:07:37 +00001798 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001799 if (len > PY_SSIZE_T_MAX) {
1800 PyErr_SetString(PyExc_OverflowError,
1801 "input: input too long");
1802 result = NULL;
1803 }
1804 else {
Victor Stinnerc0f1a1a2011-02-23 12:07:37 +00001805 len--; /* strip trailing '\n' */
1806 if (len != 0 && s[len-1] == '\r')
1807 len--; /* strip trailing '\r' */
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001808 result = PyUnicode_Decode(s, len, stdin_encoding_str,
1809 stdin_errors_str);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001810 }
1811 }
1812 Py_DECREF(stdin_encoding);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001813 Py_DECREF(stdin_errors);
1814 Py_XDECREF(po);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001815 PyMem_FREE(s);
1816 return result;
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001817 _readline_errors:
1818 Py_XDECREF(stdin_encoding);
1819 Py_XDECREF(stdout_encoding);
1820 Py_XDECREF(stdin_errors);
1821 Py_XDECREF(stdout_errors);
1822 Py_XDECREF(po);
1823 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001824 }
Guido van Rossumeba76962007-05-27 09:13:28 +00001825
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001826 /* Fallback if we're not interactive */
1827 if (promptarg != NULL) {
1828 if (PyFile_WriteObject(promptarg, fout, Py_PRINT_RAW) != 0)
1829 return NULL;
1830 }
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001831 tmp = _PyObject_CallMethodId(fout, &PyId_flush, "");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001832 if (tmp == NULL)
1833 PyErr_Clear();
1834 else
1835 Py_DECREF(tmp);
1836 return PyFile_GetLine(fin, -1);
Guido van Rossuma88a0332007-02-26 16:59:55 +00001837}
1838
1839PyDoc_STRVAR(input_doc,
1840"input([prompt]) -> string\n\
1841\n\
1842Read a string from standard input. The trailing newline is stripped.\n\
1843If the user hits EOF (Unix: Ctl-D, Windows: Ctl-Z+Return), raise EOFError.\n\
1844On Unix, GNU readline is used if enabled. The prompt string, if given,\n\
1845is printed without a trailing newline before reading.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001846
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001847
Guido van Rossum79f25d91997-04-29 20:08:16 +00001848static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001849builtin_repr(PyObject *self, PyObject *v)
Guido van Rossumc89705d1992-11-26 08:54:07 +00001850{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001851 return PyObject_Repr(v);
Guido van Rossumc89705d1992-11-26 08:54:07 +00001852}
1853
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001854PyDoc_STRVAR(repr_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001855"repr(object) -> string\n\
1856\n\
1857Return the canonical string representation of the object.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001858For most object types, eval(repr(object)) == object.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001859
1860
Guido van Rossum79f25d91997-04-29 20:08:16 +00001861static PyObject *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001862builtin_round(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum9e51f9b1993-02-12 16:29:05 +00001863{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001864 PyObject *ndigits = NULL;
1865 static char *kwlist[] = {"number", "ndigits", 0};
Benjamin Peterson214a7d22013-04-13 17:19:01 -04001866 PyObject *number, *round, *result;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001867
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001868 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|O:round",
1869 kwlist, &number, &ndigits))
1870 return NULL;
Alex Martelliae211f92007-08-22 23:21:33 +00001871
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001872 if (Py_TYPE(number)->tp_dict == NULL) {
1873 if (PyType_Ready(Py_TYPE(number)) < 0)
1874 return NULL;
1875 }
Guido van Rossum15d3d042007-08-24 02:02:45 +00001876
Benjamin Peterson214a7d22013-04-13 17:19:01 -04001877 round = _PyObject_LookupSpecial(number, &PyId___round__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001878 if (round == NULL) {
Benjamin Peterson214a7d22013-04-13 17:19:01 -04001879 if (!PyErr_Occurred())
1880 PyErr_Format(PyExc_TypeError,
1881 "type %.100s doesn't define __round__ method",
1882 Py_TYPE(number)->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001883 return NULL;
1884 }
Alex Martelliae211f92007-08-22 23:21:33 +00001885
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001886 if (ndigits == NULL)
Benjamin Peterson214a7d22013-04-13 17:19:01 -04001887 result = PyObject_CallFunctionObjArgs(round, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001888 else
Benjamin Peterson214a7d22013-04-13 17:19:01 -04001889 result = PyObject_CallFunctionObjArgs(round, ndigits, NULL);
1890 Py_DECREF(round);
1891 return result;
Guido van Rossum9e51f9b1993-02-12 16:29:05 +00001892}
1893
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001894PyDoc_STRVAR(round_doc,
Mark Dickinson1124e712009-01-28 21:25:58 +00001895"round(number[, ndigits]) -> number\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001896\n\
1897Round a number to a given precision in decimal digits (default 0 digits).\n\
Mark Dickinson0d748c22008-07-05 11:29:03 +00001898This returns an int when called with one argument, otherwise the\n\
Georg Brandl809ddaa2008-07-01 20:39:59 +00001899same type as the number. ndigits may be negative.");
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001900
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001901
Raymond Hettinger64958a12003-12-17 20:43:33 +00001902static PyObject *
1903builtin_sorted(PyObject *self, PyObject *args, PyObject *kwds)
1904{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001905 PyObject *newlist, *v, *seq, *keyfunc=NULL, *newargs;
1906 PyObject *callable;
1907 static char *kwlist[] = {"iterable", "key", "reverse", 0};
1908 int reverse;
Raymond Hettinger64958a12003-12-17 20:43:33 +00001909
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001910 /* args 1-3 should match listsort in Objects/listobject.c */
1911 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|Oi:sorted",
1912 kwlist, &seq, &keyfunc, &reverse))
1913 return NULL;
Raymond Hettinger64958a12003-12-17 20:43:33 +00001914
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001915 newlist = PySequence_List(seq);
1916 if (newlist == NULL)
1917 return NULL;
Raymond Hettinger64958a12003-12-17 20:43:33 +00001918
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02001919 callable = _PyObject_GetAttrId(newlist, &PyId_sort);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001920 if (callable == NULL) {
1921 Py_DECREF(newlist);
1922 return NULL;
1923 }
Georg Brandl99d7e4e2005-08-31 22:21:15 +00001924
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001925 newargs = PyTuple_GetSlice(args, 1, 4);
1926 if (newargs == NULL) {
1927 Py_DECREF(newlist);
1928 Py_DECREF(callable);
1929 return NULL;
1930 }
Raymond Hettinger64958a12003-12-17 20:43:33 +00001931
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001932 v = PyObject_Call(callable, newargs, kwds);
1933 Py_DECREF(newargs);
1934 Py_DECREF(callable);
1935 if (v == NULL) {
1936 Py_DECREF(newlist);
1937 return NULL;
1938 }
1939 Py_DECREF(v);
1940 return newlist;
Raymond Hettinger64958a12003-12-17 20:43:33 +00001941}
1942
1943PyDoc_STRVAR(sorted_doc,
Raymond Hettinger70b64fc2008-01-30 20:15:17 +00001944"sorted(iterable, key=None, reverse=False) --> new sorted list");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001945
Guido van Rossum79f25d91997-04-29 20:08:16 +00001946static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001947builtin_vars(PyObject *self, PyObject *args)
Guido van Rossum2d951851994-08-29 12:52:16 +00001948{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001949 PyObject *v = NULL;
1950 PyObject *d;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001951
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001952 if (!PyArg_UnpackTuple(args, "vars", 0, 1, &v))
1953 return NULL;
1954 if (v == NULL) {
1955 d = PyEval_GetLocals();
Victor Stinner41bb43a2013-10-29 01:19:37 +01001956 if (d == NULL)
1957 return NULL;
1958 Py_INCREF(d);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001959 }
1960 else {
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02001961 d = _PyObject_GetAttrId(v, &PyId___dict__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001962 if (d == NULL) {
1963 PyErr_SetString(PyExc_TypeError,
1964 "vars() argument must have __dict__ attribute");
1965 return NULL;
1966 }
1967 }
1968 return d;
Guido van Rossum2d951851994-08-29 12:52:16 +00001969}
1970
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001971PyDoc_STRVAR(vars_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001972"vars([object]) -> dictionary\n\
1973\n\
1974Without arguments, equivalent to locals().\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001975With an argument, equivalent to object.__dict__.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001976
Alex Martellia70b1912003-04-22 08:12:33 +00001977static PyObject*
1978builtin_sum(PyObject *self, PyObject *args)
1979{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001980 PyObject *seq;
1981 PyObject *result = NULL;
1982 PyObject *temp, *item, *iter;
Alex Martellia70b1912003-04-22 08:12:33 +00001983
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001984 if (!PyArg_UnpackTuple(args, "sum", 1, 2, &seq, &result))
1985 return NULL;
Alex Martellia70b1912003-04-22 08:12:33 +00001986
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001987 iter = PyObject_GetIter(seq);
1988 if (iter == NULL)
1989 return NULL;
Alex Martellia70b1912003-04-22 08:12:33 +00001990
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001991 if (result == NULL) {
1992 result = PyLong_FromLong(0);
1993 if (result == NULL) {
1994 Py_DECREF(iter);
1995 return NULL;
1996 }
1997 } else {
1998 /* reject string values for 'start' parameter */
1999 if (PyUnicode_Check(result)) {
2000 PyErr_SetString(PyExc_TypeError,
2001 "sum() can't sum strings [use ''.join(seq) instead]");
2002 Py_DECREF(iter);
2003 return NULL;
2004 }
Benjamin Petersonce071ca2011-07-29 14:23:47 -05002005 if (PyBytes_Check(result)) {
2006 PyErr_SetString(PyExc_TypeError,
2007 "sum() can't sum bytes [use b''.join(seq) instead]");
Benjamin Peterson405f32c2011-07-29 22:43:45 -05002008 Py_DECREF(iter);
Benjamin Petersonce071ca2011-07-29 14:23:47 -05002009 return NULL;
2010 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002011 if (PyByteArray_Check(result)) {
2012 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson4f921c22011-07-29 14:24:29 -05002013 "sum() can't sum bytearray [use b''.join(seq) instead]");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002014 Py_DECREF(iter);
2015 return NULL;
2016 }
Guido van Rossum3172c5d2007-10-16 18:12:55 +00002017
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002018 Py_INCREF(result);
2019 }
Alex Martellia70b1912003-04-22 08:12:33 +00002020
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002021#ifndef SLOW_SUM
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002022 /* Fast addition by keeping temporary sums in C instead of new Python objects.
2023 Assumes all inputs are the same type. If the assumption fails, default
2024 to the more general routine.
2025 */
2026 if (PyLong_CheckExact(result)) {
2027 int overflow;
2028 long i_result = PyLong_AsLongAndOverflow(result, &overflow);
2029 /* If this already overflowed, don't even enter the loop. */
2030 if (overflow == 0) {
2031 Py_DECREF(result);
2032 result = NULL;
2033 }
2034 while(result == NULL) {
2035 item = PyIter_Next(iter);
2036 if (item == NULL) {
2037 Py_DECREF(iter);
2038 if (PyErr_Occurred())
2039 return NULL;
2040 return PyLong_FromLong(i_result);
2041 }
2042 if (PyLong_CheckExact(item)) {
2043 long b = PyLong_AsLongAndOverflow(item, &overflow);
2044 long x = i_result + b;
2045 if (overflow == 0 && ((x^i_result) >= 0 || (x^b) >= 0)) {
2046 i_result = x;
2047 Py_DECREF(item);
2048 continue;
2049 }
2050 }
2051 /* Either overflowed or is not an int. Restore real objects and process normally */
2052 result = PyLong_FromLong(i_result);
Christian Heimes704e2d32013-07-26 22:49:26 +02002053 if (result == NULL) {
2054 Py_DECREF(item);
2055 Py_DECREF(iter);
2056 return NULL;
2057 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002058 temp = PyNumber_Add(result, item);
2059 Py_DECREF(result);
2060 Py_DECREF(item);
2061 result = temp;
2062 if (result == NULL) {
2063 Py_DECREF(iter);
2064 return NULL;
2065 }
2066 }
2067 }
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002068
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002069 if (PyFloat_CheckExact(result)) {
2070 double f_result = PyFloat_AS_DOUBLE(result);
2071 Py_DECREF(result);
2072 result = NULL;
2073 while(result == NULL) {
2074 item = PyIter_Next(iter);
2075 if (item == NULL) {
2076 Py_DECREF(iter);
2077 if (PyErr_Occurred())
2078 return NULL;
2079 return PyFloat_FromDouble(f_result);
2080 }
2081 if (PyFloat_CheckExact(item)) {
2082 PyFPE_START_PROTECT("add", Py_DECREF(item); Py_DECREF(iter); return 0)
2083 f_result += PyFloat_AS_DOUBLE(item);
2084 PyFPE_END_PROTECT(f_result)
2085 Py_DECREF(item);
2086 continue;
2087 }
2088 if (PyLong_CheckExact(item)) {
2089 long value;
2090 int overflow;
2091 value = PyLong_AsLongAndOverflow(item, &overflow);
2092 if (!overflow) {
2093 PyFPE_START_PROTECT("add", Py_DECREF(item); Py_DECREF(iter); return 0)
2094 f_result += (double)value;
2095 PyFPE_END_PROTECT(f_result)
2096 Py_DECREF(item);
2097 continue;
2098 }
2099 }
2100 result = PyFloat_FromDouble(f_result);
2101 temp = PyNumber_Add(result, item);
2102 Py_DECREF(result);
2103 Py_DECREF(item);
2104 result = temp;
2105 if (result == NULL) {
2106 Py_DECREF(iter);
2107 return NULL;
2108 }
2109 }
2110 }
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002111#endif
2112
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002113 for(;;) {
2114 item = PyIter_Next(iter);
2115 if (item == NULL) {
2116 /* error, or end-of-sequence */
2117 if (PyErr_Occurred()) {
2118 Py_DECREF(result);
2119 result = NULL;
2120 }
2121 break;
2122 }
2123 /* It's tempting to use PyNumber_InPlaceAdd instead of
2124 PyNumber_Add here, to avoid quadratic running time
2125 when doing 'sum(list_of_lists, [])'. However, this
2126 would produce a change in behaviour: a snippet like
Mark Dickinson9acadc52009-10-26 14:19:42 +00002127
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002128 empty = []
2129 sum([[x] for x in range(10)], empty)
Mark Dickinson9acadc52009-10-26 14:19:42 +00002130
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002131 would change the value of empty. */
2132 temp = PyNumber_Add(result, item);
2133 Py_DECREF(result);
2134 Py_DECREF(item);
2135 result = temp;
2136 if (result == NULL)
2137 break;
2138 }
2139 Py_DECREF(iter);
2140 return result;
Alex Martellia70b1912003-04-22 08:12:33 +00002141}
2142
2143PyDoc_STRVAR(sum_doc,
Georg Brandld11ae5d2008-05-16 13:27:32 +00002144"sum(iterable[, start]) -> value\n\
Alex Martellia70b1912003-04-22 08:12:33 +00002145\n\
R David Murray87ead112013-07-10 16:22:14 -04002146Return the sum of an iterable of numbers (NOT strings) plus the value\n\
Georg Brandld11ae5d2008-05-16 13:27:32 +00002147of parameter 'start' (which defaults to 0). When the iterable is\n\
R David Murray87ead112013-07-10 16:22:14 -04002148empty, return start.");
Alex Martellia70b1912003-04-22 08:12:33 +00002149
2150
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002151static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002152builtin_isinstance(PyObject *self, PyObject *args)
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002153{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002154 PyObject *inst;
2155 PyObject *cls;
2156 int retval;
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002157
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002158 if (!PyArg_UnpackTuple(args, "isinstance", 2, 2, &inst, &cls))
2159 return NULL;
Guido van Rossumf5dd9141997-12-02 19:11:45 +00002160
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002161 retval = PyObject_IsInstance(inst, cls);
2162 if (retval < 0)
2163 return NULL;
2164 return PyBool_FromLong(retval);
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002165}
2166
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002167PyDoc_STRVAR(isinstance_doc,
Guido van Rossum77f6a652002-04-03 22:41:51 +00002168"isinstance(object, class-or-type-or-tuple) -> bool\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002169\n\
2170Return whether an object is an instance of a class or of a subclass thereof.\n\
Guido van Rossum03290ec2001-10-07 20:54:12 +00002171With a type as second argument, return whether that is the object's type.\n\
2172The form using a tuple, isinstance(x, (A, B, ...)), is a shortcut for\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002173isinstance(x, A) or isinstance(x, B) or ... (etc.).");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002174
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002175
2176static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002177builtin_issubclass(PyObject *self, PyObject *args)
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002178{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002179 PyObject *derived;
2180 PyObject *cls;
2181 int retval;
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002182
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002183 if (!PyArg_UnpackTuple(args, "issubclass", 2, 2, &derived, &cls))
2184 return NULL;
Guido van Rossum668213d1999-06-16 17:28:37 +00002185
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002186 retval = PyObject_IsSubclass(derived, cls);
2187 if (retval < 0)
2188 return NULL;
2189 return PyBool_FromLong(retval);
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002190}
2191
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002192PyDoc_STRVAR(issubclass_doc,
Guido van Rossum77f6a652002-04-03 22:41:51 +00002193"issubclass(C, B) -> bool\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002194\n\
Walter Dörwaldd9a6ad32002-12-12 16:41:44 +00002195Return whether class C is a subclass (i.e., a derived class) of class B.\n\
2196When using a tuple as the second argument issubclass(X, (A, B, ...)),\n\
2197is a shortcut for issubclass(X, A) or issubclass(X, B) or ... (etc.).");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002198
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002199
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002200typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002201 PyObject_HEAD
2202 Py_ssize_t tuplesize;
2203 PyObject *ittuple; /* tuple of iterators */
2204 PyObject *result;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002205} zipobject;
2206
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002207static PyObject *
2208zip_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
Barry Warsawbd599b52000-08-03 15:45:29 +00002209{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002210 zipobject *lz;
2211 Py_ssize_t i;
2212 PyObject *ittuple; /* tuple of iterators */
2213 PyObject *result;
2214 Py_ssize_t tuplesize = PySequence_Length(args);
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002215
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002216 if (type == &PyZip_Type && !_PyArg_NoKeywords("zip()", kwds))
2217 return NULL;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002218
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002219 /* args must be a tuple */
2220 assert(PyTuple_Check(args));
Barry Warsawbd599b52000-08-03 15:45:29 +00002221
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002222 /* obtain iterators */
2223 ittuple = PyTuple_New(tuplesize);
2224 if (ittuple == NULL)
2225 return NULL;
2226 for (i=0; i < tuplesize; ++i) {
2227 PyObject *item = PyTuple_GET_ITEM(args, i);
2228 PyObject *it = PyObject_GetIter(item);
2229 if (it == NULL) {
2230 if (PyErr_ExceptionMatches(PyExc_TypeError))
2231 PyErr_Format(PyExc_TypeError,
2232 "zip argument #%zd must support iteration",
2233 i+1);
2234 Py_DECREF(ittuple);
2235 return NULL;
2236 }
2237 PyTuple_SET_ITEM(ittuple, i, it);
2238 }
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002239
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002240 /* create a result holder */
2241 result = PyTuple_New(tuplesize);
2242 if (result == NULL) {
2243 Py_DECREF(ittuple);
2244 return NULL;
2245 }
2246 for (i=0 ; i < tuplesize ; i++) {
2247 Py_INCREF(Py_None);
2248 PyTuple_SET_ITEM(result, i, Py_None);
2249 }
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002250
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002251 /* create zipobject structure */
2252 lz = (zipobject *)type->tp_alloc(type, 0);
2253 if (lz == NULL) {
2254 Py_DECREF(ittuple);
2255 Py_DECREF(result);
2256 return NULL;
2257 }
2258 lz->ittuple = ittuple;
2259 lz->tuplesize = tuplesize;
2260 lz->result = result;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002261
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002262 return (PyObject *)lz;
Barry Warsawbd599b52000-08-03 15:45:29 +00002263}
2264
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002265static void
2266zip_dealloc(zipobject *lz)
2267{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002268 PyObject_GC_UnTrack(lz);
2269 Py_XDECREF(lz->ittuple);
2270 Py_XDECREF(lz->result);
2271 Py_TYPE(lz)->tp_free(lz);
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002272}
2273
2274static int
2275zip_traverse(zipobject *lz, visitproc visit, void *arg)
2276{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002277 Py_VISIT(lz->ittuple);
2278 Py_VISIT(lz->result);
2279 return 0;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002280}
2281
2282static PyObject *
2283zip_next(zipobject *lz)
2284{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002285 Py_ssize_t i;
2286 Py_ssize_t tuplesize = lz->tuplesize;
2287 PyObject *result = lz->result;
2288 PyObject *it;
2289 PyObject *item;
2290 PyObject *olditem;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002291
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002292 if (tuplesize == 0)
2293 return NULL;
2294 if (Py_REFCNT(result) == 1) {
2295 Py_INCREF(result);
2296 for (i=0 ; i < tuplesize ; i++) {
2297 it = PyTuple_GET_ITEM(lz->ittuple, i);
2298 item = (*Py_TYPE(it)->tp_iternext)(it);
Serhiy Storchaka278d03b2013-04-06 22:52:34 +03002299 if (item == NULL) {
2300 Py_DECREF(result);
2301 return NULL;
2302 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002303 olditem = PyTuple_GET_ITEM(result, i);
2304 PyTuple_SET_ITEM(result, i, item);
2305 Py_DECREF(olditem);
2306 }
2307 } else {
2308 result = PyTuple_New(tuplesize);
2309 if (result == NULL)
Serhiy Storchaka278d03b2013-04-06 22:52:34 +03002310 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002311 for (i=0 ; i < tuplesize ; i++) {
2312 it = PyTuple_GET_ITEM(lz->ittuple, i);
2313 item = (*Py_TYPE(it)->tp_iternext)(it);
Serhiy Storchaka278d03b2013-04-06 22:52:34 +03002314 if (item == NULL) {
2315 Py_DECREF(result);
2316 return NULL;
2317 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002318 PyTuple_SET_ITEM(result, i, item);
2319 }
2320 }
2321 return result;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002322}
Barry Warsawbd599b52000-08-03 15:45:29 +00002323
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002324static PyObject *
2325zip_reduce(zipobject *lz)
2326{
2327 /* Just recreate the zip with the internal iterator tuple */
2328 return Py_BuildValue("OO", Py_TYPE(lz), lz->ittuple);
2329}
2330
2331static PyMethodDef zip_methods[] = {
2332 {"__reduce__", (PyCFunction)zip_reduce, METH_NOARGS, reduce_doc},
2333 {NULL, NULL} /* sentinel */
2334};
2335
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002336PyDoc_STRVAR(zip_doc,
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002337"zip(iter1 [,iter2 [...]]) --> zip object\n\
Barry Warsawbd599b52000-08-03 15:45:29 +00002338\n\
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002339Return a zip object whose .__next__() method returns a tuple where\n\
2340the i-th element comes from the i-th iterable argument. The .__next__()\n\
2341method continues until the shortest iterable in the argument sequence\n\
Georg Brandlced51db2008-12-04 18:28:38 +00002342is exhausted and then it raises StopIteration.");
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002343
2344PyTypeObject PyZip_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002345 PyVarObject_HEAD_INIT(&PyType_Type, 0)
2346 "zip", /* tp_name */
2347 sizeof(zipobject), /* tp_basicsize */
2348 0, /* tp_itemsize */
2349 /* methods */
2350 (destructor)zip_dealloc, /* tp_dealloc */
2351 0, /* tp_print */
2352 0, /* tp_getattr */
2353 0, /* tp_setattr */
2354 0, /* tp_reserved */
2355 0, /* tp_repr */
2356 0, /* tp_as_number */
2357 0, /* tp_as_sequence */
2358 0, /* tp_as_mapping */
2359 0, /* tp_hash */
2360 0, /* tp_call */
2361 0, /* tp_str */
2362 PyObject_GenericGetAttr, /* tp_getattro */
2363 0, /* tp_setattro */
2364 0, /* tp_as_buffer */
2365 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
2366 Py_TPFLAGS_BASETYPE, /* tp_flags */
2367 zip_doc, /* tp_doc */
2368 (traverseproc)zip_traverse, /* tp_traverse */
2369 0, /* tp_clear */
2370 0, /* tp_richcompare */
2371 0, /* tp_weaklistoffset */
2372 PyObject_SelfIter, /* tp_iter */
2373 (iternextfunc)zip_next, /* tp_iternext */
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002374 zip_methods, /* tp_methods */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002375 0, /* tp_members */
2376 0, /* tp_getset */
2377 0, /* tp_base */
2378 0, /* tp_dict */
2379 0, /* tp_descr_get */
2380 0, /* tp_descr_set */
2381 0, /* tp_dictoffset */
2382 0, /* tp_init */
2383 PyType_GenericAlloc, /* tp_alloc */
2384 zip_new, /* tp_new */
2385 PyObject_GC_Del, /* tp_free */
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002386};
Barry Warsawbd599b52000-08-03 15:45:29 +00002387
2388
Guido van Rossum79f25d91997-04-29 20:08:16 +00002389static PyMethodDef builtin_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002390 {"__build_class__", (PyCFunction)builtin___build_class__,
2391 METH_VARARGS | METH_KEYWORDS, build_class_doc},
2392 {"__import__", (PyCFunction)builtin___import__, METH_VARARGS | METH_KEYWORDS, import_doc},
2393 {"abs", builtin_abs, METH_O, abs_doc},
2394 {"all", builtin_all, METH_O, all_doc},
2395 {"any", builtin_any, METH_O, any_doc},
2396 {"ascii", builtin_ascii, METH_O, ascii_doc},
2397 {"bin", builtin_bin, METH_O, bin_doc},
Antoine Pitroue71362d2010-11-27 22:00:11 +00002398 {"callable", builtin_callable, METH_O, callable_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002399 {"chr", builtin_chr, METH_VARARGS, chr_doc},
2400 {"compile", (PyCFunction)builtin_compile, METH_VARARGS | METH_KEYWORDS, compile_doc},
2401 {"delattr", builtin_delattr, METH_VARARGS, delattr_doc},
2402 {"dir", builtin_dir, METH_VARARGS, dir_doc},
2403 {"divmod", builtin_divmod, METH_VARARGS, divmod_doc},
2404 {"eval", builtin_eval, METH_VARARGS, eval_doc},
2405 {"exec", builtin_exec, METH_VARARGS, exec_doc},
2406 {"format", builtin_format, METH_VARARGS, format_doc},
2407 {"getattr", builtin_getattr, METH_VARARGS, getattr_doc},
2408 {"globals", (PyCFunction)builtin_globals, METH_NOARGS, globals_doc},
2409 {"hasattr", builtin_hasattr, METH_VARARGS, hasattr_doc},
2410 {"hash", builtin_hash, METH_O, hash_doc},
2411 {"hex", builtin_hex, METH_O, hex_doc},
2412 {"id", builtin_id, METH_O, id_doc},
2413 {"input", builtin_input, METH_VARARGS, input_doc},
2414 {"isinstance", builtin_isinstance, METH_VARARGS, isinstance_doc},
2415 {"issubclass", builtin_issubclass, METH_VARARGS, issubclass_doc},
2416 {"iter", builtin_iter, METH_VARARGS, iter_doc},
2417 {"len", builtin_len, METH_O, len_doc},
2418 {"locals", (PyCFunction)builtin_locals, METH_NOARGS, locals_doc},
2419 {"max", (PyCFunction)builtin_max, METH_VARARGS | METH_KEYWORDS, max_doc},
2420 {"min", (PyCFunction)builtin_min, METH_VARARGS | METH_KEYWORDS, min_doc},
2421 {"next", (PyCFunction)builtin_next, METH_VARARGS, next_doc},
2422 {"oct", builtin_oct, METH_O, oct_doc},
2423 {"ord", builtin_ord, METH_O, ord_doc},
2424 {"pow", builtin_pow, METH_VARARGS, pow_doc},
2425 {"print", (PyCFunction)builtin_print, METH_VARARGS | METH_KEYWORDS, print_doc},
2426 {"repr", builtin_repr, METH_O, repr_doc},
2427 {"round", (PyCFunction)builtin_round, METH_VARARGS | METH_KEYWORDS, round_doc},
2428 {"setattr", builtin_setattr, METH_VARARGS, setattr_doc},
2429 {"sorted", (PyCFunction)builtin_sorted, METH_VARARGS | METH_KEYWORDS, sorted_doc},
2430 {"sum", builtin_sum, METH_VARARGS, sum_doc},
2431 {"vars", builtin_vars, METH_VARARGS, vars_doc},
2432 {NULL, NULL},
Guido van Rossum3f5da241990-12-20 15:06:42 +00002433};
2434
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002435PyDoc_STRVAR(builtin_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002436"Built-in functions, exceptions, and other objects.\n\
2437\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002438Noteworthy: None is the `nil' object; Ellipsis represents `...' in slices.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002439
Martin v. Löwis1a214512008-06-11 05:26:20 +00002440static struct PyModuleDef builtinsmodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002441 PyModuleDef_HEAD_INIT,
2442 "builtins",
2443 builtin_doc,
2444 -1, /* multiple "initialization" just copies the module dict. */
2445 builtin_methods,
2446 NULL,
2447 NULL,
2448 NULL,
2449 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00002450};
2451
2452
Guido van Rossum25ce5661997-08-02 03:10:38 +00002453PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002454_PyBuiltin_Init(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +00002455{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002456 PyObject *mod, *dict, *debug;
Benjamin Peterson42124a72012-10-30 23:41:54 -04002457
2458 if (PyType_Ready(&PyFilter_Type) < 0 ||
2459 PyType_Ready(&PyMap_Type) < 0 ||
2460 PyType_Ready(&PyZip_Type) < 0)
2461 return NULL;
2462
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002463 mod = PyModule_Create(&builtinsmodule);
2464 if (mod == NULL)
2465 return NULL;
2466 dict = PyModule_GetDict(mod);
Tim Peters4b7625e2001-09-13 21:37:17 +00002467
Tim Peters7571a0f2003-03-23 17:52:28 +00002468#ifdef Py_TRACE_REFS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002469 /* "builtins" exposes a number of statically allocated objects
2470 * that, before this code was added in 2.3, never showed up in
2471 * the list of "all objects" maintained by Py_TRACE_REFS. As a
2472 * result, programs leaking references to None and False (etc)
2473 * couldn't be diagnosed by examining sys.getobjects(0).
2474 */
Tim Peters7571a0f2003-03-23 17:52:28 +00002475#define ADD_TO_ALL(OBJECT) _Py_AddToAllObjects((PyObject *)(OBJECT), 0)
2476#else
2477#define ADD_TO_ALL(OBJECT) (void)0
2478#endif
2479
Tim Peters4b7625e2001-09-13 21:37:17 +00002480#define SETBUILTIN(NAME, OBJECT) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002481 if (PyDict_SetItemString(dict, NAME, (PyObject *)OBJECT) < 0) \
2482 return NULL; \
2483 ADD_TO_ALL(OBJECT)
Tim Peters4b7625e2001-09-13 21:37:17 +00002484
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002485 SETBUILTIN("None", Py_None);
2486 SETBUILTIN("Ellipsis", Py_Ellipsis);
2487 SETBUILTIN("NotImplemented", Py_NotImplemented);
2488 SETBUILTIN("False", Py_False);
2489 SETBUILTIN("True", Py_True);
2490 SETBUILTIN("bool", &PyBool_Type);
2491 SETBUILTIN("memoryview", &PyMemoryView_Type);
2492 SETBUILTIN("bytearray", &PyByteArray_Type);
2493 SETBUILTIN("bytes", &PyBytes_Type);
2494 SETBUILTIN("classmethod", &PyClassMethod_Type);
2495 SETBUILTIN("complex", &PyComplex_Type);
2496 SETBUILTIN("dict", &PyDict_Type);
2497 SETBUILTIN("enumerate", &PyEnum_Type);
2498 SETBUILTIN("filter", &PyFilter_Type);
2499 SETBUILTIN("float", &PyFloat_Type);
2500 SETBUILTIN("frozenset", &PyFrozenSet_Type);
2501 SETBUILTIN("property", &PyProperty_Type);
2502 SETBUILTIN("int", &PyLong_Type);
2503 SETBUILTIN("list", &PyList_Type);
2504 SETBUILTIN("map", &PyMap_Type);
2505 SETBUILTIN("object", &PyBaseObject_Type);
2506 SETBUILTIN("range", &PyRange_Type);
2507 SETBUILTIN("reversed", &PyReversed_Type);
2508 SETBUILTIN("set", &PySet_Type);
2509 SETBUILTIN("slice", &PySlice_Type);
2510 SETBUILTIN("staticmethod", &PyStaticMethod_Type);
2511 SETBUILTIN("str", &PyUnicode_Type);
2512 SETBUILTIN("super", &PySuper_Type);
2513 SETBUILTIN("tuple", &PyTuple_Type);
2514 SETBUILTIN("type", &PyType_Type);
2515 SETBUILTIN("zip", &PyZip_Type);
2516 debug = PyBool_FromLong(Py_OptimizeFlag == 0);
2517 if (PyDict_SetItemString(dict, "__debug__", debug) < 0) {
2518 Py_XDECREF(debug);
2519 return NULL;
2520 }
2521 Py_XDECREF(debug);
Barry Warsaw757af0e1997-08-29 22:13:51 +00002522
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002523 return mod;
Tim Peters7571a0f2003-03-23 17:52:28 +00002524#undef ADD_TO_ALL
Tim Peters4b7625e2001-09-13 21:37:17 +00002525#undef SETBUILTIN
Guido van Rossum3f5da241990-12-20 15:06:42 +00002526}