blob: 2754b69e9b0e542e54ee77e749da8a944e311bb1 [file] [log] [blame]
Guido van Rossum3f5da241990-12-20 15:06:42 +00001/* Built-in functions */
2
Guido van Rossum79f25d91997-04-29 20:08:16 +00003#include "Python.h"
Martin v. Löwis618dc5e2008-03-30 20:03:44 +00004#include "Python-ast.h"
Guido van Rossum3f5da241990-12-20 15:06:42 +00005
6#include "node.h"
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00007#include "code.h"
Guido van Rossum3f5da241990-12-20 15:06:42 +00008
Benjamin Petersonea281a52011-08-12 23:10:50 -05009#include "asdl.h"
10#include "ast.h"
11
Guido van Rossum6bf62da1997-04-11 20:37:35 +000012#include <ctype.h>
13
Victor Stinnerb744ba12010-05-15 12:27:16 +000014#ifdef HAVE_LANGINFO_H
15#include <langinfo.h> /* CODESET */
16#endif
17
Mark Hammond26cffde42001-05-14 12:17:34 +000018/* The default encoding used by the platform file system APIs
19 Can remain NULL for all platforms that don't have such a concept
Guido van Rossum00bc0e02007-10-15 02:52:41 +000020
21 Don't forget to modify PyUnicode_DecodeFSDefault() if you touch any of the
22 values for Py_FileSystemDefaultEncoding!
Mark Hammond26cffde42001-05-14 12:17:34 +000023*/
Victor Stinner99b95382011-07-04 14:23:54 +020024#ifdef HAVE_MBCS
Mark Hammond26cffde42001-05-14 12:17:34 +000025const char *Py_FileSystemDefaultEncoding = "mbcs";
Martin v. Löwis04dc25c2008-10-03 16:09:28 +000026int Py_HasFileSystemDefaultEncoding = 1;
Just van Rossumb9b8e9c2003-02-10 09:22:01 +000027#elif defined(__APPLE__)
28const char *Py_FileSystemDefaultEncoding = "utf-8";
Martin v. Löwis04dc25c2008-10-03 16:09:28 +000029int Py_HasFileSystemDefaultEncoding = 1;
Victor Stinnerd64e8a72011-07-04 13:48:30 +020030#else
Victor Stinnerb744ba12010-05-15 12:27:16 +000031const char *Py_FileSystemDefaultEncoding = NULL; /* set by initfsencoding() */
Martin v. Löwis04dc25c2008-10-03 16:09:28 +000032int Py_HasFileSystemDefaultEncoding = 0;
Mark Hammond26cffde42001-05-14 12:17:34 +000033#endif
Mark Hammondef8b6542001-05-13 08:04:26 +000034
Martin v. Löwisbd928fe2011-10-14 10:20:37 +020035_Py_IDENTIFIER(fileno);
36_Py_IDENTIFIER(flush);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +020037
Guido van Rossum79f25d91997-04-29 20:08:16 +000038static PyObject *
Guido van Rossum52cc1d82007-03-18 15:41:51 +000039builtin___build_class__(PyObject *self, PyObject *args, PyObject *kwds)
40{
Nick Coghlande31b192011-10-23 22:04:16 +100041 PyObject *func, *name, *bases, *mkw, *meta, *winner, *prep, *ns, *cell;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000042 PyObject *cls = NULL;
Florent Xicluna4d46c2a2011-10-28 15:00:50 +020043 Py_ssize_t nargs;
Nick Coghlande31b192011-10-23 22:04:16 +100044 int isclass;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +020045 _Py_IDENTIFIER(__prepare__);
Guido van Rossum52cc1d82007-03-18 15:41:51 +000046
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000047 assert(args != NULL);
48 if (!PyTuple_Check(args)) {
49 PyErr_SetString(PyExc_TypeError,
50 "__build_class__: args is not a tuple");
51 return NULL;
52 }
53 nargs = PyTuple_GET_SIZE(args);
54 if (nargs < 2) {
55 PyErr_SetString(PyExc_TypeError,
56 "__build_class__: not enough arguments");
57 return NULL;
58 }
59 func = PyTuple_GET_ITEM(args, 0); /* Better be callable */
60 name = PyTuple_GET_ITEM(args, 1);
61 if (!PyUnicode_Check(name)) {
62 PyErr_SetString(PyExc_TypeError,
63 "__build_class__: name is not a string");
64 return NULL;
65 }
66 bases = PyTuple_GetSlice(args, 2, nargs);
67 if (bases == NULL)
68 return NULL;
Guido van Rossum52cc1d82007-03-18 15:41:51 +000069
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000070 if (kwds == NULL) {
71 meta = NULL;
72 mkw = NULL;
73 }
74 else {
75 mkw = PyDict_Copy(kwds); /* Don't modify kwds passed in! */
76 if (mkw == NULL) {
77 Py_DECREF(bases);
78 return NULL;
Guido van Rossum52cc1d82007-03-18 15:41:51 +000079 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000080 meta = PyDict_GetItemString(mkw, "metaclass");
81 if (meta != NULL) {
82 Py_INCREF(meta);
83 if (PyDict_DelItemString(mkw, "metaclass") < 0) {
84 Py_DECREF(meta);
85 Py_DECREF(mkw);
86 Py_DECREF(bases);
87 return NULL;
88 }
Nick Coghlande31b192011-10-23 22:04:16 +100089 /* metaclass is explicitly given, check if it's indeed a class */
90 isclass = PyType_Check(meta);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000091 }
92 }
93 if (meta == NULL) {
Nick Coghlande31b192011-10-23 22:04:16 +100094 /* if there are no bases, use type: */
95 if (PyTuple_GET_SIZE(bases) == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000096 meta = (PyObject *) (&PyType_Type);
Nick Coghlande31b192011-10-23 22:04:16 +100097 }
98 /* else get the type of the first base */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000099 else {
100 PyObject *base0 = PyTuple_GET_ITEM(bases, 0);
101 meta = (PyObject *) (base0->ob_type);
102 }
103 Py_INCREF(meta);
Nick Coghlande31b192011-10-23 22:04:16 +1000104 isclass = 1; /* meta is really a class */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000105 }
Nick Coghlan9715d262011-10-23 22:36:42 +1000106
Nick Coghlande31b192011-10-23 22:04:16 +1000107 if (isclass) {
108 /* meta is really a class, so check for a more derived
109 metaclass, or possible metaclass conflicts: */
110 winner = (PyObject *)_PyType_CalculateMetaclass((PyTypeObject *)meta,
111 bases);
112 if (winner == NULL) {
113 Py_DECREF(meta);
114 Py_XDECREF(mkw);
115 Py_DECREF(bases);
116 return NULL;
117 }
118 if (winner != meta) {
119 Py_DECREF(meta);
120 meta = winner;
121 Py_INCREF(meta);
122 }
123 }
124 /* else: meta is not a class, so we cannot do the metaclass
125 calculation, so we will use the explicitly given object as it is */
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +0200126 prep = _PyObject_GetAttrId(meta, &PyId___prepare__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000127 if (prep == NULL) {
128 if (PyErr_ExceptionMatches(PyExc_AttributeError)) {
129 PyErr_Clear();
130 ns = PyDict_New();
131 }
132 else {
133 Py_DECREF(meta);
134 Py_XDECREF(mkw);
135 Py_DECREF(bases);
136 return NULL;
137 }
138 }
139 else {
140 PyObject *pargs = PyTuple_Pack(2, name, bases);
141 if (pargs == NULL) {
142 Py_DECREF(prep);
143 Py_DECREF(meta);
144 Py_XDECREF(mkw);
145 Py_DECREF(bases);
146 return NULL;
147 }
148 ns = PyEval_CallObjectWithKeywords(prep, pargs, mkw);
149 Py_DECREF(pargs);
150 Py_DECREF(prep);
151 }
152 if (ns == NULL) {
153 Py_DECREF(meta);
154 Py_XDECREF(mkw);
155 Py_DECREF(bases);
156 return NULL;
157 }
158 cell = PyObject_CallFunctionObjArgs(func, ns, NULL);
159 if (cell != NULL) {
160 PyObject *margs;
161 margs = PyTuple_Pack(3, name, bases, ns);
162 if (margs != NULL) {
163 cls = PyEval_CallObjectWithKeywords(meta, margs, mkw);
164 Py_DECREF(margs);
165 }
Benjamin Peterson8e8fbea2012-06-01 23:57:36 -0700166 if (cls != NULL && PyCell_Check(cell))
167 PyCell_Set(cell, cls);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000168 Py_DECREF(cell);
169 }
170 Py_DECREF(ns);
171 Py_DECREF(meta);
172 Py_XDECREF(mkw);
173 Py_DECREF(bases);
174 return cls;
Guido van Rossum52cc1d82007-03-18 15:41:51 +0000175}
176
177PyDoc_STRVAR(build_class_doc,
178"__build_class__(func, name, *bases, metaclass=None, **kwds) -> class\n\
179\n\
180Internal helper function used by the class statement.");
181
182static PyObject *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000183builtin___import__(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000184{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000185 static char *kwlist[] = {"name", "globals", "locals", "fromlist",
186 "level", 0};
Victor Stinnerfe93faf2011-03-14 15:54:52 -0400187 PyObject *name, *globals = NULL, *locals = NULL, *fromlist = NULL;
Brett Cannonfd074152012-04-14 14:10:13 -0400188 int level = 0;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000189
Victor Stinnerfe93faf2011-03-14 15:54:52 -0400190 if (!PyArg_ParseTupleAndKeywords(args, kwds, "U|OOOi:__import__",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000191 kwlist, &name, &globals, &locals, &fromlist, &level))
192 return NULL;
Victor Stinnerfe93faf2011-03-14 15:54:52 -0400193 return PyImport_ImportModuleLevelObject(name, globals, locals,
194 fromlist, level);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000195}
196
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000197PyDoc_STRVAR(import_doc,
Brett Cannoncb4996a2012-08-06 16:34:44 -0400198"__import__(name, globals=None, locals=None, fromlist=(), level=0) -> module\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000199\n\
Brett Cannon5305a992010-09-27 21:08:38 +0000200Import a module. Because this function is meant for use by the Python\n\
201interpreter and not for general use it is better to use\n\
202importlib.import_module() to programmatically import a module.\n\
203\n\
204The globals argument is only used to determine the context;\n\
205they are not modified. The locals argument is unused. The fromlist\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000206should be a list of names to emulate ``from name import ...'', or an\n\
207empty list to emulate ``import name''.\n\
208When importing a module from a package, note that __import__('A.B', ...)\n\
209returns package A when fromlist is empty, but its submodule B when\n\
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000210fromlist is not empty. Level is used to determine whether to perform \n\
Brett Cannon722d3ae2012-07-30 17:45:54 -0400211absolute or relative imports. 0 is absolute while a positive number\n\
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000212is the number of parent directories to search relative to the current module.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000213
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000214
Guido van Rossum79f25d91997-04-29 20:08:16 +0000215static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000216builtin_abs(PyObject *self, PyObject *v)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000217{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000218 return PyNumber_Absolute(v);
Guido van Rossum3f5da241990-12-20 15:06:42 +0000219}
220
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000221PyDoc_STRVAR(abs_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000222"abs(number) -> number\n\
223\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000224Return the absolute value of the argument.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000225
Raymond Hettinger96229b12005-03-11 06:49:40 +0000226static PyObject *
227builtin_all(PyObject *self, PyObject *v)
228{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000229 PyObject *it, *item;
230 PyObject *(*iternext)(PyObject *);
231 int cmp;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000232
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000233 it = PyObject_GetIter(v);
234 if (it == NULL)
235 return NULL;
236 iternext = *Py_TYPE(it)->tp_iternext;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000237
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000238 for (;;) {
239 item = iternext(it);
240 if (item == NULL)
241 break;
242 cmp = PyObject_IsTrue(item);
243 Py_DECREF(item);
244 if (cmp < 0) {
245 Py_DECREF(it);
246 return NULL;
247 }
248 if (cmp == 0) {
249 Py_DECREF(it);
250 Py_RETURN_FALSE;
251 }
252 }
253 Py_DECREF(it);
254 if (PyErr_Occurred()) {
255 if (PyErr_ExceptionMatches(PyExc_StopIteration))
256 PyErr_Clear();
257 else
258 return NULL;
259 }
260 Py_RETURN_TRUE;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000261}
262
263PyDoc_STRVAR(all_doc,
264"all(iterable) -> bool\n\
265\n\
Ezio Melottib19ed572013-02-15 23:35:14 +0200266Return True if bool(x) is True for all values x in the iterable.\n\
267If the iterable is empty, return True.");
Raymond Hettinger96229b12005-03-11 06:49:40 +0000268
269static PyObject *
270builtin_any(PyObject *self, PyObject *v)
271{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000272 PyObject *it, *item;
273 PyObject *(*iternext)(PyObject *);
274 int cmp;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000275
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000276 it = PyObject_GetIter(v);
277 if (it == NULL)
278 return NULL;
279 iternext = *Py_TYPE(it)->tp_iternext;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000280
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000281 for (;;) {
282 item = iternext(it);
283 if (item == NULL)
284 break;
285 cmp = PyObject_IsTrue(item);
286 Py_DECREF(item);
287 if (cmp < 0) {
288 Py_DECREF(it);
289 return NULL;
290 }
291 if (cmp == 1) {
292 Py_DECREF(it);
293 Py_RETURN_TRUE;
294 }
295 }
296 Py_DECREF(it);
297 if (PyErr_Occurred()) {
298 if (PyErr_ExceptionMatches(PyExc_StopIteration))
299 PyErr_Clear();
300 else
301 return NULL;
302 }
303 Py_RETURN_FALSE;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000304}
305
306PyDoc_STRVAR(any_doc,
307"any(iterable) -> bool\n\
308\n\
Ezio Melottib19ed572013-02-15 23:35:14 +0200309Return True if bool(x) is True for any x in the iterable.\n\
310If the iterable is empty, return False.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000311
Georg Brandl559e5d72008-06-11 18:37:52 +0000312static PyObject *
313builtin_ascii(PyObject *self, PyObject *v)
314{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000315 return PyObject_ASCII(v);
Georg Brandl559e5d72008-06-11 18:37:52 +0000316}
317
318PyDoc_STRVAR(ascii_doc,
319"ascii(object) -> string\n\
320\n\
321As repr(), return a string containing a printable representation of an\n\
322object, but escape the non-ASCII characters in the string returned by\n\
323repr() using \\x, \\u or \\U escapes. This generates a string similar\n\
324to that returned by repr() in Python 2.");
325
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000326
Guido van Rossum79f25d91997-04-29 20:08:16 +0000327static PyObject *
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000328builtin_bin(PyObject *self, PyObject *v)
329{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000330 return PyNumber_ToBase(v, 2);
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000331}
332
333PyDoc_STRVAR(bin_doc,
334"bin(number) -> string\n\
335\n\
Alexander Belopolsky12338ab2011-04-07 00:15:33 -0400336Return the binary representation of an integer.");
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000337
338
Antoine Pitroue71362d2010-11-27 22:00:11 +0000339static PyObject *
340builtin_callable(PyObject *self, PyObject *v)
341{
342 return PyBool_FromLong((long)PyCallable_Check(v));
343}
344
345PyDoc_STRVAR(callable_doc,
346"callable(object) -> bool\n\
347\n\
348Return whether the object is callable (i.e., some kind of function).\n\
349Note that classes are callable, as are instances of classes with a\n\
350__call__() method.");
351
352
Raymond Hettinger17301e92008-03-13 00:19:26 +0000353typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000354 PyObject_HEAD
355 PyObject *func;
356 PyObject *it;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000357} filterobject;
358
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000359static PyObject *
Raymond Hettinger17301e92008-03-13 00:19:26 +0000360filter_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
Guido van Rossum12d12c51993-10-26 17:58:25 +0000361{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000362 PyObject *func, *seq;
363 PyObject *it;
364 filterobject *lz;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000365
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000366 if (type == &PyFilter_Type && !_PyArg_NoKeywords("filter()", kwds))
367 return NULL;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000368
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000369 if (!PyArg_UnpackTuple(args, "filter", 2, 2, &func, &seq))
370 return NULL;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000371
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000372 /* Get iterator. */
373 it = PyObject_GetIter(seq);
374 if (it == NULL)
375 return NULL;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000376
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000377 /* create filterobject structure */
378 lz = (filterobject *)type->tp_alloc(type, 0);
379 if (lz == NULL) {
380 Py_DECREF(it);
381 return NULL;
382 }
383 Py_INCREF(func);
384 lz->func = func;
385 lz->it = it;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000386
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000387 return (PyObject *)lz;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000388}
389
390static void
391filter_dealloc(filterobject *lz)
392{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000393 PyObject_GC_UnTrack(lz);
Serhiy Storchakae8f706e2013-04-06 21:14:43 +0300394 Py_TRASHCAN_SAFE_BEGIN(lz)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000395 Py_XDECREF(lz->func);
396 Py_XDECREF(lz->it);
397 Py_TYPE(lz)->tp_free(lz);
Serhiy Storchakae8f706e2013-04-06 21:14:43 +0300398 Py_TRASHCAN_SAFE_END(lz)
Raymond Hettinger17301e92008-03-13 00:19:26 +0000399}
400
401static int
402filter_traverse(filterobject *lz, visitproc visit, void *arg)
403{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000404 Py_VISIT(lz->it);
405 Py_VISIT(lz->func);
406 return 0;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000407}
408
409static PyObject *
410filter_next(filterobject *lz)
411{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000412 PyObject *item;
413 PyObject *it = lz->it;
414 long ok;
415 PyObject *(*iternext)(PyObject *);
Raymond Hettinger17301e92008-03-13 00:19:26 +0000416
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000417 iternext = *Py_TYPE(it)->tp_iternext;
418 for (;;) {
Serhiy Storchakae8f706e2013-04-06 21:14:43 +0300419 if (Py_EnterRecursiveCall(" while iterating"))
420 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000421 item = iternext(it);
Serhiy Storchakae8f706e2013-04-06 21:14:43 +0300422 Py_LeaveRecursiveCall();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000423 if (item == NULL)
424 return NULL;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000425
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000426 if (lz->func == Py_None || lz->func == (PyObject *)&PyBool_Type) {
427 ok = PyObject_IsTrue(item);
428 } else {
429 PyObject *good;
430 good = PyObject_CallFunctionObjArgs(lz->func,
431 item, NULL);
432 if (good == NULL) {
433 Py_DECREF(item);
434 return NULL;
435 }
436 ok = PyObject_IsTrue(good);
437 Py_DECREF(good);
438 }
Antoine Pitrou6f430e42012-08-15 23:18:25 +0200439 if (ok > 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000440 return item;
441 Py_DECREF(item);
Antoine Pitrou6f430e42012-08-15 23:18:25 +0200442 if (ok < 0)
443 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000444 }
Guido van Rossum12d12c51993-10-26 17:58:25 +0000445}
446
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +0000447static PyObject *
448filter_reduce(filterobject *lz)
449{
450 return Py_BuildValue("O(OO)", Py_TYPE(lz), lz->func, lz->it);
451}
452
453PyDoc_STRVAR(reduce_doc, "Return state information for pickling.");
454
455static PyMethodDef filter_methods[] = {
456 {"__reduce__", (PyCFunction)filter_reduce, METH_NOARGS, reduce_doc},
457 {NULL, NULL} /* sentinel */
458};
459
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000460PyDoc_STRVAR(filter_doc,
Georg Brandld11ae5d2008-05-16 13:27:32 +0000461"filter(function or None, iterable) --> filter object\n\
Guido van Rossumc1f779c2007-07-03 08:25:58 +0000462\n\
Georg Brandld11ae5d2008-05-16 13:27:32 +0000463Return an iterator yielding those items of iterable for which function(item)\n\
Raymond Hettinger17301e92008-03-13 00:19:26 +0000464is true. If function is None, return the items that are true.");
465
466PyTypeObject PyFilter_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000467 PyVarObject_HEAD_INIT(&PyType_Type, 0)
468 "filter", /* tp_name */
469 sizeof(filterobject), /* tp_basicsize */
470 0, /* tp_itemsize */
471 /* methods */
472 (destructor)filter_dealloc, /* tp_dealloc */
473 0, /* tp_print */
474 0, /* tp_getattr */
475 0, /* tp_setattr */
476 0, /* tp_reserved */
477 0, /* tp_repr */
478 0, /* tp_as_number */
479 0, /* tp_as_sequence */
480 0, /* tp_as_mapping */
481 0, /* tp_hash */
482 0, /* tp_call */
483 0, /* tp_str */
484 PyObject_GenericGetAttr, /* tp_getattro */
485 0, /* tp_setattro */
486 0, /* tp_as_buffer */
487 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
488 Py_TPFLAGS_BASETYPE, /* tp_flags */
489 filter_doc, /* tp_doc */
490 (traverseproc)filter_traverse, /* tp_traverse */
491 0, /* tp_clear */
492 0, /* tp_richcompare */
493 0, /* tp_weaklistoffset */
494 PyObject_SelfIter, /* tp_iter */
495 (iternextfunc)filter_next, /* tp_iternext */
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +0000496 filter_methods, /* tp_methods */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000497 0, /* tp_members */
498 0, /* tp_getset */
499 0, /* tp_base */
500 0, /* tp_dict */
501 0, /* tp_descr_get */
502 0, /* tp_descr_set */
503 0, /* tp_dictoffset */
504 0, /* tp_init */
505 PyType_GenericAlloc, /* tp_alloc */
506 filter_new, /* tp_new */
507 PyObject_GC_Del, /* tp_free */
Raymond Hettinger17301e92008-03-13 00:19:26 +0000508};
509
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000510
Eric Smith8c663262007-08-25 02:26:07 +0000511static PyObject *
512builtin_format(PyObject *self, PyObject *args)
513{
Christian Heimes94b7d3d2007-12-11 20:20:39 +0000514 PyObject *value;
Eric Smith8fd3eba2008-02-17 19:48:00 +0000515 PyObject *format_spec = NULL;
Eric Smith8c663262007-08-25 02:26:07 +0000516
Eric Smith8fd3eba2008-02-17 19:48:00 +0000517 if (!PyArg_ParseTuple(args, "O|U:format", &value, &format_spec))
Benjamin Petersona12d5c62012-01-03 16:47:22 -0600518 return NULL;
Eric Smith8c663262007-08-25 02:26:07 +0000519
Eric Smith8fd3eba2008-02-17 19:48:00 +0000520 return PyObject_Format(value, format_spec);
Eric Smith8c663262007-08-25 02:26:07 +0000521}
522
Eric Smith8c663262007-08-25 02:26:07 +0000523PyDoc_STRVAR(format_doc,
Eric Smith81936692007-08-31 01:14:01 +0000524"format(value[, format_spec]) -> string\n\
Eric Smith8c663262007-08-25 02:26:07 +0000525\n\
Eric Smith81936692007-08-31 01:14:01 +0000526Returns value.__format__(format_spec)\n\
527format_spec defaults to \"\"");
528
Guido van Rossum7fcf2242007-05-04 17:43:11 +0000529static PyObject *
Walter Dörwalde7efd592007-06-05 20:07:21 +0000530builtin_chr(PyObject *self, PyObject *args)
Guido van Rossum09095f32000-03-10 23:00:52 +0000531{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000532 int x;
Guido van Rossum09095f32000-03-10 23:00:52 +0000533
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000534 if (!PyArg_ParseTuple(args, "i:chr", &x))
535 return NULL;
Fredrik Lundh0dcf67e2001-06-26 20:01:56 +0000536
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000537 return PyUnicode_FromOrdinal(x);
Guido van Rossum09095f32000-03-10 23:00:52 +0000538}
539
Victor Stinner63ab8752011-11-22 03:31:20 +0100540PyDoc_STRVAR(chr_doc,
Guido van Rossum84fc66d2007-05-03 17:18:26 +0000541"chr(i) -> Unicode character\n\
Guido van Rossum09095f32000-03-10 23:00:52 +0000542\n\
Victor Stinner63ab8752011-11-22 03:31:20 +0100543Return a Unicode string of one character with ordinal i; 0 <= i <= 0x10ffff.");
Guido van Rossum09095f32000-03-10 23:00:52 +0000544
545
Guido van Rossumf15a29f2007-05-04 00:41:39 +0000546static char *
Benjamin Petersonf5b52242009-03-02 23:31:26 +0000547source_as_string(PyObject *cmd, char *funcname, char *what, PyCompilerFlags *cf)
Guido van Rossumf15a29f2007-05-04 00:41:39 +0000548{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000549 char *str;
550 Py_ssize_t size;
Guido van Rossumf15a29f2007-05-04 00:41:39 +0000551
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000552 if (PyUnicode_Check(cmd)) {
553 cf->cf_flags |= PyCF_IGNORE_COOKIE;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200554 str = PyUnicode_AsUTF8AndSize(cmd, &size);
555 if (str == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000556 return NULL;
557 }
558 else if (!PyObject_CheckReadBuffer(cmd)) {
559 PyErr_Format(PyExc_TypeError,
560 "%s() arg 1 must be a %s object",
561 funcname, what);
562 return NULL;
563 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200564 else if (PyObject_AsReadBuffer(cmd, (const void **)&str, &size) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000565 return NULL;
566 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200567
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000568 if (strlen(str) != size) {
569 PyErr_SetString(PyExc_TypeError,
570 "source code string cannot contain null bytes");
571 return NULL;
572 }
573 return str;
Guido van Rossumf15a29f2007-05-04 00:41:39 +0000574}
575
Guido van Rossum79f25d91997-04-29 20:08:16 +0000576static PyObject *
Guido van Rossumd8faa362007-04-27 19:54:29 +0000577builtin_compile(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum5b722181993-03-30 17:46:03 +0000578{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000579 char *str;
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000580 PyObject *filename_obj;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000581 char *filename;
582 char *startstr;
583 int mode = -1;
584 int dont_inherit = 0;
585 int supplied_flags = 0;
Georg Brandl8334fd92010-12-04 10:26:46 +0000586 int optimize = -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000587 int is_ast;
588 PyCompilerFlags cf;
589 PyObject *cmd;
590 static char *kwlist[] = {"source", "filename", "mode", "flags",
Georg Brandl8334fd92010-12-04 10:26:46 +0000591 "dont_inherit", "optimize", NULL};
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000592 int start[] = {Py_file_input, Py_eval_input, Py_single_input};
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000593 PyObject *result;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000594
Georg Brandl8334fd92010-12-04 10:26:46 +0000595 if (!PyArg_ParseTupleAndKeywords(args, kwds, "OO&s|iii:compile", kwlist,
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000596 &cmd,
597 PyUnicode_FSConverter, &filename_obj,
598 &startstr, &supplied_flags,
Georg Brandl8334fd92010-12-04 10:26:46 +0000599 &dont_inherit, &optimize))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000600 return NULL;
Tim Peters6cd6a822001-08-17 22:11:27 +0000601
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000602 filename = PyBytes_AS_STRING(filename_obj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000603 cf.cf_flags = supplied_flags | PyCF_SOURCE_IS_UTF8;
Just van Rossum3aaf42c2003-02-10 08:21:10 +0000604
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000605 if (supplied_flags &
606 ~(PyCF_MASK | PyCF_MASK_OBSOLETE | PyCF_DONT_IMPLY_DEDENT | PyCF_ONLY_AST))
607 {
608 PyErr_SetString(PyExc_ValueError,
609 "compile(): unrecognised flags");
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000610 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000611 }
612 /* XXX Warn if (supplied_flags & PyCF_MASK_OBSOLETE) != 0? */
Tim Peters6cd6a822001-08-17 22:11:27 +0000613
Georg Brandl8334fd92010-12-04 10:26:46 +0000614 if (optimize < -1 || optimize > 2) {
615 PyErr_SetString(PyExc_ValueError,
616 "compile(): invalid optimize value");
617 goto error;
618 }
619
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000620 if (!dont_inherit) {
621 PyEval_MergeCompilerFlags(&cf);
622 }
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000623
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000624 if (strcmp(startstr, "exec") == 0)
625 mode = 0;
626 else if (strcmp(startstr, "eval") == 0)
627 mode = 1;
628 else if (strcmp(startstr, "single") == 0)
629 mode = 2;
630 else {
631 PyErr_SetString(PyExc_ValueError,
632 "compile() arg 3 must be 'exec', 'eval' or 'single'");
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000633 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000634 }
Neal Norwitzdb4115f2008-03-31 04:20:05 +0000635
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000636 is_ast = PyAST_Check(cmd);
637 if (is_ast == -1)
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000638 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000639 if (is_ast) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000640 if (supplied_flags & PyCF_ONLY_AST) {
641 Py_INCREF(cmd);
642 result = cmd;
643 }
644 else {
645 PyArena *arena;
646 mod_ty mod;
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000647
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000648 arena = PyArena_New();
Stefan Krah07795df2012-08-20 17:19:50 +0200649 if (arena == NULL)
650 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000651 mod = PyAST_obj2mod(cmd, arena, mode);
652 if (mod == NULL) {
653 PyArena_Free(arena);
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000654 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000655 }
Benjamin Peterson832bfe22011-08-09 16:15:04 -0500656 if (!PyAST_Validate(mod)) {
657 PyArena_Free(arena);
658 goto error;
659 }
Georg Brandl8334fd92010-12-04 10:26:46 +0000660 result = (PyObject*)PyAST_CompileEx(mod, filename,
661 &cf, optimize, arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000662 PyArena_Free(arena);
663 }
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000664 goto finally;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000665 }
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000666
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000667 str = source_as_string(cmd, "compile", "string, bytes, AST or code", &cf);
668 if (str == NULL)
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000669 goto error;
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000670
Georg Brandl8334fd92010-12-04 10:26:46 +0000671 result = Py_CompileStringExFlags(str, filename, start[mode], &cf, optimize);
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000672 goto finally;
673
674error:
675 result = NULL;
676finally:
677 Py_DECREF(filename_obj);
678 return result;
Guido van Rossum5b722181993-03-30 17:46:03 +0000679}
680
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000681PyDoc_STRVAR(compile_doc,
Tim Peters6cd6a822001-08-17 22:11:27 +0000682"compile(source, filename, mode[, flags[, dont_inherit]]) -> code object\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000683\n\
684Compile the source string (a Python module, statement or expression)\n\
Georg Brandl7cae87c2006-09-06 06:51:57 +0000685into a code object that can be executed by exec() or eval().\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000686The filename will be used for run-time error messages.\n\
687The mode must be 'exec' to compile a module, 'single' to compile a\n\
Tim Peters6cd6a822001-08-17 22:11:27 +0000688single (interactive) statement, or 'eval' to compile an expression.\n\
689The flags argument, if present, controls which future statements influence\n\
690the compilation of the code.\n\
691The dont_inherit argument, if non-zero, stops the compilation inheriting\n\
692the effects of any future statements in effect in the code calling\n\
693compile; if absent or zero these statements do influence the compilation,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000694in addition to any features explicitly specified.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000695
Guido van Rossum79f25d91997-04-29 20:08:16 +0000696static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000697builtin_dir(PyObject *self, PyObject *args)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000698{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000699 PyObject *arg = NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000700
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000701 if (!PyArg_UnpackTuple(args, "dir", 0, 1, &arg))
702 return NULL;
703 return PyObject_Dir(arg);
Guido van Rossum3f5da241990-12-20 15:06:42 +0000704}
705
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000706PyDoc_STRVAR(dir_doc,
Tim Peters5d2b77c2001-09-03 05:47:38 +0000707"dir([object]) -> list of strings\n"
708"\n"
Georg Brandle32b4222007-03-10 22:13:27 +0000709"If called without an argument, return the names in the current scope.\n"
710"Else, return an alphabetized list of names comprising (some of) the attributes\n"
711"of the given object, and of attributes reachable from it.\n"
712"If the object supplies a method named __dir__, it will be used; otherwise\n"
713"the default dir() logic is used and returns:\n"
714" for a module object: the module's attributes.\n"
715" for a class object: its attributes, and recursively the attributes\n"
716" of its bases.\n"
Guido van Rossumd8faa362007-04-27 19:54:29 +0000717" for any other object: its attributes, its class's attributes, and\n"
Georg Brandle32b4222007-03-10 22:13:27 +0000718" recursively the attributes of its class's base classes.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000719
Guido van Rossum79f25d91997-04-29 20:08:16 +0000720static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000721builtin_divmod(PyObject *self, PyObject *args)
Guido van Rossum6a00cd81995-01-07 12:39:01 +0000722{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000723 PyObject *v, *w;
Guido van Rossum6a00cd81995-01-07 12:39:01 +0000724
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000725 if (!PyArg_UnpackTuple(args, "divmod", 2, 2, &v, &w))
726 return NULL;
727 return PyNumber_Divmod(v, w);
Guido van Rossum3f5da241990-12-20 15:06:42 +0000728}
729
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000730PyDoc_STRVAR(divmod_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000731"divmod(x, y) -> (div, mod)\n\
732\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000733Return the tuple ((x-x%y)/y, x%y). Invariant: div*y + mod == x.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000734
735
Guido van Rossum79f25d91997-04-29 20:08:16 +0000736static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000737builtin_eval(PyObject *self, PyObject *args)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000738{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000739 PyObject *cmd, *result, *tmp = NULL;
740 PyObject *globals = Py_None, *locals = Py_None;
741 char *str;
742 PyCompilerFlags cf;
Guido van Rossum590baa41993-11-30 13:40:46 +0000743
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000744 if (!PyArg_UnpackTuple(args, "eval", 1, 3, &cmd, &globals, &locals))
745 return NULL;
746 if (locals != Py_None && !PyMapping_Check(locals)) {
747 PyErr_SetString(PyExc_TypeError, "locals must be a mapping");
748 return NULL;
749 }
750 if (globals != Py_None && !PyDict_Check(globals)) {
751 PyErr_SetString(PyExc_TypeError, PyMapping_Check(globals) ?
752 "globals must be a real dict; try eval(expr, {}, mapping)"
753 : "globals must be a dict");
754 return NULL;
755 }
756 if (globals == Py_None) {
757 globals = PyEval_GetGlobals();
758 if (locals == Py_None)
759 locals = PyEval_GetLocals();
760 }
761 else if (locals == Py_None)
762 locals = globals;
Tim Peters9fa96be2001-08-17 23:04:59 +0000763
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000764 if (globals == NULL || locals == NULL) {
765 PyErr_SetString(PyExc_TypeError,
766 "eval must be given globals and locals "
767 "when called without a frame");
768 return NULL;
769 }
Georg Brandl77c85e62005-09-15 10:46:13 +0000770
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000771 if (PyDict_GetItemString(globals, "__builtins__") == NULL) {
772 if (PyDict_SetItemString(globals, "__builtins__",
773 PyEval_GetBuiltins()) != 0)
774 return NULL;
775 }
Tim Peters9fa96be2001-08-17 23:04:59 +0000776
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000777 if (PyCode_Check(cmd)) {
778 if (PyCode_GetNumFree((PyCodeObject *)cmd) > 0) {
779 PyErr_SetString(PyExc_TypeError,
780 "code object passed to eval() may not contain free variables");
781 return NULL;
782 }
Martin v. Löwis4d0d4712010-12-03 20:14:31 +0000783 return PyEval_EvalCode(cmd, globals, locals);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000784 }
Tim Peters9fa96be2001-08-17 23:04:59 +0000785
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000786 cf.cf_flags = PyCF_SOURCE_IS_UTF8;
787 str = source_as_string(cmd, "eval", "string, bytes or code", &cf);
788 if (str == NULL)
789 return NULL;
Just van Rossum3aaf42c2003-02-10 08:21:10 +0000790
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000791 while (*str == ' ' || *str == '\t')
792 str++;
Tim Peters9fa96be2001-08-17 23:04:59 +0000793
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000794 (void)PyEval_MergeCompilerFlags(&cf);
795 result = PyRun_StringFlags(str, Py_eval_input, globals, locals, &cf);
796 Py_XDECREF(tmp);
797 return result;
Guido van Rossum3f5da241990-12-20 15:06:42 +0000798}
799
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000800PyDoc_STRVAR(eval_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000801"eval(source[, globals[, locals]]) -> value\n\
802\n\
803Evaluate the source in the context of globals and locals.\n\
804The source may be a string representing a Python expression\n\
805or a code object as returned by compile().\n\
Thomas Wouters89f507f2006-12-13 04:49:30 +0000806The globals must be a dictionary and locals can be any mapping,\n\
Raymond Hettinger214b1c32004-07-02 06:41:07 +0000807defaulting to the current globals and locals.\n\
808If only globals is given, locals defaults to it.\n");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000809
Georg Brandl7cae87c2006-09-06 06:51:57 +0000810static PyObject *
811builtin_exec(PyObject *self, PyObject *args)
812{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000813 PyObject *v;
814 PyObject *prog, *globals = Py_None, *locals = Py_None;
Georg Brandl7cae87c2006-09-06 06:51:57 +0000815
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000816 if (!PyArg_UnpackTuple(args, "exec", 1, 3, &prog, &globals, &locals))
817 return NULL;
Georg Brandl2cabc562008-08-28 07:57:16 +0000818
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000819 if (globals == Py_None) {
820 globals = PyEval_GetGlobals();
821 if (locals == Py_None) {
822 locals = PyEval_GetLocals();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000823 }
824 if (!globals || !locals) {
825 PyErr_SetString(PyExc_SystemError,
826 "globals and locals cannot be NULL");
827 return NULL;
828 }
829 }
830 else if (locals == Py_None)
831 locals = globals;
Georg Brandl7cae87c2006-09-06 06:51:57 +0000832
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000833 if (!PyDict_Check(globals)) {
834 PyErr_Format(PyExc_TypeError, "exec() arg 2 must be a dict, not %.100s",
835 globals->ob_type->tp_name);
836 return NULL;
837 }
838 if (!PyMapping_Check(locals)) {
839 PyErr_Format(PyExc_TypeError,
840 "arg 3 must be a mapping or None, not %.100s",
841 locals->ob_type->tp_name);
842 return NULL;
843 }
844 if (PyDict_GetItemString(globals, "__builtins__") == NULL) {
845 if (PyDict_SetItemString(globals, "__builtins__",
846 PyEval_GetBuiltins()) != 0)
847 return NULL;
848 }
849
850 if (PyCode_Check(prog)) {
851 if (PyCode_GetNumFree((PyCodeObject *)prog) > 0) {
852 PyErr_SetString(PyExc_TypeError,
853 "code object passed to exec() may not "
854 "contain free variables");
855 return NULL;
856 }
Martin v. Löwis4d0d4712010-12-03 20:14:31 +0000857 v = PyEval_EvalCode(prog, globals, locals);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000858 }
859 else {
860 char *str;
861 PyCompilerFlags cf;
862 cf.cf_flags = PyCF_SOURCE_IS_UTF8;
863 str = source_as_string(prog, "exec",
864 "string, bytes or code", &cf);
865 if (str == NULL)
866 return NULL;
867 if (PyEval_MergeCompilerFlags(&cf))
868 v = PyRun_StringFlags(str, Py_file_input, globals,
869 locals, &cf);
870 else
871 v = PyRun_String(str, Py_file_input, globals, locals);
872 }
873 if (v == NULL)
874 return NULL;
875 Py_DECREF(v);
876 Py_RETURN_NONE;
Georg Brandl7cae87c2006-09-06 06:51:57 +0000877}
878
879PyDoc_STRVAR(exec_doc,
880"exec(object[, globals[, locals]])\n\
881\n\
Mark Dickinson480e8e32009-12-19 21:19:35 +0000882Read and execute code from an object, which can be a string or a code\n\
Benjamin Peterson38090262009-01-04 15:30:39 +0000883object.\n\
Georg Brandl7cae87c2006-09-06 06:51:57 +0000884The globals and locals are dictionaries, defaulting to the current\n\
885globals and locals. If only globals is given, locals defaults to it.");
886
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000887
Guido van Rossum79f25d91997-04-29 20:08:16 +0000888static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000889builtin_getattr(PyObject *self, PyObject *args)
Guido van Rossum33894be1992-01-27 16:53:09 +0000890{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000891 PyObject *v, *result, *dflt = NULL;
892 PyObject *name;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000893
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000894 if (!PyArg_UnpackTuple(args, "getattr", 2, 3, &v, &name, &dflt))
895 return NULL;
Martin v. Löwis5b222132007-06-10 09:51:05 +0000896
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000897 if (!PyUnicode_Check(name)) {
898 PyErr_SetString(PyExc_TypeError,
899 "getattr(): attribute name must be string");
900 return NULL;
901 }
902 result = PyObject_GetAttr(v, name);
903 if (result == NULL && dflt != NULL &&
904 PyErr_ExceptionMatches(PyExc_AttributeError))
905 {
906 PyErr_Clear();
907 Py_INCREF(dflt);
908 result = dflt;
909 }
910 return result;
Guido van Rossum9bfef441993-03-29 10:43:31 +0000911}
912
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000913PyDoc_STRVAR(getattr_doc,
Guido van Rossum950ff291998-06-29 13:38:57 +0000914"getattr(object, name[, default]) -> value\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000915\n\
Guido van Rossum950ff291998-06-29 13:38:57 +0000916Get a named attribute from an object; getattr(x, 'y') is equivalent to x.y.\n\
917When a default argument is given, it is returned when the attribute doesn't\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000918exist; without it, an exception is raised in that case.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000919
920
Guido van Rossum79f25d91997-04-29 20:08:16 +0000921static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000922builtin_globals(PyObject *self)
Guido van Rossum872537c1995-07-07 22:43:42 +0000923{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000924 PyObject *d;
Guido van Rossum872537c1995-07-07 22:43:42 +0000925
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000926 d = PyEval_GetGlobals();
927 Py_XINCREF(d);
928 return d;
Guido van Rossum872537c1995-07-07 22:43:42 +0000929}
930
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000931PyDoc_STRVAR(globals_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000932"globals() -> dictionary\n\
933\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000934Return the dictionary containing the current scope's global variables.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000935
936
Guido van Rossum79f25d91997-04-29 20:08:16 +0000937static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000938builtin_hasattr(PyObject *self, PyObject *args)
Guido van Rossum9bfef441993-03-29 10:43:31 +0000939{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000940 PyObject *v;
941 PyObject *name;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000942
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000943 if (!PyArg_UnpackTuple(args, "hasattr", 2, 2, &v, &name))
944 return NULL;
945 if (!PyUnicode_Check(name)) {
946 PyErr_SetString(PyExc_TypeError,
947 "hasattr(): attribute name must be string");
948 return NULL;
949 }
950 v = PyObject_GetAttr(v, name);
951 if (v == NULL) {
Benjamin Peterson17689992010-08-24 03:26:23 +0000952 if (PyErr_ExceptionMatches(PyExc_AttributeError)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000953 PyErr_Clear();
Benjamin Peterson17689992010-08-24 03:26:23 +0000954 Py_RETURN_FALSE;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000955 }
Benjamin Peterson17689992010-08-24 03:26:23 +0000956 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000957 }
958 Py_DECREF(v);
Benjamin Peterson17689992010-08-24 03:26:23 +0000959 Py_RETURN_TRUE;
Guido van Rossum33894be1992-01-27 16:53:09 +0000960}
961
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000962PyDoc_STRVAR(hasattr_doc,
Guido van Rossum77f6a652002-04-03 22:41:51 +0000963"hasattr(object, name) -> bool\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000964\n\
965Return whether the object has an attribute with the given name.\n\
Benjamin Peterson17689992010-08-24 03:26:23 +0000966(This is done by calling getattr(object, name) and catching AttributeError.)");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000967
968
Guido van Rossum79f25d91997-04-29 20:08:16 +0000969static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000970builtin_id(PyObject *self, PyObject *v)
Guido van Rossum5b722181993-03-30 17:46:03 +0000971{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000972 return PyLong_FromVoidPtr(v);
Guido van Rossum5b722181993-03-30 17:46:03 +0000973}
974
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000975PyDoc_STRVAR(id_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000976"id(object) -> integer\n\
977\n\
978Return the identity of an object. This is guaranteed to be unique among\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000979simultaneously existing objects. (Hint: it's the object's memory address.)");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000980
981
Raymond Hettingera6c60372008-03-13 01:26:19 +0000982/* map object ************************************************************/
983
984typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000985 PyObject_HEAD
986 PyObject *iters;
987 PyObject *func;
Raymond Hettingera6c60372008-03-13 01:26:19 +0000988} mapobject;
989
Guido van Rossum79f25d91997-04-29 20:08:16 +0000990static PyObject *
Raymond Hettingera6c60372008-03-13 01:26:19 +0000991map_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
Guido van Rossum12d12c51993-10-26 17:58:25 +0000992{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000993 PyObject *it, *iters, *func;
994 mapobject *lz;
995 Py_ssize_t numargs, i;
Raymond Hettingera6c60372008-03-13 01:26:19 +0000996
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000997 if (type == &PyMap_Type && !_PyArg_NoKeywords("map()", kwds))
998 return NULL;
Raymond Hettingera6c60372008-03-13 01:26:19 +0000999
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001000 numargs = PyTuple_Size(args);
1001 if (numargs < 2) {
1002 PyErr_SetString(PyExc_TypeError,
1003 "map() must have at least two arguments.");
1004 return NULL;
1005 }
Raymond Hettingera6c60372008-03-13 01:26:19 +00001006
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001007 iters = PyTuple_New(numargs-1);
1008 if (iters == NULL)
1009 return NULL;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001010
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001011 for (i=1 ; i<numargs ; i++) {
1012 /* Get iterator. */
1013 it = PyObject_GetIter(PyTuple_GET_ITEM(args, i));
1014 if (it == NULL) {
1015 Py_DECREF(iters);
1016 return NULL;
1017 }
1018 PyTuple_SET_ITEM(iters, i-1, it);
1019 }
Raymond Hettingera6c60372008-03-13 01:26:19 +00001020
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001021 /* create mapobject structure */
1022 lz = (mapobject *)type->tp_alloc(type, 0);
1023 if (lz == NULL) {
1024 Py_DECREF(iters);
1025 return NULL;
1026 }
1027 lz->iters = iters;
1028 func = PyTuple_GET_ITEM(args, 0);
1029 Py_INCREF(func);
1030 lz->func = func;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001031
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001032 return (PyObject *)lz;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001033}
1034
1035static void
1036map_dealloc(mapobject *lz)
1037{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001038 PyObject_GC_UnTrack(lz);
Serhiy Storchakae8f706e2013-04-06 21:14:43 +03001039 Py_TRASHCAN_SAFE_BEGIN(lz)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001040 Py_XDECREF(lz->iters);
1041 Py_XDECREF(lz->func);
1042 Py_TYPE(lz)->tp_free(lz);
Serhiy Storchakae8f706e2013-04-06 21:14:43 +03001043 Py_TRASHCAN_SAFE_END(lz)
Raymond Hettingera6c60372008-03-13 01:26:19 +00001044}
1045
1046static int
1047map_traverse(mapobject *lz, visitproc visit, void *arg)
1048{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001049 Py_VISIT(lz->iters);
1050 Py_VISIT(lz->func);
1051 return 0;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001052}
1053
1054static PyObject *
1055map_next(mapobject *lz)
1056{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001057 PyObject *val;
1058 PyObject *argtuple;
1059 PyObject *result;
1060 Py_ssize_t numargs, i;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001061
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001062 numargs = PyTuple_Size(lz->iters);
1063 argtuple = PyTuple_New(numargs);
1064 if (argtuple == NULL)
1065 return NULL;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001066
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001067 for (i=0 ; i<numargs ; i++) {
1068 val = PyIter_Next(PyTuple_GET_ITEM(lz->iters, i));
1069 if (val == NULL) {
1070 Py_DECREF(argtuple);
1071 return NULL;
1072 }
1073 PyTuple_SET_ITEM(argtuple, i, val);
1074 }
1075 result = PyObject_Call(lz->func, argtuple, NULL);
1076 Py_DECREF(argtuple);
1077 return result;
Guido van Rossum12d12c51993-10-26 17:58:25 +00001078}
1079
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001080static PyObject *
1081map_reduce(mapobject *lz)
1082{
1083 Py_ssize_t numargs = PyTuple_GET_SIZE(lz->iters);
1084 PyObject *args = PyTuple_New(numargs+1);
1085 Py_ssize_t i;
1086 if (args == NULL)
1087 return NULL;
1088 Py_INCREF(lz->func);
1089 PyTuple_SET_ITEM(args, 0, lz->func);
1090 for (i = 0; i<numargs; i++){
1091 PyObject *it = PyTuple_GET_ITEM(lz->iters, i);
1092 Py_INCREF(it);
1093 PyTuple_SET_ITEM(args, i+1, it);
1094 }
1095
1096 return Py_BuildValue("ON", Py_TYPE(lz), args);
1097}
1098
1099static PyMethodDef map_methods[] = {
1100 {"__reduce__", (PyCFunction)map_reduce, METH_NOARGS, reduce_doc},
1101 {NULL, NULL} /* sentinel */
1102};
1103
1104
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001105PyDoc_STRVAR(map_doc,
Raymond Hettingera6c60372008-03-13 01:26:19 +00001106"map(func, *iterables) --> map object\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001107\n\
Raymond Hettingera6c60372008-03-13 01:26:19 +00001108Make an iterator that computes the function using arguments from\n\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001109each of the iterables. Stops when the shortest iterable is exhausted.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001110
Raymond Hettingera6c60372008-03-13 01:26:19 +00001111PyTypeObject PyMap_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001112 PyVarObject_HEAD_INIT(&PyType_Type, 0)
1113 "map", /* tp_name */
1114 sizeof(mapobject), /* tp_basicsize */
1115 0, /* tp_itemsize */
1116 /* methods */
1117 (destructor)map_dealloc, /* tp_dealloc */
1118 0, /* tp_print */
1119 0, /* tp_getattr */
1120 0, /* tp_setattr */
1121 0, /* tp_reserved */
1122 0, /* tp_repr */
1123 0, /* tp_as_number */
1124 0, /* tp_as_sequence */
1125 0, /* tp_as_mapping */
1126 0, /* tp_hash */
1127 0, /* tp_call */
1128 0, /* tp_str */
1129 PyObject_GenericGetAttr, /* tp_getattro */
1130 0, /* tp_setattro */
1131 0, /* tp_as_buffer */
1132 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
1133 Py_TPFLAGS_BASETYPE, /* tp_flags */
1134 map_doc, /* tp_doc */
1135 (traverseproc)map_traverse, /* tp_traverse */
1136 0, /* tp_clear */
1137 0, /* tp_richcompare */
1138 0, /* tp_weaklistoffset */
1139 PyObject_SelfIter, /* tp_iter */
1140 (iternextfunc)map_next, /* tp_iternext */
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001141 map_methods, /* tp_methods */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001142 0, /* tp_members */
1143 0, /* tp_getset */
1144 0, /* tp_base */
1145 0, /* tp_dict */
1146 0, /* tp_descr_get */
1147 0, /* tp_descr_set */
1148 0, /* tp_dictoffset */
1149 0, /* tp_init */
1150 PyType_GenericAlloc, /* tp_alloc */
1151 map_new, /* tp_new */
1152 PyObject_GC_Del, /* tp_free */
Raymond Hettingera6c60372008-03-13 01:26:19 +00001153};
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001154
Guido van Rossum79f25d91997-04-29 20:08:16 +00001155static PyObject *
Georg Brandla18af4e2007-04-21 15:47:16 +00001156builtin_next(PyObject *self, PyObject *args)
1157{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001158 PyObject *it, *res;
1159 PyObject *def = NULL;
Georg Brandla18af4e2007-04-21 15:47:16 +00001160
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001161 if (!PyArg_UnpackTuple(args, "next", 1, 2, &it, &def))
1162 return NULL;
1163 if (!PyIter_Check(it)) {
1164 PyErr_Format(PyExc_TypeError,
Philip Jenvey50add042011-11-06 16:37:52 -08001165 "'%.200s' object is not an iterator",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001166 it->ob_type->tp_name);
1167 return NULL;
1168 }
1169
1170 res = (*it->ob_type->tp_iternext)(it);
1171 if (res != NULL) {
1172 return res;
1173 } else if (def != NULL) {
1174 if (PyErr_Occurred()) {
1175 if(!PyErr_ExceptionMatches(PyExc_StopIteration))
1176 return NULL;
1177 PyErr_Clear();
1178 }
1179 Py_INCREF(def);
1180 return def;
1181 } else if (PyErr_Occurred()) {
1182 return NULL;
1183 } else {
1184 PyErr_SetNone(PyExc_StopIteration);
1185 return NULL;
1186 }
Georg Brandla18af4e2007-04-21 15:47:16 +00001187}
1188
1189PyDoc_STRVAR(next_doc,
1190"next(iterator[, default])\n\
1191\n\
1192Return the next item from the iterator. If default is given and the iterator\n\
1193is exhausted, it is returned instead of raising StopIteration.");
1194
1195
1196static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001197builtin_setattr(PyObject *self, PyObject *args)
Guido van Rossum33894be1992-01-27 16:53:09 +00001198{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001199 PyObject *v;
1200 PyObject *name;
1201 PyObject *value;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001202
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001203 if (!PyArg_UnpackTuple(args, "setattr", 3, 3, &v, &name, &value))
1204 return NULL;
1205 if (PyObject_SetAttr(v, name, value) != 0)
1206 return NULL;
1207 Py_INCREF(Py_None);
1208 return Py_None;
Guido van Rossum33894be1992-01-27 16:53:09 +00001209}
1210
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001211PyDoc_STRVAR(setattr_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001212"setattr(object, name, value)\n\
1213\n\
1214Set a named attribute on an object; setattr(x, 'y', v) is equivalent to\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001215``x.y = v''.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001216
1217
Guido van Rossum79f25d91997-04-29 20:08:16 +00001218static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001219builtin_delattr(PyObject *self, PyObject *args)
Guido van Rossum14144fc1994-08-29 12:53:40 +00001220{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001221 PyObject *v;
1222 PyObject *name;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001223
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001224 if (!PyArg_UnpackTuple(args, "delattr", 2, 2, &v, &name))
1225 return NULL;
1226 if (PyObject_SetAttr(v, name, (PyObject *)NULL) != 0)
1227 return NULL;
1228 Py_INCREF(Py_None);
1229 return Py_None;
Guido van Rossum14144fc1994-08-29 12:53:40 +00001230}
1231
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001232PyDoc_STRVAR(delattr_doc,
Guido van Rossumdf12a591998-11-23 22:13:04 +00001233"delattr(object, name)\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001234\n\
1235Delete a named attribute on an object; delattr(x, 'y') is equivalent to\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001236``del x.y''.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001237
1238
Guido van Rossum79f25d91997-04-29 20:08:16 +00001239static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001240builtin_hash(PyObject *self, PyObject *v)
Guido van Rossum9bfef441993-03-29 10:43:31 +00001241{
Benjamin Peterson8f67d082010-10-17 20:54:53 +00001242 Py_hash_t x;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001243
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001244 x = PyObject_Hash(v);
1245 if (x == -1)
1246 return NULL;
Benjamin Peterson8f67d082010-10-17 20:54:53 +00001247 return PyLong_FromSsize_t(x);
Guido van Rossum9bfef441993-03-29 10:43:31 +00001248}
1249
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001250PyDoc_STRVAR(hash_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001251"hash(object) -> integer\n\
1252\n\
1253Return a hash value for the object. Two objects with the same value have\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001254the same hash value. The reverse is not necessarily true, but likely.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001255
1256
Guido van Rossum79f25d91997-04-29 20:08:16 +00001257static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001258builtin_hex(PyObject *self, PyObject *v)
Guido van Rossum006bcd41991-10-24 14:54:44 +00001259{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001260 return PyNumber_ToBase(v, 16);
Guido van Rossum006bcd41991-10-24 14:54:44 +00001261}
1262
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001263PyDoc_STRVAR(hex_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001264"hex(number) -> string\n\
1265\n\
Alexander Belopolsky12338ab2011-04-07 00:15:33 -04001266Return the hexadecimal representation of an integer.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001267
1268
Guido van Rossum79f25d91997-04-29 20:08:16 +00001269static PyObject *
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001270builtin_iter(PyObject *self, PyObject *args)
1271{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001272 PyObject *v, *w = NULL;
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001273
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001274 if (!PyArg_UnpackTuple(args, "iter", 1, 2, &v, &w))
1275 return NULL;
1276 if (w == NULL)
1277 return PyObject_GetIter(v);
1278 if (!PyCallable_Check(v)) {
1279 PyErr_SetString(PyExc_TypeError,
1280 "iter(v, w): v must be callable");
1281 return NULL;
1282 }
1283 return PyCallIter_New(v, w);
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001284}
1285
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001286PyDoc_STRVAR(iter_doc,
Georg Brandld11ae5d2008-05-16 13:27:32 +00001287"iter(iterable) -> iterator\n\
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001288iter(callable, sentinel) -> iterator\n\
1289\n\
1290Get an iterator from an object. In the first form, the argument must\n\
1291supply its own iterator, or be a sequence.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001292In the second form, the callable is called until it returns the sentinel.");
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001293
1294
1295static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001296builtin_len(PyObject *self, PyObject *v)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001297{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001298 Py_ssize_t res;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001299
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001300 res = PyObject_Size(v);
1301 if (res < 0 && PyErr_Occurred())
1302 return NULL;
1303 return PyLong_FromSsize_t(res);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001304}
1305
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001306PyDoc_STRVAR(len_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001307"len(object) -> integer\n\
1308\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001309Return the number of items of a sequence or mapping.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001310
1311
Guido van Rossum79f25d91997-04-29 20:08:16 +00001312static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001313builtin_locals(PyObject *self)
Guido van Rossum872537c1995-07-07 22:43:42 +00001314{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001315 PyObject *d;
Guido van Rossum872537c1995-07-07 22:43:42 +00001316
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001317 d = PyEval_GetLocals();
1318 Py_XINCREF(d);
1319 return d;
Guido van Rossum872537c1995-07-07 22:43:42 +00001320}
1321
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001322PyDoc_STRVAR(locals_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001323"locals() -> dictionary\n\
1324\n\
Raymond Hettinger69bf8f32003-01-04 02:16:22 +00001325Update and return a dictionary containing the current scope's local variables.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001326
1327
Guido van Rossum79f25d91997-04-29 20:08:16 +00001328static PyObject *
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001329min_max(PyObject *args, PyObject *kwds, int op)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001330{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001331 PyObject *v, *it, *item, *val, *maxitem, *maxval, *keyfunc=NULL;
1332 const char *name = op == Py_LT ? "min" : "max";
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001333
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001334 if (PyTuple_Size(args) > 1)
1335 v = args;
1336 else if (!PyArg_UnpackTuple(args, (char *)name, 1, 1, &v))
1337 return NULL;
Tim Peters67d687a2002-04-29 21:27:32 +00001338
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001339 if (kwds != NULL && PyDict_Check(kwds) && PyDict_Size(kwds)) {
1340 keyfunc = PyDict_GetItemString(kwds, "key");
1341 if (PyDict_Size(kwds)!=1 || keyfunc == NULL) {
1342 PyErr_Format(PyExc_TypeError,
1343 "%s() got an unexpected keyword argument", name);
1344 return NULL;
1345 }
1346 Py_INCREF(keyfunc);
1347 }
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001348
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001349 it = PyObject_GetIter(v);
1350 if (it == NULL) {
1351 Py_XDECREF(keyfunc);
1352 return NULL;
1353 }
Tim Petersc3074532001-05-03 07:00:32 +00001354
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001355 maxitem = NULL; /* the result */
1356 maxval = NULL; /* the value associated with the result */
1357 while (( item = PyIter_Next(it) )) {
1358 /* get the value from the key function */
1359 if (keyfunc != NULL) {
1360 val = PyObject_CallFunctionObjArgs(keyfunc, item, NULL);
1361 if (val == NULL)
1362 goto Fail_it_item;
1363 }
1364 /* no key function; the value is the item */
1365 else {
1366 val = item;
1367 Py_INCREF(val);
1368 }
Tim Petersc3074532001-05-03 07:00:32 +00001369
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001370 /* maximum value and item are unset; set them */
1371 if (maxval == NULL) {
1372 maxitem = item;
1373 maxval = val;
1374 }
1375 /* maximum value and item are set; update them as necessary */
1376 else {
1377 int cmp = PyObject_RichCompareBool(val, maxval, op);
1378 if (cmp < 0)
1379 goto Fail_it_item_and_val;
1380 else if (cmp > 0) {
1381 Py_DECREF(maxval);
1382 Py_DECREF(maxitem);
1383 maxval = val;
1384 maxitem = item;
1385 }
1386 else {
1387 Py_DECREF(item);
1388 Py_DECREF(val);
1389 }
1390 }
1391 }
1392 if (PyErr_Occurred())
1393 goto Fail_it;
1394 if (maxval == NULL) {
1395 PyErr_Format(PyExc_ValueError,
1396 "%s() arg is an empty sequence", name);
1397 assert(maxitem == NULL);
1398 }
1399 else
1400 Py_DECREF(maxval);
1401 Py_DECREF(it);
1402 Py_XDECREF(keyfunc);
1403 return maxitem;
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001404
1405Fail_it_item_and_val:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001406 Py_DECREF(val);
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001407Fail_it_item:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001408 Py_DECREF(item);
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001409Fail_it:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001410 Py_XDECREF(maxval);
1411 Py_XDECREF(maxitem);
1412 Py_DECREF(it);
1413 Py_XDECREF(keyfunc);
1414 return NULL;
Guido van Rossum3f5da241990-12-20 15:06:42 +00001415}
1416
Guido van Rossum79f25d91997-04-29 20:08:16 +00001417static PyObject *
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001418builtin_min(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001419{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001420 return min_max(args, kwds, Py_LT);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001421}
1422
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001423PyDoc_STRVAR(min_doc,
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001424"min(iterable[, key=func]) -> value\n\
1425min(a, b, c, ...[, key=func]) -> value\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001426\n\
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001427With a single iterable argument, return its smallest item.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001428With two or more arguments, return the smallest argument.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001429
1430
Guido van Rossum79f25d91997-04-29 20:08:16 +00001431static PyObject *
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001432builtin_max(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001433{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001434 return min_max(args, kwds, Py_GT);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001435}
1436
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001437PyDoc_STRVAR(max_doc,
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001438"max(iterable[, key=func]) -> value\n\
1439max(a, b, c, ...[, key=func]) -> value\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001440\n\
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001441With a single iterable argument, return its largest item.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001442With two or more arguments, return the largest argument.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001443
1444
Guido van Rossum79f25d91997-04-29 20:08:16 +00001445static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001446builtin_oct(PyObject *self, PyObject *v)
Guido van Rossum006bcd41991-10-24 14:54:44 +00001447{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001448 return PyNumber_ToBase(v, 8);
Guido van Rossum006bcd41991-10-24 14:54:44 +00001449}
1450
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001451PyDoc_STRVAR(oct_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001452"oct(number) -> string\n\
1453\n\
Alexander Belopolsky12338ab2011-04-07 00:15:33 -04001454Return the octal representation of an integer.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001455
1456
Guido van Rossum79f25d91997-04-29 20:08:16 +00001457static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001458builtin_ord(PyObject *self, PyObject* obj)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001459{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001460 long ord;
1461 Py_ssize_t size;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001462
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001463 if (PyBytes_Check(obj)) {
1464 size = PyBytes_GET_SIZE(obj);
1465 if (size == 1) {
1466 ord = (long)((unsigned char)*PyBytes_AS_STRING(obj));
1467 return PyLong_FromLong(ord);
1468 }
1469 }
1470 else if (PyUnicode_Check(obj)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001471 if (PyUnicode_READY(obj) == -1)
1472 return NULL;
1473 size = PyUnicode_GET_LENGTH(obj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001474 if (size == 1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001475 ord = (long)PyUnicode_READ_CHAR(obj, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001476 return PyLong_FromLong(ord);
1477 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001478 }
1479 else if (PyByteArray_Check(obj)) {
1480 /* XXX Hopefully this is temporary */
1481 size = PyByteArray_GET_SIZE(obj);
1482 if (size == 1) {
1483 ord = (long)((unsigned char)*PyByteArray_AS_STRING(obj));
1484 return PyLong_FromLong(ord);
1485 }
1486 }
1487 else {
1488 PyErr_Format(PyExc_TypeError,
1489 "ord() expected string of length 1, but " \
1490 "%.200s found", obj->ob_type->tp_name);
1491 return NULL;
1492 }
Guido van Rossum09095f32000-03-10 23:00:52 +00001493
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001494 PyErr_Format(PyExc_TypeError,
1495 "ord() expected a character, "
1496 "but string of length %zd found",
1497 size);
1498 return NULL;
Guido van Rossum3f5da241990-12-20 15:06:42 +00001499}
1500
Guido van Rossum307fa8c2007-07-16 20:46:27 +00001501PyDoc_VAR(ord_doc) = PyDoc_STR(
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001502"ord(c) -> integer\n\
1503\n\
Guido van Rossum8ac004e2007-07-15 13:00:05 +00001504Return the integer ordinal of a one-character string."
Antoine Pitrouedc60182012-06-23 14:19:58 +02001505);
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001506
1507
Guido van Rossum79f25d91997-04-29 20:08:16 +00001508static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001509builtin_pow(PyObject *self, PyObject *args)
Guido van Rossum6a00cd81995-01-07 12:39:01 +00001510{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001511 PyObject *v, *w, *z = Py_None;
Guido van Rossum6a00cd81995-01-07 12:39:01 +00001512
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001513 if (!PyArg_UnpackTuple(args, "pow", 2, 3, &v, &w, &z))
1514 return NULL;
1515 return PyNumber_Power(v, w, z);
Guido van Rossumd4905451991-05-05 20:00:36 +00001516}
1517
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001518PyDoc_STRVAR(pow_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001519"pow(x, y[, z]) -> number\n\
1520\n\
1521With two arguments, equivalent to x**y. With three arguments,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001522equivalent to (x**y) % z, but may be more efficient (e.g. for longs).");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001523
1524
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001525
Guido van Rossum34343512006-11-30 22:13:52 +00001526static PyObject *
1527builtin_print(PyObject *self, PyObject *args, PyObject *kwds)
1528{
Georg Brandlbc3b6822012-01-13 19:41:25 +01001529 static char *kwlist[] = {"sep", "end", "file", "flush", 0};
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001530 static PyObject *dummy_args;
Georg Brandlbc3b6822012-01-13 19:41:25 +01001531 PyObject *sep = NULL, *end = NULL, *file = NULL, *flush = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001532 int i, err;
Guido van Rossum34343512006-11-30 22:13:52 +00001533
Benjamin Peterson00102562012-01-11 21:00:16 -05001534 if (dummy_args == NULL && !(dummy_args = PyTuple_New(0)))
Georg Brandlbc3b6822012-01-13 19:41:25 +01001535 return NULL;
1536 if (!PyArg_ParseTupleAndKeywords(dummy_args, kwds, "|OOOO:print",
1537 kwlist, &sep, &end, &file, &flush))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001538 return NULL;
1539 if (file == NULL || file == Py_None) {
1540 file = PySys_GetObject("stdout");
1541 /* sys.stdout may be None when FILE* stdout isn't connected */
1542 if (file == Py_None)
1543 Py_RETURN_NONE;
1544 }
Guido van Rossum34343512006-11-30 22:13:52 +00001545
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001546 if (sep == Py_None) {
1547 sep = NULL;
1548 }
1549 else if (sep && !PyUnicode_Check(sep)) {
1550 PyErr_Format(PyExc_TypeError,
1551 "sep must be None or a string, not %.200s",
1552 sep->ob_type->tp_name);
1553 return NULL;
1554 }
1555 if (end == Py_None) {
1556 end = NULL;
1557 }
1558 else if (end && !PyUnicode_Check(end)) {
1559 PyErr_Format(PyExc_TypeError,
1560 "end must be None or a string, not %.200s",
1561 end->ob_type->tp_name);
1562 return NULL;
1563 }
Guido van Rossum34343512006-11-30 22:13:52 +00001564
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001565 for (i = 0; i < PyTuple_Size(args); i++) {
1566 if (i > 0) {
1567 if (sep == NULL)
1568 err = PyFile_WriteString(" ", file);
1569 else
1570 err = PyFile_WriteObject(sep, file,
1571 Py_PRINT_RAW);
1572 if (err)
1573 return NULL;
1574 }
1575 err = PyFile_WriteObject(PyTuple_GetItem(args, i), file,
1576 Py_PRINT_RAW);
1577 if (err)
1578 return NULL;
1579 }
Guido van Rossum34343512006-11-30 22:13:52 +00001580
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001581 if (end == NULL)
1582 err = PyFile_WriteString("\n", file);
1583 else
1584 err = PyFile_WriteObject(end, file, Py_PRINT_RAW);
1585 if (err)
1586 return NULL;
Guido van Rossum34343512006-11-30 22:13:52 +00001587
Georg Brandlbc3b6822012-01-13 19:41:25 +01001588 if (flush != NULL) {
1589 PyObject *tmp;
1590 int do_flush = PyObject_IsTrue(flush);
1591 if (do_flush == -1)
1592 return NULL;
1593 else if (do_flush) {
1594 tmp = PyObject_CallMethod(file, "flush", "");
1595 if (tmp == NULL)
1596 return NULL;
1597 else
1598 Py_DECREF(tmp);
1599 }
1600 }
1601
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001602 Py_RETURN_NONE;
Guido van Rossum34343512006-11-30 22:13:52 +00001603}
1604
1605PyDoc_STRVAR(print_doc,
Senthil Kumarane9175bd2012-08-10 13:53:45 -07001606"print(value, ..., sep=' ', end='\\n', file=sys.stdout, flush=False)\n\
Guido van Rossum34343512006-11-30 22:13:52 +00001607\n\
1608Prints the values to a stream, or to sys.stdout by default.\n\
1609Optional keyword arguments:\n\
Senthil Kumarane9175bd2012-08-10 13:53:45 -07001610file: a file-like object (stream); defaults to the current sys.stdout.\n\
1611sep: string inserted between values, default a space.\n\
1612end: string appended after the last value, default a newline.\n\
1613flush: whether to forcibly flush the stream.");
Guido van Rossum34343512006-11-30 22:13:52 +00001614
1615
Guido van Rossuma88a0332007-02-26 16:59:55 +00001616static PyObject *
1617builtin_input(PyObject *self, PyObject *args)
1618{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001619 PyObject *promptarg = NULL;
1620 PyObject *fin = PySys_GetObject("stdin");
1621 PyObject *fout = PySys_GetObject("stdout");
1622 PyObject *ferr = PySys_GetObject("stderr");
1623 PyObject *tmp;
1624 long fd;
1625 int tty;
Guido van Rossuma88a0332007-02-26 16:59:55 +00001626
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001627 /* Parse arguments */
1628 if (!PyArg_UnpackTuple(args, "input", 0, 1, &promptarg))
1629 return NULL;
Guido van Rossuma88a0332007-02-26 16:59:55 +00001630
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001631 /* Check that stdin/out/err are intact */
1632 if (fin == NULL || fin == Py_None) {
1633 PyErr_SetString(PyExc_RuntimeError,
1634 "input(): lost sys.stdin");
1635 return NULL;
1636 }
1637 if (fout == NULL || fout == Py_None) {
1638 PyErr_SetString(PyExc_RuntimeError,
1639 "input(): lost sys.stdout");
1640 return NULL;
1641 }
1642 if (ferr == NULL || ferr == Py_None) {
1643 PyErr_SetString(PyExc_RuntimeError,
1644 "input(): lost sys.stderr");
1645 return NULL;
1646 }
Guido van Rossumeba76962007-05-27 09:13:28 +00001647
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001648 /* First of all, flush stderr */
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001649 tmp = _PyObject_CallMethodId(ferr, &PyId_flush, "");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001650 if (tmp == NULL)
1651 PyErr_Clear();
1652 else
1653 Py_DECREF(tmp);
Guido van Rossumeba76962007-05-27 09:13:28 +00001654
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001655 /* We should only use (GNU) readline if Python's sys.stdin and
1656 sys.stdout are the same as C's stdin and stdout, because we
1657 need to pass it those. */
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001658 tmp = _PyObject_CallMethodId(fin, &PyId_fileno, "");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001659 if (tmp == NULL) {
1660 PyErr_Clear();
1661 tty = 0;
1662 }
1663 else {
1664 fd = PyLong_AsLong(tmp);
1665 Py_DECREF(tmp);
1666 if (fd < 0 && PyErr_Occurred())
1667 return NULL;
1668 tty = fd == fileno(stdin) && isatty(fd);
1669 }
1670 if (tty) {
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001671 tmp = _PyObject_CallMethodId(fout, &PyId_fileno, "");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001672 if (tmp == NULL)
1673 PyErr_Clear();
1674 else {
1675 fd = PyLong_AsLong(tmp);
1676 Py_DECREF(tmp);
1677 if (fd < 0 && PyErr_Occurred())
1678 return NULL;
1679 tty = fd == fileno(stdout) && isatty(fd);
1680 }
1681 }
Guido van Rossumeba76962007-05-27 09:13:28 +00001682
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001683 /* If we're interactive, use (GNU) readline */
1684 if (tty) {
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001685 PyObject *po = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001686 char *prompt;
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001687 char *s = NULL;
1688 PyObject *stdin_encoding = NULL, *stdin_errors = NULL;
1689 PyObject *stdout_encoding = NULL, *stdout_errors = NULL;
1690 char *stdin_encoding_str, *stdin_errors_str;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001691 PyObject *result;
Victor Stinnerc0f1a1a2011-02-23 12:07:37 +00001692 size_t len;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02001693 _Py_IDENTIFIER(encoding);
Antoine Pitrou5ee9d8a2011-11-06 00:38:45 +01001694 _Py_IDENTIFIER(errors);
Martin v. Löwis4a7b5d52007-09-04 05:24:49 +00001695
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02001696 stdin_encoding = _PyObject_GetAttrId(fin, &PyId_encoding);
Antoine Pitrou5ee9d8a2011-11-06 00:38:45 +01001697 stdin_errors = _PyObject_GetAttrId(fin, &PyId_errors);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001698 if (!stdin_encoding || !stdin_errors)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001699 /* stdin is a text stream, so it must have an
1700 encoding. */
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001701 goto _readline_errors;
Victor Stinner306f0102010-05-19 01:06:22 +00001702 stdin_encoding_str = _PyUnicode_AsString(stdin_encoding);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001703 stdin_errors_str = _PyUnicode_AsString(stdin_errors);
1704 if (!stdin_encoding_str || !stdin_errors_str)
1705 goto _readline_errors;
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001706 tmp = _PyObject_CallMethodId(fout, &PyId_flush, "");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001707 if (tmp == NULL)
1708 PyErr_Clear();
1709 else
1710 Py_DECREF(tmp);
1711 if (promptarg != NULL) {
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001712 /* We have a prompt, encode it as stdout would */
1713 char *stdout_encoding_str, *stdout_errors_str;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001714 PyObject *stringpo;
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02001715 stdout_encoding = _PyObject_GetAttrId(fout, &PyId_encoding);
Antoine Pitrou5ee9d8a2011-11-06 00:38:45 +01001716 stdout_errors = _PyObject_GetAttrId(fout, &PyId_errors);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001717 if (!stdout_encoding || !stdout_errors)
1718 goto _readline_errors;
Victor Stinner306f0102010-05-19 01:06:22 +00001719 stdout_encoding_str = _PyUnicode_AsString(stdout_encoding);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001720 stdout_errors_str = _PyUnicode_AsString(stdout_errors);
1721 if (!stdout_encoding_str || !stdout_errors_str)
1722 goto _readline_errors;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001723 stringpo = PyObject_Str(promptarg);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001724 if (stringpo == NULL)
1725 goto _readline_errors;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001726 po = PyUnicode_AsEncodedString(stringpo,
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001727 stdout_encoding_str, stdout_errors_str);
1728 Py_CLEAR(stdout_encoding);
1729 Py_CLEAR(stdout_errors);
1730 Py_CLEAR(stringpo);
1731 if (po == NULL)
1732 goto _readline_errors;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001733 prompt = PyBytes_AsString(po);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001734 if (prompt == NULL)
1735 goto _readline_errors;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001736 }
1737 else {
1738 po = NULL;
1739 prompt = "";
1740 }
1741 s = PyOS_Readline(stdin, stdout, prompt);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001742 if (s == NULL) {
Richard Oudkerk614c5782013-04-03 13:44:50 +01001743 PyErr_CheckSignals();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001744 if (!PyErr_Occurred())
1745 PyErr_SetNone(PyExc_KeyboardInterrupt);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001746 goto _readline_errors;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001747 }
Victor Stinnerc0f1a1a2011-02-23 12:07:37 +00001748
1749 len = strlen(s);
1750 if (len == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001751 PyErr_SetNone(PyExc_EOFError);
1752 result = NULL;
1753 }
Victor Stinnerc0f1a1a2011-02-23 12:07:37 +00001754 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001755 if (len > PY_SSIZE_T_MAX) {
1756 PyErr_SetString(PyExc_OverflowError,
1757 "input: input too long");
1758 result = NULL;
1759 }
1760 else {
Victor Stinnerc0f1a1a2011-02-23 12:07:37 +00001761 len--; /* strip trailing '\n' */
1762 if (len != 0 && s[len-1] == '\r')
1763 len--; /* strip trailing '\r' */
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001764 result = PyUnicode_Decode(s, len, stdin_encoding_str,
1765 stdin_errors_str);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001766 }
1767 }
1768 Py_DECREF(stdin_encoding);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001769 Py_DECREF(stdin_errors);
1770 Py_XDECREF(po);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001771 PyMem_FREE(s);
1772 return result;
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001773 _readline_errors:
1774 Py_XDECREF(stdin_encoding);
1775 Py_XDECREF(stdout_encoding);
1776 Py_XDECREF(stdin_errors);
1777 Py_XDECREF(stdout_errors);
1778 Py_XDECREF(po);
1779 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001780 }
Guido van Rossumeba76962007-05-27 09:13:28 +00001781
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001782 /* Fallback if we're not interactive */
1783 if (promptarg != NULL) {
1784 if (PyFile_WriteObject(promptarg, fout, Py_PRINT_RAW) != 0)
1785 return NULL;
1786 }
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001787 tmp = _PyObject_CallMethodId(fout, &PyId_flush, "");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001788 if (tmp == NULL)
1789 PyErr_Clear();
1790 else
1791 Py_DECREF(tmp);
1792 return PyFile_GetLine(fin, -1);
Guido van Rossuma88a0332007-02-26 16:59:55 +00001793}
1794
1795PyDoc_STRVAR(input_doc,
1796"input([prompt]) -> string\n\
1797\n\
1798Read a string from standard input. The trailing newline is stripped.\n\
1799If the user hits EOF (Unix: Ctl-D, Windows: Ctl-Z+Return), raise EOFError.\n\
1800On Unix, GNU readline is used if enabled. The prompt string, if given,\n\
1801is printed without a trailing newline before reading.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001802
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001803
Guido van Rossum79f25d91997-04-29 20:08:16 +00001804static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001805builtin_repr(PyObject *self, PyObject *v)
Guido van Rossumc89705d1992-11-26 08:54:07 +00001806{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001807 return PyObject_Repr(v);
Guido van Rossumc89705d1992-11-26 08:54:07 +00001808}
1809
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001810PyDoc_STRVAR(repr_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001811"repr(object) -> string\n\
1812\n\
1813Return the canonical string representation of the object.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001814For most object types, eval(repr(object)) == object.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001815
1816
Guido van Rossum79f25d91997-04-29 20:08:16 +00001817static PyObject *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001818builtin_round(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum9e51f9b1993-02-12 16:29:05 +00001819{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001820 static PyObject *round_str = NULL;
1821 PyObject *ndigits = NULL;
1822 static char *kwlist[] = {"number", "ndigits", 0};
1823 PyObject *number, *round;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001824
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001825 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|O:round",
1826 kwlist, &number, &ndigits))
1827 return NULL;
Alex Martelliae211f92007-08-22 23:21:33 +00001828
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001829 if (Py_TYPE(number)->tp_dict == NULL) {
1830 if (PyType_Ready(Py_TYPE(number)) < 0)
1831 return NULL;
1832 }
Guido van Rossum15d3d042007-08-24 02:02:45 +00001833
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001834 if (round_str == NULL) {
1835 round_str = PyUnicode_InternFromString("__round__");
1836 if (round_str == NULL)
1837 return NULL;
1838 }
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001839
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001840 round = _PyType_Lookup(Py_TYPE(number), round_str);
1841 if (round == NULL) {
1842 PyErr_Format(PyExc_TypeError,
1843 "type %.100s doesn't define __round__ method",
1844 Py_TYPE(number)->tp_name);
1845 return NULL;
1846 }
Alex Martelliae211f92007-08-22 23:21:33 +00001847
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001848 if (ndigits == NULL)
1849 return PyObject_CallFunction(round, "O", number);
1850 else
1851 return PyObject_CallFunction(round, "OO", number, ndigits);
Guido van Rossum9e51f9b1993-02-12 16:29:05 +00001852}
1853
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001854PyDoc_STRVAR(round_doc,
Mark Dickinson1124e712009-01-28 21:25:58 +00001855"round(number[, ndigits]) -> number\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001856\n\
1857Round a number to a given precision in decimal digits (default 0 digits).\n\
Mark Dickinson0d748c22008-07-05 11:29:03 +00001858This returns an int when called with one argument, otherwise the\n\
Georg Brandl809ddaa2008-07-01 20:39:59 +00001859same type as the number. ndigits may be negative.");
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001860
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001861
Raymond Hettinger64958a12003-12-17 20:43:33 +00001862static PyObject *
1863builtin_sorted(PyObject *self, PyObject *args, PyObject *kwds)
1864{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001865 PyObject *newlist, *v, *seq, *keyfunc=NULL, *newargs;
1866 PyObject *callable;
1867 static char *kwlist[] = {"iterable", "key", "reverse", 0};
1868 int reverse;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02001869 _Py_IDENTIFIER(sort);
Raymond Hettinger64958a12003-12-17 20:43:33 +00001870
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001871 /* args 1-3 should match listsort in Objects/listobject.c */
1872 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|Oi:sorted",
1873 kwlist, &seq, &keyfunc, &reverse))
1874 return NULL;
Raymond Hettinger64958a12003-12-17 20:43:33 +00001875
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001876 newlist = PySequence_List(seq);
1877 if (newlist == NULL)
1878 return NULL;
Raymond Hettinger64958a12003-12-17 20:43:33 +00001879
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02001880 callable = _PyObject_GetAttrId(newlist, &PyId_sort);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001881 if (callable == NULL) {
1882 Py_DECREF(newlist);
1883 return NULL;
1884 }
Georg Brandl99d7e4e2005-08-31 22:21:15 +00001885
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001886 newargs = PyTuple_GetSlice(args, 1, 4);
1887 if (newargs == NULL) {
1888 Py_DECREF(newlist);
1889 Py_DECREF(callable);
1890 return NULL;
1891 }
Raymond Hettinger64958a12003-12-17 20:43:33 +00001892
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001893 v = PyObject_Call(callable, newargs, kwds);
1894 Py_DECREF(newargs);
1895 Py_DECREF(callable);
1896 if (v == NULL) {
1897 Py_DECREF(newlist);
1898 return NULL;
1899 }
1900 Py_DECREF(v);
1901 return newlist;
Raymond Hettinger64958a12003-12-17 20:43:33 +00001902}
1903
1904PyDoc_STRVAR(sorted_doc,
Raymond Hettinger70b64fc2008-01-30 20:15:17 +00001905"sorted(iterable, key=None, reverse=False) --> new sorted list");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001906
Guido van Rossum79f25d91997-04-29 20:08:16 +00001907static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001908builtin_vars(PyObject *self, PyObject *args)
Guido van Rossum2d951851994-08-29 12:52:16 +00001909{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001910 PyObject *v = NULL;
1911 PyObject *d;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001912
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001913 if (!PyArg_UnpackTuple(args, "vars", 0, 1, &v))
1914 return NULL;
1915 if (v == NULL) {
1916 d = PyEval_GetLocals();
1917 if (d == NULL) {
1918 if (!PyErr_Occurred())
1919 PyErr_SetString(PyExc_SystemError,
1920 "vars(): no locals!?");
1921 }
1922 else
1923 Py_INCREF(d);
1924 }
1925 else {
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02001926 _Py_IDENTIFIER(__dict__);
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02001927 d = _PyObject_GetAttrId(v, &PyId___dict__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001928 if (d == NULL) {
1929 PyErr_SetString(PyExc_TypeError,
1930 "vars() argument must have __dict__ attribute");
1931 return NULL;
1932 }
1933 }
1934 return d;
Guido van Rossum2d951851994-08-29 12:52:16 +00001935}
1936
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001937PyDoc_STRVAR(vars_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001938"vars([object]) -> dictionary\n\
1939\n\
1940Without arguments, equivalent to locals().\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001941With an argument, equivalent to object.__dict__.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001942
Alex Martellia70b1912003-04-22 08:12:33 +00001943static PyObject*
1944builtin_sum(PyObject *self, PyObject *args)
1945{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001946 PyObject *seq;
1947 PyObject *result = NULL;
1948 PyObject *temp, *item, *iter;
Alex Martellia70b1912003-04-22 08:12:33 +00001949
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001950 if (!PyArg_UnpackTuple(args, "sum", 1, 2, &seq, &result))
1951 return NULL;
Alex Martellia70b1912003-04-22 08:12:33 +00001952
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001953 iter = PyObject_GetIter(seq);
1954 if (iter == NULL)
1955 return NULL;
Alex Martellia70b1912003-04-22 08:12:33 +00001956
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001957 if (result == NULL) {
1958 result = PyLong_FromLong(0);
1959 if (result == NULL) {
1960 Py_DECREF(iter);
1961 return NULL;
1962 }
1963 } else {
1964 /* reject string values for 'start' parameter */
1965 if (PyUnicode_Check(result)) {
1966 PyErr_SetString(PyExc_TypeError,
1967 "sum() can't sum strings [use ''.join(seq) instead]");
1968 Py_DECREF(iter);
1969 return NULL;
1970 }
Benjamin Petersonce071ca2011-07-29 14:23:47 -05001971 if (PyBytes_Check(result)) {
1972 PyErr_SetString(PyExc_TypeError,
1973 "sum() can't sum bytes [use b''.join(seq) instead]");
Benjamin Peterson405f32c2011-07-29 22:43:45 -05001974 Py_DECREF(iter);
Benjamin Petersonce071ca2011-07-29 14:23:47 -05001975 return NULL;
1976 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001977 if (PyByteArray_Check(result)) {
1978 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson4f921c22011-07-29 14:24:29 -05001979 "sum() can't sum bytearray [use b''.join(seq) instead]");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001980 Py_DECREF(iter);
1981 return NULL;
1982 }
Guido van Rossum3172c5d2007-10-16 18:12:55 +00001983
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001984 Py_INCREF(result);
1985 }
Alex Martellia70b1912003-04-22 08:12:33 +00001986
Guido van Rossum8ce8a782007-11-01 19:42:39 +00001987#ifndef SLOW_SUM
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001988 /* Fast addition by keeping temporary sums in C instead of new Python objects.
1989 Assumes all inputs are the same type. If the assumption fails, default
1990 to the more general routine.
1991 */
1992 if (PyLong_CheckExact(result)) {
1993 int overflow;
1994 long i_result = PyLong_AsLongAndOverflow(result, &overflow);
1995 /* If this already overflowed, don't even enter the loop. */
1996 if (overflow == 0) {
1997 Py_DECREF(result);
1998 result = NULL;
1999 }
2000 while(result == NULL) {
2001 item = PyIter_Next(iter);
2002 if (item == NULL) {
2003 Py_DECREF(iter);
2004 if (PyErr_Occurred())
2005 return NULL;
2006 return PyLong_FromLong(i_result);
2007 }
2008 if (PyLong_CheckExact(item)) {
2009 long b = PyLong_AsLongAndOverflow(item, &overflow);
2010 long x = i_result + b;
2011 if (overflow == 0 && ((x^i_result) >= 0 || (x^b) >= 0)) {
2012 i_result = x;
2013 Py_DECREF(item);
2014 continue;
2015 }
2016 }
2017 /* Either overflowed or is not an int. Restore real objects and process normally */
2018 result = PyLong_FromLong(i_result);
2019 temp = PyNumber_Add(result, item);
2020 Py_DECREF(result);
2021 Py_DECREF(item);
2022 result = temp;
2023 if (result == NULL) {
2024 Py_DECREF(iter);
2025 return NULL;
2026 }
2027 }
2028 }
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002029
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002030 if (PyFloat_CheckExact(result)) {
2031 double f_result = PyFloat_AS_DOUBLE(result);
2032 Py_DECREF(result);
2033 result = NULL;
2034 while(result == NULL) {
2035 item = PyIter_Next(iter);
2036 if (item == NULL) {
2037 Py_DECREF(iter);
2038 if (PyErr_Occurred())
2039 return NULL;
2040 return PyFloat_FromDouble(f_result);
2041 }
2042 if (PyFloat_CheckExact(item)) {
2043 PyFPE_START_PROTECT("add", Py_DECREF(item); Py_DECREF(iter); return 0)
2044 f_result += PyFloat_AS_DOUBLE(item);
2045 PyFPE_END_PROTECT(f_result)
2046 Py_DECREF(item);
2047 continue;
2048 }
2049 if (PyLong_CheckExact(item)) {
2050 long value;
2051 int overflow;
2052 value = PyLong_AsLongAndOverflow(item, &overflow);
2053 if (!overflow) {
2054 PyFPE_START_PROTECT("add", Py_DECREF(item); Py_DECREF(iter); return 0)
2055 f_result += (double)value;
2056 PyFPE_END_PROTECT(f_result)
2057 Py_DECREF(item);
2058 continue;
2059 }
2060 }
2061 result = PyFloat_FromDouble(f_result);
2062 temp = PyNumber_Add(result, item);
2063 Py_DECREF(result);
2064 Py_DECREF(item);
2065 result = temp;
2066 if (result == NULL) {
2067 Py_DECREF(iter);
2068 return NULL;
2069 }
2070 }
2071 }
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002072#endif
2073
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002074 for(;;) {
2075 item = PyIter_Next(iter);
2076 if (item == NULL) {
2077 /* error, or end-of-sequence */
2078 if (PyErr_Occurred()) {
2079 Py_DECREF(result);
2080 result = NULL;
2081 }
2082 break;
2083 }
2084 /* It's tempting to use PyNumber_InPlaceAdd instead of
2085 PyNumber_Add here, to avoid quadratic running time
2086 when doing 'sum(list_of_lists, [])'. However, this
2087 would produce a change in behaviour: a snippet like
Mark Dickinson9acadc52009-10-26 14:19:42 +00002088
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002089 empty = []
2090 sum([[x] for x in range(10)], empty)
Mark Dickinson9acadc52009-10-26 14:19:42 +00002091
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002092 would change the value of empty. */
2093 temp = PyNumber_Add(result, item);
2094 Py_DECREF(result);
2095 Py_DECREF(item);
2096 result = temp;
2097 if (result == NULL)
2098 break;
2099 }
2100 Py_DECREF(iter);
2101 return result;
Alex Martellia70b1912003-04-22 08:12:33 +00002102}
2103
2104PyDoc_STRVAR(sum_doc,
Georg Brandld11ae5d2008-05-16 13:27:32 +00002105"sum(iterable[, start]) -> value\n\
Alex Martellia70b1912003-04-22 08:12:33 +00002106\n\
Georg Brandld11ae5d2008-05-16 13:27:32 +00002107Returns the sum of an iterable of numbers (NOT strings) plus the value\n\
2108of parameter 'start' (which defaults to 0). When the iterable is\n\
Thomas Wouters89f507f2006-12-13 04:49:30 +00002109empty, returns start.");
Alex Martellia70b1912003-04-22 08:12:33 +00002110
2111
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002112static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002113builtin_isinstance(PyObject *self, PyObject *args)
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002114{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002115 PyObject *inst;
2116 PyObject *cls;
2117 int retval;
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002118
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002119 if (!PyArg_UnpackTuple(args, "isinstance", 2, 2, &inst, &cls))
2120 return NULL;
Guido van Rossumf5dd9141997-12-02 19:11:45 +00002121
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002122 retval = PyObject_IsInstance(inst, cls);
2123 if (retval < 0)
2124 return NULL;
2125 return PyBool_FromLong(retval);
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002126}
2127
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002128PyDoc_STRVAR(isinstance_doc,
Guido van Rossum77f6a652002-04-03 22:41:51 +00002129"isinstance(object, class-or-type-or-tuple) -> bool\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002130\n\
2131Return whether an object is an instance of a class or of a subclass thereof.\n\
Guido van Rossum03290ec2001-10-07 20:54:12 +00002132With a type as second argument, return whether that is the object's type.\n\
2133The form using a tuple, isinstance(x, (A, B, ...)), is a shortcut for\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002134isinstance(x, A) or isinstance(x, B) or ... (etc.).");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002135
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002136
2137static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002138builtin_issubclass(PyObject *self, PyObject *args)
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002139{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002140 PyObject *derived;
2141 PyObject *cls;
2142 int retval;
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002143
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002144 if (!PyArg_UnpackTuple(args, "issubclass", 2, 2, &derived, &cls))
2145 return NULL;
Guido van Rossum668213d1999-06-16 17:28:37 +00002146
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002147 retval = PyObject_IsSubclass(derived, cls);
2148 if (retval < 0)
2149 return NULL;
2150 return PyBool_FromLong(retval);
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002151}
2152
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002153PyDoc_STRVAR(issubclass_doc,
Guido van Rossum77f6a652002-04-03 22:41:51 +00002154"issubclass(C, B) -> bool\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002155\n\
Walter Dörwaldd9a6ad32002-12-12 16:41:44 +00002156Return whether class C is a subclass (i.e., a derived class) of class B.\n\
2157When using a tuple as the second argument issubclass(X, (A, B, ...)),\n\
2158is a shortcut for issubclass(X, A) or issubclass(X, B) or ... (etc.).");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002159
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002160
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002161typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002162 PyObject_HEAD
2163 Py_ssize_t tuplesize;
2164 PyObject *ittuple; /* tuple of iterators */
2165 PyObject *result;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002166} zipobject;
2167
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002168static PyObject *
2169zip_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
Barry Warsawbd599b52000-08-03 15:45:29 +00002170{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002171 zipobject *lz;
2172 Py_ssize_t i;
2173 PyObject *ittuple; /* tuple of iterators */
2174 PyObject *result;
2175 Py_ssize_t tuplesize = PySequence_Length(args);
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002176
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002177 if (type == &PyZip_Type && !_PyArg_NoKeywords("zip()", kwds))
2178 return NULL;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002179
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002180 /* args must be a tuple */
2181 assert(PyTuple_Check(args));
Barry Warsawbd599b52000-08-03 15:45:29 +00002182
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002183 /* obtain iterators */
2184 ittuple = PyTuple_New(tuplesize);
2185 if (ittuple == NULL)
2186 return NULL;
2187 for (i=0; i < tuplesize; ++i) {
2188 PyObject *item = PyTuple_GET_ITEM(args, i);
2189 PyObject *it = PyObject_GetIter(item);
2190 if (it == NULL) {
2191 if (PyErr_ExceptionMatches(PyExc_TypeError))
2192 PyErr_Format(PyExc_TypeError,
2193 "zip argument #%zd must support iteration",
2194 i+1);
2195 Py_DECREF(ittuple);
2196 return NULL;
2197 }
2198 PyTuple_SET_ITEM(ittuple, i, it);
2199 }
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002200
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002201 /* create a result holder */
2202 result = PyTuple_New(tuplesize);
2203 if (result == NULL) {
2204 Py_DECREF(ittuple);
2205 return NULL;
2206 }
2207 for (i=0 ; i < tuplesize ; i++) {
2208 Py_INCREF(Py_None);
2209 PyTuple_SET_ITEM(result, i, Py_None);
2210 }
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002211
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002212 /* create zipobject structure */
2213 lz = (zipobject *)type->tp_alloc(type, 0);
2214 if (lz == NULL) {
2215 Py_DECREF(ittuple);
2216 Py_DECREF(result);
2217 return NULL;
2218 }
2219 lz->ittuple = ittuple;
2220 lz->tuplesize = tuplesize;
2221 lz->result = result;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002222
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002223 return (PyObject *)lz;
Barry Warsawbd599b52000-08-03 15:45:29 +00002224}
2225
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002226static void
2227zip_dealloc(zipobject *lz)
2228{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002229 PyObject_GC_UnTrack(lz);
Serhiy Storchakae8f706e2013-04-06 21:14:43 +03002230 Py_TRASHCAN_SAFE_BEGIN(lz)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002231 Py_XDECREF(lz->ittuple);
2232 Py_XDECREF(lz->result);
2233 Py_TYPE(lz)->tp_free(lz);
Serhiy Storchakae8f706e2013-04-06 21:14:43 +03002234 Py_TRASHCAN_SAFE_END(lz)
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002235}
2236
2237static int
2238zip_traverse(zipobject *lz, visitproc visit, void *arg)
2239{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002240 Py_VISIT(lz->ittuple);
2241 Py_VISIT(lz->result);
2242 return 0;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002243}
2244
2245static PyObject *
2246zip_next(zipobject *lz)
2247{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002248 Py_ssize_t i;
2249 Py_ssize_t tuplesize = lz->tuplesize;
2250 PyObject *result = lz->result;
2251 PyObject *it;
2252 PyObject *item;
2253 PyObject *olditem;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002254
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002255 if (tuplesize == 0)
2256 return NULL;
Serhiy Storchakae8f706e2013-04-06 21:14:43 +03002257 if (Py_EnterRecursiveCall(" while iterating"))
2258 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002259 if (Py_REFCNT(result) == 1) {
2260 Py_INCREF(result);
2261 for (i=0 ; i < tuplesize ; i++) {
2262 it = PyTuple_GET_ITEM(lz->ittuple, i);
2263 item = (*Py_TYPE(it)->tp_iternext)(it);
Serhiy Storchakae8f706e2013-04-06 21:14:43 +03002264 if (item == NULL)
2265 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002266 olditem = PyTuple_GET_ITEM(result, i);
2267 PyTuple_SET_ITEM(result, i, item);
2268 Py_DECREF(olditem);
2269 }
2270 } else {
2271 result = PyTuple_New(tuplesize);
2272 if (result == NULL)
Serhiy Storchakae8f706e2013-04-06 21:14:43 +03002273 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002274 for (i=0 ; i < tuplesize ; i++) {
2275 it = PyTuple_GET_ITEM(lz->ittuple, i);
2276 item = (*Py_TYPE(it)->tp_iternext)(it);
Serhiy Storchakae8f706e2013-04-06 21:14:43 +03002277 if (item == NULL)
2278 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002279 PyTuple_SET_ITEM(result, i, item);
2280 }
2281 }
Serhiy Storchakae8f706e2013-04-06 21:14:43 +03002282 Py_LeaveRecursiveCall();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002283 return result;
Serhiy Storchakae8f706e2013-04-06 21:14:43 +03002284error:
2285 Py_XDECREF(result);
2286 Py_LeaveRecursiveCall();
2287 return NULL;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002288}
Barry Warsawbd599b52000-08-03 15:45:29 +00002289
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002290static PyObject *
2291zip_reduce(zipobject *lz)
2292{
2293 /* Just recreate the zip with the internal iterator tuple */
2294 return Py_BuildValue("OO", Py_TYPE(lz), lz->ittuple);
2295}
2296
2297static PyMethodDef zip_methods[] = {
2298 {"__reduce__", (PyCFunction)zip_reduce, METH_NOARGS, reduce_doc},
2299 {NULL, NULL} /* sentinel */
2300};
2301
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002302PyDoc_STRVAR(zip_doc,
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002303"zip(iter1 [,iter2 [...]]) --> zip object\n\
Barry Warsawbd599b52000-08-03 15:45:29 +00002304\n\
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002305Return a zip object whose .__next__() method returns a tuple where\n\
2306the i-th element comes from the i-th iterable argument. The .__next__()\n\
2307method continues until the shortest iterable in the argument sequence\n\
Georg Brandlced51db2008-12-04 18:28:38 +00002308is exhausted and then it raises StopIteration.");
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002309
2310PyTypeObject PyZip_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002311 PyVarObject_HEAD_INIT(&PyType_Type, 0)
2312 "zip", /* tp_name */
2313 sizeof(zipobject), /* tp_basicsize */
2314 0, /* tp_itemsize */
2315 /* methods */
2316 (destructor)zip_dealloc, /* tp_dealloc */
2317 0, /* tp_print */
2318 0, /* tp_getattr */
2319 0, /* tp_setattr */
2320 0, /* tp_reserved */
2321 0, /* tp_repr */
2322 0, /* tp_as_number */
2323 0, /* tp_as_sequence */
2324 0, /* tp_as_mapping */
2325 0, /* tp_hash */
2326 0, /* tp_call */
2327 0, /* tp_str */
2328 PyObject_GenericGetAttr, /* tp_getattro */
2329 0, /* tp_setattro */
2330 0, /* tp_as_buffer */
2331 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
2332 Py_TPFLAGS_BASETYPE, /* tp_flags */
2333 zip_doc, /* tp_doc */
2334 (traverseproc)zip_traverse, /* tp_traverse */
2335 0, /* tp_clear */
2336 0, /* tp_richcompare */
2337 0, /* tp_weaklistoffset */
2338 PyObject_SelfIter, /* tp_iter */
2339 (iternextfunc)zip_next, /* tp_iternext */
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002340 zip_methods, /* tp_methods */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002341 0, /* tp_members */
2342 0, /* tp_getset */
2343 0, /* tp_base */
2344 0, /* tp_dict */
2345 0, /* tp_descr_get */
2346 0, /* tp_descr_set */
2347 0, /* tp_dictoffset */
2348 0, /* tp_init */
2349 PyType_GenericAlloc, /* tp_alloc */
2350 zip_new, /* tp_new */
2351 PyObject_GC_Del, /* tp_free */
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002352};
Barry Warsawbd599b52000-08-03 15:45:29 +00002353
2354
Guido van Rossum79f25d91997-04-29 20:08:16 +00002355static PyMethodDef builtin_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002356 {"__build_class__", (PyCFunction)builtin___build_class__,
2357 METH_VARARGS | METH_KEYWORDS, build_class_doc},
2358 {"__import__", (PyCFunction)builtin___import__, METH_VARARGS | METH_KEYWORDS, import_doc},
2359 {"abs", builtin_abs, METH_O, abs_doc},
2360 {"all", builtin_all, METH_O, all_doc},
2361 {"any", builtin_any, METH_O, any_doc},
2362 {"ascii", builtin_ascii, METH_O, ascii_doc},
2363 {"bin", builtin_bin, METH_O, bin_doc},
Antoine Pitroue71362d2010-11-27 22:00:11 +00002364 {"callable", builtin_callable, METH_O, callable_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002365 {"chr", builtin_chr, METH_VARARGS, chr_doc},
2366 {"compile", (PyCFunction)builtin_compile, METH_VARARGS | METH_KEYWORDS, compile_doc},
2367 {"delattr", builtin_delattr, METH_VARARGS, delattr_doc},
2368 {"dir", builtin_dir, METH_VARARGS, dir_doc},
2369 {"divmod", builtin_divmod, METH_VARARGS, divmod_doc},
2370 {"eval", builtin_eval, METH_VARARGS, eval_doc},
2371 {"exec", builtin_exec, METH_VARARGS, exec_doc},
2372 {"format", builtin_format, METH_VARARGS, format_doc},
2373 {"getattr", builtin_getattr, METH_VARARGS, getattr_doc},
2374 {"globals", (PyCFunction)builtin_globals, METH_NOARGS, globals_doc},
2375 {"hasattr", builtin_hasattr, METH_VARARGS, hasattr_doc},
2376 {"hash", builtin_hash, METH_O, hash_doc},
2377 {"hex", builtin_hex, METH_O, hex_doc},
2378 {"id", builtin_id, METH_O, id_doc},
2379 {"input", builtin_input, METH_VARARGS, input_doc},
2380 {"isinstance", builtin_isinstance, METH_VARARGS, isinstance_doc},
2381 {"issubclass", builtin_issubclass, METH_VARARGS, issubclass_doc},
2382 {"iter", builtin_iter, METH_VARARGS, iter_doc},
2383 {"len", builtin_len, METH_O, len_doc},
2384 {"locals", (PyCFunction)builtin_locals, METH_NOARGS, locals_doc},
2385 {"max", (PyCFunction)builtin_max, METH_VARARGS | METH_KEYWORDS, max_doc},
2386 {"min", (PyCFunction)builtin_min, METH_VARARGS | METH_KEYWORDS, min_doc},
2387 {"next", (PyCFunction)builtin_next, METH_VARARGS, next_doc},
2388 {"oct", builtin_oct, METH_O, oct_doc},
2389 {"ord", builtin_ord, METH_O, ord_doc},
2390 {"pow", builtin_pow, METH_VARARGS, pow_doc},
2391 {"print", (PyCFunction)builtin_print, METH_VARARGS | METH_KEYWORDS, print_doc},
2392 {"repr", builtin_repr, METH_O, repr_doc},
2393 {"round", (PyCFunction)builtin_round, METH_VARARGS | METH_KEYWORDS, round_doc},
2394 {"setattr", builtin_setattr, METH_VARARGS, setattr_doc},
2395 {"sorted", (PyCFunction)builtin_sorted, METH_VARARGS | METH_KEYWORDS, sorted_doc},
2396 {"sum", builtin_sum, METH_VARARGS, sum_doc},
2397 {"vars", builtin_vars, METH_VARARGS, vars_doc},
2398 {NULL, NULL},
Guido van Rossum3f5da241990-12-20 15:06:42 +00002399};
2400
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002401PyDoc_STRVAR(builtin_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002402"Built-in functions, exceptions, and other objects.\n\
2403\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002404Noteworthy: None is the `nil' object; Ellipsis represents `...' in slices.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002405
Martin v. Löwis1a214512008-06-11 05:26:20 +00002406static struct PyModuleDef builtinsmodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002407 PyModuleDef_HEAD_INIT,
2408 "builtins",
2409 builtin_doc,
2410 -1, /* multiple "initialization" just copies the module dict. */
2411 builtin_methods,
2412 NULL,
2413 NULL,
2414 NULL,
2415 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00002416};
2417
2418
Guido van Rossum25ce5661997-08-02 03:10:38 +00002419PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002420_PyBuiltin_Init(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +00002421{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002422 PyObject *mod, *dict, *debug;
2423 mod = PyModule_Create(&builtinsmodule);
2424 if (mod == NULL)
2425 return NULL;
2426 dict = PyModule_GetDict(mod);
Tim Peters4b7625e2001-09-13 21:37:17 +00002427
Tim Peters7571a0f2003-03-23 17:52:28 +00002428#ifdef Py_TRACE_REFS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002429 /* "builtins" exposes a number of statically allocated objects
2430 * that, before this code was added in 2.3, never showed up in
2431 * the list of "all objects" maintained by Py_TRACE_REFS. As a
2432 * result, programs leaking references to None and False (etc)
2433 * couldn't be diagnosed by examining sys.getobjects(0).
2434 */
Tim Peters7571a0f2003-03-23 17:52:28 +00002435#define ADD_TO_ALL(OBJECT) _Py_AddToAllObjects((PyObject *)(OBJECT), 0)
2436#else
2437#define ADD_TO_ALL(OBJECT) (void)0
2438#endif
2439
Tim Peters4b7625e2001-09-13 21:37:17 +00002440#define SETBUILTIN(NAME, OBJECT) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002441 if (PyDict_SetItemString(dict, NAME, (PyObject *)OBJECT) < 0) \
2442 return NULL; \
2443 ADD_TO_ALL(OBJECT)
Tim Peters4b7625e2001-09-13 21:37:17 +00002444
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002445 SETBUILTIN("None", Py_None);
2446 SETBUILTIN("Ellipsis", Py_Ellipsis);
2447 SETBUILTIN("NotImplemented", Py_NotImplemented);
2448 SETBUILTIN("False", Py_False);
2449 SETBUILTIN("True", Py_True);
2450 SETBUILTIN("bool", &PyBool_Type);
2451 SETBUILTIN("memoryview", &PyMemoryView_Type);
2452 SETBUILTIN("bytearray", &PyByteArray_Type);
2453 SETBUILTIN("bytes", &PyBytes_Type);
2454 SETBUILTIN("classmethod", &PyClassMethod_Type);
2455 SETBUILTIN("complex", &PyComplex_Type);
2456 SETBUILTIN("dict", &PyDict_Type);
2457 SETBUILTIN("enumerate", &PyEnum_Type);
2458 SETBUILTIN("filter", &PyFilter_Type);
2459 SETBUILTIN("float", &PyFloat_Type);
2460 SETBUILTIN("frozenset", &PyFrozenSet_Type);
2461 SETBUILTIN("property", &PyProperty_Type);
2462 SETBUILTIN("int", &PyLong_Type);
2463 SETBUILTIN("list", &PyList_Type);
2464 SETBUILTIN("map", &PyMap_Type);
2465 SETBUILTIN("object", &PyBaseObject_Type);
2466 SETBUILTIN("range", &PyRange_Type);
2467 SETBUILTIN("reversed", &PyReversed_Type);
2468 SETBUILTIN("set", &PySet_Type);
2469 SETBUILTIN("slice", &PySlice_Type);
2470 SETBUILTIN("staticmethod", &PyStaticMethod_Type);
2471 SETBUILTIN("str", &PyUnicode_Type);
2472 SETBUILTIN("super", &PySuper_Type);
2473 SETBUILTIN("tuple", &PyTuple_Type);
2474 SETBUILTIN("type", &PyType_Type);
2475 SETBUILTIN("zip", &PyZip_Type);
2476 debug = PyBool_FromLong(Py_OptimizeFlag == 0);
2477 if (PyDict_SetItemString(dict, "__debug__", debug) < 0) {
2478 Py_XDECREF(debug);
2479 return NULL;
2480 }
2481 Py_XDECREF(debug);
Barry Warsaw757af0e1997-08-29 22:13:51 +00002482
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002483 return mod;
Tim Peters7571a0f2003-03-23 17:52:28 +00002484#undef ADD_TO_ALL
Tim Peters4b7625e2001-09-13 21:37:17 +00002485#undef SETBUILTIN
Guido van Rossum3f5da241990-12-20 15:06:42 +00002486}