blob: 7f3593c69521eef0a234f8703e7628869911159d [file] [log] [blame]
Guido van Rossum3f5da241990-12-20 15:06:42 +00001/* Built-in functions */
2
Guido van Rossum79f25d91997-04-29 20:08:16 +00003#include "Python.h"
Martin v. Löwis618dc5e2008-03-30 20:03:44 +00004#include "Python-ast.h"
Guido van Rossum3f5da241990-12-20 15:06:42 +00005
6#include "node.h"
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00007#include "code.h"
Guido van Rossum3f5da241990-12-20 15:06:42 +00008
Benjamin Petersonea281a52011-08-12 23:10:50 -05009#include "asdl.h"
10#include "ast.h"
11
Guido van Rossum6bf62da1997-04-11 20:37:35 +000012#include <ctype.h>
13
Victor Stinnerb744ba12010-05-15 12:27:16 +000014#ifdef HAVE_LANGINFO_H
15#include <langinfo.h> /* CODESET */
16#endif
17
Mark Hammond26cffde42001-05-14 12:17:34 +000018/* The default encoding used by the platform file system APIs
19 Can remain NULL for all platforms that don't have such a concept
Guido van Rossum00bc0e02007-10-15 02:52:41 +000020
21 Don't forget to modify PyUnicode_DecodeFSDefault() if you touch any of the
22 values for Py_FileSystemDefaultEncoding!
Mark Hammond26cffde42001-05-14 12:17:34 +000023*/
Victor Stinner99b95382011-07-04 14:23:54 +020024#ifdef HAVE_MBCS
Mark Hammond26cffde42001-05-14 12:17:34 +000025const char *Py_FileSystemDefaultEncoding = "mbcs";
Martin v. Löwis04dc25c2008-10-03 16:09:28 +000026int Py_HasFileSystemDefaultEncoding = 1;
Just van Rossumb9b8e9c2003-02-10 09:22:01 +000027#elif defined(__APPLE__)
28const char *Py_FileSystemDefaultEncoding = "utf-8";
Martin v. Löwis04dc25c2008-10-03 16:09:28 +000029int Py_HasFileSystemDefaultEncoding = 1;
Victor Stinnerd64e8a72011-07-04 13:48:30 +020030#else
Victor Stinnerb744ba12010-05-15 12:27:16 +000031const char *Py_FileSystemDefaultEncoding = NULL; /* set by initfsencoding() */
Martin v. Löwis04dc25c2008-10-03 16:09:28 +000032int Py_HasFileSystemDefaultEncoding = 0;
Mark Hammond26cffde42001-05-14 12:17:34 +000033#endif
Mark Hammondef8b6542001-05-13 08:04:26 +000034
Martin v. Löwisbd928fe2011-10-14 10:20:37 +020035_Py_IDENTIFIER(fileno);
36_Py_IDENTIFIER(flush);
Victor Stinnerb44562b2013-11-06 19:03:11 +010037_Py_IDENTIFIER(__builtins__);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +020038
Guido van Rossum79f25d91997-04-29 20:08:16 +000039static PyObject *
Guido van Rossum52cc1d82007-03-18 15:41:51 +000040builtin___build_class__(PyObject *self, PyObject *args, PyObject *kwds)
41{
Nick Coghlande31b192011-10-23 22:04:16 +100042 PyObject *func, *name, *bases, *mkw, *meta, *winner, *prep, *ns, *cell;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000043 PyObject *cls = NULL;
Florent Xicluna4d46c2a2011-10-28 15:00:50 +020044 Py_ssize_t nargs;
Nick Coghlande31b192011-10-23 22:04:16 +100045 int isclass;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +020046 _Py_IDENTIFIER(__prepare__);
Victor Stinnerae9f1612013-11-06 22:46:51 +010047 _Py_IDENTIFIER(metaclass);
Guido van Rossum52cc1d82007-03-18 15:41:51 +000048
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000049 assert(args != NULL);
50 if (!PyTuple_Check(args)) {
51 PyErr_SetString(PyExc_TypeError,
52 "__build_class__: args is not a tuple");
53 return NULL;
54 }
55 nargs = PyTuple_GET_SIZE(args);
56 if (nargs < 2) {
57 PyErr_SetString(PyExc_TypeError,
58 "__build_class__: not enough arguments");
59 return NULL;
60 }
61 func = PyTuple_GET_ITEM(args, 0); /* Better be callable */
Benjamin Petersone8e14592013-05-16 14:37:25 -050062 if (!PyFunction_Check(func)) {
63 PyErr_SetString(PyExc_TypeError,
64 "__build__class__: func must be a function");
65 return NULL;
66 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000067 name = PyTuple_GET_ITEM(args, 1);
68 if (!PyUnicode_Check(name)) {
69 PyErr_SetString(PyExc_TypeError,
70 "__build_class__: name is not a string");
71 return NULL;
72 }
73 bases = PyTuple_GetSlice(args, 2, nargs);
74 if (bases == NULL)
75 return NULL;
Guido van Rossum52cc1d82007-03-18 15:41:51 +000076
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000077 if (kwds == NULL) {
78 meta = NULL;
79 mkw = NULL;
80 }
81 else {
82 mkw = PyDict_Copy(kwds); /* Don't modify kwds passed in! */
83 if (mkw == NULL) {
84 Py_DECREF(bases);
85 return NULL;
Guido van Rossum52cc1d82007-03-18 15:41:51 +000086 }
Victor Stinnerae9f1612013-11-06 22:46:51 +010087 meta = _PyDict_GetItemId(mkw, &PyId_metaclass);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000088 if (meta != NULL) {
89 Py_INCREF(meta);
Victor Stinnerae9f1612013-11-06 22:46:51 +010090 if (_PyDict_DelItemId(mkw, &PyId_metaclass) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000091 Py_DECREF(meta);
92 Py_DECREF(mkw);
93 Py_DECREF(bases);
94 return NULL;
95 }
Nick Coghlande31b192011-10-23 22:04:16 +100096 /* metaclass is explicitly given, check if it's indeed a class */
97 isclass = PyType_Check(meta);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000098 }
99 }
100 if (meta == NULL) {
Nick Coghlande31b192011-10-23 22:04:16 +1000101 /* if there are no bases, use type: */
102 if (PyTuple_GET_SIZE(bases) == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000103 meta = (PyObject *) (&PyType_Type);
Nick Coghlande31b192011-10-23 22:04:16 +1000104 }
105 /* else get the type of the first base */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000106 else {
107 PyObject *base0 = PyTuple_GET_ITEM(bases, 0);
108 meta = (PyObject *) (base0->ob_type);
109 }
110 Py_INCREF(meta);
Nick Coghlande31b192011-10-23 22:04:16 +1000111 isclass = 1; /* meta is really a class */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000112 }
Nick Coghlan9715d262011-10-23 22:36:42 +1000113
Nick Coghlande31b192011-10-23 22:04:16 +1000114 if (isclass) {
115 /* meta is really a class, so check for a more derived
116 metaclass, or possible metaclass conflicts: */
117 winner = (PyObject *)_PyType_CalculateMetaclass((PyTypeObject *)meta,
118 bases);
119 if (winner == NULL) {
120 Py_DECREF(meta);
121 Py_XDECREF(mkw);
122 Py_DECREF(bases);
123 return NULL;
124 }
125 if (winner != meta) {
126 Py_DECREF(meta);
127 meta = winner;
128 Py_INCREF(meta);
129 }
130 }
131 /* else: meta is not a class, so we cannot do the metaclass
132 calculation, so we will use the explicitly given object as it is */
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +0200133 prep = _PyObject_GetAttrId(meta, &PyId___prepare__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000134 if (prep == NULL) {
135 if (PyErr_ExceptionMatches(PyExc_AttributeError)) {
136 PyErr_Clear();
137 ns = PyDict_New();
138 }
139 else {
140 Py_DECREF(meta);
141 Py_XDECREF(mkw);
142 Py_DECREF(bases);
143 return NULL;
144 }
145 }
146 else {
147 PyObject *pargs = PyTuple_Pack(2, name, bases);
148 if (pargs == NULL) {
149 Py_DECREF(prep);
150 Py_DECREF(meta);
151 Py_XDECREF(mkw);
152 Py_DECREF(bases);
153 return NULL;
154 }
155 ns = PyEval_CallObjectWithKeywords(prep, pargs, mkw);
156 Py_DECREF(pargs);
157 Py_DECREF(prep);
158 }
159 if (ns == NULL) {
160 Py_DECREF(meta);
161 Py_XDECREF(mkw);
162 Py_DECREF(bases);
163 return NULL;
164 }
Benjamin Petersone8e14592013-05-16 14:37:25 -0500165 cell = PyEval_EvalCodeEx(PyFunction_GET_CODE(func), PyFunction_GET_GLOBALS(func), ns,
166 NULL, 0, NULL, 0, NULL, 0, NULL,
167 PyFunction_GET_CLOSURE(func));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000168 if (cell != NULL) {
169 PyObject *margs;
170 margs = PyTuple_Pack(3, name, bases, ns);
171 if (margs != NULL) {
172 cls = PyEval_CallObjectWithKeywords(meta, margs, mkw);
173 Py_DECREF(margs);
174 }
Benjamin Peterson8e8fbea2012-06-01 23:57:36 -0700175 if (cls != NULL && PyCell_Check(cell))
176 PyCell_Set(cell, cls);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000177 Py_DECREF(cell);
178 }
179 Py_DECREF(ns);
180 Py_DECREF(meta);
181 Py_XDECREF(mkw);
182 Py_DECREF(bases);
183 return cls;
Guido van Rossum52cc1d82007-03-18 15:41:51 +0000184}
185
186PyDoc_STRVAR(build_class_doc,
187"__build_class__(func, name, *bases, metaclass=None, **kwds) -> class\n\
188\n\
189Internal helper function used by the class statement.");
190
191static PyObject *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000192builtin___import__(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000193{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000194 static char *kwlist[] = {"name", "globals", "locals", "fromlist",
195 "level", 0};
Victor Stinnerfe93faf2011-03-14 15:54:52 -0400196 PyObject *name, *globals = NULL, *locals = NULL, *fromlist = NULL;
Brett Cannonfd074152012-04-14 14:10:13 -0400197 int level = 0;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000198
Victor Stinnerfe93faf2011-03-14 15:54:52 -0400199 if (!PyArg_ParseTupleAndKeywords(args, kwds, "U|OOOi:__import__",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000200 kwlist, &name, &globals, &locals, &fromlist, &level))
201 return NULL;
Victor Stinnerfe93faf2011-03-14 15:54:52 -0400202 return PyImport_ImportModuleLevelObject(name, globals, locals,
203 fromlist, level);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000204}
205
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000206PyDoc_STRVAR(import_doc,
Brett Cannoncb4996a2012-08-06 16:34:44 -0400207"__import__(name, globals=None, locals=None, fromlist=(), level=0) -> module\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000208\n\
Brett Cannon5305a992010-09-27 21:08:38 +0000209Import a module. Because this function is meant for use by the Python\n\
210interpreter and not for general use it is better to use\n\
211importlib.import_module() to programmatically import a module.\n\
212\n\
213The globals argument is only used to determine the context;\n\
214they are not modified. The locals argument is unused. The fromlist\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000215should be a list of names to emulate ``from name import ...'', or an\n\
216empty list to emulate ``import name''.\n\
217When importing a module from a package, note that __import__('A.B', ...)\n\
218returns package A when fromlist is empty, but its submodule B when\n\
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000219fromlist is not empty. Level is used to determine whether to perform \n\
Brett Cannon722d3ae2012-07-30 17:45:54 -0400220absolute or relative imports. 0 is absolute while a positive number\n\
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000221is the number of parent directories to search relative to the current module.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000222
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000223
Guido van Rossum79f25d91997-04-29 20:08:16 +0000224static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000225builtin_abs(PyObject *self, PyObject *v)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000226{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000227 return PyNumber_Absolute(v);
Guido van Rossum3f5da241990-12-20 15:06:42 +0000228}
229
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000230PyDoc_STRVAR(abs_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000231"abs(number) -> number\n\
232\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000233Return the absolute value of the argument.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000234
Raymond Hettinger96229b12005-03-11 06:49:40 +0000235static PyObject *
236builtin_all(PyObject *self, PyObject *v)
237{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000238 PyObject *it, *item;
239 PyObject *(*iternext)(PyObject *);
240 int cmp;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000241
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000242 it = PyObject_GetIter(v);
243 if (it == NULL)
244 return NULL;
245 iternext = *Py_TYPE(it)->tp_iternext;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000246
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000247 for (;;) {
248 item = iternext(it);
249 if (item == NULL)
250 break;
251 cmp = PyObject_IsTrue(item);
252 Py_DECREF(item);
253 if (cmp < 0) {
254 Py_DECREF(it);
255 return NULL;
256 }
257 if (cmp == 0) {
258 Py_DECREF(it);
259 Py_RETURN_FALSE;
260 }
261 }
262 Py_DECREF(it);
263 if (PyErr_Occurred()) {
264 if (PyErr_ExceptionMatches(PyExc_StopIteration))
265 PyErr_Clear();
266 else
267 return NULL;
268 }
269 Py_RETURN_TRUE;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000270}
271
272PyDoc_STRVAR(all_doc,
273"all(iterable) -> bool\n\
274\n\
Ezio Melottib19ed572013-02-15 23:35:14 +0200275Return True if bool(x) is True for all values x in the iterable.\n\
276If the iterable is empty, return True.");
Raymond Hettinger96229b12005-03-11 06:49:40 +0000277
278static PyObject *
279builtin_any(PyObject *self, PyObject *v)
280{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000281 PyObject *it, *item;
282 PyObject *(*iternext)(PyObject *);
283 int cmp;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000284
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000285 it = PyObject_GetIter(v);
286 if (it == NULL)
287 return NULL;
288 iternext = *Py_TYPE(it)->tp_iternext;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000289
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000290 for (;;) {
291 item = iternext(it);
292 if (item == NULL)
293 break;
294 cmp = PyObject_IsTrue(item);
295 Py_DECREF(item);
296 if (cmp < 0) {
297 Py_DECREF(it);
298 return NULL;
299 }
300 if (cmp == 1) {
301 Py_DECREF(it);
302 Py_RETURN_TRUE;
303 }
304 }
305 Py_DECREF(it);
306 if (PyErr_Occurred()) {
307 if (PyErr_ExceptionMatches(PyExc_StopIteration))
308 PyErr_Clear();
309 else
310 return NULL;
311 }
312 Py_RETURN_FALSE;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000313}
314
315PyDoc_STRVAR(any_doc,
316"any(iterable) -> bool\n\
317\n\
Ezio Melottib19ed572013-02-15 23:35:14 +0200318Return True if bool(x) is True for any x in the iterable.\n\
319If the iterable is empty, return False.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000320
Georg Brandl559e5d72008-06-11 18:37:52 +0000321static PyObject *
322builtin_ascii(PyObject *self, PyObject *v)
323{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000324 return PyObject_ASCII(v);
Georg Brandl559e5d72008-06-11 18:37:52 +0000325}
326
327PyDoc_STRVAR(ascii_doc,
328"ascii(object) -> string\n\
329\n\
330As repr(), return a string containing a printable representation of an\n\
331object, but escape the non-ASCII characters in the string returned by\n\
332repr() using \\x, \\u or \\U escapes. This generates a string similar\n\
333to that returned by repr() in Python 2.");
334
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000335
Guido van Rossum79f25d91997-04-29 20:08:16 +0000336static PyObject *
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000337builtin_bin(PyObject *self, PyObject *v)
338{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000339 return PyNumber_ToBase(v, 2);
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000340}
341
342PyDoc_STRVAR(bin_doc,
343"bin(number) -> string\n\
344\n\
Alexander Belopolsky12338ab2011-04-07 00:15:33 -0400345Return the binary representation of an integer.");
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000346
347
Antoine Pitroue71362d2010-11-27 22:00:11 +0000348static PyObject *
349builtin_callable(PyObject *self, PyObject *v)
350{
351 return PyBool_FromLong((long)PyCallable_Check(v));
352}
353
354PyDoc_STRVAR(callable_doc,
355"callable(object) -> bool\n\
356\n\
357Return whether the object is callable (i.e., some kind of function).\n\
358Note that classes are callable, as are instances of classes with a\n\
359__call__() method.");
360
361
Raymond Hettinger17301e92008-03-13 00:19:26 +0000362typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000363 PyObject_HEAD
364 PyObject *func;
365 PyObject *it;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000366} filterobject;
367
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000368static PyObject *
Raymond Hettinger17301e92008-03-13 00:19:26 +0000369filter_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
Guido van Rossum12d12c51993-10-26 17:58:25 +0000370{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000371 PyObject *func, *seq;
372 PyObject *it;
373 filterobject *lz;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000374
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000375 if (type == &PyFilter_Type && !_PyArg_NoKeywords("filter()", kwds))
376 return NULL;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000377
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000378 if (!PyArg_UnpackTuple(args, "filter", 2, 2, &func, &seq))
379 return NULL;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000380
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000381 /* Get iterator. */
382 it = PyObject_GetIter(seq);
383 if (it == NULL)
384 return NULL;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000385
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000386 /* create filterobject structure */
387 lz = (filterobject *)type->tp_alloc(type, 0);
388 if (lz == NULL) {
389 Py_DECREF(it);
390 return NULL;
391 }
392 Py_INCREF(func);
393 lz->func = func;
394 lz->it = it;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000395
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000396 return (PyObject *)lz;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000397}
398
399static void
400filter_dealloc(filterobject *lz)
401{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000402 PyObject_GC_UnTrack(lz);
403 Py_XDECREF(lz->func);
404 Py_XDECREF(lz->it);
405 Py_TYPE(lz)->tp_free(lz);
Raymond Hettinger17301e92008-03-13 00:19:26 +0000406}
407
408static int
409filter_traverse(filterobject *lz, visitproc visit, void *arg)
410{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000411 Py_VISIT(lz->it);
412 Py_VISIT(lz->func);
413 return 0;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000414}
415
416static PyObject *
417filter_next(filterobject *lz)
418{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000419 PyObject *item;
420 PyObject *it = lz->it;
421 long ok;
422 PyObject *(*iternext)(PyObject *);
Raymond Hettinger17301e92008-03-13 00:19:26 +0000423
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000424 iternext = *Py_TYPE(it)->tp_iternext;
425 for (;;) {
426 item = iternext(it);
427 if (item == NULL)
428 return NULL;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000429
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000430 if (lz->func == Py_None || lz->func == (PyObject *)&PyBool_Type) {
431 ok = PyObject_IsTrue(item);
432 } else {
433 PyObject *good;
434 good = PyObject_CallFunctionObjArgs(lz->func,
435 item, NULL);
436 if (good == NULL) {
437 Py_DECREF(item);
438 return NULL;
439 }
440 ok = PyObject_IsTrue(good);
441 Py_DECREF(good);
442 }
Antoine Pitrou6f430e42012-08-15 23:18:25 +0200443 if (ok > 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000444 return item;
445 Py_DECREF(item);
Antoine Pitrou6f430e42012-08-15 23:18:25 +0200446 if (ok < 0)
447 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000448 }
Guido van Rossum12d12c51993-10-26 17:58:25 +0000449}
450
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +0000451static PyObject *
452filter_reduce(filterobject *lz)
453{
454 return Py_BuildValue("O(OO)", Py_TYPE(lz), lz->func, lz->it);
455}
456
457PyDoc_STRVAR(reduce_doc, "Return state information for pickling.");
458
459static PyMethodDef filter_methods[] = {
460 {"__reduce__", (PyCFunction)filter_reduce, METH_NOARGS, reduce_doc},
461 {NULL, NULL} /* sentinel */
462};
463
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000464PyDoc_STRVAR(filter_doc,
Georg Brandld11ae5d2008-05-16 13:27:32 +0000465"filter(function or None, iterable) --> filter object\n\
Guido van Rossumc1f779c2007-07-03 08:25:58 +0000466\n\
Georg Brandld11ae5d2008-05-16 13:27:32 +0000467Return an iterator yielding those items of iterable for which function(item)\n\
Raymond Hettinger17301e92008-03-13 00:19:26 +0000468is true. If function is None, return the items that are true.");
469
470PyTypeObject PyFilter_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000471 PyVarObject_HEAD_INIT(&PyType_Type, 0)
472 "filter", /* tp_name */
473 sizeof(filterobject), /* tp_basicsize */
474 0, /* tp_itemsize */
475 /* methods */
476 (destructor)filter_dealloc, /* tp_dealloc */
477 0, /* tp_print */
478 0, /* tp_getattr */
479 0, /* tp_setattr */
480 0, /* tp_reserved */
481 0, /* tp_repr */
482 0, /* tp_as_number */
483 0, /* tp_as_sequence */
484 0, /* tp_as_mapping */
485 0, /* tp_hash */
486 0, /* tp_call */
487 0, /* tp_str */
488 PyObject_GenericGetAttr, /* tp_getattro */
489 0, /* tp_setattro */
490 0, /* tp_as_buffer */
491 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
492 Py_TPFLAGS_BASETYPE, /* tp_flags */
493 filter_doc, /* tp_doc */
494 (traverseproc)filter_traverse, /* tp_traverse */
495 0, /* tp_clear */
496 0, /* tp_richcompare */
497 0, /* tp_weaklistoffset */
498 PyObject_SelfIter, /* tp_iter */
499 (iternextfunc)filter_next, /* tp_iternext */
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +0000500 filter_methods, /* tp_methods */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000501 0, /* tp_members */
502 0, /* tp_getset */
503 0, /* tp_base */
504 0, /* tp_dict */
505 0, /* tp_descr_get */
506 0, /* tp_descr_set */
507 0, /* tp_dictoffset */
508 0, /* tp_init */
509 PyType_GenericAlloc, /* tp_alloc */
510 filter_new, /* tp_new */
511 PyObject_GC_Del, /* tp_free */
Raymond Hettinger17301e92008-03-13 00:19:26 +0000512};
513
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000514
Eric Smith8c663262007-08-25 02:26:07 +0000515static PyObject *
516builtin_format(PyObject *self, PyObject *args)
517{
Christian Heimes94b7d3d2007-12-11 20:20:39 +0000518 PyObject *value;
Eric Smith8fd3eba2008-02-17 19:48:00 +0000519 PyObject *format_spec = NULL;
Eric Smith8c663262007-08-25 02:26:07 +0000520
Eric Smith8fd3eba2008-02-17 19:48:00 +0000521 if (!PyArg_ParseTuple(args, "O|U:format", &value, &format_spec))
Benjamin Petersona12d5c62012-01-03 16:47:22 -0600522 return NULL;
Eric Smith8c663262007-08-25 02:26:07 +0000523
Eric Smith8fd3eba2008-02-17 19:48:00 +0000524 return PyObject_Format(value, format_spec);
Eric Smith8c663262007-08-25 02:26:07 +0000525}
526
Eric Smith8c663262007-08-25 02:26:07 +0000527PyDoc_STRVAR(format_doc,
Eric Smith81936692007-08-31 01:14:01 +0000528"format(value[, format_spec]) -> string\n\
Eric Smith8c663262007-08-25 02:26:07 +0000529\n\
Eric Smith81936692007-08-31 01:14:01 +0000530Returns value.__format__(format_spec)\n\
531format_spec defaults to \"\"");
532
Guido van Rossum7fcf2242007-05-04 17:43:11 +0000533static PyObject *
Walter Dörwalde7efd592007-06-05 20:07:21 +0000534builtin_chr(PyObject *self, PyObject *args)
Guido van Rossum09095f32000-03-10 23:00:52 +0000535{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000536 int x;
Guido van Rossum09095f32000-03-10 23:00:52 +0000537
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000538 if (!PyArg_ParseTuple(args, "i:chr", &x))
539 return NULL;
Fredrik Lundh0dcf67e2001-06-26 20:01:56 +0000540
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000541 return PyUnicode_FromOrdinal(x);
Guido van Rossum09095f32000-03-10 23:00:52 +0000542}
543
Victor Stinner63ab8752011-11-22 03:31:20 +0100544PyDoc_STRVAR(chr_doc,
Guido van Rossum84fc66d2007-05-03 17:18:26 +0000545"chr(i) -> Unicode character\n\
Guido van Rossum09095f32000-03-10 23:00:52 +0000546\n\
Victor Stinner63ab8752011-11-22 03:31:20 +0100547Return a Unicode string of one character with ordinal i; 0 <= i <= 0x10ffff.");
Guido van Rossum09095f32000-03-10 23:00:52 +0000548
549
Guido van Rossumf15a29f2007-05-04 00:41:39 +0000550static char *
Benjamin Petersonf5b52242009-03-02 23:31:26 +0000551source_as_string(PyObject *cmd, char *funcname, char *what, PyCompilerFlags *cf)
Guido van Rossumf15a29f2007-05-04 00:41:39 +0000552{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000553 char *str;
554 Py_ssize_t size;
Guido van Rossumf15a29f2007-05-04 00:41:39 +0000555
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000556 if (PyUnicode_Check(cmd)) {
557 cf->cf_flags |= PyCF_IGNORE_COOKIE;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200558 str = PyUnicode_AsUTF8AndSize(cmd, &size);
559 if (str == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000560 return NULL;
561 }
562 else if (!PyObject_CheckReadBuffer(cmd)) {
563 PyErr_Format(PyExc_TypeError,
564 "%s() arg 1 must be a %s object",
565 funcname, what);
566 return NULL;
567 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200568 else if (PyObject_AsReadBuffer(cmd, (const void **)&str, &size) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000569 return NULL;
570 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200571
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000572 if (strlen(str) != size) {
573 PyErr_SetString(PyExc_TypeError,
574 "source code string cannot contain null bytes");
575 return NULL;
576 }
577 return str;
Guido van Rossumf15a29f2007-05-04 00:41:39 +0000578}
579
Guido van Rossum79f25d91997-04-29 20:08:16 +0000580static PyObject *
Guido van Rossumd8faa362007-04-27 19:54:29 +0000581builtin_compile(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum5b722181993-03-30 17:46:03 +0000582{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000583 char *str;
Victor Stinner14e461d2013-08-26 22:28:21 +0200584 PyObject *filename;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000585 char *startstr;
586 int mode = -1;
587 int dont_inherit = 0;
588 int supplied_flags = 0;
Georg Brandl8334fd92010-12-04 10:26:46 +0000589 int optimize = -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000590 int is_ast;
591 PyCompilerFlags cf;
592 PyObject *cmd;
593 static char *kwlist[] = {"source", "filename", "mode", "flags",
Georg Brandl8334fd92010-12-04 10:26:46 +0000594 "dont_inherit", "optimize", NULL};
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000595 int start[] = {Py_file_input, Py_eval_input, Py_single_input};
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000596 PyObject *result;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000597
Georg Brandl8334fd92010-12-04 10:26:46 +0000598 if (!PyArg_ParseTupleAndKeywords(args, kwds, "OO&s|iii:compile", kwlist,
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000599 &cmd,
Victor Stinner14e461d2013-08-26 22:28:21 +0200600 PyUnicode_FSDecoder, &filename,
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000601 &startstr, &supplied_flags,
Georg Brandl8334fd92010-12-04 10:26:46 +0000602 &dont_inherit, &optimize))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000603 return NULL;
Tim Peters6cd6a822001-08-17 22:11:27 +0000604
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000605 cf.cf_flags = supplied_flags | PyCF_SOURCE_IS_UTF8;
Just van Rossum3aaf42c2003-02-10 08:21:10 +0000606
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000607 if (supplied_flags &
608 ~(PyCF_MASK | PyCF_MASK_OBSOLETE | PyCF_DONT_IMPLY_DEDENT | PyCF_ONLY_AST))
609 {
610 PyErr_SetString(PyExc_ValueError,
611 "compile(): unrecognised flags");
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000612 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000613 }
614 /* XXX Warn if (supplied_flags & PyCF_MASK_OBSOLETE) != 0? */
Tim Peters6cd6a822001-08-17 22:11:27 +0000615
Georg Brandl8334fd92010-12-04 10:26:46 +0000616 if (optimize < -1 || optimize > 2) {
617 PyErr_SetString(PyExc_ValueError,
618 "compile(): invalid optimize value");
619 goto error;
620 }
621
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000622 if (!dont_inherit) {
623 PyEval_MergeCompilerFlags(&cf);
624 }
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000625
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000626 if (strcmp(startstr, "exec") == 0)
627 mode = 0;
628 else if (strcmp(startstr, "eval") == 0)
629 mode = 1;
630 else if (strcmp(startstr, "single") == 0)
631 mode = 2;
632 else {
633 PyErr_SetString(PyExc_ValueError,
634 "compile() arg 3 must be 'exec', 'eval' or 'single'");
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000635 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000636 }
Neal Norwitzdb4115f2008-03-31 04:20:05 +0000637
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000638 is_ast = PyAST_Check(cmd);
639 if (is_ast == -1)
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000640 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000641 if (is_ast) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000642 if (supplied_flags & PyCF_ONLY_AST) {
643 Py_INCREF(cmd);
644 result = cmd;
645 }
646 else {
647 PyArena *arena;
648 mod_ty mod;
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000649
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000650 arena = PyArena_New();
Stefan Krah07795df2012-08-20 17:19:50 +0200651 if (arena == NULL)
652 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000653 mod = PyAST_obj2mod(cmd, arena, mode);
654 if (mod == NULL) {
655 PyArena_Free(arena);
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000656 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000657 }
Benjamin Peterson832bfe22011-08-09 16:15:04 -0500658 if (!PyAST_Validate(mod)) {
659 PyArena_Free(arena);
660 goto error;
661 }
Victor Stinner14e461d2013-08-26 22:28:21 +0200662 result = (PyObject*)PyAST_CompileObject(mod, filename,
663 &cf, optimize, arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000664 PyArena_Free(arena);
665 }
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000666 goto finally;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000667 }
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000668
Philip Jenveyf76f0ee2012-12-13 15:44:18 -0800669 str = source_as_string(cmd, "compile", "string, bytes or AST", &cf);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000670 if (str == NULL)
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000671 goto error;
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000672
Victor Stinner14e461d2013-08-26 22:28:21 +0200673 result = Py_CompileStringObject(str, filename, start[mode], &cf, optimize);
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000674 goto finally;
675
676error:
677 result = NULL;
678finally:
Victor Stinner14e461d2013-08-26 22:28:21 +0200679 Py_DECREF(filename);
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000680 return result;
Guido van Rossum5b722181993-03-30 17:46:03 +0000681}
682
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000683PyDoc_STRVAR(compile_doc,
Tim Peters6cd6a822001-08-17 22:11:27 +0000684"compile(source, filename, mode[, flags[, dont_inherit]]) -> code object\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000685\n\
686Compile the source string (a Python module, statement or expression)\n\
Georg Brandl7cae87c2006-09-06 06:51:57 +0000687into a code object that can be executed by exec() or eval().\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000688The filename will be used for run-time error messages.\n\
689The mode must be 'exec' to compile a module, 'single' to compile a\n\
Tim Peters6cd6a822001-08-17 22:11:27 +0000690single (interactive) statement, or 'eval' to compile an expression.\n\
691The flags argument, if present, controls which future statements influence\n\
692the compilation of the code.\n\
693The dont_inherit argument, if non-zero, stops the compilation inheriting\n\
694the effects of any future statements in effect in the code calling\n\
695compile; if absent or zero these statements do influence the compilation,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000696in addition to any features explicitly specified.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000697
Guido van Rossum79f25d91997-04-29 20:08:16 +0000698static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000699builtin_dir(PyObject *self, PyObject *args)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000700{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000701 PyObject *arg = NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000702
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000703 if (!PyArg_UnpackTuple(args, "dir", 0, 1, &arg))
704 return NULL;
705 return PyObject_Dir(arg);
Guido van Rossum3f5da241990-12-20 15:06:42 +0000706}
707
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000708PyDoc_STRVAR(dir_doc,
Tim Peters5d2b77c2001-09-03 05:47:38 +0000709"dir([object]) -> list of strings\n"
710"\n"
Georg Brandle32b4222007-03-10 22:13:27 +0000711"If called without an argument, return the names in the current scope.\n"
712"Else, return an alphabetized list of names comprising (some of) the attributes\n"
713"of the given object, and of attributes reachable from it.\n"
714"If the object supplies a method named __dir__, it will be used; otherwise\n"
715"the default dir() logic is used and returns:\n"
716" for a module object: the module's attributes.\n"
717" for a class object: its attributes, and recursively the attributes\n"
718" of its bases.\n"
Guido van Rossumd8faa362007-04-27 19:54:29 +0000719" for any other object: its attributes, its class's attributes, and\n"
Georg Brandle32b4222007-03-10 22:13:27 +0000720" recursively the attributes of its class's base classes.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000721
Guido van Rossum79f25d91997-04-29 20:08:16 +0000722static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000723builtin_divmod(PyObject *self, PyObject *args)
Guido van Rossum6a00cd81995-01-07 12:39:01 +0000724{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000725 PyObject *v, *w;
Guido van Rossum6a00cd81995-01-07 12:39:01 +0000726
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000727 if (!PyArg_UnpackTuple(args, "divmod", 2, 2, &v, &w))
728 return NULL;
729 return PyNumber_Divmod(v, w);
Guido van Rossum3f5da241990-12-20 15:06:42 +0000730}
731
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000732PyDoc_STRVAR(divmod_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000733"divmod(x, y) -> (div, mod)\n\
734\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000735Return the tuple ((x-x%y)/y, x%y). Invariant: div*y + mod == x.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000736
737
Guido van Rossum79f25d91997-04-29 20:08:16 +0000738static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000739builtin_eval(PyObject *self, PyObject *args)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000740{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000741 PyObject *cmd, *result, *tmp = NULL;
742 PyObject *globals = Py_None, *locals = Py_None;
743 char *str;
744 PyCompilerFlags cf;
Guido van Rossum590baa41993-11-30 13:40:46 +0000745
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000746 if (!PyArg_UnpackTuple(args, "eval", 1, 3, &cmd, &globals, &locals))
747 return NULL;
748 if (locals != Py_None && !PyMapping_Check(locals)) {
749 PyErr_SetString(PyExc_TypeError, "locals must be a mapping");
750 return NULL;
751 }
752 if (globals != Py_None && !PyDict_Check(globals)) {
753 PyErr_SetString(PyExc_TypeError, PyMapping_Check(globals) ?
754 "globals must be a real dict; try eval(expr, {}, mapping)"
755 : "globals must be a dict");
756 return NULL;
757 }
758 if (globals == Py_None) {
759 globals = PyEval_GetGlobals();
Victor Stinner41bb43a2013-10-29 01:19:37 +0100760 if (locals == Py_None) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000761 locals = PyEval_GetLocals();
Victor Stinner41bb43a2013-10-29 01:19:37 +0100762 if (locals == NULL)
763 return NULL;
764 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000765 }
766 else if (locals == Py_None)
767 locals = globals;
Tim Peters9fa96be2001-08-17 23:04:59 +0000768
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000769 if (globals == NULL || locals == NULL) {
770 PyErr_SetString(PyExc_TypeError,
771 "eval must be given globals and locals "
772 "when called without a frame");
773 return NULL;
774 }
Georg Brandl77c85e62005-09-15 10:46:13 +0000775
Victor Stinnerb44562b2013-11-06 19:03:11 +0100776 if (_PyDict_GetItemId(globals, &PyId___builtins__) == NULL) {
777 if (_PyDict_SetItemId(globals, &PyId___builtins__,
778 PyEval_GetBuiltins()) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000779 return NULL;
780 }
Tim Peters9fa96be2001-08-17 23:04:59 +0000781
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000782 if (PyCode_Check(cmd)) {
783 if (PyCode_GetNumFree((PyCodeObject *)cmd) > 0) {
784 PyErr_SetString(PyExc_TypeError,
785 "code object passed to eval() may not contain free variables");
786 return NULL;
787 }
Martin v. Löwis4d0d4712010-12-03 20:14:31 +0000788 return PyEval_EvalCode(cmd, globals, locals);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000789 }
Tim Peters9fa96be2001-08-17 23:04:59 +0000790
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000791 cf.cf_flags = PyCF_SOURCE_IS_UTF8;
792 str = source_as_string(cmd, "eval", "string, bytes or code", &cf);
793 if (str == NULL)
794 return NULL;
Just van Rossum3aaf42c2003-02-10 08:21:10 +0000795
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000796 while (*str == ' ' || *str == '\t')
797 str++;
Tim Peters9fa96be2001-08-17 23:04:59 +0000798
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000799 (void)PyEval_MergeCompilerFlags(&cf);
800 result = PyRun_StringFlags(str, Py_eval_input, globals, locals, &cf);
801 Py_XDECREF(tmp);
802 return result;
Guido van Rossum3f5da241990-12-20 15:06:42 +0000803}
804
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000805PyDoc_STRVAR(eval_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000806"eval(source[, globals[, locals]]) -> value\n\
807\n\
808Evaluate the source in the context of globals and locals.\n\
809The source may be a string representing a Python expression\n\
810or a code object as returned by compile().\n\
Thomas Wouters89f507f2006-12-13 04:49:30 +0000811The globals must be a dictionary and locals can be any mapping,\n\
Raymond Hettinger214b1c32004-07-02 06:41:07 +0000812defaulting to the current globals and locals.\n\
813If only globals is given, locals defaults to it.\n");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000814
Georg Brandl7cae87c2006-09-06 06:51:57 +0000815static PyObject *
816builtin_exec(PyObject *self, PyObject *args)
817{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000818 PyObject *v;
819 PyObject *prog, *globals = Py_None, *locals = Py_None;
Georg Brandl7cae87c2006-09-06 06:51:57 +0000820
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000821 if (!PyArg_UnpackTuple(args, "exec", 1, 3, &prog, &globals, &locals))
822 return NULL;
Georg Brandl2cabc562008-08-28 07:57:16 +0000823
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000824 if (globals == Py_None) {
825 globals = PyEval_GetGlobals();
826 if (locals == Py_None) {
827 locals = PyEval_GetLocals();
Victor Stinner41bb43a2013-10-29 01:19:37 +0100828 if (locals == NULL)
829 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000830 }
831 if (!globals || !locals) {
832 PyErr_SetString(PyExc_SystemError,
833 "globals and locals cannot be NULL");
834 return NULL;
835 }
836 }
837 else if (locals == Py_None)
838 locals = globals;
Georg Brandl7cae87c2006-09-06 06:51:57 +0000839
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000840 if (!PyDict_Check(globals)) {
841 PyErr_Format(PyExc_TypeError, "exec() arg 2 must be a dict, not %.100s",
842 globals->ob_type->tp_name);
843 return NULL;
844 }
845 if (!PyMapping_Check(locals)) {
846 PyErr_Format(PyExc_TypeError,
847 "arg 3 must be a mapping or None, not %.100s",
848 locals->ob_type->tp_name);
849 return NULL;
850 }
Victor Stinnerb44562b2013-11-06 19:03:11 +0100851 if (_PyDict_GetItemId(globals, &PyId___builtins__) == NULL) {
852 if (_PyDict_SetItemId(globals, &PyId___builtins__,
853 PyEval_GetBuiltins()) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000854 return NULL;
855 }
856
857 if (PyCode_Check(prog)) {
858 if (PyCode_GetNumFree((PyCodeObject *)prog) > 0) {
859 PyErr_SetString(PyExc_TypeError,
860 "code object passed to exec() may not "
861 "contain free variables");
862 return NULL;
863 }
Martin v. Löwis4d0d4712010-12-03 20:14:31 +0000864 v = PyEval_EvalCode(prog, globals, locals);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000865 }
866 else {
867 char *str;
868 PyCompilerFlags cf;
869 cf.cf_flags = PyCF_SOURCE_IS_UTF8;
870 str = source_as_string(prog, "exec",
871 "string, bytes or code", &cf);
872 if (str == NULL)
873 return NULL;
874 if (PyEval_MergeCompilerFlags(&cf))
875 v = PyRun_StringFlags(str, Py_file_input, globals,
876 locals, &cf);
877 else
878 v = PyRun_String(str, Py_file_input, globals, locals);
879 }
880 if (v == NULL)
881 return NULL;
882 Py_DECREF(v);
883 Py_RETURN_NONE;
Georg Brandl7cae87c2006-09-06 06:51:57 +0000884}
885
886PyDoc_STRVAR(exec_doc,
887"exec(object[, globals[, locals]])\n\
888\n\
Mark Dickinson480e8e32009-12-19 21:19:35 +0000889Read and execute code from an object, which can be a string or a code\n\
Benjamin Peterson38090262009-01-04 15:30:39 +0000890object.\n\
Georg Brandl7cae87c2006-09-06 06:51:57 +0000891The globals and locals are dictionaries, defaulting to the current\n\
892globals and locals. If only globals is given, locals defaults to it.");
893
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000894
Guido van Rossum79f25d91997-04-29 20:08:16 +0000895static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000896builtin_getattr(PyObject *self, PyObject *args)
Guido van Rossum33894be1992-01-27 16:53:09 +0000897{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000898 PyObject *v, *result, *dflt = NULL;
899 PyObject *name;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000900
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000901 if (!PyArg_UnpackTuple(args, "getattr", 2, 3, &v, &name, &dflt))
902 return NULL;
Martin v. Löwis5b222132007-06-10 09:51:05 +0000903
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000904 if (!PyUnicode_Check(name)) {
905 PyErr_SetString(PyExc_TypeError,
906 "getattr(): attribute name must be string");
907 return NULL;
908 }
909 result = PyObject_GetAttr(v, name);
910 if (result == NULL && dflt != NULL &&
911 PyErr_ExceptionMatches(PyExc_AttributeError))
912 {
913 PyErr_Clear();
914 Py_INCREF(dflt);
915 result = dflt;
916 }
917 return result;
Guido van Rossum9bfef441993-03-29 10:43:31 +0000918}
919
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000920PyDoc_STRVAR(getattr_doc,
Guido van Rossum950ff291998-06-29 13:38:57 +0000921"getattr(object, name[, default]) -> value\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000922\n\
Guido van Rossum950ff291998-06-29 13:38:57 +0000923Get a named attribute from an object; getattr(x, 'y') is equivalent to x.y.\n\
924When a default argument is given, it is returned when the attribute doesn't\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000925exist; without it, an exception is raised in that case.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000926
927
Guido van Rossum79f25d91997-04-29 20:08:16 +0000928static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000929builtin_globals(PyObject *self)
Guido van Rossum872537c1995-07-07 22:43:42 +0000930{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000931 PyObject *d;
Guido van Rossum872537c1995-07-07 22:43:42 +0000932
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000933 d = PyEval_GetGlobals();
934 Py_XINCREF(d);
935 return d;
Guido van Rossum872537c1995-07-07 22:43:42 +0000936}
937
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000938PyDoc_STRVAR(globals_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000939"globals() -> dictionary\n\
940\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000941Return the dictionary containing the current scope's global variables.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000942
943
Guido van Rossum79f25d91997-04-29 20:08:16 +0000944static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000945builtin_hasattr(PyObject *self, PyObject *args)
Guido van Rossum9bfef441993-03-29 10:43:31 +0000946{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000947 PyObject *v;
948 PyObject *name;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000949
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000950 if (!PyArg_UnpackTuple(args, "hasattr", 2, 2, &v, &name))
951 return NULL;
952 if (!PyUnicode_Check(name)) {
953 PyErr_SetString(PyExc_TypeError,
954 "hasattr(): attribute name must be string");
955 return NULL;
956 }
957 v = PyObject_GetAttr(v, name);
958 if (v == NULL) {
Benjamin Peterson17689992010-08-24 03:26:23 +0000959 if (PyErr_ExceptionMatches(PyExc_AttributeError)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000960 PyErr_Clear();
Benjamin Peterson17689992010-08-24 03:26:23 +0000961 Py_RETURN_FALSE;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000962 }
Benjamin Peterson17689992010-08-24 03:26:23 +0000963 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000964 }
965 Py_DECREF(v);
Benjamin Peterson17689992010-08-24 03:26:23 +0000966 Py_RETURN_TRUE;
Guido van Rossum33894be1992-01-27 16:53:09 +0000967}
968
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000969PyDoc_STRVAR(hasattr_doc,
Guido van Rossum77f6a652002-04-03 22:41:51 +0000970"hasattr(object, name) -> bool\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000971\n\
972Return whether the object has an attribute with the given name.\n\
Benjamin Peterson17689992010-08-24 03:26:23 +0000973(This is done by calling getattr(object, name) and catching AttributeError.)");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000974
975
Guido van Rossum79f25d91997-04-29 20:08:16 +0000976static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000977builtin_id(PyObject *self, PyObject *v)
Guido van Rossum5b722181993-03-30 17:46:03 +0000978{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000979 return PyLong_FromVoidPtr(v);
Guido van Rossum5b722181993-03-30 17:46:03 +0000980}
981
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000982PyDoc_STRVAR(id_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000983"id(object) -> integer\n\
984\n\
985Return the identity of an object. This is guaranteed to be unique among\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000986simultaneously existing objects. (Hint: it's the object's memory address.)");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000987
988
Raymond Hettingera6c60372008-03-13 01:26:19 +0000989/* map object ************************************************************/
990
991typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000992 PyObject_HEAD
993 PyObject *iters;
994 PyObject *func;
Raymond Hettingera6c60372008-03-13 01:26:19 +0000995} mapobject;
996
Guido van Rossum79f25d91997-04-29 20:08:16 +0000997static PyObject *
Raymond Hettingera6c60372008-03-13 01:26:19 +0000998map_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
Guido van Rossum12d12c51993-10-26 17:58:25 +0000999{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001000 PyObject *it, *iters, *func;
1001 mapobject *lz;
1002 Py_ssize_t numargs, i;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001003
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001004 if (type == &PyMap_Type && !_PyArg_NoKeywords("map()", kwds))
1005 return NULL;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001006
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001007 numargs = PyTuple_Size(args);
1008 if (numargs < 2) {
1009 PyErr_SetString(PyExc_TypeError,
1010 "map() must have at least two arguments.");
1011 return NULL;
1012 }
Raymond Hettingera6c60372008-03-13 01:26:19 +00001013
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001014 iters = PyTuple_New(numargs-1);
1015 if (iters == NULL)
1016 return NULL;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001017
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001018 for (i=1 ; i<numargs ; i++) {
1019 /* Get iterator. */
1020 it = PyObject_GetIter(PyTuple_GET_ITEM(args, i));
1021 if (it == NULL) {
1022 Py_DECREF(iters);
1023 return NULL;
1024 }
1025 PyTuple_SET_ITEM(iters, i-1, it);
1026 }
Raymond Hettingera6c60372008-03-13 01:26:19 +00001027
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001028 /* create mapobject structure */
1029 lz = (mapobject *)type->tp_alloc(type, 0);
1030 if (lz == NULL) {
1031 Py_DECREF(iters);
1032 return NULL;
1033 }
1034 lz->iters = iters;
1035 func = PyTuple_GET_ITEM(args, 0);
1036 Py_INCREF(func);
1037 lz->func = func;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001038
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001039 return (PyObject *)lz;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001040}
1041
1042static void
1043map_dealloc(mapobject *lz)
1044{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001045 PyObject_GC_UnTrack(lz);
1046 Py_XDECREF(lz->iters);
1047 Py_XDECREF(lz->func);
1048 Py_TYPE(lz)->tp_free(lz);
Raymond Hettingera6c60372008-03-13 01:26:19 +00001049}
1050
1051static int
1052map_traverse(mapobject *lz, visitproc visit, void *arg)
1053{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001054 Py_VISIT(lz->iters);
1055 Py_VISIT(lz->func);
1056 return 0;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001057}
1058
1059static PyObject *
1060map_next(mapobject *lz)
1061{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001062 PyObject *val;
1063 PyObject *argtuple;
1064 PyObject *result;
1065 Py_ssize_t numargs, i;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001066
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001067 numargs = PyTuple_Size(lz->iters);
1068 argtuple = PyTuple_New(numargs);
1069 if (argtuple == NULL)
1070 return NULL;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001071
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001072 for (i=0 ; i<numargs ; i++) {
1073 val = PyIter_Next(PyTuple_GET_ITEM(lz->iters, i));
1074 if (val == NULL) {
1075 Py_DECREF(argtuple);
1076 return NULL;
1077 }
1078 PyTuple_SET_ITEM(argtuple, i, val);
1079 }
1080 result = PyObject_Call(lz->func, argtuple, NULL);
1081 Py_DECREF(argtuple);
1082 return result;
Guido van Rossum12d12c51993-10-26 17:58:25 +00001083}
1084
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001085static PyObject *
1086map_reduce(mapobject *lz)
1087{
1088 Py_ssize_t numargs = PyTuple_GET_SIZE(lz->iters);
1089 PyObject *args = PyTuple_New(numargs+1);
1090 Py_ssize_t i;
1091 if (args == NULL)
1092 return NULL;
1093 Py_INCREF(lz->func);
1094 PyTuple_SET_ITEM(args, 0, lz->func);
1095 for (i = 0; i<numargs; i++){
1096 PyObject *it = PyTuple_GET_ITEM(lz->iters, i);
1097 Py_INCREF(it);
1098 PyTuple_SET_ITEM(args, i+1, it);
1099 }
1100
1101 return Py_BuildValue("ON", Py_TYPE(lz), args);
1102}
1103
1104static PyMethodDef map_methods[] = {
1105 {"__reduce__", (PyCFunction)map_reduce, METH_NOARGS, reduce_doc},
1106 {NULL, NULL} /* sentinel */
1107};
1108
1109
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001110PyDoc_STRVAR(map_doc,
Raymond Hettingera6c60372008-03-13 01:26:19 +00001111"map(func, *iterables) --> map object\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001112\n\
Raymond Hettingera6c60372008-03-13 01:26:19 +00001113Make an iterator that computes the function using arguments from\n\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001114each of the iterables. Stops when the shortest iterable is exhausted.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001115
Raymond Hettingera6c60372008-03-13 01:26:19 +00001116PyTypeObject PyMap_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001117 PyVarObject_HEAD_INIT(&PyType_Type, 0)
1118 "map", /* tp_name */
1119 sizeof(mapobject), /* tp_basicsize */
1120 0, /* tp_itemsize */
1121 /* methods */
1122 (destructor)map_dealloc, /* tp_dealloc */
1123 0, /* tp_print */
1124 0, /* tp_getattr */
1125 0, /* tp_setattr */
1126 0, /* tp_reserved */
1127 0, /* tp_repr */
1128 0, /* tp_as_number */
1129 0, /* tp_as_sequence */
1130 0, /* tp_as_mapping */
1131 0, /* tp_hash */
1132 0, /* tp_call */
1133 0, /* tp_str */
1134 PyObject_GenericGetAttr, /* tp_getattro */
1135 0, /* tp_setattro */
1136 0, /* tp_as_buffer */
1137 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
1138 Py_TPFLAGS_BASETYPE, /* tp_flags */
1139 map_doc, /* tp_doc */
1140 (traverseproc)map_traverse, /* tp_traverse */
1141 0, /* tp_clear */
1142 0, /* tp_richcompare */
1143 0, /* tp_weaklistoffset */
1144 PyObject_SelfIter, /* tp_iter */
1145 (iternextfunc)map_next, /* tp_iternext */
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001146 map_methods, /* tp_methods */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001147 0, /* tp_members */
1148 0, /* tp_getset */
1149 0, /* tp_base */
1150 0, /* tp_dict */
1151 0, /* tp_descr_get */
1152 0, /* tp_descr_set */
1153 0, /* tp_dictoffset */
1154 0, /* tp_init */
1155 PyType_GenericAlloc, /* tp_alloc */
1156 map_new, /* tp_new */
1157 PyObject_GC_Del, /* tp_free */
Raymond Hettingera6c60372008-03-13 01:26:19 +00001158};
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001159
Guido van Rossum79f25d91997-04-29 20:08:16 +00001160static PyObject *
Georg Brandla18af4e2007-04-21 15:47:16 +00001161builtin_next(PyObject *self, PyObject *args)
1162{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001163 PyObject *it, *res;
1164 PyObject *def = NULL;
Georg Brandla18af4e2007-04-21 15:47:16 +00001165
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001166 if (!PyArg_UnpackTuple(args, "next", 1, 2, &it, &def))
1167 return NULL;
1168 if (!PyIter_Check(it)) {
1169 PyErr_Format(PyExc_TypeError,
Philip Jenvey50add042011-11-06 16:37:52 -08001170 "'%.200s' object is not an iterator",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001171 it->ob_type->tp_name);
1172 return NULL;
1173 }
1174
1175 res = (*it->ob_type->tp_iternext)(it);
1176 if (res != NULL) {
1177 return res;
1178 } else if (def != NULL) {
1179 if (PyErr_Occurred()) {
1180 if(!PyErr_ExceptionMatches(PyExc_StopIteration))
1181 return NULL;
1182 PyErr_Clear();
1183 }
1184 Py_INCREF(def);
1185 return def;
1186 } else if (PyErr_Occurred()) {
1187 return NULL;
1188 } else {
1189 PyErr_SetNone(PyExc_StopIteration);
1190 return NULL;
1191 }
Georg Brandla18af4e2007-04-21 15:47:16 +00001192}
1193
1194PyDoc_STRVAR(next_doc,
1195"next(iterator[, default])\n\
1196\n\
1197Return the next item from the iterator. If default is given and the iterator\n\
1198is exhausted, it is returned instead of raising StopIteration.");
1199
1200
1201static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001202builtin_setattr(PyObject *self, PyObject *args)
Guido van Rossum33894be1992-01-27 16:53:09 +00001203{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001204 PyObject *v;
1205 PyObject *name;
1206 PyObject *value;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001207
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001208 if (!PyArg_UnpackTuple(args, "setattr", 3, 3, &v, &name, &value))
1209 return NULL;
1210 if (PyObject_SetAttr(v, name, value) != 0)
1211 return NULL;
1212 Py_INCREF(Py_None);
1213 return Py_None;
Guido van Rossum33894be1992-01-27 16:53:09 +00001214}
1215
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001216PyDoc_STRVAR(setattr_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001217"setattr(object, name, value)\n\
1218\n\
1219Set a named attribute on an object; setattr(x, 'y', v) is equivalent to\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001220``x.y = v''.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001221
1222
Guido van Rossum79f25d91997-04-29 20:08:16 +00001223static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001224builtin_delattr(PyObject *self, PyObject *args)
Guido van Rossum14144fc1994-08-29 12:53:40 +00001225{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001226 PyObject *v;
1227 PyObject *name;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001228
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001229 if (!PyArg_UnpackTuple(args, "delattr", 2, 2, &v, &name))
1230 return NULL;
1231 if (PyObject_SetAttr(v, name, (PyObject *)NULL) != 0)
1232 return NULL;
1233 Py_INCREF(Py_None);
1234 return Py_None;
Guido van Rossum14144fc1994-08-29 12:53:40 +00001235}
1236
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001237PyDoc_STRVAR(delattr_doc,
Guido van Rossumdf12a591998-11-23 22:13:04 +00001238"delattr(object, name)\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001239\n\
1240Delete a named attribute on an object; delattr(x, 'y') is equivalent to\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001241``del x.y''.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001242
1243
Guido van Rossum79f25d91997-04-29 20:08:16 +00001244static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001245builtin_hash(PyObject *self, PyObject *v)
Guido van Rossum9bfef441993-03-29 10:43:31 +00001246{
Benjamin Peterson8f67d082010-10-17 20:54:53 +00001247 Py_hash_t x;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001248
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001249 x = PyObject_Hash(v);
1250 if (x == -1)
1251 return NULL;
Benjamin Peterson8f67d082010-10-17 20:54:53 +00001252 return PyLong_FromSsize_t(x);
Guido van Rossum9bfef441993-03-29 10:43:31 +00001253}
1254
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001255PyDoc_STRVAR(hash_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001256"hash(object) -> integer\n\
1257\n\
1258Return a hash value for the object. Two objects with the same value have\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001259the same hash value. The reverse is not necessarily true, but likely.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001260
1261
Guido van Rossum79f25d91997-04-29 20:08:16 +00001262static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001263builtin_hex(PyObject *self, PyObject *v)
Guido van Rossum006bcd41991-10-24 14:54:44 +00001264{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001265 return PyNumber_ToBase(v, 16);
Guido van Rossum006bcd41991-10-24 14:54:44 +00001266}
1267
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001268PyDoc_STRVAR(hex_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001269"hex(number) -> string\n\
1270\n\
Alexander Belopolsky12338ab2011-04-07 00:15:33 -04001271Return the hexadecimal representation of an integer.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001272
1273
Guido van Rossum79f25d91997-04-29 20:08:16 +00001274static PyObject *
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001275builtin_iter(PyObject *self, PyObject *args)
1276{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001277 PyObject *v, *w = NULL;
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001278
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001279 if (!PyArg_UnpackTuple(args, "iter", 1, 2, &v, &w))
1280 return NULL;
1281 if (w == NULL)
1282 return PyObject_GetIter(v);
1283 if (!PyCallable_Check(v)) {
1284 PyErr_SetString(PyExc_TypeError,
1285 "iter(v, w): v must be callable");
1286 return NULL;
1287 }
1288 return PyCallIter_New(v, w);
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001289}
1290
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001291PyDoc_STRVAR(iter_doc,
Georg Brandld11ae5d2008-05-16 13:27:32 +00001292"iter(iterable) -> iterator\n\
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001293iter(callable, sentinel) -> iterator\n\
1294\n\
1295Get an iterator from an object. In the first form, the argument must\n\
1296supply its own iterator, or be a sequence.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001297In the second form, the callable is called until it returns the sentinel.");
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001298
1299
1300static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001301builtin_len(PyObject *self, PyObject *v)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001302{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001303 Py_ssize_t res;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001304
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001305 res = PyObject_Size(v);
1306 if (res < 0 && PyErr_Occurred())
1307 return NULL;
1308 return PyLong_FromSsize_t(res);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001309}
1310
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001311PyDoc_STRVAR(len_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001312"len(object) -> integer\n\
1313\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001314Return the number of items of a sequence or mapping.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001315
1316
Guido van Rossum79f25d91997-04-29 20:08:16 +00001317static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001318builtin_locals(PyObject *self)
Guido van Rossum872537c1995-07-07 22:43:42 +00001319{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001320 PyObject *d;
Guido van Rossum872537c1995-07-07 22:43:42 +00001321
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001322 d = PyEval_GetLocals();
1323 Py_XINCREF(d);
1324 return d;
Guido van Rossum872537c1995-07-07 22:43:42 +00001325}
1326
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001327PyDoc_STRVAR(locals_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001328"locals() -> dictionary\n\
1329\n\
Raymond Hettinger69bf8f32003-01-04 02:16:22 +00001330Update and return a dictionary containing the current scope's local variables.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001331
1332
Guido van Rossum79f25d91997-04-29 20:08:16 +00001333static PyObject *
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001334min_max(PyObject *args, PyObject *kwds, int op)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001335{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001336 PyObject *v, *it, *item, *val, *maxitem, *maxval, *keyfunc=NULL;
Raymond Hettinger4d6018f2013-06-24 22:43:02 -07001337 PyObject *emptytuple, *defaultval = NULL;
1338 static char *kwlist[] = {"key", "default", NULL};
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001339 const char *name = op == Py_LT ? "min" : "max";
Raymond Hettinger4d6018f2013-06-24 22:43:02 -07001340 const int positional = PyTuple_Size(args) > 1;
1341 int ret;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001342
Raymond Hettinger4d6018f2013-06-24 22:43:02 -07001343 if (positional)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001344 v = args;
Serhiy Storchakac6792272013-10-19 21:03:34 +03001345 else if (!PyArg_UnpackTuple(args, name, 1, 1, &v))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001346 return NULL;
Tim Peters67d687a2002-04-29 21:27:32 +00001347
Raymond Hettinger4d6018f2013-06-24 22:43:02 -07001348 emptytuple = PyTuple_New(0);
1349 if (emptytuple == NULL)
1350 return NULL;
1351 ret = PyArg_ParseTupleAndKeywords(emptytuple, kwds, "|$OO", kwlist,
1352 &keyfunc, &defaultval);
1353 Py_DECREF(emptytuple);
1354 if (!ret)
1355 return NULL;
1356
1357 if (positional && defaultval != NULL) {
1358 PyErr_Format(PyExc_TypeError,
1359 "Cannot specify a default for %s() with multiple "
1360 "positional arguments", name);
1361 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001362 }
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001363
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001364 it = PyObject_GetIter(v);
1365 if (it == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001366 return NULL;
1367 }
Tim Petersc3074532001-05-03 07:00:32 +00001368
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001369 maxitem = NULL; /* the result */
1370 maxval = NULL; /* the value associated with the result */
1371 while (( item = PyIter_Next(it) )) {
1372 /* get the value from the key function */
1373 if (keyfunc != NULL) {
1374 val = PyObject_CallFunctionObjArgs(keyfunc, item, NULL);
1375 if (val == NULL)
1376 goto Fail_it_item;
1377 }
1378 /* no key function; the value is the item */
1379 else {
1380 val = item;
1381 Py_INCREF(val);
1382 }
Tim Petersc3074532001-05-03 07:00:32 +00001383
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001384 /* maximum value and item are unset; set them */
1385 if (maxval == NULL) {
1386 maxitem = item;
1387 maxval = val;
1388 }
1389 /* maximum value and item are set; update them as necessary */
1390 else {
1391 int cmp = PyObject_RichCompareBool(val, maxval, op);
1392 if (cmp < 0)
1393 goto Fail_it_item_and_val;
1394 else if (cmp > 0) {
1395 Py_DECREF(maxval);
1396 Py_DECREF(maxitem);
1397 maxval = val;
1398 maxitem = item;
1399 }
1400 else {
1401 Py_DECREF(item);
1402 Py_DECREF(val);
1403 }
1404 }
1405 }
1406 if (PyErr_Occurred())
1407 goto Fail_it;
1408 if (maxval == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001409 assert(maxitem == NULL);
Raymond Hettinger4d6018f2013-06-24 22:43:02 -07001410 if (defaultval != NULL) {
1411 Py_INCREF(defaultval);
1412 maxitem = defaultval;
1413 } else {
1414 PyErr_Format(PyExc_ValueError,
1415 "%s() arg is an empty sequence", name);
1416 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001417 }
1418 else
1419 Py_DECREF(maxval);
1420 Py_DECREF(it);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001421 return maxitem;
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001422
1423Fail_it_item_and_val:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001424 Py_DECREF(val);
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001425Fail_it_item:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001426 Py_DECREF(item);
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001427Fail_it:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001428 Py_XDECREF(maxval);
1429 Py_XDECREF(maxitem);
1430 Py_DECREF(it);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001431 return NULL;
Guido van Rossum3f5da241990-12-20 15:06:42 +00001432}
1433
Guido van Rossum79f25d91997-04-29 20:08:16 +00001434static PyObject *
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001435builtin_min(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001436{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001437 return min_max(args, kwds, Py_LT);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001438}
1439
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001440PyDoc_STRVAR(min_doc,
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001441"min(iterable[, key=func]) -> value\n\
1442min(a, b, c, ...[, key=func]) -> value\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001443\n\
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001444With a single iterable argument, return its smallest item.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001445With two or more arguments, return the smallest argument.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001446
1447
Guido van Rossum79f25d91997-04-29 20:08:16 +00001448static PyObject *
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001449builtin_max(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001450{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001451 return min_max(args, kwds, Py_GT);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001452}
1453
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001454PyDoc_STRVAR(max_doc,
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001455"max(iterable[, key=func]) -> value\n\
1456max(a, b, c, ...[, key=func]) -> value\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001457\n\
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001458With a single iterable argument, return its largest item.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001459With two or more arguments, return the largest argument.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001460
1461
Guido van Rossum79f25d91997-04-29 20:08:16 +00001462static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001463builtin_oct(PyObject *self, PyObject *v)
Guido van Rossum006bcd41991-10-24 14:54:44 +00001464{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001465 return PyNumber_ToBase(v, 8);
Guido van Rossum006bcd41991-10-24 14:54:44 +00001466}
1467
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001468PyDoc_STRVAR(oct_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001469"oct(number) -> string\n\
1470\n\
Alexander Belopolsky12338ab2011-04-07 00:15:33 -04001471Return the octal representation of an integer.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001472
1473
Guido van Rossum79f25d91997-04-29 20:08:16 +00001474static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001475builtin_ord(PyObject *self, PyObject* obj)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001476{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001477 long ord;
1478 Py_ssize_t size;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001479
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001480 if (PyBytes_Check(obj)) {
1481 size = PyBytes_GET_SIZE(obj);
1482 if (size == 1) {
1483 ord = (long)((unsigned char)*PyBytes_AS_STRING(obj));
1484 return PyLong_FromLong(ord);
1485 }
1486 }
1487 else if (PyUnicode_Check(obj)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001488 if (PyUnicode_READY(obj) == -1)
1489 return NULL;
1490 size = PyUnicode_GET_LENGTH(obj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001491 if (size == 1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001492 ord = (long)PyUnicode_READ_CHAR(obj, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001493 return PyLong_FromLong(ord);
1494 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001495 }
1496 else if (PyByteArray_Check(obj)) {
1497 /* XXX Hopefully this is temporary */
1498 size = PyByteArray_GET_SIZE(obj);
1499 if (size == 1) {
1500 ord = (long)((unsigned char)*PyByteArray_AS_STRING(obj));
1501 return PyLong_FromLong(ord);
1502 }
1503 }
1504 else {
1505 PyErr_Format(PyExc_TypeError,
1506 "ord() expected string of length 1, but " \
1507 "%.200s found", obj->ob_type->tp_name);
1508 return NULL;
1509 }
Guido van Rossum09095f32000-03-10 23:00:52 +00001510
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001511 PyErr_Format(PyExc_TypeError,
1512 "ord() expected a character, "
1513 "but string of length %zd found",
1514 size);
1515 return NULL;
Guido van Rossum3f5da241990-12-20 15:06:42 +00001516}
1517
Guido van Rossum307fa8c2007-07-16 20:46:27 +00001518PyDoc_VAR(ord_doc) = PyDoc_STR(
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001519"ord(c) -> integer\n\
1520\n\
Guido van Rossum8ac004e2007-07-15 13:00:05 +00001521Return the integer ordinal of a one-character string."
Antoine Pitrouedc60182012-06-23 14:19:58 +02001522);
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001523
1524
Guido van Rossum79f25d91997-04-29 20:08:16 +00001525static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001526builtin_pow(PyObject *self, PyObject *args)
Guido van Rossum6a00cd81995-01-07 12:39:01 +00001527{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001528 PyObject *v, *w, *z = Py_None;
Guido van Rossum6a00cd81995-01-07 12:39:01 +00001529
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001530 if (!PyArg_UnpackTuple(args, "pow", 2, 3, &v, &w, &z))
1531 return NULL;
1532 return PyNumber_Power(v, w, z);
Guido van Rossumd4905451991-05-05 20:00:36 +00001533}
1534
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001535PyDoc_STRVAR(pow_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001536"pow(x, y[, z]) -> number\n\
1537\n\
1538With two arguments, equivalent to x**y. With three arguments,\n\
Serhiy Storchaka95949422013-08-27 19:40:23 +03001539equivalent to (x**y) % z, but may be more efficient (e.g. for ints).");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001540
1541
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001542
Guido van Rossum34343512006-11-30 22:13:52 +00001543static PyObject *
1544builtin_print(PyObject *self, PyObject *args, PyObject *kwds)
1545{
Georg Brandlbc3b6822012-01-13 19:41:25 +01001546 static char *kwlist[] = {"sep", "end", "file", "flush", 0};
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001547 static PyObject *dummy_args;
Georg Brandlbc3b6822012-01-13 19:41:25 +01001548 PyObject *sep = NULL, *end = NULL, *file = NULL, *flush = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001549 int i, err;
Victor Stinnereaa28832013-11-07 00:01:51 +01001550 _Py_IDENTIFIER(flush);
Guido van Rossum34343512006-11-30 22:13:52 +00001551
Benjamin Peterson00102562012-01-11 21:00:16 -05001552 if (dummy_args == NULL && !(dummy_args = PyTuple_New(0)))
Georg Brandlbc3b6822012-01-13 19:41:25 +01001553 return NULL;
1554 if (!PyArg_ParseTupleAndKeywords(dummy_args, kwds, "|OOOO:print",
1555 kwlist, &sep, &end, &file, &flush))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001556 return NULL;
1557 if (file == NULL || file == Py_None) {
Victor Stinner09054372013-11-06 22:41:44 +01001558 file = _PySys_GetObjectId(&_PyId_stdout);
Victor Stinner1e53bba2013-07-16 22:26:05 +02001559 if (file == NULL) {
1560 PyErr_SetString(PyExc_RuntimeError, "lost sys.stdout");
1561 return NULL;
1562 }
1563
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001564 /* sys.stdout may be None when FILE* stdout isn't connected */
1565 if (file == Py_None)
1566 Py_RETURN_NONE;
1567 }
Guido van Rossum34343512006-11-30 22:13:52 +00001568
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001569 if (sep == Py_None) {
1570 sep = NULL;
1571 }
1572 else if (sep && !PyUnicode_Check(sep)) {
1573 PyErr_Format(PyExc_TypeError,
1574 "sep must be None or a string, not %.200s",
1575 sep->ob_type->tp_name);
1576 return NULL;
1577 }
1578 if (end == Py_None) {
1579 end = NULL;
1580 }
1581 else if (end && !PyUnicode_Check(end)) {
1582 PyErr_Format(PyExc_TypeError,
1583 "end must be None or a string, not %.200s",
1584 end->ob_type->tp_name);
1585 return NULL;
1586 }
Guido van Rossum34343512006-11-30 22:13:52 +00001587
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001588 for (i = 0; i < PyTuple_Size(args); i++) {
1589 if (i > 0) {
1590 if (sep == NULL)
1591 err = PyFile_WriteString(" ", file);
1592 else
1593 err = PyFile_WriteObject(sep, file,
1594 Py_PRINT_RAW);
1595 if (err)
1596 return NULL;
1597 }
1598 err = PyFile_WriteObject(PyTuple_GetItem(args, i), file,
1599 Py_PRINT_RAW);
1600 if (err)
1601 return NULL;
1602 }
Guido van Rossum34343512006-11-30 22:13:52 +00001603
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001604 if (end == NULL)
1605 err = PyFile_WriteString("\n", file);
1606 else
1607 err = PyFile_WriteObject(end, file, Py_PRINT_RAW);
1608 if (err)
1609 return NULL;
Guido van Rossum34343512006-11-30 22:13:52 +00001610
Georg Brandlbc3b6822012-01-13 19:41:25 +01001611 if (flush != NULL) {
1612 PyObject *tmp;
1613 int do_flush = PyObject_IsTrue(flush);
1614 if (do_flush == -1)
1615 return NULL;
1616 else if (do_flush) {
Victor Stinnereaa28832013-11-07 00:01:51 +01001617 tmp = _PyObject_CallMethodId(file, &PyId_flush, "");
Georg Brandlbc3b6822012-01-13 19:41:25 +01001618 if (tmp == NULL)
1619 return NULL;
1620 else
1621 Py_DECREF(tmp);
1622 }
1623 }
1624
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001625 Py_RETURN_NONE;
Guido van Rossum34343512006-11-30 22:13:52 +00001626}
1627
1628PyDoc_STRVAR(print_doc,
Senthil Kumarane9175bd2012-08-10 13:53:45 -07001629"print(value, ..., sep=' ', end='\\n', file=sys.stdout, flush=False)\n\
Guido van Rossum34343512006-11-30 22:13:52 +00001630\n\
1631Prints the values to a stream, or to sys.stdout by default.\n\
1632Optional keyword arguments:\n\
Senthil Kumarane9175bd2012-08-10 13:53:45 -07001633file: a file-like object (stream); defaults to the current sys.stdout.\n\
1634sep: string inserted between values, default a space.\n\
1635end: string appended after the last value, default a newline.\n\
1636flush: whether to forcibly flush the stream.");
Guido van Rossum34343512006-11-30 22:13:52 +00001637
1638
Guido van Rossuma88a0332007-02-26 16:59:55 +00001639static PyObject *
1640builtin_input(PyObject *self, PyObject *args)
1641{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001642 PyObject *promptarg = NULL;
Victor Stinner09054372013-11-06 22:41:44 +01001643 PyObject *fin = _PySys_GetObjectId(&_PyId_stdin);
1644 PyObject *fout = _PySys_GetObjectId(&_PyId_stdout);
1645 PyObject *ferr = _PySys_GetObjectId(&_PyId_stderr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001646 PyObject *tmp;
1647 long fd;
1648 int tty;
Guido van Rossuma88a0332007-02-26 16:59:55 +00001649
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001650 /* Parse arguments */
1651 if (!PyArg_UnpackTuple(args, "input", 0, 1, &promptarg))
1652 return NULL;
Guido van Rossuma88a0332007-02-26 16:59:55 +00001653
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001654 /* Check that stdin/out/err are intact */
1655 if (fin == NULL || fin == Py_None) {
1656 PyErr_SetString(PyExc_RuntimeError,
1657 "input(): lost sys.stdin");
1658 return NULL;
1659 }
1660 if (fout == NULL || fout == Py_None) {
1661 PyErr_SetString(PyExc_RuntimeError,
1662 "input(): lost sys.stdout");
1663 return NULL;
1664 }
1665 if (ferr == NULL || ferr == Py_None) {
1666 PyErr_SetString(PyExc_RuntimeError,
1667 "input(): lost sys.stderr");
1668 return NULL;
1669 }
Guido van Rossumeba76962007-05-27 09:13:28 +00001670
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001671 /* First of all, flush stderr */
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001672 tmp = _PyObject_CallMethodId(ferr, &PyId_flush, "");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001673 if (tmp == NULL)
1674 PyErr_Clear();
1675 else
1676 Py_DECREF(tmp);
Guido van Rossumeba76962007-05-27 09:13:28 +00001677
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001678 /* We should only use (GNU) readline if Python's sys.stdin and
1679 sys.stdout are the same as C's stdin and stdout, because we
1680 need to pass it those. */
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001681 tmp = _PyObject_CallMethodId(fin, &PyId_fileno, "");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001682 if (tmp == NULL) {
1683 PyErr_Clear();
1684 tty = 0;
1685 }
1686 else {
1687 fd = PyLong_AsLong(tmp);
1688 Py_DECREF(tmp);
1689 if (fd < 0 && PyErr_Occurred())
1690 return NULL;
1691 tty = fd == fileno(stdin) && isatty(fd);
1692 }
1693 if (tty) {
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001694 tmp = _PyObject_CallMethodId(fout, &PyId_fileno, "");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001695 if (tmp == NULL)
1696 PyErr_Clear();
1697 else {
1698 fd = PyLong_AsLong(tmp);
1699 Py_DECREF(tmp);
1700 if (fd < 0 && PyErr_Occurred())
1701 return NULL;
1702 tty = fd == fileno(stdout) && isatty(fd);
1703 }
1704 }
Guido van Rossumeba76962007-05-27 09:13:28 +00001705
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001706 /* If we're interactive, use (GNU) readline */
1707 if (tty) {
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001708 PyObject *po = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001709 char *prompt;
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001710 char *s = NULL;
1711 PyObject *stdin_encoding = NULL, *stdin_errors = NULL;
1712 PyObject *stdout_encoding = NULL, *stdout_errors = NULL;
1713 char *stdin_encoding_str, *stdin_errors_str;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001714 PyObject *result;
Victor Stinnerc0f1a1a2011-02-23 12:07:37 +00001715 size_t len;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02001716 _Py_IDENTIFIER(encoding);
Antoine Pitrou5ee9d8a2011-11-06 00:38:45 +01001717 _Py_IDENTIFIER(errors);
Martin v. Löwis4a7b5d52007-09-04 05:24:49 +00001718
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02001719 stdin_encoding = _PyObject_GetAttrId(fin, &PyId_encoding);
Antoine Pitrou5ee9d8a2011-11-06 00:38:45 +01001720 stdin_errors = _PyObject_GetAttrId(fin, &PyId_errors);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001721 if (!stdin_encoding || !stdin_errors)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001722 /* stdin is a text stream, so it must have an
1723 encoding. */
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001724 goto _readline_errors;
Victor Stinner306f0102010-05-19 01:06:22 +00001725 stdin_encoding_str = _PyUnicode_AsString(stdin_encoding);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001726 stdin_errors_str = _PyUnicode_AsString(stdin_errors);
1727 if (!stdin_encoding_str || !stdin_errors_str)
1728 goto _readline_errors;
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001729 tmp = _PyObject_CallMethodId(fout, &PyId_flush, "");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001730 if (tmp == NULL)
1731 PyErr_Clear();
1732 else
1733 Py_DECREF(tmp);
1734 if (promptarg != NULL) {
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001735 /* We have a prompt, encode it as stdout would */
1736 char *stdout_encoding_str, *stdout_errors_str;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001737 PyObject *stringpo;
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02001738 stdout_encoding = _PyObject_GetAttrId(fout, &PyId_encoding);
Antoine Pitrou5ee9d8a2011-11-06 00:38:45 +01001739 stdout_errors = _PyObject_GetAttrId(fout, &PyId_errors);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001740 if (!stdout_encoding || !stdout_errors)
1741 goto _readline_errors;
Victor Stinner306f0102010-05-19 01:06:22 +00001742 stdout_encoding_str = _PyUnicode_AsString(stdout_encoding);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001743 stdout_errors_str = _PyUnicode_AsString(stdout_errors);
1744 if (!stdout_encoding_str || !stdout_errors_str)
1745 goto _readline_errors;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001746 stringpo = PyObject_Str(promptarg);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001747 if (stringpo == NULL)
1748 goto _readline_errors;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001749 po = PyUnicode_AsEncodedString(stringpo,
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001750 stdout_encoding_str, stdout_errors_str);
1751 Py_CLEAR(stdout_encoding);
1752 Py_CLEAR(stdout_errors);
1753 Py_CLEAR(stringpo);
1754 if (po == NULL)
1755 goto _readline_errors;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001756 prompt = PyBytes_AsString(po);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001757 if (prompt == NULL)
1758 goto _readline_errors;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001759 }
1760 else {
1761 po = NULL;
1762 prompt = "";
1763 }
1764 s = PyOS_Readline(stdin, stdout, prompt);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001765 if (s == NULL) {
Richard Oudkerk614c5782013-04-03 13:44:50 +01001766 PyErr_CheckSignals();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001767 if (!PyErr_Occurred())
1768 PyErr_SetNone(PyExc_KeyboardInterrupt);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001769 goto _readline_errors;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001770 }
Victor Stinnerc0f1a1a2011-02-23 12:07:37 +00001771
1772 len = strlen(s);
1773 if (len == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001774 PyErr_SetNone(PyExc_EOFError);
1775 result = NULL;
1776 }
Victor Stinnerc0f1a1a2011-02-23 12:07:37 +00001777 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001778 if (len > PY_SSIZE_T_MAX) {
1779 PyErr_SetString(PyExc_OverflowError,
1780 "input: input too long");
1781 result = NULL;
1782 }
1783 else {
Victor Stinnerc0f1a1a2011-02-23 12:07:37 +00001784 len--; /* strip trailing '\n' */
1785 if (len != 0 && s[len-1] == '\r')
1786 len--; /* strip trailing '\r' */
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001787 result = PyUnicode_Decode(s, len, stdin_encoding_str,
1788 stdin_errors_str);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001789 }
1790 }
1791 Py_DECREF(stdin_encoding);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001792 Py_DECREF(stdin_errors);
1793 Py_XDECREF(po);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001794 PyMem_FREE(s);
1795 return result;
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001796 _readline_errors:
1797 Py_XDECREF(stdin_encoding);
1798 Py_XDECREF(stdout_encoding);
1799 Py_XDECREF(stdin_errors);
1800 Py_XDECREF(stdout_errors);
1801 Py_XDECREF(po);
1802 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001803 }
Guido van Rossumeba76962007-05-27 09:13:28 +00001804
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001805 /* Fallback if we're not interactive */
1806 if (promptarg != NULL) {
1807 if (PyFile_WriteObject(promptarg, fout, Py_PRINT_RAW) != 0)
1808 return NULL;
1809 }
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001810 tmp = _PyObject_CallMethodId(fout, &PyId_flush, "");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001811 if (tmp == NULL)
1812 PyErr_Clear();
1813 else
1814 Py_DECREF(tmp);
1815 return PyFile_GetLine(fin, -1);
Guido van Rossuma88a0332007-02-26 16:59:55 +00001816}
1817
1818PyDoc_STRVAR(input_doc,
1819"input([prompt]) -> string\n\
1820\n\
1821Read a string from standard input. The trailing newline is stripped.\n\
1822If the user hits EOF (Unix: Ctl-D, Windows: Ctl-Z+Return), raise EOFError.\n\
1823On Unix, GNU readline is used if enabled. The prompt string, if given,\n\
1824is printed without a trailing newline before reading.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001825
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001826
Guido van Rossum79f25d91997-04-29 20:08:16 +00001827static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001828builtin_repr(PyObject *self, PyObject *v)
Guido van Rossumc89705d1992-11-26 08:54:07 +00001829{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001830 return PyObject_Repr(v);
Guido van Rossumc89705d1992-11-26 08:54:07 +00001831}
1832
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001833PyDoc_STRVAR(repr_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001834"repr(object) -> string\n\
1835\n\
1836Return the canonical string representation of the object.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001837For most object types, eval(repr(object)) == object.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001838
1839
Guido van Rossum79f25d91997-04-29 20:08:16 +00001840static PyObject *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001841builtin_round(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum9e51f9b1993-02-12 16:29:05 +00001842{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001843 PyObject *ndigits = NULL;
1844 static char *kwlist[] = {"number", "ndigits", 0};
Benjamin Peterson214a7d22013-04-13 17:19:01 -04001845 PyObject *number, *round, *result;
1846 _Py_IDENTIFIER(__round__);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001847
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001848 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|O:round",
1849 kwlist, &number, &ndigits))
1850 return NULL;
Alex Martelliae211f92007-08-22 23:21:33 +00001851
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001852 if (Py_TYPE(number)->tp_dict == NULL) {
1853 if (PyType_Ready(Py_TYPE(number)) < 0)
1854 return NULL;
1855 }
Guido van Rossum15d3d042007-08-24 02:02:45 +00001856
Benjamin Peterson214a7d22013-04-13 17:19:01 -04001857 round = _PyObject_LookupSpecial(number, &PyId___round__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001858 if (round == NULL) {
Benjamin Peterson214a7d22013-04-13 17:19:01 -04001859 if (!PyErr_Occurred())
1860 PyErr_Format(PyExc_TypeError,
1861 "type %.100s doesn't define __round__ method",
1862 Py_TYPE(number)->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001863 return NULL;
1864 }
Alex Martelliae211f92007-08-22 23:21:33 +00001865
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001866 if (ndigits == NULL)
Benjamin Peterson214a7d22013-04-13 17:19:01 -04001867 result = PyObject_CallFunctionObjArgs(round, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001868 else
Benjamin Peterson214a7d22013-04-13 17:19:01 -04001869 result = PyObject_CallFunctionObjArgs(round, ndigits, NULL);
1870 Py_DECREF(round);
1871 return result;
Guido van Rossum9e51f9b1993-02-12 16:29:05 +00001872}
1873
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001874PyDoc_STRVAR(round_doc,
Mark Dickinson1124e712009-01-28 21:25:58 +00001875"round(number[, ndigits]) -> number\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001876\n\
1877Round a number to a given precision in decimal digits (default 0 digits).\n\
Mark Dickinson0d748c22008-07-05 11:29:03 +00001878This returns an int when called with one argument, otherwise the\n\
Georg Brandl809ddaa2008-07-01 20:39:59 +00001879same type as the number. ndigits may be negative.");
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001880
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001881
Raymond Hettinger64958a12003-12-17 20:43:33 +00001882static PyObject *
1883builtin_sorted(PyObject *self, PyObject *args, PyObject *kwds)
1884{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001885 PyObject *newlist, *v, *seq, *keyfunc=NULL, *newargs;
1886 PyObject *callable;
1887 static char *kwlist[] = {"iterable", "key", "reverse", 0};
1888 int reverse;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02001889 _Py_IDENTIFIER(sort);
Raymond Hettinger64958a12003-12-17 20:43:33 +00001890
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001891 /* args 1-3 should match listsort in Objects/listobject.c */
1892 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|Oi:sorted",
1893 kwlist, &seq, &keyfunc, &reverse))
1894 return NULL;
Raymond Hettinger64958a12003-12-17 20:43:33 +00001895
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001896 newlist = PySequence_List(seq);
1897 if (newlist == NULL)
1898 return NULL;
Raymond Hettinger64958a12003-12-17 20:43:33 +00001899
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02001900 callable = _PyObject_GetAttrId(newlist, &PyId_sort);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001901 if (callable == NULL) {
1902 Py_DECREF(newlist);
1903 return NULL;
1904 }
Georg Brandl99d7e4e2005-08-31 22:21:15 +00001905
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001906 newargs = PyTuple_GetSlice(args, 1, 4);
1907 if (newargs == NULL) {
1908 Py_DECREF(newlist);
1909 Py_DECREF(callable);
1910 return NULL;
1911 }
Raymond Hettinger64958a12003-12-17 20:43:33 +00001912
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001913 v = PyObject_Call(callable, newargs, kwds);
1914 Py_DECREF(newargs);
1915 Py_DECREF(callable);
1916 if (v == NULL) {
1917 Py_DECREF(newlist);
1918 return NULL;
1919 }
1920 Py_DECREF(v);
1921 return newlist;
Raymond Hettinger64958a12003-12-17 20:43:33 +00001922}
1923
1924PyDoc_STRVAR(sorted_doc,
Raymond Hettinger70b64fc2008-01-30 20:15:17 +00001925"sorted(iterable, key=None, reverse=False) --> new sorted list");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001926
Guido van Rossum79f25d91997-04-29 20:08:16 +00001927static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001928builtin_vars(PyObject *self, PyObject *args)
Guido van Rossum2d951851994-08-29 12:52:16 +00001929{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001930 PyObject *v = NULL;
1931 PyObject *d;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001932
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001933 if (!PyArg_UnpackTuple(args, "vars", 0, 1, &v))
1934 return NULL;
1935 if (v == NULL) {
1936 d = PyEval_GetLocals();
Victor Stinner41bb43a2013-10-29 01:19:37 +01001937 if (d == NULL)
1938 return NULL;
1939 Py_INCREF(d);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001940 }
1941 else {
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02001942 _Py_IDENTIFIER(__dict__);
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02001943 d = _PyObject_GetAttrId(v, &PyId___dict__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001944 if (d == NULL) {
1945 PyErr_SetString(PyExc_TypeError,
1946 "vars() argument must have __dict__ attribute");
1947 return NULL;
1948 }
1949 }
1950 return d;
Guido van Rossum2d951851994-08-29 12:52:16 +00001951}
1952
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001953PyDoc_STRVAR(vars_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001954"vars([object]) -> dictionary\n\
1955\n\
1956Without arguments, equivalent to locals().\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001957With an argument, equivalent to object.__dict__.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001958
Alex Martellia70b1912003-04-22 08:12:33 +00001959static PyObject*
1960builtin_sum(PyObject *self, PyObject *args)
1961{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001962 PyObject *seq;
1963 PyObject *result = NULL;
1964 PyObject *temp, *item, *iter;
Alex Martellia70b1912003-04-22 08:12:33 +00001965
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001966 if (!PyArg_UnpackTuple(args, "sum", 1, 2, &seq, &result))
1967 return NULL;
Alex Martellia70b1912003-04-22 08:12:33 +00001968
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001969 iter = PyObject_GetIter(seq);
1970 if (iter == NULL)
1971 return NULL;
Alex Martellia70b1912003-04-22 08:12:33 +00001972
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001973 if (result == NULL) {
1974 result = PyLong_FromLong(0);
1975 if (result == NULL) {
1976 Py_DECREF(iter);
1977 return NULL;
1978 }
1979 } else {
1980 /* reject string values for 'start' parameter */
1981 if (PyUnicode_Check(result)) {
1982 PyErr_SetString(PyExc_TypeError,
1983 "sum() can't sum strings [use ''.join(seq) instead]");
1984 Py_DECREF(iter);
1985 return NULL;
1986 }
Benjamin Petersonce071ca2011-07-29 14:23:47 -05001987 if (PyBytes_Check(result)) {
1988 PyErr_SetString(PyExc_TypeError,
1989 "sum() can't sum bytes [use b''.join(seq) instead]");
Benjamin Peterson405f32c2011-07-29 22:43:45 -05001990 Py_DECREF(iter);
Benjamin Petersonce071ca2011-07-29 14:23:47 -05001991 return NULL;
1992 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001993 if (PyByteArray_Check(result)) {
1994 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson4f921c22011-07-29 14:24:29 -05001995 "sum() can't sum bytearray [use b''.join(seq) instead]");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001996 Py_DECREF(iter);
1997 return NULL;
1998 }
Guido van Rossum3172c5d2007-10-16 18:12:55 +00001999
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002000 Py_INCREF(result);
2001 }
Alex Martellia70b1912003-04-22 08:12:33 +00002002
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002003#ifndef SLOW_SUM
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002004 /* Fast addition by keeping temporary sums in C instead of new Python objects.
2005 Assumes all inputs are the same type. If the assumption fails, default
2006 to the more general routine.
2007 */
2008 if (PyLong_CheckExact(result)) {
2009 int overflow;
2010 long i_result = PyLong_AsLongAndOverflow(result, &overflow);
2011 /* If this already overflowed, don't even enter the loop. */
2012 if (overflow == 0) {
2013 Py_DECREF(result);
2014 result = NULL;
2015 }
2016 while(result == NULL) {
2017 item = PyIter_Next(iter);
2018 if (item == NULL) {
2019 Py_DECREF(iter);
2020 if (PyErr_Occurred())
2021 return NULL;
2022 return PyLong_FromLong(i_result);
2023 }
2024 if (PyLong_CheckExact(item)) {
2025 long b = PyLong_AsLongAndOverflow(item, &overflow);
2026 long x = i_result + b;
2027 if (overflow == 0 && ((x^i_result) >= 0 || (x^b) >= 0)) {
2028 i_result = x;
2029 Py_DECREF(item);
2030 continue;
2031 }
2032 }
2033 /* Either overflowed or is not an int. Restore real objects and process normally */
2034 result = PyLong_FromLong(i_result);
Christian Heimes704e2d32013-07-26 22:49:26 +02002035 if (result == NULL) {
2036 Py_DECREF(item);
2037 Py_DECREF(iter);
2038 return NULL;
2039 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002040 temp = PyNumber_Add(result, item);
2041 Py_DECREF(result);
2042 Py_DECREF(item);
2043 result = temp;
2044 if (result == NULL) {
2045 Py_DECREF(iter);
2046 return NULL;
2047 }
2048 }
2049 }
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002050
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002051 if (PyFloat_CheckExact(result)) {
2052 double f_result = PyFloat_AS_DOUBLE(result);
2053 Py_DECREF(result);
2054 result = NULL;
2055 while(result == NULL) {
2056 item = PyIter_Next(iter);
2057 if (item == NULL) {
2058 Py_DECREF(iter);
2059 if (PyErr_Occurred())
2060 return NULL;
2061 return PyFloat_FromDouble(f_result);
2062 }
2063 if (PyFloat_CheckExact(item)) {
2064 PyFPE_START_PROTECT("add", Py_DECREF(item); Py_DECREF(iter); return 0)
2065 f_result += PyFloat_AS_DOUBLE(item);
2066 PyFPE_END_PROTECT(f_result)
2067 Py_DECREF(item);
2068 continue;
2069 }
2070 if (PyLong_CheckExact(item)) {
2071 long value;
2072 int overflow;
2073 value = PyLong_AsLongAndOverflow(item, &overflow);
2074 if (!overflow) {
2075 PyFPE_START_PROTECT("add", Py_DECREF(item); Py_DECREF(iter); return 0)
2076 f_result += (double)value;
2077 PyFPE_END_PROTECT(f_result)
2078 Py_DECREF(item);
2079 continue;
2080 }
2081 }
2082 result = PyFloat_FromDouble(f_result);
2083 temp = PyNumber_Add(result, item);
2084 Py_DECREF(result);
2085 Py_DECREF(item);
2086 result = temp;
2087 if (result == NULL) {
2088 Py_DECREF(iter);
2089 return NULL;
2090 }
2091 }
2092 }
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002093#endif
2094
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002095 for(;;) {
2096 item = PyIter_Next(iter);
2097 if (item == NULL) {
2098 /* error, or end-of-sequence */
2099 if (PyErr_Occurred()) {
2100 Py_DECREF(result);
2101 result = NULL;
2102 }
2103 break;
2104 }
2105 /* It's tempting to use PyNumber_InPlaceAdd instead of
2106 PyNumber_Add here, to avoid quadratic running time
2107 when doing 'sum(list_of_lists, [])'. However, this
2108 would produce a change in behaviour: a snippet like
Mark Dickinson9acadc52009-10-26 14:19:42 +00002109
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002110 empty = []
2111 sum([[x] for x in range(10)], empty)
Mark Dickinson9acadc52009-10-26 14:19:42 +00002112
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002113 would change the value of empty. */
2114 temp = PyNumber_Add(result, item);
2115 Py_DECREF(result);
2116 Py_DECREF(item);
2117 result = temp;
2118 if (result == NULL)
2119 break;
2120 }
2121 Py_DECREF(iter);
2122 return result;
Alex Martellia70b1912003-04-22 08:12:33 +00002123}
2124
2125PyDoc_STRVAR(sum_doc,
Georg Brandld11ae5d2008-05-16 13:27:32 +00002126"sum(iterable[, start]) -> value\n\
Alex Martellia70b1912003-04-22 08:12:33 +00002127\n\
R David Murray87ead112013-07-10 16:22:14 -04002128Return the sum of an iterable of numbers (NOT strings) plus the value\n\
Georg Brandld11ae5d2008-05-16 13:27:32 +00002129of parameter 'start' (which defaults to 0). When the iterable is\n\
R David Murray87ead112013-07-10 16:22:14 -04002130empty, return start.");
Alex Martellia70b1912003-04-22 08:12:33 +00002131
2132
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002133static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002134builtin_isinstance(PyObject *self, PyObject *args)
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002135{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002136 PyObject *inst;
2137 PyObject *cls;
2138 int retval;
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002139
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002140 if (!PyArg_UnpackTuple(args, "isinstance", 2, 2, &inst, &cls))
2141 return NULL;
Guido van Rossumf5dd9141997-12-02 19:11:45 +00002142
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002143 retval = PyObject_IsInstance(inst, cls);
2144 if (retval < 0)
2145 return NULL;
2146 return PyBool_FromLong(retval);
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002147}
2148
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002149PyDoc_STRVAR(isinstance_doc,
Guido van Rossum77f6a652002-04-03 22:41:51 +00002150"isinstance(object, class-or-type-or-tuple) -> bool\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002151\n\
2152Return whether an object is an instance of a class or of a subclass thereof.\n\
Guido van Rossum03290ec2001-10-07 20:54:12 +00002153With a type as second argument, return whether that is the object's type.\n\
2154The form using a tuple, isinstance(x, (A, B, ...)), is a shortcut for\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002155isinstance(x, A) or isinstance(x, B) or ... (etc.).");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002156
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002157
2158static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002159builtin_issubclass(PyObject *self, PyObject *args)
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002160{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002161 PyObject *derived;
2162 PyObject *cls;
2163 int retval;
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002164
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002165 if (!PyArg_UnpackTuple(args, "issubclass", 2, 2, &derived, &cls))
2166 return NULL;
Guido van Rossum668213d1999-06-16 17:28:37 +00002167
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002168 retval = PyObject_IsSubclass(derived, cls);
2169 if (retval < 0)
2170 return NULL;
2171 return PyBool_FromLong(retval);
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002172}
2173
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002174PyDoc_STRVAR(issubclass_doc,
Guido van Rossum77f6a652002-04-03 22:41:51 +00002175"issubclass(C, B) -> bool\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002176\n\
Walter Dörwaldd9a6ad32002-12-12 16:41:44 +00002177Return whether class C is a subclass (i.e., a derived class) of class B.\n\
2178When using a tuple as the second argument issubclass(X, (A, B, ...)),\n\
2179is a shortcut for issubclass(X, A) or issubclass(X, B) or ... (etc.).");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002180
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002181
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002182typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002183 PyObject_HEAD
2184 Py_ssize_t tuplesize;
2185 PyObject *ittuple; /* tuple of iterators */
2186 PyObject *result;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002187} zipobject;
2188
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002189static PyObject *
2190zip_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
Barry Warsawbd599b52000-08-03 15:45:29 +00002191{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002192 zipobject *lz;
2193 Py_ssize_t i;
2194 PyObject *ittuple; /* tuple of iterators */
2195 PyObject *result;
2196 Py_ssize_t tuplesize = PySequence_Length(args);
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002197
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002198 if (type == &PyZip_Type && !_PyArg_NoKeywords("zip()", kwds))
2199 return NULL;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002200
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002201 /* args must be a tuple */
2202 assert(PyTuple_Check(args));
Barry Warsawbd599b52000-08-03 15:45:29 +00002203
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002204 /* obtain iterators */
2205 ittuple = PyTuple_New(tuplesize);
2206 if (ittuple == NULL)
2207 return NULL;
2208 for (i=0; i < tuplesize; ++i) {
2209 PyObject *item = PyTuple_GET_ITEM(args, i);
2210 PyObject *it = PyObject_GetIter(item);
2211 if (it == NULL) {
2212 if (PyErr_ExceptionMatches(PyExc_TypeError))
2213 PyErr_Format(PyExc_TypeError,
2214 "zip argument #%zd must support iteration",
2215 i+1);
2216 Py_DECREF(ittuple);
2217 return NULL;
2218 }
2219 PyTuple_SET_ITEM(ittuple, i, it);
2220 }
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002221
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002222 /* create a result holder */
2223 result = PyTuple_New(tuplesize);
2224 if (result == NULL) {
2225 Py_DECREF(ittuple);
2226 return NULL;
2227 }
2228 for (i=0 ; i < tuplesize ; i++) {
2229 Py_INCREF(Py_None);
2230 PyTuple_SET_ITEM(result, i, Py_None);
2231 }
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002232
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002233 /* create zipobject structure */
2234 lz = (zipobject *)type->tp_alloc(type, 0);
2235 if (lz == NULL) {
2236 Py_DECREF(ittuple);
2237 Py_DECREF(result);
2238 return NULL;
2239 }
2240 lz->ittuple = ittuple;
2241 lz->tuplesize = tuplesize;
2242 lz->result = result;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002243
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002244 return (PyObject *)lz;
Barry Warsawbd599b52000-08-03 15:45:29 +00002245}
2246
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002247static void
2248zip_dealloc(zipobject *lz)
2249{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002250 PyObject_GC_UnTrack(lz);
2251 Py_XDECREF(lz->ittuple);
2252 Py_XDECREF(lz->result);
2253 Py_TYPE(lz)->tp_free(lz);
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002254}
2255
2256static int
2257zip_traverse(zipobject *lz, visitproc visit, void *arg)
2258{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002259 Py_VISIT(lz->ittuple);
2260 Py_VISIT(lz->result);
2261 return 0;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002262}
2263
2264static PyObject *
2265zip_next(zipobject *lz)
2266{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002267 Py_ssize_t i;
2268 Py_ssize_t tuplesize = lz->tuplesize;
2269 PyObject *result = lz->result;
2270 PyObject *it;
2271 PyObject *item;
2272 PyObject *olditem;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002273
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002274 if (tuplesize == 0)
2275 return NULL;
2276 if (Py_REFCNT(result) == 1) {
2277 Py_INCREF(result);
2278 for (i=0 ; i < tuplesize ; i++) {
2279 it = PyTuple_GET_ITEM(lz->ittuple, i);
2280 item = (*Py_TYPE(it)->tp_iternext)(it);
Serhiy Storchaka278d03b2013-04-06 22:52:34 +03002281 if (item == NULL) {
2282 Py_DECREF(result);
2283 return NULL;
2284 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002285 olditem = PyTuple_GET_ITEM(result, i);
2286 PyTuple_SET_ITEM(result, i, item);
2287 Py_DECREF(olditem);
2288 }
2289 } else {
2290 result = PyTuple_New(tuplesize);
2291 if (result == NULL)
Serhiy Storchaka278d03b2013-04-06 22:52:34 +03002292 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002293 for (i=0 ; i < tuplesize ; i++) {
2294 it = PyTuple_GET_ITEM(lz->ittuple, i);
2295 item = (*Py_TYPE(it)->tp_iternext)(it);
Serhiy Storchaka278d03b2013-04-06 22:52:34 +03002296 if (item == NULL) {
2297 Py_DECREF(result);
2298 return NULL;
2299 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002300 PyTuple_SET_ITEM(result, i, item);
2301 }
2302 }
2303 return result;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002304}
Barry Warsawbd599b52000-08-03 15:45:29 +00002305
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002306static PyObject *
2307zip_reduce(zipobject *lz)
2308{
2309 /* Just recreate the zip with the internal iterator tuple */
2310 return Py_BuildValue("OO", Py_TYPE(lz), lz->ittuple);
2311}
2312
2313static PyMethodDef zip_methods[] = {
2314 {"__reduce__", (PyCFunction)zip_reduce, METH_NOARGS, reduce_doc},
2315 {NULL, NULL} /* sentinel */
2316};
2317
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002318PyDoc_STRVAR(zip_doc,
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002319"zip(iter1 [,iter2 [...]]) --> zip object\n\
Barry Warsawbd599b52000-08-03 15:45:29 +00002320\n\
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002321Return a zip object whose .__next__() method returns a tuple where\n\
2322the i-th element comes from the i-th iterable argument. The .__next__()\n\
2323method continues until the shortest iterable in the argument sequence\n\
Georg Brandlced51db2008-12-04 18:28:38 +00002324is exhausted and then it raises StopIteration.");
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002325
2326PyTypeObject PyZip_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002327 PyVarObject_HEAD_INIT(&PyType_Type, 0)
2328 "zip", /* tp_name */
2329 sizeof(zipobject), /* tp_basicsize */
2330 0, /* tp_itemsize */
2331 /* methods */
2332 (destructor)zip_dealloc, /* tp_dealloc */
2333 0, /* tp_print */
2334 0, /* tp_getattr */
2335 0, /* tp_setattr */
2336 0, /* tp_reserved */
2337 0, /* tp_repr */
2338 0, /* tp_as_number */
2339 0, /* tp_as_sequence */
2340 0, /* tp_as_mapping */
2341 0, /* tp_hash */
2342 0, /* tp_call */
2343 0, /* tp_str */
2344 PyObject_GenericGetAttr, /* tp_getattro */
2345 0, /* tp_setattro */
2346 0, /* tp_as_buffer */
2347 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
2348 Py_TPFLAGS_BASETYPE, /* tp_flags */
2349 zip_doc, /* tp_doc */
2350 (traverseproc)zip_traverse, /* tp_traverse */
2351 0, /* tp_clear */
2352 0, /* tp_richcompare */
2353 0, /* tp_weaklistoffset */
2354 PyObject_SelfIter, /* tp_iter */
2355 (iternextfunc)zip_next, /* tp_iternext */
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002356 zip_methods, /* tp_methods */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002357 0, /* tp_members */
2358 0, /* tp_getset */
2359 0, /* tp_base */
2360 0, /* tp_dict */
2361 0, /* tp_descr_get */
2362 0, /* tp_descr_set */
2363 0, /* tp_dictoffset */
2364 0, /* tp_init */
2365 PyType_GenericAlloc, /* tp_alloc */
2366 zip_new, /* tp_new */
2367 PyObject_GC_Del, /* tp_free */
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002368};
Barry Warsawbd599b52000-08-03 15:45:29 +00002369
2370
Guido van Rossum79f25d91997-04-29 20:08:16 +00002371static PyMethodDef builtin_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002372 {"__build_class__", (PyCFunction)builtin___build_class__,
2373 METH_VARARGS | METH_KEYWORDS, build_class_doc},
2374 {"__import__", (PyCFunction)builtin___import__, METH_VARARGS | METH_KEYWORDS, import_doc},
2375 {"abs", builtin_abs, METH_O, abs_doc},
2376 {"all", builtin_all, METH_O, all_doc},
2377 {"any", builtin_any, METH_O, any_doc},
2378 {"ascii", builtin_ascii, METH_O, ascii_doc},
2379 {"bin", builtin_bin, METH_O, bin_doc},
Antoine Pitroue71362d2010-11-27 22:00:11 +00002380 {"callable", builtin_callable, METH_O, callable_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002381 {"chr", builtin_chr, METH_VARARGS, chr_doc},
2382 {"compile", (PyCFunction)builtin_compile, METH_VARARGS | METH_KEYWORDS, compile_doc},
2383 {"delattr", builtin_delattr, METH_VARARGS, delattr_doc},
2384 {"dir", builtin_dir, METH_VARARGS, dir_doc},
2385 {"divmod", builtin_divmod, METH_VARARGS, divmod_doc},
2386 {"eval", builtin_eval, METH_VARARGS, eval_doc},
2387 {"exec", builtin_exec, METH_VARARGS, exec_doc},
2388 {"format", builtin_format, METH_VARARGS, format_doc},
2389 {"getattr", builtin_getattr, METH_VARARGS, getattr_doc},
2390 {"globals", (PyCFunction)builtin_globals, METH_NOARGS, globals_doc},
2391 {"hasattr", builtin_hasattr, METH_VARARGS, hasattr_doc},
2392 {"hash", builtin_hash, METH_O, hash_doc},
2393 {"hex", builtin_hex, METH_O, hex_doc},
2394 {"id", builtin_id, METH_O, id_doc},
2395 {"input", builtin_input, METH_VARARGS, input_doc},
2396 {"isinstance", builtin_isinstance, METH_VARARGS, isinstance_doc},
2397 {"issubclass", builtin_issubclass, METH_VARARGS, issubclass_doc},
2398 {"iter", builtin_iter, METH_VARARGS, iter_doc},
2399 {"len", builtin_len, METH_O, len_doc},
2400 {"locals", (PyCFunction)builtin_locals, METH_NOARGS, locals_doc},
2401 {"max", (PyCFunction)builtin_max, METH_VARARGS | METH_KEYWORDS, max_doc},
2402 {"min", (PyCFunction)builtin_min, METH_VARARGS | METH_KEYWORDS, min_doc},
2403 {"next", (PyCFunction)builtin_next, METH_VARARGS, next_doc},
2404 {"oct", builtin_oct, METH_O, oct_doc},
2405 {"ord", builtin_ord, METH_O, ord_doc},
2406 {"pow", builtin_pow, METH_VARARGS, pow_doc},
2407 {"print", (PyCFunction)builtin_print, METH_VARARGS | METH_KEYWORDS, print_doc},
2408 {"repr", builtin_repr, METH_O, repr_doc},
2409 {"round", (PyCFunction)builtin_round, METH_VARARGS | METH_KEYWORDS, round_doc},
2410 {"setattr", builtin_setattr, METH_VARARGS, setattr_doc},
2411 {"sorted", (PyCFunction)builtin_sorted, METH_VARARGS | METH_KEYWORDS, sorted_doc},
2412 {"sum", builtin_sum, METH_VARARGS, sum_doc},
2413 {"vars", builtin_vars, METH_VARARGS, vars_doc},
2414 {NULL, NULL},
Guido van Rossum3f5da241990-12-20 15:06:42 +00002415};
2416
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002417PyDoc_STRVAR(builtin_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002418"Built-in functions, exceptions, and other objects.\n\
2419\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002420Noteworthy: None is the `nil' object; Ellipsis represents `...' in slices.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002421
Martin v. Löwis1a214512008-06-11 05:26:20 +00002422static struct PyModuleDef builtinsmodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002423 PyModuleDef_HEAD_INIT,
2424 "builtins",
2425 builtin_doc,
2426 -1, /* multiple "initialization" just copies the module dict. */
2427 builtin_methods,
2428 NULL,
2429 NULL,
2430 NULL,
2431 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00002432};
2433
2434
Guido van Rossum25ce5661997-08-02 03:10:38 +00002435PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002436_PyBuiltin_Init(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +00002437{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002438 PyObject *mod, *dict, *debug;
Benjamin Peterson42124a72012-10-30 23:41:54 -04002439
2440 if (PyType_Ready(&PyFilter_Type) < 0 ||
2441 PyType_Ready(&PyMap_Type) < 0 ||
2442 PyType_Ready(&PyZip_Type) < 0)
2443 return NULL;
2444
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002445 mod = PyModule_Create(&builtinsmodule);
2446 if (mod == NULL)
2447 return NULL;
2448 dict = PyModule_GetDict(mod);
Tim Peters4b7625e2001-09-13 21:37:17 +00002449
Tim Peters7571a0f2003-03-23 17:52:28 +00002450#ifdef Py_TRACE_REFS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002451 /* "builtins" exposes a number of statically allocated objects
2452 * that, before this code was added in 2.3, never showed up in
2453 * the list of "all objects" maintained by Py_TRACE_REFS. As a
2454 * result, programs leaking references to None and False (etc)
2455 * couldn't be diagnosed by examining sys.getobjects(0).
2456 */
Tim Peters7571a0f2003-03-23 17:52:28 +00002457#define ADD_TO_ALL(OBJECT) _Py_AddToAllObjects((PyObject *)(OBJECT), 0)
2458#else
2459#define ADD_TO_ALL(OBJECT) (void)0
2460#endif
2461
Tim Peters4b7625e2001-09-13 21:37:17 +00002462#define SETBUILTIN(NAME, OBJECT) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002463 if (PyDict_SetItemString(dict, NAME, (PyObject *)OBJECT) < 0) \
2464 return NULL; \
2465 ADD_TO_ALL(OBJECT)
Tim Peters4b7625e2001-09-13 21:37:17 +00002466
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002467 SETBUILTIN("None", Py_None);
2468 SETBUILTIN("Ellipsis", Py_Ellipsis);
2469 SETBUILTIN("NotImplemented", Py_NotImplemented);
2470 SETBUILTIN("False", Py_False);
2471 SETBUILTIN("True", Py_True);
2472 SETBUILTIN("bool", &PyBool_Type);
2473 SETBUILTIN("memoryview", &PyMemoryView_Type);
2474 SETBUILTIN("bytearray", &PyByteArray_Type);
2475 SETBUILTIN("bytes", &PyBytes_Type);
2476 SETBUILTIN("classmethod", &PyClassMethod_Type);
2477 SETBUILTIN("complex", &PyComplex_Type);
2478 SETBUILTIN("dict", &PyDict_Type);
2479 SETBUILTIN("enumerate", &PyEnum_Type);
2480 SETBUILTIN("filter", &PyFilter_Type);
2481 SETBUILTIN("float", &PyFloat_Type);
2482 SETBUILTIN("frozenset", &PyFrozenSet_Type);
2483 SETBUILTIN("property", &PyProperty_Type);
2484 SETBUILTIN("int", &PyLong_Type);
2485 SETBUILTIN("list", &PyList_Type);
2486 SETBUILTIN("map", &PyMap_Type);
2487 SETBUILTIN("object", &PyBaseObject_Type);
2488 SETBUILTIN("range", &PyRange_Type);
2489 SETBUILTIN("reversed", &PyReversed_Type);
2490 SETBUILTIN("set", &PySet_Type);
2491 SETBUILTIN("slice", &PySlice_Type);
2492 SETBUILTIN("staticmethod", &PyStaticMethod_Type);
2493 SETBUILTIN("str", &PyUnicode_Type);
2494 SETBUILTIN("super", &PySuper_Type);
2495 SETBUILTIN("tuple", &PyTuple_Type);
2496 SETBUILTIN("type", &PyType_Type);
2497 SETBUILTIN("zip", &PyZip_Type);
2498 debug = PyBool_FromLong(Py_OptimizeFlag == 0);
2499 if (PyDict_SetItemString(dict, "__debug__", debug) < 0) {
2500 Py_XDECREF(debug);
2501 return NULL;
2502 }
2503 Py_XDECREF(debug);
Barry Warsaw757af0e1997-08-29 22:13:51 +00002504
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002505 return mod;
Tim Peters7571a0f2003-03-23 17:52:28 +00002506#undef ADD_TO_ALL
Tim Peters4b7625e2001-09-13 21:37:17 +00002507#undef SETBUILTIN
Guido van Rossum3f5da241990-12-20 15:06:42 +00002508}