blob: dffdf46a62df9e839b6b4a4a86b7188e1f833f8e [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);
394 Py_XDECREF(lz->func);
395 Py_XDECREF(lz->it);
396 Py_TYPE(lz)->tp_free(lz);
Raymond Hettinger17301e92008-03-13 00:19:26 +0000397}
398
399static int
400filter_traverse(filterobject *lz, visitproc visit, void *arg)
401{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000402 Py_VISIT(lz->it);
403 Py_VISIT(lz->func);
404 return 0;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000405}
406
407static PyObject *
408filter_next(filterobject *lz)
409{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000410 PyObject *item;
411 PyObject *it = lz->it;
412 long ok;
413 PyObject *(*iternext)(PyObject *);
Raymond Hettinger17301e92008-03-13 00:19:26 +0000414
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000415 iternext = *Py_TYPE(it)->tp_iternext;
416 for (;;) {
417 item = iternext(it);
418 if (item == NULL)
419 return NULL;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000420
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000421 if (lz->func == Py_None || lz->func == (PyObject *)&PyBool_Type) {
422 ok = PyObject_IsTrue(item);
423 } else {
424 PyObject *good;
425 good = PyObject_CallFunctionObjArgs(lz->func,
426 item, NULL);
427 if (good == NULL) {
428 Py_DECREF(item);
429 return NULL;
430 }
431 ok = PyObject_IsTrue(good);
432 Py_DECREF(good);
433 }
Antoine Pitrou6f430e42012-08-15 23:18:25 +0200434 if (ok > 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000435 return item;
436 Py_DECREF(item);
Antoine Pitrou6f430e42012-08-15 23:18:25 +0200437 if (ok < 0)
438 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000439 }
Guido van Rossum12d12c51993-10-26 17:58:25 +0000440}
441
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +0000442static PyObject *
443filter_reduce(filterobject *lz)
444{
445 return Py_BuildValue("O(OO)", Py_TYPE(lz), lz->func, lz->it);
446}
447
448PyDoc_STRVAR(reduce_doc, "Return state information for pickling.");
449
450static PyMethodDef filter_methods[] = {
451 {"__reduce__", (PyCFunction)filter_reduce, METH_NOARGS, reduce_doc},
452 {NULL, NULL} /* sentinel */
453};
454
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000455PyDoc_STRVAR(filter_doc,
Georg Brandld11ae5d2008-05-16 13:27:32 +0000456"filter(function or None, iterable) --> filter object\n\
Guido van Rossumc1f779c2007-07-03 08:25:58 +0000457\n\
Georg Brandld11ae5d2008-05-16 13:27:32 +0000458Return an iterator yielding those items of iterable for which function(item)\n\
Raymond Hettinger17301e92008-03-13 00:19:26 +0000459is true. If function is None, return the items that are true.");
460
461PyTypeObject PyFilter_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000462 PyVarObject_HEAD_INIT(&PyType_Type, 0)
463 "filter", /* tp_name */
464 sizeof(filterobject), /* tp_basicsize */
465 0, /* tp_itemsize */
466 /* methods */
467 (destructor)filter_dealloc, /* tp_dealloc */
468 0, /* tp_print */
469 0, /* tp_getattr */
470 0, /* tp_setattr */
471 0, /* tp_reserved */
472 0, /* tp_repr */
473 0, /* tp_as_number */
474 0, /* tp_as_sequence */
475 0, /* tp_as_mapping */
476 0, /* tp_hash */
477 0, /* tp_call */
478 0, /* tp_str */
479 PyObject_GenericGetAttr, /* tp_getattro */
480 0, /* tp_setattro */
481 0, /* tp_as_buffer */
482 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
483 Py_TPFLAGS_BASETYPE, /* tp_flags */
484 filter_doc, /* tp_doc */
485 (traverseproc)filter_traverse, /* tp_traverse */
486 0, /* tp_clear */
487 0, /* tp_richcompare */
488 0, /* tp_weaklistoffset */
489 PyObject_SelfIter, /* tp_iter */
490 (iternextfunc)filter_next, /* tp_iternext */
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +0000491 filter_methods, /* tp_methods */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000492 0, /* tp_members */
493 0, /* tp_getset */
494 0, /* tp_base */
495 0, /* tp_dict */
496 0, /* tp_descr_get */
497 0, /* tp_descr_set */
498 0, /* tp_dictoffset */
499 0, /* tp_init */
500 PyType_GenericAlloc, /* tp_alloc */
501 filter_new, /* tp_new */
502 PyObject_GC_Del, /* tp_free */
Raymond Hettinger17301e92008-03-13 00:19:26 +0000503};
504
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000505
Eric Smith8c663262007-08-25 02:26:07 +0000506static PyObject *
507builtin_format(PyObject *self, PyObject *args)
508{
Christian Heimes94b7d3d2007-12-11 20:20:39 +0000509 PyObject *value;
Eric Smith8fd3eba2008-02-17 19:48:00 +0000510 PyObject *format_spec = NULL;
Eric Smith8c663262007-08-25 02:26:07 +0000511
Eric Smith8fd3eba2008-02-17 19:48:00 +0000512 if (!PyArg_ParseTuple(args, "O|U:format", &value, &format_spec))
Benjamin Petersona12d5c62012-01-03 16:47:22 -0600513 return NULL;
Eric Smith8c663262007-08-25 02:26:07 +0000514
Eric Smith8fd3eba2008-02-17 19:48:00 +0000515 return PyObject_Format(value, format_spec);
Eric Smith8c663262007-08-25 02:26:07 +0000516}
517
Eric Smith8c663262007-08-25 02:26:07 +0000518PyDoc_STRVAR(format_doc,
Eric Smith81936692007-08-31 01:14:01 +0000519"format(value[, format_spec]) -> string\n\
Eric Smith8c663262007-08-25 02:26:07 +0000520\n\
Eric Smith81936692007-08-31 01:14:01 +0000521Returns value.__format__(format_spec)\n\
522format_spec defaults to \"\"");
523
Guido van Rossum7fcf2242007-05-04 17:43:11 +0000524static PyObject *
Walter Dörwalde7efd592007-06-05 20:07:21 +0000525builtin_chr(PyObject *self, PyObject *args)
Guido van Rossum09095f32000-03-10 23:00:52 +0000526{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000527 int x;
Guido van Rossum09095f32000-03-10 23:00:52 +0000528
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000529 if (!PyArg_ParseTuple(args, "i:chr", &x))
530 return NULL;
Fredrik Lundh0dcf67e2001-06-26 20:01:56 +0000531
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000532 return PyUnicode_FromOrdinal(x);
Guido van Rossum09095f32000-03-10 23:00:52 +0000533}
534
Victor Stinner63ab8752011-11-22 03:31:20 +0100535PyDoc_STRVAR(chr_doc,
Guido van Rossum84fc66d2007-05-03 17:18:26 +0000536"chr(i) -> Unicode character\n\
Guido van Rossum09095f32000-03-10 23:00:52 +0000537\n\
Victor Stinner63ab8752011-11-22 03:31:20 +0100538Return a Unicode string of one character with ordinal i; 0 <= i <= 0x10ffff.");
Guido van Rossum09095f32000-03-10 23:00:52 +0000539
540
Guido van Rossumf15a29f2007-05-04 00:41:39 +0000541static char *
Benjamin Petersonf5b52242009-03-02 23:31:26 +0000542source_as_string(PyObject *cmd, char *funcname, char *what, PyCompilerFlags *cf)
Guido van Rossumf15a29f2007-05-04 00:41:39 +0000543{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000544 char *str;
545 Py_ssize_t size;
Guido van Rossumf15a29f2007-05-04 00:41:39 +0000546
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000547 if (PyUnicode_Check(cmd)) {
548 cf->cf_flags |= PyCF_IGNORE_COOKIE;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200549 str = PyUnicode_AsUTF8AndSize(cmd, &size);
550 if (str == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000551 return NULL;
552 }
553 else if (!PyObject_CheckReadBuffer(cmd)) {
554 PyErr_Format(PyExc_TypeError,
555 "%s() arg 1 must be a %s object",
556 funcname, what);
557 return NULL;
558 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200559 else if (PyObject_AsReadBuffer(cmd, (const void **)&str, &size) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000560 return NULL;
561 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200562
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000563 if (strlen(str) != size) {
564 PyErr_SetString(PyExc_TypeError,
565 "source code string cannot contain null bytes");
566 return NULL;
567 }
568 return str;
Guido van Rossumf15a29f2007-05-04 00:41:39 +0000569}
570
Guido van Rossum79f25d91997-04-29 20:08:16 +0000571static PyObject *
Guido van Rossumd8faa362007-04-27 19:54:29 +0000572builtin_compile(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum5b722181993-03-30 17:46:03 +0000573{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000574 char *str;
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000575 PyObject *filename_obj;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000576 char *filename;
577 char *startstr;
578 int mode = -1;
579 int dont_inherit = 0;
580 int supplied_flags = 0;
Georg Brandl8334fd92010-12-04 10:26:46 +0000581 int optimize = -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000582 int is_ast;
583 PyCompilerFlags cf;
584 PyObject *cmd;
585 static char *kwlist[] = {"source", "filename", "mode", "flags",
Georg Brandl8334fd92010-12-04 10:26:46 +0000586 "dont_inherit", "optimize", NULL};
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000587 int start[] = {Py_file_input, Py_eval_input, Py_single_input};
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000588 PyObject *result;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000589
Georg Brandl8334fd92010-12-04 10:26:46 +0000590 if (!PyArg_ParseTupleAndKeywords(args, kwds, "OO&s|iii:compile", kwlist,
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000591 &cmd,
592 PyUnicode_FSConverter, &filename_obj,
593 &startstr, &supplied_flags,
Georg Brandl8334fd92010-12-04 10:26:46 +0000594 &dont_inherit, &optimize))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000595 return NULL;
Tim Peters6cd6a822001-08-17 22:11:27 +0000596
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000597 filename = PyBytes_AS_STRING(filename_obj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000598 cf.cf_flags = supplied_flags | PyCF_SOURCE_IS_UTF8;
Just van Rossum3aaf42c2003-02-10 08:21:10 +0000599
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000600 if (supplied_flags &
601 ~(PyCF_MASK | PyCF_MASK_OBSOLETE | PyCF_DONT_IMPLY_DEDENT | PyCF_ONLY_AST))
602 {
603 PyErr_SetString(PyExc_ValueError,
604 "compile(): unrecognised flags");
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000605 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000606 }
607 /* XXX Warn if (supplied_flags & PyCF_MASK_OBSOLETE) != 0? */
Tim Peters6cd6a822001-08-17 22:11:27 +0000608
Georg Brandl8334fd92010-12-04 10:26:46 +0000609 if (optimize < -1 || optimize > 2) {
610 PyErr_SetString(PyExc_ValueError,
611 "compile(): invalid optimize value");
612 goto error;
613 }
614
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000615 if (!dont_inherit) {
616 PyEval_MergeCompilerFlags(&cf);
617 }
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000618
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000619 if (strcmp(startstr, "exec") == 0)
620 mode = 0;
621 else if (strcmp(startstr, "eval") == 0)
622 mode = 1;
623 else if (strcmp(startstr, "single") == 0)
624 mode = 2;
625 else {
626 PyErr_SetString(PyExc_ValueError,
627 "compile() arg 3 must be 'exec', 'eval' or 'single'");
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000628 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000629 }
Neal Norwitzdb4115f2008-03-31 04:20:05 +0000630
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000631 is_ast = PyAST_Check(cmd);
632 if (is_ast == -1)
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000633 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000634 if (is_ast) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000635 if (supplied_flags & PyCF_ONLY_AST) {
636 Py_INCREF(cmd);
637 result = cmd;
638 }
639 else {
640 PyArena *arena;
641 mod_ty mod;
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000642
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000643 arena = PyArena_New();
Stefan Krah07795df2012-08-20 17:19:50 +0200644 if (arena == NULL)
645 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000646 mod = PyAST_obj2mod(cmd, arena, mode);
647 if (mod == NULL) {
648 PyArena_Free(arena);
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000649 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000650 }
Benjamin Peterson832bfe22011-08-09 16:15:04 -0500651 if (!PyAST_Validate(mod)) {
652 PyArena_Free(arena);
653 goto error;
654 }
Georg Brandl8334fd92010-12-04 10:26:46 +0000655 result = (PyObject*)PyAST_CompileEx(mod, filename,
656 &cf, optimize, arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000657 PyArena_Free(arena);
658 }
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000659 goto finally;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000660 }
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000661
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000662 str = source_as_string(cmd, "compile", "string, bytes, AST or code", &cf);
663 if (str == NULL)
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000664 goto error;
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000665
Georg Brandl8334fd92010-12-04 10:26:46 +0000666 result = Py_CompileStringExFlags(str, filename, start[mode], &cf, optimize);
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000667 goto finally;
668
669error:
670 result = NULL;
671finally:
672 Py_DECREF(filename_obj);
673 return result;
Guido van Rossum5b722181993-03-30 17:46:03 +0000674}
675
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000676PyDoc_STRVAR(compile_doc,
Tim Peters6cd6a822001-08-17 22:11:27 +0000677"compile(source, filename, mode[, flags[, dont_inherit]]) -> code object\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000678\n\
679Compile the source string (a Python module, statement or expression)\n\
Georg Brandl7cae87c2006-09-06 06:51:57 +0000680into a code object that can be executed by exec() or eval().\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000681The filename will be used for run-time error messages.\n\
682The mode must be 'exec' to compile a module, 'single' to compile a\n\
Tim Peters6cd6a822001-08-17 22:11:27 +0000683single (interactive) statement, or 'eval' to compile an expression.\n\
684The flags argument, if present, controls which future statements influence\n\
685the compilation of the code.\n\
686The dont_inherit argument, if non-zero, stops the compilation inheriting\n\
687the effects of any future statements in effect in the code calling\n\
688compile; if absent or zero these statements do influence the compilation,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000689in addition to any features explicitly specified.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000690
Guido van Rossum79f25d91997-04-29 20:08:16 +0000691static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000692builtin_dir(PyObject *self, PyObject *args)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000693{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000694 PyObject *arg = NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000695
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000696 if (!PyArg_UnpackTuple(args, "dir", 0, 1, &arg))
697 return NULL;
698 return PyObject_Dir(arg);
Guido van Rossum3f5da241990-12-20 15:06:42 +0000699}
700
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000701PyDoc_STRVAR(dir_doc,
Tim Peters5d2b77c2001-09-03 05:47:38 +0000702"dir([object]) -> list of strings\n"
703"\n"
Georg Brandle32b4222007-03-10 22:13:27 +0000704"If called without an argument, return the names in the current scope.\n"
705"Else, return an alphabetized list of names comprising (some of) the attributes\n"
706"of the given object, and of attributes reachable from it.\n"
707"If the object supplies a method named __dir__, it will be used; otherwise\n"
708"the default dir() logic is used and returns:\n"
709" for a module object: the module's attributes.\n"
710" for a class object: its attributes, and recursively the attributes\n"
711" of its bases.\n"
Guido van Rossumd8faa362007-04-27 19:54:29 +0000712" for any other object: its attributes, its class's attributes, and\n"
Georg Brandle32b4222007-03-10 22:13:27 +0000713" recursively the attributes of its class's base classes.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000714
Guido van Rossum79f25d91997-04-29 20:08:16 +0000715static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000716builtin_divmod(PyObject *self, PyObject *args)
Guido van Rossum6a00cd81995-01-07 12:39:01 +0000717{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000718 PyObject *v, *w;
Guido van Rossum6a00cd81995-01-07 12:39:01 +0000719
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000720 if (!PyArg_UnpackTuple(args, "divmod", 2, 2, &v, &w))
721 return NULL;
722 return PyNumber_Divmod(v, w);
Guido van Rossum3f5da241990-12-20 15:06:42 +0000723}
724
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000725PyDoc_STRVAR(divmod_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000726"divmod(x, y) -> (div, mod)\n\
727\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000728Return the tuple ((x-x%y)/y, x%y). Invariant: div*y + mod == x.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000729
730
Guido van Rossum79f25d91997-04-29 20:08:16 +0000731static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000732builtin_eval(PyObject *self, PyObject *args)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000733{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000734 PyObject *cmd, *result, *tmp = NULL;
735 PyObject *globals = Py_None, *locals = Py_None;
736 char *str;
737 PyCompilerFlags cf;
Guido van Rossum590baa41993-11-30 13:40:46 +0000738
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000739 if (!PyArg_UnpackTuple(args, "eval", 1, 3, &cmd, &globals, &locals))
740 return NULL;
741 if (locals != Py_None && !PyMapping_Check(locals)) {
742 PyErr_SetString(PyExc_TypeError, "locals must be a mapping");
743 return NULL;
744 }
745 if (globals != Py_None && !PyDict_Check(globals)) {
746 PyErr_SetString(PyExc_TypeError, PyMapping_Check(globals) ?
747 "globals must be a real dict; try eval(expr, {}, mapping)"
748 : "globals must be a dict");
749 return NULL;
750 }
751 if (globals == Py_None) {
752 globals = PyEval_GetGlobals();
753 if (locals == Py_None)
754 locals = PyEval_GetLocals();
755 }
756 else if (locals == Py_None)
757 locals = globals;
Tim Peters9fa96be2001-08-17 23:04:59 +0000758
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000759 if (globals == NULL || locals == NULL) {
760 PyErr_SetString(PyExc_TypeError,
761 "eval must be given globals and locals "
762 "when called without a frame");
763 return NULL;
764 }
Georg Brandl77c85e62005-09-15 10:46:13 +0000765
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000766 if (PyDict_GetItemString(globals, "__builtins__") == NULL) {
767 if (PyDict_SetItemString(globals, "__builtins__",
768 PyEval_GetBuiltins()) != 0)
769 return NULL;
770 }
Tim Peters9fa96be2001-08-17 23:04:59 +0000771
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000772 if (PyCode_Check(cmd)) {
773 if (PyCode_GetNumFree((PyCodeObject *)cmd) > 0) {
774 PyErr_SetString(PyExc_TypeError,
775 "code object passed to eval() may not contain free variables");
776 return NULL;
777 }
Martin v. Löwis4d0d4712010-12-03 20:14:31 +0000778 return PyEval_EvalCode(cmd, globals, locals);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000779 }
Tim Peters9fa96be2001-08-17 23:04:59 +0000780
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000781 cf.cf_flags = PyCF_SOURCE_IS_UTF8;
782 str = source_as_string(cmd, "eval", "string, bytes or code", &cf);
783 if (str == NULL)
784 return NULL;
Just van Rossum3aaf42c2003-02-10 08:21:10 +0000785
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000786 while (*str == ' ' || *str == '\t')
787 str++;
Tim Peters9fa96be2001-08-17 23:04:59 +0000788
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000789 (void)PyEval_MergeCompilerFlags(&cf);
790 result = PyRun_StringFlags(str, Py_eval_input, globals, locals, &cf);
791 Py_XDECREF(tmp);
792 return result;
Guido van Rossum3f5da241990-12-20 15:06:42 +0000793}
794
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000795PyDoc_STRVAR(eval_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000796"eval(source[, globals[, locals]]) -> value\n\
797\n\
798Evaluate the source in the context of globals and locals.\n\
799The source may be a string representing a Python expression\n\
800or a code object as returned by compile().\n\
Thomas Wouters89f507f2006-12-13 04:49:30 +0000801The globals must be a dictionary and locals can be any mapping,\n\
Raymond Hettinger214b1c32004-07-02 06:41:07 +0000802defaulting to the current globals and locals.\n\
803If only globals is given, locals defaults to it.\n");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000804
Georg Brandl7cae87c2006-09-06 06:51:57 +0000805static PyObject *
806builtin_exec(PyObject *self, PyObject *args)
807{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000808 PyObject *v;
809 PyObject *prog, *globals = Py_None, *locals = Py_None;
Georg Brandl7cae87c2006-09-06 06:51:57 +0000810
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000811 if (!PyArg_UnpackTuple(args, "exec", 1, 3, &prog, &globals, &locals))
812 return NULL;
Georg Brandl2cabc562008-08-28 07:57:16 +0000813
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000814 if (globals == Py_None) {
815 globals = PyEval_GetGlobals();
816 if (locals == Py_None) {
817 locals = PyEval_GetLocals();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000818 }
819 if (!globals || !locals) {
820 PyErr_SetString(PyExc_SystemError,
821 "globals and locals cannot be NULL");
822 return NULL;
823 }
824 }
825 else if (locals == Py_None)
826 locals = globals;
Georg Brandl7cae87c2006-09-06 06:51:57 +0000827
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000828 if (!PyDict_Check(globals)) {
829 PyErr_Format(PyExc_TypeError, "exec() arg 2 must be a dict, not %.100s",
830 globals->ob_type->tp_name);
831 return NULL;
832 }
833 if (!PyMapping_Check(locals)) {
834 PyErr_Format(PyExc_TypeError,
835 "arg 3 must be a mapping or None, not %.100s",
836 locals->ob_type->tp_name);
837 return NULL;
838 }
839 if (PyDict_GetItemString(globals, "__builtins__") == NULL) {
840 if (PyDict_SetItemString(globals, "__builtins__",
841 PyEval_GetBuiltins()) != 0)
842 return NULL;
843 }
844
845 if (PyCode_Check(prog)) {
846 if (PyCode_GetNumFree((PyCodeObject *)prog) > 0) {
847 PyErr_SetString(PyExc_TypeError,
848 "code object passed to exec() may not "
849 "contain free variables");
850 return NULL;
851 }
Martin v. Löwis4d0d4712010-12-03 20:14:31 +0000852 v = PyEval_EvalCode(prog, globals, locals);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000853 }
854 else {
855 char *str;
856 PyCompilerFlags cf;
857 cf.cf_flags = PyCF_SOURCE_IS_UTF8;
858 str = source_as_string(prog, "exec",
859 "string, bytes or code", &cf);
860 if (str == NULL)
861 return NULL;
862 if (PyEval_MergeCompilerFlags(&cf))
863 v = PyRun_StringFlags(str, Py_file_input, globals,
864 locals, &cf);
865 else
866 v = PyRun_String(str, Py_file_input, globals, locals);
867 }
868 if (v == NULL)
869 return NULL;
870 Py_DECREF(v);
871 Py_RETURN_NONE;
Georg Brandl7cae87c2006-09-06 06:51:57 +0000872}
873
874PyDoc_STRVAR(exec_doc,
875"exec(object[, globals[, locals]])\n\
876\n\
Mark Dickinson480e8e32009-12-19 21:19:35 +0000877Read and execute code from an object, which can be a string or a code\n\
Benjamin Peterson38090262009-01-04 15:30:39 +0000878object.\n\
Georg Brandl7cae87c2006-09-06 06:51:57 +0000879The globals and locals are dictionaries, defaulting to the current\n\
880globals and locals. If only globals is given, locals defaults to it.");
881
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000882
Guido van Rossum79f25d91997-04-29 20:08:16 +0000883static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000884builtin_getattr(PyObject *self, PyObject *args)
Guido van Rossum33894be1992-01-27 16:53:09 +0000885{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000886 PyObject *v, *result, *dflt = NULL;
887 PyObject *name;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000888
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000889 if (!PyArg_UnpackTuple(args, "getattr", 2, 3, &v, &name, &dflt))
890 return NULL;
Martin v. Löwis5b222132007-06-10 09:51:05 +0000891
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000892 if (!PyUnicode_Check(name)) {
893 PyErr_SetString(PyExc_TypeError,
894 "getattr(): attribute name must be string");
895 return NULL;
896 }
897 result = PyObject_GetAttr(v, name);
898 if (result == NULL && dflt != NULL &&
899 PyErr_ExceptionMatches(PyExc_AttributeError))
900 {
901 PyErr_Clear();
902 Py_INCREF(dflt);
903 result = dflt;
904 }
905 return result;
Guido van Rossum9bfef441993-03-29 10:43:31 +0000906}
907
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000908PyDoc_STRVAR(getattr_doc,
Guido van Rossum950ff291998-06-29 13:38:57 +0000909"getattr(object, name[, default]) -> value\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000910\n\
Guido van Rossum950ff291998-06-29 13:38:57 +0000911Get a named attribute from an object; getattr(x, 'y') is equivalent to x.y.\n\
912When a default argument is given, it is returned when the attribute doesn't\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000913exist; without it, an exception is raised in that case.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000914
915
Guido van Rossum79f25d91997-04-29 20:08:16 +0000916static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000917builtin_globals(PyObject *self)
Guido van Rossum872537c1995-07-07 22:43:42 +0000918{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000919 PyObject *d;
Guido van Rossum872537c1995-07-07 22:43:42 +0000920
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000921 d = PyEval_GetGlobals();
922 Py_XINCREF(d);
923 return d;
Guido van Rossum872537c1995-07-07 22:43:42 +0000924}
925
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000926PyDoc_STRVAR(globals_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000927"globals() -> dictionary\n\
928\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000929Return the dictionary containing the current scope's global variables.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000930
931
Guido van Rossum79f25d91997-04-29 20:08:16 +0000932static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000933builtin_hasattr(PyObject *self, PyObject *args)
Guido van Rossum9bfef441993-03-29 10:43:31 +0000934{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000935 PyObject *v;
936 PyObject *name;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000937
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000938 if (!PyArg_UnpackTuple(args, "hasattr", 2, 2, &v, &name))
939 return NULL;
940 if (!PyUnicode_Check(name)) {
941 PyErr_SetString(PyExc_TypeError,
942 "hasattr(): attribute name must be string");
943 return NULL;
944 }
945 v = PyObject_GetAttr(v, name);
946 if (v == NULL) {
Benjamin Peterson17689992010-08-24 03:26:23 +0000947 if (PyErr_ExceptionMatches(PyExc_AttributeError)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000948 PyErr_Clear();
Benjamin Peterson17689992010-08-24 03:26:23 +0000949 Py_RETURN_FALSE;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000950 }
Benjamin Peterson17689992010-08-24 03:26:23 +0000951 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000952 }
953 Py_DECREF(v);
Benjamin Peterson17689992010-08-24 03:26:23 +0000954 Py_RETURN_TRUE;
Guido van Rossum33894be1992-01-27 16:53:09 +0000955}
956
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000957PyDoc_STRVAR(hasattr_doc,
Guido van Rossum77f6a652002-04-03 22:41:51 +0000958"hasattr(object, name) -> bool\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000959\n\
960Return whether the object has an attribute with the given name.\n\
Benjamin Peterson17689992010-08-24 03:26:23 +0000961(This is done by calling getattr(object, name) and catching AttributeError.)");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000962
963
Guido van Rossum79f25d91997-04-29 20:08:16 +0000964static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000965builtin_id(PyObject *self, PyObject *v)
Guido van Rossum5b722181993-03-30 17:46:03 +0000966{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000967 return PyLong_FromVoidPtr(v);
Guido van Rossum5b722181993-03-30 17:46:03 +0000968}
969
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000970PyDoc_STRVAR(id_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000971"id(object) -> integer\n\
972\n\
973Return the identity of an object. This is guaranteed to be unique among\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000974simultaneously existing objects. (Hint: it's the object's memory address.)");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000975
976
Raymond Hettingera6c60372008-03-13 01:26:19 +0000977/* map object ************************************************************/
978
979typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000980 PyObject_HEAD
981 PyObject *iters;
982 PyObject *func;
Raymond Hettingera6c60372008-03-13 01:26:19 +0000983} mapobject;
984
Guido van Rossum79f25d91997-04-29 20:08:16 +0000985static PyObject *
Raymond Hettingera6c60372008-03-13 01:26:19 +0000986map_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
Guido van Rossum12d12c51993-10-26 17:58:25 +0000987{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000988 PyObject *it, *iters, *func;
989 mapobject *lz;
990 Py_ssize_t numargs, i;
Raymond Hettingera6c60372008-03-13 01:26:19 +0000991
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000992 if (type == &PyMap_Type && !_PyArg_NoKeywords("map()", kwds))
993 return NULL;
Raymond Hettingera6c60372008-03-13 01:26:19 +0000994
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000995 numargs = PyTuple_Size(args);
996 if (numargs < 2) {
997 PyErr_SetString(PyExc_TypeError,
998 "map() must have at least two arguments.");
999 return NULL;
1000 }
Raymond Hettingera6c60372008-03-13 01:26:19 +00001001
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001002 iters = PyTuple_New(numargs-1);
1003 if (iters == NULL)
1004 return NULL;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001005
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001006 for (i=1 ; i<numargs ; i++) {
1007 /* Get iterator. */
1008 it = PyObject_GetIter(PyTuple_GET_ITEM(args, i));
1009 if (it == NULL) {
1010 Py_DECREF(iters);
1011 return NULL;
1012 }
1013 PyTuple_SET_ITEM(iters, i-1, it);
1014 }
Raymond Hettingera6c60372008-03-13 01:26:19 +00001015
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001016 /* create mapobject structure */
1017 lz = (mapobject *)type->tp_alloc(type, 0);
1018 if (lz == NULL) {
1019 Py_DECREF(iters);
1020 return NULL;
1021 }
1022 lz->iters = iters;
1023 func = PyTuple_GET_ITEM(args, 0);
1024 Py_INCREF(func);
1025 lz->func = func;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001026
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001027 return (PyObject *)lz;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001028}
1029
1030static void
1031map_dealloc(mapobject *lz)
1032{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001033 PyObject_GC_UnTrack(lz);
1034 Py_XDECREF(lz->iters);
1035 Py_XDECREF(lz->func);
1036 Py_TYPE(lz)->tp_free(lz);
Raymond Hettingera6c60372008-03-13 01:26:19 +00001037}
1038
1039static int
1040map_traverse(mapobject *lz, visitproc visit, void *arg)
1041{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001042 Py_VISIT(lz->iters);
1043 Py_VISIT(lz->func);
1044 return 0;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001045}
1046
1047static PyObject *
1048map_next(mapobject *lz)
1049{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001050 PyObject *val;
1051 PyObject *argtuple;
1052 PyObject *result;
1053 Py_ssize_t numargs, i;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001054
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001055 numargs = PyTuple_Size(lz->iters);
1056 argtuple = PyTuple_New(numargs);
1057 if (argtuple == NULL)
1058 return NULL;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001059
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001060 for (i=0 ; i<numargs ; i++) {
1061 val = PyIter_Next(PyTuple_GET_ITEM(lz->iters, i));
1062 if (val == NULL) {
1063 Py_DECREF(argtuple);
1064 return NULL;
1065 }
1066 PyTuple_SET_ITEM(argtuple, i, val);
1067 }
1068 result = PyObject_Call(lz->func, argtuple, NULL);
1069 Py_DECREF(argtuple);
1070 return result;
Guido van Rossum12d12c51993-10-26 17:58:25 +00001071}
1072
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001073static PyObject *
1074map_reduce(mapobject *lz)
1075{
1076 Py_ssize_t numargs = PyTuple_GET_SIZE(lz->iters);
1077 PyObject *args = PyTuple_New(numargs+1);
1078 Py_ssize_t i;
1079 if (args == NULL)
1080 return NULL;
1081 Py_INCREF(lz->func);
1082 PyTuple_SET_ITEM(args, 0, lz->func);
1083 for (i = 0; i<numargs; i++){
1084 PyObject *it = PyTuple_GET_ITEM(lz->iters, i);
1085 Py_INCREF(it);
1086 PyTuple_SET_ITEM(args, i+1, it);
1087 }
1088
1089 return Py_BuildValue("ON", Py_TYPE(lz), args);
1090}
1091
1092static PyMethodDef map_methods[] = {
1093 {"__reduce__", (PyCFunction)map_reduce, METH_NOARGS, reduce_doc},
1094 {NULL, NULL} /* sentinel */
1095};
1096
1097
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001098PyDoc_STRVAR(map_doc,
Raymond Hettingera6c60372008-03-13 01:26:19 +00001099"map(func, *iterables) --> map object\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001100\n\
Raymond Hettingera6c60372008-03-13 01:26:19 +00001101Make an iterator that computes the function using arguments from\n\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001102each of the iterables. Stops when the shortest iterable is exhausted.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001103
Raymond Hettingera6c60372008-03-13 01:26:19 +00001104PyTypeObject PyMap_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001105 PyVarObject_HEAD_INIT(&PyType_Type, 0)
1106 "map", /* tp_name */
1107 sizeof(mapobject), /* tp_basicsize */
1108 0, /* tp_itemsize */
1109 /* methods */
1110 (destructor)map_dealloc, /* tp_dealloc */
1111 0, /* tp_print */
1112 0, /* tp_getattr */
1113 0, /* tp_setattr */
1114 0, /* tp_reserved */
1115 0, /* tp_repr */
1116 0, /* tp_as_number */
1117 0, /* tp_as_sequence */
1118 0, /* tp_as_mapping */
1119 0, /* tp_hash */
1120 0, /* tp_call */
1121 0, /* tp_str */
1122 PyObject_GenericGetAttr, /* tp_getattro */
1123 0, /* tp_setattro */
1124 0, /* tp_as_buffer */
1125 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
1126 Py_TPFLAGS_BASETYPE, /* tp_flags */
1127 map_doc, /* tp_doc */
1128 (traverseproc)map_traverse, /* tp_traverse */
1129 0, /* tp_clear */
1130 0, /* tp_richcompare */
1131 0, /* tp_weaklistoffset */
1132 PyObject_SelfIter, /* tp_iter */
1133 (iternextfunc)map_next, /* tp_iternext */
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001134 map_methods, /* tp_methods */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001135 0, /* tp_members */
1136 0, /* tp_getset */
1137 0, /* tp_base */
1138 0, /* tp_dict */
1139 0, /* tp_descr_get */
1140 0, /* tp_descr_set */
1141 0, /* tp_dictoffset */
1142 0, /* tp_init */
1143 PyType_GenericAlloc, /* tp_alloc */
1144 map_new, /* tp_new */
1145 PyObject_GC_Del, /* tp_free */
Raymond Hettingera6c60372008-03-13 01:26:19 +00001146};
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001147
Guido van Rossum79f25d91997-04-29 20:08:16 +00001148static PyObject *
Georg Brandla18af4e2007-04-21 15:47:16 +00001149builtin_next(PyObject *self, PyObject *args)
1150{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001151 PyObject *it, *res;
1152 PyObject *def = NULL;
Georg Brandla18af4e2007-04-21 15:47:16 +00001153
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001154 if (!PyArg_UnpackTuple(args, "next", 1, 2, &it, &def))
1155 return NULL;
1156 if (!PyIter_Check(it)) {
1157 PyErr_Format(PyExc_TypeError,
Philip Jenvey50add042011-11-06 16:37:52 -08001158 "'%.200s' object is not an iterator",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001159 it->ob_type->tp_name);
1160 return NULL;
1161 }
1162
1163 res = (*it->ob_type->tp_iternext)(it);
1164 if (res != NULL) {
1165 return res;
1166 } else if (def != NULL) {
1167 if (PyErr_Occurred()) {
1168 if(!PyErr_ExceptionMatches(PyExc_StopIteration))
1169 return NULL;
1170 PyErr_Clear();
1171 }
1172 Py_INCREF(def);
1173 return def;
1174 } else if (PyErr_Occurred()) {
1175 return NULL;
1176 } else {
1177 PyErr_SetNone(PyExc_StopIteration);
1178 return NULL;
1179 }
Georg Brandla18af4e2007-04-21 15:47:16 +00001180}
1181
1182PyDoc_STRVAR(next_doc,
1183"next(iterator[, default])\n\
1184\n\
1185Return the next item from the iterator. If default is given and the iterator\n\
1186is exhausted, it is returned instead of raising StopIteration.");
1187
1188
1189static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001190builtin_setattr(PyObject *self, PyObject *args)
Guido van Rossum33894be1992-01-27 16:53:09 +00001191{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001192 PyObject *v;
1193 PyObject *name;
1194 PyObject *value;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001195
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001196 if (!PyArg_UnpackTuple(args, "setattr", 3, 3, &v, &name, &value))
1197 return NULL;
1198 if (PyObject_SetAttr(v, name, value) != 0)
1199 return NULL;
1200 Py_INCREF(Py_None);
1201 return Py_None;
Guido van Rossum33894be1992-01-27 16:53:09 +00001202}
1203
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001204PyDoc_STRVAR(setattr_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001205"setattr(object, name, value)\n\
1206\n\
1207Set a named attribute on an object; setattr(x, 'y', v) is equivalent to\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001208``x.y = v''.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001209
1210
Guido van Rossum79f25d91997-04-29 20:08:16 +00001211static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001212builtin_delattr(PyObject *self, PyObject *args)
Guido van Rossum14144fc1994-08-29 12:53:40 +00001213{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001214 PyObject *v;
1215 PyObject *name;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001216
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001217 if (!PyArg_UnpackTuple(args, "delattr", 2, 2, &v, &name))
1218 return NULL;
1219 if (PyObject_SetAttr(v, name, (PyObject *)NULL) != 0)
1220 return NULL;
1221 Py_INCREF(Py_None);
1222 return Py_None;
Guido van Rossum14144fc1994-08-29 12:53:40 +00001223}
1224
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001225PyDoc_STRVAR(delattr_doc,
Guido van Rossumdf12a591998-11-23 22:13:04 +00001226"delattr(object, name)\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001227\n\
1228Delete a named attribute on an object; delattr(x, 'y') is equivalent to\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001229``del x.y''.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001230
1231
Guido van Rossum79f25d91997-04-29 20:08:16 +00001232static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001233builtin_hash(PyObject *self, PyObject *v)
Guido van Rossum9bfef441993-03-29 10:43:31 +00001234{
Benjamin Peterson8f67d082010-10-17 20:54:53 +00001235 Py_hash_t x;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001236
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001237 x = PyObject_Hash(v);
1238 if (x == -1)
1239 return NULL;
Benjamin Peterson8f67d082010-10-17 20:54:53 +00001240 return PyLong_FromSsize_t(x);
Guido van Rossum9bfef441993-03-29 10:43:31 +00001241}
1242
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001243PyDoc_STRVAR(hash_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001244"hash(object) -> integer\n\
1245\n\
1246Return a hash value for the object. Two objects with the same value have\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001247the same hash value. The reverse is not necessarily true, but likely.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001248
1249
Guido van Rossum79f25d91997-04-29 20:08:16 +00001250static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001251builtin_hex(PyObject *self, PyObject *v)
Guido van Rossum006bcd41991-10-24 14:54:44 +00001252{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001253 return PyNumber_ToBase(v, 16);
Guido van Rossum006bcd41991-10-24 14:54:44 +00001254}
1255
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001256PyDoc_STRVAR(hex_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001257"hex(number) -> string\n\
1258\n\
Alexander Belopolsky12338ab2011-04-07 00:15:33 -04001259Return the hexadecimal representation of an integer.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001260
1261
Guido van Rossum79f25d91997-04-29 20:08:16 +00001262static PyObject *
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001263builtin_iter(PyObject *self, PyObject *args)
1264{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001265 PyObject *v, *w = NULL;
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001266
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001267 if (!PyArg_UnpackTuple(args, "iter", 1, 2, &v, &w))
1268 return NULL;
1269 if (w == NULL)
1270 return PyObject_GetIter(v);
1271 if (!PyCallable_Check(v)) {
1272 PyErr_SetString(PyExc_TypeError,
1273 "iter(v, w): v must be callable");
1274 return NULL;
1275 }
1276 return PyCallIter_New(v, w);
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001277}
1278
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001279PyDoc_STRVAR(iter_doc,
Georg Brandld11ae5d2008-05-16 13:27:32 +00001280"iter(iterable) -> iterator\n\
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001281iter(callable, sentinel) -> iterator\n\
1282\n\
1283Get an iterator from an object. In the first form, the argument must\n\
1284supply its own iterator, or be a sequence.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001285In the second form, the callable is called until it returns the sentinel.");
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001286
1287
1288static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001289builtin_len(PyObject *self, PyObject *v)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001290{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001291 Py_ssize_t res;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001292
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001293 res = PyObject_Size(v);
1294 if (res < 0 && PyErr_Occurred())
1295 return NULL;
1296 return PyLong_FromSsize_t(res);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001297}
1298
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001299PyDoc_STRVAR(len_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001300"len(object) -> integer\n\
1301\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001302Return the number of items of a sequence or mapping.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001303
1304
Guido van Rossum79f25d91997-04-29 20:08:16 +00001305static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001306builtin_locals(PyObject *self)
Guido van Rossum872537c1995-07-07 22:43:42 +00001307{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001308 PyObject *d;
Guido van Rossum872537c1995-07-07 22:43:42 +00001309
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001310 d = PyEval_GetLocals();
1311 Py_XINCREF(d);
1312 return d;
Guido van Rossum872537c1995-07-07 22:43:42 +00001313}
1314
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001315PyDoc_STRVAR(locals_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001316"locals() -> dictionary\n\
1317\n\
Raymond Hettinger69bf8f32003-01-04 02:16:22 +00001318Update and return a dictionary containing the current scope's local variables.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001319
1320
Guido van Rossum79f25d91997-04-29 20:08:16 +00001321static PyObject *
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001322min_max(PyObject *args, PyObject *kwds, int op)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001323{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001324 PyObject *v, *it, *item, *val, *maxitem, *maxval, *keyfunc=NULL;
1325 const char *name = op == Py_LT ? "min" : "max";
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001326
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001327 if (PyTuple_Size(args) > 1)
1328 v = args;
1329 else if (!PyArg_UnpackTuple(args, (char *)name, 1, 1, &v))
1330 return NULL;
Tim Peters67d687a2002-04-29 21:27:32 +00001331
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001332 if (kwds != NULL && PyDict_Check(kwds) && PyDict_Size(kwds)) {
1333 keyfunc = PyDict_GetItemString(kwds, "key");
1334 if (PyDict_Size(kwds)!=1 || keyfunc == NULL) {
1335 PyErr_Format(PyExc_TypeError,
1336 "%s() got an unexpected keyword argument", name);
1337 return NULL;
1338 }
1339 Py_INCREF(keyfunc);
1340 }
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001341
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001342 it = PyObject_GetIter(v);
1343 if (it == NULL) {
1344 Py_XDECREF(keyfunc);
1345 return NULL;
1346 }
Tim Petersc3074532001-05-03 07:00:32 +00001347
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001348 maxitem = NULL; /* the result */
1349 maxval = NULL; /* the value associated with the result */
1350 while (( item = PyIter_Next(it) )) {
1351 /* get the value from the key function */
1352 if (keyfunc != NULL) {
1353 val = PyObject_CallFunctionObjArgs(keyfunc, item, NULL);
1354 if (val == NULL)
1355 goto Fail_it_item;
1356 }
1357 /* no key function; the value is the item */
1358 else {
1359 val = item;
1360 Py_INCREF(val);
1361 }
Tim Petersc3074532001-05-03 07:00:32 +00001362
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001363 /* maximum value and item are unset; set them */
1364 if (maxval == NULL) {
1365 maxitem = item;
1366 maxval = val;
1367 }
1368 /* maximum value and item are set; update them as necessary */
1369 else {
1370 int cmp = PyObject_RichCompareBool(val, maxval, op);
1371 if (cmp < 0)
1372 goto Fail_it_item_and_val;
1373 else if (cmp > 0) {
1374 Py_DECREF(maxval);
1375 Py_DECREF(maxitem);
1376 maxval = val;
1377 maxitem = item;
1378 }
1379 else {
1380 Py_DECREF(item);
1381 Py_DECREF(val);
1382 }
1383 }
1384 }
1385 if (PyErr_Occurred())
1386 goto Fail_it;
1387 if (maxval == NULL) {
1388 PyErr_Format(PyExc_ValueError,
1389 "%s() arg is an empty sequence", name);
1390 assert(maxitem == NULL);
1391 }
1392 else
1393 Py_DECREF(maxval);
1394 Py_DECREF(it);
1395 Py_XDECREF(keyfunc);
1396 return maxitem;
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001397
1398Fail_it_item_and_val:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001399 Py_DECREF(val);
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001400Fail_it_item:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001401 Py_DECREF(item);
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001402Fail_it:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001403 Py_XDECREF(maxval);
1404 Py_XDECREF(maxitem);
1405 Py_DECREF(it);
1406 Py_XDECREF(keyfunc);
1407 return NULL;
Guido van Rossum3f5da241990-12-20 15:06:42 +00001408}
1409
Guido van Rossum79f25d91997-04-29 20:08:16 +00001410static PyObject *
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001411builtin_min(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001412{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001413 return min_max(args, kwds, Py_LT);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001414}
1415
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001416PyDoc_STRVAR(min_doc,
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001417"min(iterable[, key=func]) -> value\n\
1418min(a, b, c, ...[, key=func]) -> value\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001419\n\
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001420With a single iterable argument, return its smallest item.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001421With two or more arguments, return the smallest argument.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001422
1423
Guido van Rossum79f25d91997-04-29 20:08:16 +00001424static PyObject *
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001425builtin_max(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001426{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001427 return min_max(args, kwds, Py_GT);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001428}
1429
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001430PyDoc_STRVAR(max_doc,
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001431"max(iterable[, key=func]) -> value\n\
1432max(a, b, c, ...[, key=func]) -> value\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001433\n\
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001434With a single iterable argument, return its largest item.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001435With two or more arguments, return the largest argument.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001436
1437
Guido van Rossum79f25d91997-04-29 20:08:16 +00001438static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001439builtin_oct(PyObject *self, PyObject *v)
Guido van Rossum006bcd41991-10-24 14:54:44 +00001440{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001441 return PyNumber_ToBase(v, 8);
Guido van Rossum006bcd41991-10-24 14:54:44 +00001442}
1443
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001444PyDoc_STRVAR(oct_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001445"oct(number) -> string\n\
1446\n\
Alexander Belopolsky12338ab2011-04-07 00:15:33 -04001447Return the octal representation of an integer.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001448
1449
Guido van Rossum79f25d91997-04-29 20:08:16 +00001450static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001451builtin_ord(PyObject *self, PyObject* obj)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001452{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001453 long ord;
1454 Py_ssize_t size;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001455
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001456 if (PyBytes_Check(obj)) {
1457 size = PyBytes_GET_SIZE(obj);
1458 if (size == 1) {
1459 ord = (long)((unsigned char)*PyBytes_AS_STRING(obj));
1460 return PyLong_FromLong(ord);
1461 }
1462 }
1463 else if (PyUnicode_Check(obj)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001464 if (PyUnicode_READY(obj) == -1)
1465 return NULL;
1466 size = PyUnicode_GET_LENGTH(obj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001467 if (size == 1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001468 ord = (long)PyUnicode_READ_CHAR(obj, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001469 return PyLong_FromLong(ord);
1470 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001471 }
1472 else if (PyByteArray_Check(obj)) {
1473 /* XXX Hopefully this is temporary */
1474 size = PyByteArray_GET_SIZE(obj);
1475 if (size == 1) {
1476 ord = (long)((unsigned char)*PyByteArray_AS_STRING(obj));
1477 return PyLong_FromLong(ord);
1478 }
1479 }
1480 else {
1481 PyErr_Format(PyExc_TypeError,
1482 "ord() expected string of length 1, but " \
1483 "%.200s found", obj->ob_type->tp_name);
1484 return NULL;
1485 }
Guido van Rossum09095f32000-03-10 23:00:52 +00001486
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001487 PyErr_Format(PyExc_TypeError,
1488 "ord() expected a character, "
1489 "but string of length %zd found",
1490 size);
1491 return NULL;
Guido van Rossum3f5da241990-12-20 15:06:42 +00001492}
1493
Guido van Rossum307fa8c2007-07-16 20:46:27 +00001494PyDoc_VAR(ord_doc) = PyDoc_STR(
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001495"ord(c) -> integer\n\
1496\n\
Guido van Rossum8ac004e2007-07-15 13:00:05 +00001497Return the integer ordinal of a one-character string."
Antoine Pitrouedc60182012-06-23 14:19:58 +02001498);
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001499
1500
Guido van Rossum79f25d91997-04-29 20:08:16 +00001501static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001502builtin_pow(PyObject *self, PyObject *args)
Guido van Rossum6a00cd81995-01-07 12:39:01 +00001503{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001504 PyObject *v, *w, *z = Py_None;
Guido van Rossum6a00cd81995-01-07 12:39:01 +00001505
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001506 if (!PyArg_UnpackTuple(args, "pow", 2, 3, &v, &w, &z))
1507 return NULL;
1508 return PyNumber_Power(v, w, z);
Guido van Rossumd4905451991-05-05 20:00:36 +00001509}
1510
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001511PyDoc_STRVAR(pow_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001512"pow(x, y[, z]) -> number\n\
1513\n\
1514With two arguments, equivalent to x**y. With three arguments,\n\
Serhiy Storchaka95949422013-08-27 19:40:23 +03001515equivalent to (x**y) % z, but may be more efficient (e.g. for ints).");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001516
1517
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001518
Guido van Rossum34343512006-11-30 22:13:52 +00001519static PyObject *
1520builtin_print(PyObject *self, PyObject *args, PyObject *kwds)
1521{
Georg Brandlbc3b6822012-01-13 19:41:25 +01001522 static char *kwlist[] = {"sep", "end", "file", "flush", 0};
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001523 static PyObject *dummy_args;
Georg Brandlbc3b6822012-01-13 19:41:25 +01001524 PyObject *sep = NULL, *end = NULL, *file = NULL, *flush = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001525 int i, err;
Guido van Rossum34343512006-11-30 22:13:52 +00001526
Benjamin Peterson00102562012-01-11 21:00:16 -05001527 if (dummy_args == NULL && !(dummy_args = PyTuple_New(0)))
Georg Brandlbc3b6822012-01-13 19:41:25 +01001528 return NULL;
1529 if (!PyArg_ParseTupleAndKeywords(dummy_args, kwds, "|OOOO:print",
1530 kwlist, &sep, &end, &file, &flush))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001531 return NULL;
1532 if (file == NULL || file == Py_None) {
1533 file = PySys_GetObject("stdout");
1534 /* sys.stdout may be None when FILE* stdout isn't connected */
1535 if (file == Py_None)
1536 Py_RETURN_NONE;
1537 }
Guido van Rossum34343512006-11-30 22:13:52 +00001538
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001539 if (sep == Py_None) {
1540 sep = NULL;
1541 }
1542 else if (sep && !PyUnicode_Check(sep)) {
1543 PyErr_Format(PyExc_TypeError,
1544 "sep must be None or a string, not %.200s",
1545 sep->ob_type->tp_name);
1546 return NULL;
1547 }
1548 if (end == Py_None) {
1549 end = NULL;
1550 }
1551 else if (end && !PyUnicode_Check(end)) {
1552 PyErr_Format(PyExc_TypeError,
1553 "end must be None or a string, not %.200s",
1554 end->ob_type->tp_name);
1555 return NULL;
1556 }
Guido van Rossum34343512006-11-30 22:13:52 +00001557
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001558 for (i = 0; i < PyTuple_Size(args); i++) {
1559 if (i > 0) {
1560 if (sep == NULL)
1561 err = PyFile_WriteString(" ", file);
1562 else
1563 err = PyFile_WriteObject(sep, file,
1564 Py_PRINT_RAW);
1565 if (err)
1566 return NULL;
1567 }
1568 err = PyFile_WriteObject(PyTuple_GetItem(args, i), file,
1569 Py_PRINT_RAW);
1570 if (err)
1571 return NULL;
1572 }
Guido van Rossum34343512006-11-30 22:13:52 +00001573
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001574 if (end == NULL)
1575 err = PyFile_WriteString("\n", file);
1576 else
1577 err = PyFile_WriteObject(end, file, Py_PRINT_RAW);
1578 if (err)
1579 return NULL;
Guido van Rossum34343512006-11-30 22:13:52 +00001580
Georg Brandlbc3b6822012-01-13 19:41:25 +01001581 if (flush != NULL) {
1582 PyObject *tmp;
1583 int do_flush = PyObject_IsTrue(flush);
1584 if (do_flush == -1)
1585 return NULL;
1586 else if (do_flush) {
1587 tmp = PyObject_CallMethod(file, "flush", "");
1588 if (tmp == NULL)
1589 return NULL;
1590 else
1591 Py_DECREF(tmp);
1592 }
1593 }
1594
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001595 Py_RETURN_NONE;
Guido van Rossum34343512006-11-30 22:13:52 +00001596}
1597
1598PyDoc_STRVAR(print_doc,
Senthil Kumarane9175bd2012-08-10 13:53:45 -07001599"print(value, ..., sep=' ', end='\\n', file=sys.stdout, flush=False)\n\
Guido van Rossum34343512006-11-30 22:13:52 +00001600\n\
1601Prints the values to a stream, or to sys.stdout by default.\n\
1602Optional keyword arguments:\n\
Senthil Kumarane9175bd2012-08-10 13:53:45 -07001603file: a file-like object (stream); defaults to the current sys.stdout.\n\
1604sep: string inserted between values, default a space.\n\
1605end: string appended after the last value, default a newline.\n\
1606flush: whether to forcibly flush the stream.");
Guido van Rossum34343512006-11-30 22:13:52 +00001607
1608
Guido van Rossuma88a0332007-02-26 16:59:55 +00001609static PyObject *
1610builtin_input(PyObject *self, PyObject *args)
1611{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001612 PyObject *promptarg = NULL;
1613 PyObject *fin = PySys_GetObject("stdin");
1614 PyObject *fout = PySys_GetObject("stdout");
1615 PyObject *ferr = PySys_GetObject("stderr");
1616 PyObject *tmp;
1617 long fd;
1618 int tty;
Guido van Rossuma88a0332007-02-26 16:59:55 +00001619
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001620 /* Parse arguments */
1621 if (!PyArg_UnpackTuple(args, "input", 0, 1, &promptarg))
1622 return NULL;
Guido van Rossuma88a0332007-02-26 16:59:55 +00001623
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001624 /* Check that stdin/out/err are intact */
1625 if (fin == NULL || fin == Py_None) {
1626 PyErr_SetString(PyExc_RuntimeError,
1627 "input(): lost sys.stdin");
1628 return NULL;
1629 }
1630 if (fout == NULL || fout == Py_None) {
1631 PyErr_SetString(PyExc_RuntimeError,
1632 "input(): lost sys.stdout");
1633 return NULL;
1634 }
1635 if (ferr == NULL || ferr == Py_None) {
1636 PyErr_SetString(PyExc_RuntimeError,
1637 "input(): lost sys.stderr");
1638 return NULL;
1639 }
Guido van Rossumeba76962007-05-27 09:13:28 +00001640
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001641 /* First of all, flush stderr */
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001642 tmp = _PyObject_CallMethodId(ferr, &PyId_flush, "");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001643 if (tmp == NULL)
1644 PyErr_Clear();
1645 else
1646 Py_DECREF(tmp);
Guido van Rossumeba76962007-05-27 09:13:28 +00001647
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001648 /* We should only use (GNU) readline if Python's sys.stdin and
1649 sys.stdout are the same as C's stdin and stdout, because we
1650 need to pass it those. */
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001651 tmp = _PyObject_CallMethodId(fin, &PyId_fileno, "");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001652 if (tmp == NULL) {
1653 PyErr_Clear();
1654 tty = 0;
1655 }
1656 else {
1657 fd = PyLong_AsLong(tmp);
1658 Py_DECREF(tmp);
1659 if (fd < 0 && PyErr_Occurred())
1660 return NULL;
1661 tty = fd == fileno(stdin) && isatty(fd);
1662 }
1663 if (tty) {
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001664 tmp = _PyObject_CallMethodId(fout, &PyId_fileno, "");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001665 if (tmp == NULL)
1666 PyErr_Clear();
1667 else {
1668 fd = PyLong_AsLong(tmp);
1669 Py_DECREF(tmp);
1670 if (fd < 0 && PyErr_Occurred())
1671 return NULL;
1672 tty = fd == fileno(stdout) && isatty(fd);
1673 }
1674 }
Guido van Rossumeba76962007-05-27 09:13:28 +00001675
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001676 /* If we're interactive, use (GNU) readline */
1677 if (tty) {
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001678 PyObject *po = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001679 char *prompt;
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001680 char *s = NULL;
1681 PyObject *stdin_encoding = NULL, *stdin_errors = NULL;
1682 PyObject *stdout_encoding = NULL, *stdout_errors = NULL;
1683 char *stdin_encoding_str, *stdin_errors_str;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001684 PyObject *result;
Victor Stinnerc0f1a1a2011-02-23 12:07:37 +00001685 size_t len;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02001686 _Py_IDENTIFIER(encoding);
Antoine Pitrou5ee9d8a2011-11-06 00:38:45 +01001687 _Py_IDENTIFIER(errors);
Martin v. Löwis4a7b5d52007-09-04 05:24:49 +00001688
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02001689 stdin_encoding = _PyObject_GetAttrId(fin, &PyId_encoding);
Antoine Pitrou5ee9d8a2011-11-06 00:38:45 +01001690 stdin_errors = _PyObject_GetAttrId(fin, &PyId_errors);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001691 if (!stdin_encoding || !stdin_errors)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001692 /* stdin is a text stream, so it must have an
1693 encoding. */
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001694 goto _readline_errors;
Victor Stinner306f0102010-05-19 01:06:22 +00001695 stdin_encoding_str = _PyUnicode_AsString(stdin_encoding);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001696 stdin_errors_str = _PyUnicode_AsString(stdin_errors);
1697 if (!stdin_encoding_str || !stdin_errors_str)
1698 goto _readline_errors;
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001699 tmp = _PyObject_CallMethodId(fout, &PyId_flush, "");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001700 if (tmp == NULL)
1701 PyErr_Clear();
1702 else
1703 Py_DECREF(tmp);
1704 if (promptarg != NULL) {
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001705 /* We have a prompt, encode it as stdout would */
1706 char *stdout_encoding_str, *stdout_errors_str;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001707 PyObject *stringpo;
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02001708 stdout_encoding = _PyObject_GetAttrId(fout, &PyId_encoding);
Antoine Pitrou5ee9d8a2011-11-06 00:38:45 +01001709 stdout_errors = _PyObject_GetAttrId(fout, &PyId_errors);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001710 if (!stdout_encoding || !stdout_errors)
1711 goto _readline_errors;
Victor Stinner306f0102010-05-19 01:06:22 +00001712 stdout_encoding_str = _PyUnicode_AsString(stdout_encoding);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001713 stdout_errors_str = _PyUnicode_AsString(stdout_errors);
1714 if (!stdout_encoding_str || !stdout_errors_str)
1715 goto _readline_errors;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001716 stringpo = PyObject_Str(promptarg);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001717 if (stringpo == NULL)
1718 goto _readline_errors;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001719 po = PyUnicode_AsEncodedString(stringpo,
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001720 stdout_encoding_str, stdout_errors_str);
1721 Py_CLEAR(stdout_encoding);
1722 Py_CLEAR(stdout_errors);
1723 Py_CLEAR(stringpo);
1724 if (po == NULL)
1725 goto _readline_errors;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001726 prompt = PyBytes_AsString(po);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001727 if (prompt == NULL)
1728 goto _readline_errors;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001729 }
1730 else {
1731 po = NULL;
1732 prompt = "";
1733 }
1734 s = PyOS_Readline(stdin, stdout, prompt);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001735 if (s == NULL) {
Richard Oudkerk614c5782013-04-03 13:44:50 +01001736 PyErr_CheckSignals();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001737 if (!PyErr_Occurred())
1738 PyErr_SetNone(PyExc_KeyboardInterrupt);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001739 goto _readline_errors;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001740 }
Victor Stinnerc0f1a1a2011-02-23 12:07:37 +00001741
1742 len = strlen(s);
1743 if (len == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001744 PyErr_SetNone(PyExc_EOFError);
1745 result = NULL;
1746 }
Victor Stinnerc0f1a1a2011-02-23 12:07:37 +00001747 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001748 if (len > PY_SSIZE_T_MAX) {
1749 PyErr_SetString(PyExc_OverflowError,
1750 "input: input too long");
1751 result = NULL;
1752 }
1753 else {
Victor Stinnerc0f1a1a2011-02-23 12:07:37 +00001754 len--; /* strip trailing '\n' */
1755 if (len != 0 && s[len-1] == '\r')
1756 len--; /* strip trailing '\r' */
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001757 result = PyUnicode_Decode(s, len, stdin_encoding_str,
1758 stdin_errors_str);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001759 }
1760 }
1761 Py_DECREF(stdin_encoding);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001762 Py_DECREF(stdin_errors);
1763 Py_XDECREF(po);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001764 PyMem_FREE(s);
1765 return result;
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001766 _readline_errors:
1767 Py_XDECREF(stdin_encoding);
1768 Py_XDECREF(stdout_encoding);
1769 Py_XDECREF(stdin_errors);
1770 Py_XDECREF(stdout_errors);
1771 Py_XDECREF(po);
1772 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001773 }
Guido van Rossumeba76962007-05-27 09:13:28 +00001774
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001775 /* Fallback if we're not interactive */
1776 if (promptarg != NULL) {
1777 if (PyFile_WriteObject(promptarg, fout, Py_PRINT_RAW) != 0)
1778 return NULL;
1779 }
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001780 tmp = _PyObject_CallMethodId(fout, &PyId_flush, "");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001781 if (tmp == NULL)
1782 PyErr_Clear();
1783 else
1784 Py_DECREF(tmp);
1785 return PyFile_GetLine(fin, -1);
Guido van Rossuma88a0332007-02-26 16:59:55 +00001786}
1787
1788PyDoc_STRVAR(input_doc,
1789"input([prompt]) -> string\n\
1790\n\
1791Read a string from standard input. The trailing newline is stripped.\n\
1792If the user hits EOF (Unix: Ctl-D, Windows: Ctl-Z+Return), raise EOFError.\n\
1793On Unix, GNU readline is used if enabled. The prompt string, if given,\n\
1794is printed without a trailing newline before reading.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001795
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001796
Guido van Rossum79f25d91997-04-29 20:08:16 +00001797static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001798builtin_repr(PyObject *self, PyObject *v)
Guido van Rossumc89705d1992-11-26 08:54:07 +00001799{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001800 return PyObject_Repr(v);
Guido van Rossumc89705d1992-11-26 08:54:07 +00001801}
1802
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001803PyDoc_STRVAR(repr_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001804"repr(object) -> string\n\
1805\n\
1806Return the canonical string representation of the object.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001807For most object types, eval(repr(object)) == object.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001808
1809
Guido van Rossum79f25d91997-04-29 20:08:16 +00001810static PyObject *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001811builtin_round(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum9e51f9b1993-02-12 16:29:05 +00001812{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001813 static PyObject *round_str = NULL;
1814 PyObject *ndigits = NULL;
1815 static char *kwlist[] = {"number", "ndigits", 0};
1816 PyObject *number, *round;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001817
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001818 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|O:round",
1819 kwlist, &number, &ndigits))
1820 return NULL;
Alex Martelliae211f92007-08-22 23:21:33 +00001821
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001822 if (Py_TYPE(number)->tp_dict == NULL) {
1823 if (PyType_Ready(Py_TYPE(number)) < 0)
1824 return NULL;
1825 }
Guido van Rossum15d3d042007-08-24 02:02:45 +00001826
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001827 if (round_str == NULL) {
1828 round_str = PyUnicode_InternFromString("__round__");
1829 if (round_str == NULL)
1830 return NULL;
1831 }
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001832
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001833 round = _PyType_Lookup(Py_TYPE(number), round_str);
1834 if (round == NULL) {
1835 PyErr_Format(PyExc_TypeError,
1836 "type %.100s doesn't define __round__ method",
1837 Py_TYPE(number)->tp_name);
1838 return NULL;
1839 }
Alex Martelliae211f92007-08-22 23:21:33 +00001840
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001841 if (ndigits == NULL)
1842 return PyObject_CallFunction(round, "O", number);
1843 else
1844 return PyObject_CallFunction(round, "OO", number, ndigits);
Guido van Rossum9e51f9b1993-02-12 16:29:05 +00001845}
1846
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001847PyDoc_STRVAR(round_doc,
Mark Dickinson1124e712009-01-28 21:25:58 +00001848"round(number[, ndigits]) -> number\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001849\n\
1850Round a number to a given precision in decimal digits (default 0 digits).\n\
Mark Dickinson0d748c22008-07-05 11:29:03 +00001851This returns an int when called with one argument, otherwise the\n\
Georg Brandl809ddaa2008-07-01 20:39:59 +00001852same type as the number. ndigits may be negative.");
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001853
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001854
Raymond Hettinger64958a12003-12-17 20:43:33 +00001855static PyObject *
1856builtin_sorted(PyObject *self, PyObject *args, PyObject *kwds)
1857{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001858 PyObject *newlist, *v, *seq, *keyfunc=NULL, *newargs;
1859 PyObject *callable;
1860 static char *kwlist[] = {"iterable", "key", "reverse", 0};
1861 int reverse;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02001862 _Py_IDENTIFIER(sort);
Raymond Hettinger64958a12003-12-17 20:43:33 +00001863
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001864 /* args 1-3 should match listsort in Objects/listobject.c */
1865 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|Oi:sorted",
1866 kwlist, &seq, &keyfunc, &reverse))
1867 return NULL;
Raymond Hettinger64958a12003-12-17 20:43:33 +00001868
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001869 newlist = PySequence_List(seq);
1870 if (newlist == NULL)
1871 return NULL;
Raymond Hettinger64958a12003-12-17 20:43:33 +00001872
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02001873 callable = _PyObject_GetAttrId(newlist, &PyId_sort);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001874 if (callable == NULL) {
1875 Py_DECREF(newlist);
1876 return NULL;
1877 }
Georg Brandl99d7e4e2005-08-31 22:21:15 +00001878
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001879 newargs = PyTuple_GetSlice(args, 1, 4);
1880 if (newargs == NULL) {
1881 Py_DECREF(newlist);
1882 Py_DECREF(callable);
1883 return NULL;
1884 }
Raymond Hettinger64958a12003-12-17 20:43:33 +00001885
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001886 v = PyObject_Call(callable, newargs, kwds);
1887 Py_DECREF(newargs);
1888 Py_DECREF(callable);
1889 if (v == NULL) {
1890 Py_DECREF(newlist);
1891 return NULL;
1892 }
1893 Py_DECREF(v);
1894 return newlist;
Raymond Hettinger64958a12003-12-17 20:43:33 +00001895}
1896
1897PyDoc_STRVAR(sorted_doc,
Raymond Hettinger70b64fc2008-01-30 20:15:17 +00001898"sorted(iterable, key=None, reverse=False) --> new sorted list");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001899
Guido van Rossum79f25d91997-04-29 20:08:16 +00001900static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001901builtin_vars(PyObject *self, PyObject *args)
Guido van Rossum2d951851994-08-29 12:52:16 +00001902{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001903 PyObject *v = NULL;
1904 PyObject *d;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001905
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001906 if (!PyArg_UnpackTuple(args, "vars", 0, 1, &v))
1907 return NULL;
1908 if (v == NULL) {
1909 d = PyEval_GetLocals();
1910 if (d == NULL) {
1911 if (!PyErr_Occurred())
1912 PyErr_SetString(PyExc_SystemError,
1913 "vars(): no locals!?");
1914 }
1915 else
1916 Py_INCREF(d);
1917 }
1918 else {
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02001919 _Py_IDENTIFIER(__dict__);
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02001920 d = _PyObject_GetAttrId(v, &PyId___dict__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001921 if (d == NULL) {
1922 PyErr_SetString(PyExc_TypeError,
1923 "vars() argument must have __dict__ attribute");
1924 return NULL;
1925 }
1926 }
1927 return d;
Guido van Rossum2d951851994-08-29 12:52:16 +00001928}
1929
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001930PyDoc_STRVAR(vars_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001931"vars([object]) -> dictionary\n\
1932\n\
1933Without arguments, equivalent to locals().\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001934With an argument, equivalent to object.__dict__.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001935
Alex Martellia70b1912003-04-22 08:12:33 +00001936static PyObject*
1937builtin_sum(PyObject *self, PyObject *args)
1938{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001939 PyObject *seq;
1940 PyObject *result = NULL;
1941 PyObject *temp, *item, *iter;
Alex Martellia70b1912003-04-22 08:12:33 +00001942
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001943 if (!PyArg_UnpackTuple(args, "sum", 1, 2, &seq, &result))
1944 return NULL;
Alex Martellia70b1912003-04-22 08:12:33 +00001945
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001946 iter = PyObject_GetIter(seq);
1947 if (iter == NULL)
1948 return NULL;
Alex Martellia70b1912003-04-22 08:12:33 +00001949
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001950 if (result == NULL) {
1951 result = PyLong_FromLong(0);
1952 if (result == NULL) {
1953 Py_DECREF(iter);
1954 return NULL;
1955 }
1956 } else {
1957 /* reject string values for 'start' parameter */
1958 if (PyUnicode_Check(result)) {
1959 PyErr_SetString(PyExc_TypeError,
1960 "sum() can't sum strings [use ''.join(seq) instead]");
1961 Py_DECREF(iter);
1962 return NULL;
1963 }
Benjamin Petersonce071ca2011-07-29 14:23:47 -05001964 if (PyBytes_Check(result)) {
1965 PyErr_SetString(PyExc_TypeError,
1966 "sum() can't sum bytes [use b''.join(seq) instead]");
Benjamin Peterson405f32c2011-07-29 22:43:45 -05001967 Py_DECREF(iter);
Benjamin Petersonce071ca2011-07-29 14:23:47 -05001968 return NULL;
1969 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001970 if (PyByteArray_Check(result)) {
1971 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson4f921c22011-07-29 14:24:29 -05001972 "sum() can't sum bytearray [use b''.join(seq) instead]");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001973 Py_DECREF(iter);
1974 return NULL;
1975 }
Guido van Rossum3172c5d2007-10-16 18:12:55 +00001976
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001977 Py_INCREF(result);
1978 }
Alex Martellia70b1912003-04-22 08:12:33 +00001979
Guido van Rossum8ce8a782007-11-01 19:42:39 +00001980#ifndef SLOW_SUM
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001981 /* Fast addition by keeping temporary sums in C instead of new Python objects.
1982 Assumes all inputs are the same type. If the assumption fails, default
1983 to the more general routine.
1984 */
1985 if (PyLong_CheckExact(result)) {
1986 int overflow;
1987 long i_result = PyLong_AsLongAndOverflow(result, &overflow);
1988 /* If this already overflowed, don't even enter the loop. */
1989 if (overflow == 0) {
1990 Py_DECREF(result);
1991 result = NULL;
1992 }
1993 while(result == NULL) {
1994 item = PyIter_Next(iter);
1995 if (item == NULL) {
1996 Py_DECREF(iter);
1997 if (PyErr_Occurred())
1998 return NULL;
1999 return PyLong_FromLong(i_result);
2000 }
2001 if (PyLong_CheckExact(item)) {
2002 long b = PyLong_AsLongAndOverflow(item, &overflow);
2003 long x = i_result + b;
2004 if (overflow == 0 && ((x^i_result) >= 0 || (x^b) >= 0)) {
2005 i_result = x;
2006 Py_DECREF(item);
2007 continue;
2008 }
2009 }
2010 /* Either overflowed or is not an int. Restore real objects and process normally */
2011 result = PyLong_FromLong(i_result);
Christian Heimes704e2d32013-07-26 22:49:26 +02002012 if (result == NULL) {
2013 Py_DECREF(item);
2014 Py_DECREF(iter);
2015 return NULL;
2016 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002017 temp = PyNumber_Add(result, item);
2018 Py_DECREF(result);
2019 Py_DECREF(item);
2020 result = temp;
2021 if (result == NULL) {
2022 Py_DECREF(iter);
2023 return NULL;
2024 }
2025 }
2026 }
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002027
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002028 if (PyFloat_CheckExact(result)) {
2029 double f_result = PyFloat_AS_DOUBLE(result);
2030 Py_DECREF(result);
2031 result = NULL;
2032 while(result == NULL) {
2033 item = PyIter_Next(iter);
2034 if (item == NULL) {
2035 Py_DECREF(iter);
2036 if (PyErr_Occurred())
2037 return NULL;
2038 return PyFloat_FromDouble(f_result);
2039 }
2040 if (PyFloat_CheckExact(item)) {
2041 PyFPE_START_PROTECT("add", Py_DECREF(item); Py_DECREF(iter); return 0)
2042 f_result += PyFloat_AS_DOUBLE(item);
2043 PyFPE_END_PROTECT(f_result)
2044 Py_DECREF(item);
2045 continue;
2046 }
2047 if (PyLong_CheckExact(item)) {
2048 long value;
2049 int overflow;
2050 value = PyLong_AsLongAndOverflow(item, &overflow);
2051 if (!overflow) {
2052 PyFPE_START_PROTECT("add", Py_DECREF(item); Py_DECREF(iter); return 0)
2053 f_result += (double)value;
2054 PyFPE_END_PROTECT(f_result)
2055 Py_DECREF(item);
2056 continue;
2057 }
2058 }
2059 result = PyFloat_FromDouble(f_result);
2060 temp = PyNumber_Add(result, item);
2061 Py_DECREF(result);
2062 Py_DECREF(item);
2063 result = temp;
2064 if (result == NULL) {
2065 Py_DECREF(iter);
2066 return NULL;
2067 }
2068 }
2069 }
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002070#endif
2071
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002072 for(;;) {
2073 item = PyIter_Next(iter);
2074 if (item == NULL) {
2075 /* error, or end-of-sequence */
2076 if (PyErr_Occurred()) {
2077 Py_DECREF(result);
2078 result = NULL;
2079 }
2080 break;
2081 }
2082 /* It's tempting to use PyNumber_InPlaceAdd instead of
2083 PyNumber_Add here, to avoid quadratic running time
2084 when doing 'sum(list_of_lists, [])'. However, this
2085 would produce a change in behaviour: a snippet like
Mark Dickinson9acadc52009-10-26 14:19:42 +00002086
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002087 empty = []
2088 sum([[x] for x in range(10)], empty)
Mark Dickinson9acadc52009-10-26 14:19:42 +00002089
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002090 would change the value of empty. */
2091 temp = PyNumber_Add(result, item);
2092 Py_DECREF(result);
2093 Py_DECREF(item);
2094 result = temp;
2095 if (result == NULL)
2096 break;
2097 }
2098 Py_DECREF(iter);
2099 return result;
Alex Martellia70b1912003-04-22 08:12:33 +00002100}
2101
2102PyDoc_STRVAR(sum_doc,
Georg Brandld11ae5d2008-05-16 13:27:32 +00002103"sum(iterable[, start]) -> value\n\
Alex Martellia70b1912003-04-22 08:12:33 +00002104\n\
R David Murray87ead112013-07-10 16:22:14 -04002105Return the sum of an iterable of numbers (NOT strings) plus the value\n\
Georg Brandld11ae5d2008-05-16 13:27:32 +00002106of parameter 'start' (which defaults to 0). When the iterable is\n\
R David Murray87ead112013-07-10 16:22:14 -04002107empty, return start.");
Alex Martellia70b1912003-04-22 08:12:33 +00002108
2109
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002110static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002111builtin_isinstance(PyObject *self, PyObject *args)
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002112{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002113 PyObject *inst;
2114 PyObject *cls;
2115 int retval;
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002116
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002117 if (!PyArg_UnpackTuple(args, "isinstance", 2, 2, &inst, &cls))
2118 return NULL;
Guido van Rossumf5dd9141997-12-02 19:11:45 +00002119
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002120 retval = PyObject_IsInstance(inst, cls);
2121 if (retval < 0)
2122 return NULL;
2123 return PyBool_FromLong(retval);
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002124}
2125
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002126PyDoc_STRVAR(isinstance_doc,
Guido van Rossum77f6a652002-04-03 22:41:51 +00002127"isinstance(object, class-or-type-or-tuple) -> bool\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002128\n\
2129Return whether an object is an instance of a class or of a subclass thereof.\n\
Guido van Rossum03290ec2001-10-07 20:54:12 +00002130With a type as second argument, return whether that is the object's type.\n\
2131The form using a tuple, isinstance(x, (A, B, ...)), is a shortcut for\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002132isinstance(x, A) or isinstance(x, B) or ... (etc.).");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002133
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002134
2135static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002136builtin_issubclass(PyObject *self, PyObject *args)
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002137{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002138 PyObject *derived;
2139 PyObject *cls;
2140 int retval;
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002141
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002142 if (!PyArg_UnpackTuple(args, "issubclass", 2, 2, &derived, &cls))
2143 return NULL;
Guido van Rossum668213d1999-06-16 17:28:37 +00002144
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002145 retval = PyObject_IsSubclass(derived, cls);
2146 if (retval < 0)
2147 return NULL;
2148 return PyBool_FromLong(retval);
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002149}
2150
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002151PyDoc_STRVAR(issubclass_doc,
Guido van Rossum77f6a652002-04-03 22:41:51 +00002152"issubclass(C, B) -> bool\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002153\n\
Walter Dörwaldd9a6ad32002-12-12 16:41:44 +00002154Return whether class C is a subclass (i.e., a derived class) of class B.\n\
2155When using a tuple as the second argument issubclass(X, (A, B, ...)),\n\
2156is a shortcut for issubclass(X, A) or issubclass(X, B) or ... (etc.).");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002157
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002158
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002159typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002160 PyObject_HEAD
2161 Py_ssize_t tuplesize;
2162 PyObject *ittuple; /* tuple of iterators */
2163 PyObject *result;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002164} zipobject;
2165
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002166static PyObject *
2167zip_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
Barry Warsawbd599b52000-08-03 15:45:29 +00002168{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002169 zipobject *lz;
2170 Py_ssize_t i;
2171 PyObject *ittuple; /* tuple of iterators */
2172 PyObject *result;
2173 Py_ssize_t tuplesize = PySequence_Length(args);
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002174
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002175 if (type == &PyZip_Type && !_PyArg_NoKeywords("zip()", kwds))
2176 return NULL;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002177
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002178 /* args must be a tuple */
2179 assert(PyTuple_Check(args));
Barry Warsawbd599b52000-08-03 15:45:29 +00002180
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002181 /* obtain iterators */
2182 ittuple = PyTuple_New(tuplesize);
2183 if (ittuple == NULL)
2184 return NULL;
2185 for (i=0; i < tuplesize; ++i) {
2186 PyObject *item = PyTuple_GET_ITEM(args, i);
2187 PyObject *it = PyObject_GetIter(item);
2188 if (it == NULL) {
2189 if (PyErr_ExceptionMatches(PyExc_TypeError))
2190 PyErr_Format(PyExc_TypeError,
2191 "zip argument #%zd must support iteration",
2192 i+1);
2193 Py_DECREF(ittuple);
2194 return NULL;
2195 }
2196 PyTuple_SET_ITEM(ittuple, i, it);
2197 }
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002198
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002199 /* create a result holder */
2200 result = PyTuple_New(tuplesize);
2201 if (result == NULL) {
2202 Py_DECREF(ittuple);
2203 return NULL;
2204 }
2205 for (i=0 ; i < tuplesize ; i++) {
2206 Py_INCREF(Py_None);
2207 PyTuple_SET_ITEM(result, i, Py_None);
2208 }
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002209
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002210 /* create zipobject structure */
2211 lz = (zipobject *)type->tp_alloc(type, 0);
2212 if (lz == NULL) {
2213 Py_DECREF(ittuple);
2214 Py_DECREF(result);
2215 return NULL;
2216 }
2217 lz->ittuple = ittuple;
2218 lz->tuplesize = tuplesize;
2219 lz->result = result;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002220
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002221 return (PyObject *)lz;
Barry Warsawbd599b52000-08-03 15:45:29 +00002222}
2223
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002224static void
2225zip_dealloc(zipobject *lz)
2226{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002227 PyObject_GC_UnTrack(lz);
2228 Py_XDECREF(lz->ittuple);
2229 Py_XDECREF(lz->result);
2230 Py_TYPE(lz)->tp_free(lz);
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002231}
2232
2233static int
2234zip_traverse(zipobject *lz, visitproc visit, void *arg)
2235{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002236 Py_VISIT(lz->ittuple);
2237 Py_VISIT(lz->result);
2238 return 0;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002239}
2240
2241static PyObject *
2242zip_next(zipobject *lz)
2243{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002244 Py_ssize_t i;
2245 Py_ssize_t tuplesize = lz->tuplesize;
2246 PyObject *result = lz->result;
2247 PyObject *it;
2248 PyObject *item;
2249 PyObject *olditem;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002250
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002251 if (tuplesize == 0)
2252 return NULL;
2253 if (Py_REFCNT(result) == 1) {
2254 Py_INCREF(result);
2255 for (i=0 ; i < tuplesize ; i++) {
2256 it = PyTuple_GET_ITEM(lz->ittuple, i);
2257 item = (*Py_TYPE(it)->tp_iternext)(it);
Serhiy Storchaka278d03b2013-04-06 22:52:34 +03002258 if (item == NULL) {
2259 Py_DECREF(result);
2260 return NULL;
2261 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002262 olditem = PyTuple_GET_ITEM(result, i);
2263 PyTuple_SET_ITEM(result, i, item);
2264 Py_DECREF(olditem);
2265 }
2266 } else {
2267 result = PyTuple_New(tuplesize);
2268 if (result == NULL)
Serhiy Storchaka278d03b2013-04-06 22:52:34 +03002269 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002270 for (i=0 ; i < tuplesize ; i++) {
2271 it = PyTuple_GET_ITEM(lz->ittuple, i);
2272 item = (*Py_TYPE(it)->tp_iternext)(it);
Serhiy Storchaka278d03b2013-04-06 22:52:34 +03002273 if (item == NULL) {
2274 Py_DECREF(result);
2275 return NULL;
2276 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002277 PyTuple_SET_ITEM(result, i, item);
2278 }
2279 }
2280 return result;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002281}
Barry Warsawbd599b52000-08-03 15:45:29 +00002282
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002283static PyObject *
2284zip_reduce(zipobject *lz)
2285{
2286 /* Just recreate the zip with the internal iterator tuple */
2287 return Py_BuildValue("OO", Py_TYPE(lz), lz->ittuple);
2288}
2289
2290static PyMethodDef zip_methods[] = {
2291 {"__reduce__", (PyCFunction)zip_reduce, METH_NOARGS, reduce_doc},
2292 {NULL, NULL} /* sentinel */
2293};
2294
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002295PyDoc_STRVAR(zip_doc,
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002296"zip(iter1 [,iter2 [...]]) --> zip object\n\
Barry Warsawbd599b52000-08-03 15:45:29 +00002297\n\
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002298Return a zip object whose .__next__() method returns a tuple where\n\
2299the i-th element comes from the i-th iterable argument. The .__next__()\n\
2300method continues until the shortest iterable in the argument sequence\n\
Georg Brandlced51db2008-12-04 18:28:38 +00002301is exhausted and then it raises StopIteration.");
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002302
2303PyTypeObject PyZip_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002304 PyVarObject_HEAD_INIT(&PyType_Type, 0)
2305 "zip", /* tp_name */
2306 sizeof(zipobject), /* tp_basicsize */
2307 0, /* tp_itemsize */
2308 /* methods */
2309 (destructor)zip_dealloc, /* tp_dealloc */
2310 0, /* tp_print */
2311 0, /* tp_getattr */
2312 0, /* tp_setattr */
2313 0, /* tp_reserved */
2314 0, /* tp_repr */
2315 0, /* tp_as_number */
2316 0, /* tp_as_sequence */
2317 0, /* tp_as_mapping */
2318 0, /* tp_hash */
2319 0, /* tp_call */
2320 0, /* tp_str */
2321 PyObject_GenericGetAttr, /* tp_getattro */
2322 0, /* tp_setattro */
2323 0, /* tp_as_buffer */
2324 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
2325 Py_TPFLAGS_BASETYPE, /* tp_flags */
2326 zip_doc, /* tp_doc */
2327 (traverseproc)zip_traverse, /* tp_traverse */
2328 0, /* tp_clear */
2329 0, /* tp_richcompare */
2330 0, /* tp_weaklistoffset */
2331 PyObject_SelfIter, /* tp_iter */
2332 (iternextfunc)zip_next, /* tp_iternext */
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002333 zip_methods, /* tp_methods */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002334 0, /* tp_members */
2335 0, /* tp_getset */
2336 0, /* tp_base */
2337 0, /* tp_dict */
2338 0, /* tp_descr_get */
2339 0, /* tp_descr_set */
2340 0, /* tp_dictoffset */
2341 0, /* tp_init */
2342 PyType_GenericAlloc, /* tp_alloc */
2343 zip_new, /* tp_new */
2344 PyObject_GC_Del, /* tp_free */
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002345};
Barry Warsawbd599b52000-08-03 15:45:29 +00002346
2347
Guido van Rossum79f25d91997-04-29 20:08:16 +00002348static PyMethodDef builtin_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002349 {"__build_class__", (PyCFunction)builtin___build_class__,
2350 METH_VARARGS | METH_KEYWORDS, build_class_doc},
2351 {"__import__", (PyCFunction)builtin___import__, METH_VARARGS | METH_KEYWORDS, import_doc},
2352 {"abs", builtin_abs, METH_O, abs_doc},
2353 {"all", builtin_all, METH_O, all_doc},
2354 {"any", builtin_any, METH_O, any_doc},
2355 {"ascii", builtin_ascii, METH_O, ascii_doc},
2356 {"bin", builtin_bin, METH_O, bin_doc},
Antoine Pitroue71362d2010-11-27 22:00:11 +00002357 {"callable", builtin_callable, METH_O, callable_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002358 {"chr", builtin_chr, METH_VARARGS, chr_doc},
2359 {"compile", (PyCFunction)builtin_compile, METH_VARARGS | METH_KEYWORDS, compile_doc},
2360 {"delattr", builtin_delattr, METH_VARARGS, delattr_doc},
2361 {"dir", builtin_dir, METH_VARARGS, dir_doc},
2362 {"divmod", builtin_divmod, METH_VARARGS, divmod_doc},
2363 {"eval", builtin_eval, METH_VARARGS, eval_doc},
2364 {"exec", builtin_exec, METH_VARARGS, exec_doc},
2365 {"format", builtin_format, METH_VARARGS, format_doc},
2366 {"getattr", builtin_getattr, METH_VARARGS, getattr_doc},
2367 {"globals", (PyCFunction)builtin_globals, METH_NOARGS, globals_doc},
2368 {"hasattr", builtin_hasattr, METH_VARARGS, hasattr_doc},
2369 {"hash", builtin_hash, METH_O, hash_doc},
2370 {"hex", builtin_hex, METH_O, hex_doc},
2371 {"id", builtin_id, METH_O, id_doc},
2372 {"input", builtin_input, METH_VARARGS, input_doc},
2373 {"isinstance", builtin_isinstance, METH_VARARGS, isinstance_doc},
2374 {"issubclass", builtin_issubclass, METH_VARARGS, issubclass_doc},
2375 {"iter", builtin_iter, METH_VARARGS, iter_doc},
2376 {"len", builtin_len, METH_O, len_doc},
2377 {"locals", (PyCFunction)builtin_locals, METH_NOARGS, locals_doc},
2378 {"max", (PyCFunction)builtin_max, METH_VARARGS | METH_KEYWORDS, max_doc},
2379 {"min", (PyCFunction)builtin_min, METH_VARARGS | METH_KEYWORDS, min_doc},
2380 {"next", (PyCFunction)builtin_next, METH_VARARGS, next_doc},
2381 {"oct", builtin_oct, METH_O, oct_doc},
2382 {"ord", builtin_ord, METH_O, ord_doc},
2383 {"pow", builtin_pow, METH_VARARGS, pow_doc},
2384 {"print", (PyCFunction)builtin_print, METH_VARARGS | METH_KEYWORDS, print_doc},
2385 {"repr", builtin_repr, METH_O, repr_doc},
2386 {"round", (PyCFunction)builtin_round, METH_VARARGS | METH_KEYWORDS, round_doc},
2387 {"setattr", builtin_setattr, METH_VARARGS, setattr_doc},
2388 {"sorted", (PyCFunction)builtin_sorted, METH_VARARGS | METH_KEYWORDS, sorted_doc},
2389 {"sum", builtin_sum, METH_VARARGS, sum_doc},
2390 {"vars", builtin_vars, METH_VARARGS, vars_doc},
2391 {NULL, NULL},
Guido van Rossum3f5da241990-12-20 15:06:42 +00002392};
2393
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002394PyDoc_STRVAR(builtin_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002395"Built-in functions, exceptions, and other objects.\n\
2396\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002397Noteworthy: None is the `nil' object; Ellipsis represents `...' in slices.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002398
Martin v. Löwis1a214512008-06-11 05:26:20 +00002399static struct PyModuleDef builtinsmodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002400 PyModuleDef_HEAD_INIT,
2401 "builtins",
2402 builtin_doc,
2403 -1, /* multiple "initialization" just copies the module dict. */
2404 builtin_methods,
2405 NULL,
2406 NULL,
2407 NULL,
2408 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00002409};
2410
2411
Guido van Rossum25ce5661997-08-02 03:10:38 +00002412PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002413_PyBuiltin_Init(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +00002414{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002415 PyObject *mod, *dict, *debug;
2416 mod = PyModule_Create(&builtinsmodule);
2417 if (mod == NULL)
2418 return NULL;
2419 dict = PyModule_GetDict(mod);
Tim Peters4b7625e2001-09-13 21:37:17 +00002420
Tim Peters7571a0f2003-03-23 17:52:28 +00002421#ifdef Py_TRACE_REFS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002422 /* "builtins" exposes a number of statically allocated objects
2423 * that, before this code was added in 2.3, never showed up in
2424 * the list of "all objects" maintained by Py_TRACE_REFS. As a
2425 * result, programs leaking references to None and False (etc)
2426 * couldn't be diagnosed by examining sys.getobjects(0).
2427 */
Tim Peters7571a0f2003-03-23 17:52:28 +00002428#define ADD_TO_ALL(OBJECT) _Py_AddToAllObjects((PyObject *)(OBJECT), 0)
2429#else
2430#define ADD_TO_ALL(OBJECT) (void)0
2431#endif
2432
Tim Peters4b7625e2001-09-13 21:37:17 +00002433#define SETBUILTIN(NAME, OBJECT) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002434 if (PyDict_SetItemString(dict, NAME, (PyObject *)OBJECT) < 0) \
2435 return NULL; \
2436 ADD_TO_ALL(OBJECT)
Tim Peters4b7625e2001-09-13 21:37:17 +00002437
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002438 SETBUILTIN("None", Py_None);
2439 SETBUILTIN("Ellipsis", Py_Ellipsis);
2440 SETBUILTIN("NotImplemented", Py_NotImplemented);
2441 SETBUILTIN("False", Py_False);
2442 SETBUILTIN("True", Py_True);
2443 SETBUILTIN("bool", &PyBool_Type);
2444 SETBUILTIN("memoryview", &PyMemoryView_Type);
2445 SETBUILTIN("bytearray", &PyByteArray_Type);
2446 SETBUILTIN("bytes", &PyBytes_Type);
2447 SETBUILTIN("classmethod", &PyClassMethod_Type);
2448 SETBUILTIN("complex", &PyComplex_Type);
2449 SETBUILTIN("dict", &PyDict_Type);
2450 SETBUILTIN("enumerate", &PyEnum_Type);
2451 SETBUILTIN("filter", &PyFilter_Type);
2452 SETBUILTIN("float", &PyFloat_Type);
2453 SETBUILTIN("frozenset", &PyFrozenSet_Type);
2454 SETBUILTIN("property", &PyProperty_Type);
2455 SETBUILTIN("int", &PyLong_Type);
2456 SETBUILTIN("list", &PyList_Type);
2457 SETBUILTIN("map", &PyMap_Type);
2458 SETBUILTIN("object", &PyBaseObject_Type);
2459 SETBUILTIN("range", &PyRange_Type);
2460 SETBUILTIN("reversed", &PyReversed_Type);
2461 SETBUILTIN("set", &PySet_Type);
2462 SETBUILTIN("slice", &PySlice_Type);
2463 SETBUILTIN("staticmethod", &PyStaticMethod_Type);
2464 SETBUILTIN("str", &PyUnicode_Type);
2465 SETBUILTIN("super", &PySuper_Type);
2466 SETBUILTIN("tuple", &PyTuple_Type);
2467 SETBUILTIN("type", &PyType_Type);
2468 SETBUILTIN("zip", &PyZip_Type);
2469 debug = PyBool_FromLong(Py_OptimizeFlag == 0);
2470 if (PyDict_SetItemString(dict, "__debug__", debug) < 0) {
2471 Py_XDECREF(debug);
2472 return NULL;
2473 }
2474 Py_XDECREF(debug);
Barry Warsaw757af0e1997-08-29 22:13:51 +00002475
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002476 return mod;
Tim Peters7571a0f2003-03-23 17:52:28 +00002477#undef ADD_TO_ALL
Tim Peters4b7625e2001-09-13 21:37:17 +00002478#undef SETBUILTIN
Guido van Rossum3f5da241990-12-20 15:06:42 +00002479}