blob: 0e6e6ff9ff37fe0c42155b3065c235c9de53d4c4 [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\
266Return True if bool(x) is True for all values x in the iterable.");
267
268static PyObject *
269builtin_any(PyObject *self, PyObject *v)
270{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000271 PyObject *it, *item;
272 PyObject *(*iternext)(PyObject *);
273 int cmp;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000274
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000275 it = PyObject_GetIter(v);
276 if (it == NULL)
277 return NULL;
278 iternext = *Py_TYPE(it)->tp_iternext;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000279
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000280 for (;;) {
281 item = iternext(it);
282 if (item == NULL)
283 break;
284 cmp = PyObject_IsTrue(item);
285 Py_DECREF(item);
286 if (cmp < 0) {
287 Py_DECREF(it);
288 return NULL;
289 }
290 if (cmp == 1) {
291 Py_DECREF(it);
292 Py_RETURN_TRUE;
293 }
294 }
295 Py_DECREF(it);
296 if (PyErr_Occurred()) {
297 if (PyErr_ExceptionMatches(PyExc_StopIteration))
298 PyErr_Clear();
299 else
300 return NULL;
301 }
302 Py_RETURN_FALSE;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000303}
304
305PyDoc_STRVAR(any_doc,
306"any(iterable) -> bool\n\
307\n\
308Return True if bool(x) is True for any x in the iterable.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000309
Georg Brandl559e5d72008-06-11 18:37:52 +0000310static PyObject *
311builtin_ascii(PyObject *self, PyObject *v)
312{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000313 return PyObject_ASCII(v);
Georg Brandl559e5d72008-06-11 18:37:52 +0000314}
315
316PyDoc_STRVAR(ascii_doc,
317"ascii(object) -> string\n\
318\n\
319As repr(), return a string containing a printable representation of an\n\
320object, but escape the non-ASCII characters in the string returned by\n\
321repr() using \\x, \\u or \\U escapes. This generates a string similar\n\
322to that returned by repr() in Python 2.");
323
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000324
Guido van Rossum79f25d91997-04-29 20:08:16 +0000325static PyObject *
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000326builtin_bin(PyObject *self, PyObject *v)
327{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000328 return PyNumber_ToBase(v, 2);
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000329}
330
331PyDoc_STRVAR(bin_doc,
332"bin(number) -> string\n\
333\n\
Alexander Belopolsky12338ab2011-04-07 00:15:33 -0400334Return the binary representation of an integer.");
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000335
336
Antoine Pitroue71362d2010-11-27 22:00:11 +0000337static PyObject *
338builtin_callable(PyObject *self, PyObject *v)
339{
340 return PyBool_FromLong((long)PyCallable_Check(v));
341}
342
343PyDoc_STRVAR(callable_doc,
344"callable(object) -> bool\n\
345\n\
346Return whether the object is callable (i.e., some kind of function).\n\
347Note that classes are callable, as are instances of classes with a\n\
348__call__() method.");
349
350
Raymond Hettinger17301e92008-03-13 00:19:26 +0000351typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000352 PyObject_HEAD
353 PyObject *func;
354 PyObject *it;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000355} filterobject;
356
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000357static PyObject *
Raymond Hettinger17301e92008-03-13 00:19:26 +0000358filter_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
Guido van Rossum12d12c51993-10-26 17:58:25 +0000359{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000360 PyObject *func, *seq;
361 PyObject *it;
362 filterobject *lz;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000363
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000364 if (type == &PyFilter_Type && !_PyArg_NoKeywords("filter()", kwds))
365 return NULL;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000366
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000367 if (!PyArg_UnpackTuple(args, "filter", 2, 2, &func, &seq))
368 return NULL;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000369
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000370 /* Get iterator. */
371 it = PyObject_GetIter(seq);
372 if (it == NULL)
373 return NULL;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000374
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000375 /* create filterobject structure */
376 lz = (filterobject *)type->tp_alloc(type, 0);
377 if (lz == NULL) {
378 Py_DECREF(it);
379 return NULL;
380 }
381 Py_INCREF(func);
382 lz->func = func;
383 lz->it = it;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000384
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000385 return (PyObject *)lz;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000386}
387
388static void
389filter_dealloc(filterobject *lz)
390{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000391 PyObject_GC_UnTrack(lz);
392 Py_XDECREF(lz->func);
393 Py_XDECREF(lz->it);
394 Py_TYPE(lz)->tp_free(lz);
Raymond Hettinger17301e92008-03-13 00:19:26 +0000395}
396
397static int
398filter_traverse(filterobject *lz, visitproc visit, void *arg)
399{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000400 Py_VISIT(lz->it);
401 Py_VISIT(lz->func);
402 return 0;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000403}
404
405static PyObject *
406filter_next(filterobject *lz)
407{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000408 PyObject *item;
409 PyObject *it = lz->it;
410 long ok;
411 PyObject *(*iternext)(PyObject *);
Raymond Hettinger17301e92008-03-13 00:19:26 +0000412
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000413 iternext = *Py_TYPE(it)->tp_iternext;
414 for (;;) {
415 item = iternext(it);
416 if (item == NULL)
417 return NULL;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000418
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000419 if (lz->func == Py_None || lz->func == (PyObject *)&PyBool_Type) {
420 ok = PyObject_IsTrue(item);
421 } else {
422 PyObject *good;
423 good = PyObject_CallFunctionObjArgs(lz->func,
424 item, NULL);
425 if (good == NULL) {
426 Py_DECREF(item);
427 return NULL;
428 }
429 ok = PyObject_IsTrue(good);
430 Py_DECREF(good);
431 }
Antoine Pitrou6f430e42012-08-15 23:18:25 +0200432 if (ok > 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000433 return item;
434 Py_DECREF(item);
Antoine Pitrou6f430e42012-08-15 23:18:25 +0200435 if (ok < 0)
436 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000437 }
Guido van Rossum12d12c51993-10-26 17:58:25 +0000438}
439
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +0000440static PyObject *
441filter_reduce(filterobject *lz)
442{
443 return Py_BuildValue("O(OO)", Py_TYPE(lz), lz->func, lz->it);
444}
445
446PyDoc_STRVAR(reduce_doc, "Return state information for pickling.");
447
448static PyMethodDef filter_methods[] = {
449 {"__reduce__", (PyCFunction)filter_reduce, METH_NOARGS, reduce_doc},
450 {NULL, NULL} /* sentinel */
451};
452
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000453PyDoc_STRVAR(filter_doc,
Georg Brandld11ae5d2008-05-16 13:27:32 +0000454"filter(function or None, iterable) --> filter object\n\
Guido van Rossumc1f779c2007-07-03 08:25:58 +0000455\n\
Georg Brandld11ae5d2008-05-16 13:27:32 +0000456Return an iterator yielding those items of iterable for which function(item)\n\
Raymond Hettinger17301e92008-03-13 00:19:26 +0000457is true. If function is None, return the items that are true.");
458
459PyTypeObject PyFilter_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000460 PyVarObject_HEAD_INIT(&PyType_Type, 0)
461 "filter", /* tp_name */
462 sizeof(filterobject), /* tp_basicsize */
463 0, /* tp_itemsize */
464 /* methods */
465 (destructor)filter_dealloc, /* tp_dealloc */
466 0, /* tp_print */
467 0, /* tp_getattr */
468 0, /* tp_setattr */
469 0, /* tp_reserved */
470 0, /* tp_repr */
471 0, /* tp_as_number */
472 0, /* tp_as_sequence */
473 0, /* tp_as_mapping */
474 0, /* tp_hash */
475 0, /* tp_call */
476 0, /* tp_str */
477 PyObject_GenericGetAttr, /* tp_getattro */
478 0, /* tp_setattro */
479 0, /* tp_as_buffer */
480 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
481 Py_TPFLAGS_BASETYPE, /* tp_flags */
482 filter_doc, /* tp_doc */
483 (traverseproc)filter_traverse, /* tp_traverse */
484 0, /* tp_clear */
485 0, /* tp_richcompare */
486 0, /* tp_weaklistoffset */
487 PyObject_SelfIter, /* tp_iter */
488 (iternextfunc)filter_next, /* tp_iternext */
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +0000489 filter_methods, /* tp_methods */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000490 0, /* tp_members */
491 0, /* tp_getset */
492 0, /* tp_base */
493 0, /* tp_dict */
494 0, /* tp_descr_get */
495 0, /* tp_descr_set */
496 0, /* tp_dictoffset */
497 0, /* tp_init */
498 PyType_GenericAlloc, /* tp_alloc */
499 filter_new, /* tp_new */
500 PyObject_GC_Del, /* tp_free */
Raymond Hettinger17301e92008-03-13 00:19:26 +0000501};
502
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000503
Eric Smith8c663262007-08-25 02:26:07 +0000504static PyObject *
505builtin_format(PyObject *self, PyObject *args)
506{
Christian Heimes94b7d3d2007-12-11 20:20:39 +0000507 PyObject *value;
Eric Smith8fd3eba2008-02-17 19:48:00 +0000508 PyObject *format_spec = NULL;
Eric Smith8c663262007-08-25 02:26:07 +0000509
Eric Smith8fd3eba2008-02-17 19:48:00 +0000510 if (!PyArg_ParseTuple(args, "O|U:format", &value, &format_spec))
Benjamin Petersona12d5c62012-01-03 16:47:22 -0600511 return NULL;
Eric Smith8c663262007-08-25 02:26:07 +0000512
Eric Smith8fd3eba2008-02-17 19:48:00 +0000513 return PyObject_Format(value, format_spec);
Eric Smith8c663262007-08-25 02:26:07 +0000514}
515
Eric Smith8c663262007-08-25 02:26:07 +0000516PyDoc_STRVAR(format_doc,
Eric Smith81936692007-08-31 01:14:01 +0000517"format(value[, format_spec]) -> string\n\
Eric Smith8c663262007-08-25 02:26:07 +0000518\n\
Eric Smith81936692007-08-31 01:14:01 +0000519Returns value.__format__(format_spec)\n\
520format_spec defaults to \"\"");
521
Guido van Rossum7fcf2242007-05-04 17:43:11 +0000522static PyObject *
Walter Dörwalde7efd592007-06-05 20:07:21 +0000523builtin_chr(PyObject *self, PyObject *args)
Guido van Rossum09095f32000-03-10 23:00:52 +0000524{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000525 int x;
Guido van Rossum09095f32000-03-10 23:00:52 +0000526
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000527 if (!PyArg_ParseTuple(args, "i:chr", &x))
528 return NULL;
Fredrik Lundh0dcf67e2001-06-26 20:01:56 +0000529
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000530 return PyUnicode_FromOrdinal(x);
Guido van Rossum09095f32000-03-10 23:00:52 +0000531}
532
Victor Stinner63ab8752011-11-22 03:31:20 +0100533PyDoc_STRVAR(chr_doc,
Guido van Rossum84fc66d2007-05-03 17:18:26 +0000534"chr(i) -> Unicode character\n\
Guido van Rossum09095f32000-03-10 23:00:52 +0000535\n\
Victor Stinner63ab8752011-11-22 03:31:20 +0100536Return a Unicode string of one character with ordinal i; 0 <= i <= 0x10ffff.");
Guido van Rossum09095f32000-03-10 23:00:52 +0000537
538
Guido van Rossumf15a29f2007-05-04 00:41:39 +0000539static char *
Benjamin Petersonf5b52242009-03-02 23:31:26 +0000540source_as_string(PyObject *cmd, char *funcname, char *what, PyCompilerFlags *cf)
Guido van Rossumf15a29f2007-05-04 00:41:39 +0000541{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000542 char *str;
543 Py_ssize_t size;
Guido van Rossumf15a29f2007-05-04 00:41:39 +0000544
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000545 if (PyUnicode_Check(cmd)) {
546 cf->cf_flags |= PyCF_IGNORE_COOKIE;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200547 str = PyUnicode_AsUTF8AndSize(cmd, &size);
548 if (str == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000549 return NULL;
550 }
551 else if (!PyObject_CheckReadBuffer(cmd)) {
552 PyErr_Format(PyExc_TypeError,
553 "%s() arg 1 must be a %s object",
554 funcname, what);
555 return NULL;
556 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200557 else if (PyObject_AsReadBuffer(cmd, (const void **)&str, &size) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000558 return NULL;
559 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200560
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000561 if (strlen(str) != size) {
562 PyErr_SetString(PyExc_TypeError,
563 "source code string cannot contain null bytes");
564 return NULL;
565 }
566 return str;
Guido van Rossumf15a29f2007-05-04 00:41:39 +0000567}
568
Guido van Rossum79f25d91997-04-29 20:08:16 +0000569static PyObject *
Guido van Rossumd8faa362007-04-27 19:54:29 +0000570builtin_compile(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum5b722181993-03-30 17:46:03 +0000571{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000572 char *str;
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000573 PyObject *filename_obj;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000574 char *filename;
575 char *startstr;
576 int mode = -1;
577 int dont_inherit = 0;
578 int supplied_flags = 0;
Georg Brandl8334fd92010-12-04 10:26:46 +0000579 int optimize = -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000580 int is_ast;
581 PyCompilerFlags cf;
582 PyObject *cmd;
583 static char *kwlist[] = {"source", "filename", "mode", "flags",
Georg Brandl8334fd92010-12-04 10:26:46 +0000584 "dont_inherit", "optimize", NULL};
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000585 int start[] = {Py_file_input, Py_eval_input, Py_single_input};
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000586 PyObject *result;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000587
Georg Brandl8334fd92010-12-04 10:26:46 +0000588 if (!PyArg_ParseTupleAndKeywords(args, kwds, "OO&s|iii:compile", kwlist,
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000589 &cmd,
590 PyUnicode_FSConverter, &filename_obj,
591 &startstr, &supplied_flags,
Georg Brandl8334fd92010-12-04 10:26:46 +0000592 &dont_inherit, &optimize))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000593 return NULL;
Tim Peters6cd6a822001-08-17 22:11:27 +0000594
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000595 filename = PyBytes_AS_STRING(filename_obj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000596 cf.cf_flags = supplied_flags | PyCF_SOURCE_IS_UTF8;
Just van Rossum3aaf42c2003-02-10 08:21:10 +0000597
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000598 if (supplied_flags &
599 ~(PyCF_MASK | PyCF_MASK_OBSOLETE | PyCF_DONT_IMPLY_DEDENT | PyCF_ONLY_AST))
600 {
601 PyErr_SetString(PyExc_ValueError,
602 "compile(): unrecognised flags");
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000603 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000604 }
605 /* XXX Warn if (supplied_flags & PyCF_MASK_OBSOLETE) != 0? */
Tim Peters6cd6a822001-08-17 22:11:27 +0000606
Georg Brandl8334fd92010-12-04 10:26:46 +0000607 if (optimize < -1 || optimize > 2) {
608 PyErr_SetString(PyExc_ValueError,
609 "compile(): invalid optimize value");
610 goto error;
611 }
612
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000613 if (!dont_inherit) {
614 PyEval_MergeCompilerFlags(&cf);
615 }
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000616
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000617 if (strcmp(startstr, "exec") == 0)
618 mode = 0;
619 else if (strcmp(startstr, "eval") == 0)
620 mode = 1;
621 else if (strcmp(startstr, "single") == 0)
622 mode = 2;
623 else {
624 PyErr_SetString(PyExc_ValueError,
625 "compile() arg 3 must be 'exec', 'eval' or 'single'");
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000626 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000627 }
Neal Norwitzdb4115f2008-03-31 04:20:05 +0000628
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000629 is_ast = PyAST_Check(cmd);
630 if (is_ast == -1)
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000631 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000632 if (is_ast) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000633 if (supplied_flags & PyCF_ONLY_AST) {
634 Py_INCREF(cmd);
635 result = cmd;
636 }
637 else {
638 PyArena *arena;
639 mod_ty mod;
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000640
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000641 arena = PyArena_New();
Stefan Krah07795df2012-08-20 17:19:50 +0200642 if (arena == NULL)
643 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000644 mod = PyAST_obj2mod(cmd, arena, mode);
645 if (mod == NULL) {
646 PyArena_Free(arena);
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000647 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000648 }
Benjamin Peterson832bfe22011-08-09 16:15:04 -0500649 if (!PyAST_Validate(mod)) {
650 PyArena_Free(arena);
651 goto error;
652 }
Georg Brandl8334fd92010-12-04 10:26:46 +0000653 result = (PyObject*)PyAST_CompileEx(mod, filename,
654 &cf, optimize, arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000655 PyArena_Free(arena);
656 }
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000657 goto finally;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000658 }
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000659
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000660 str = source_as_string(cmd, "compile", "string, bytes, AST or code", &cf);
661 if (str == NULL)
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000662 goto error;
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000663
Georg Brandl8334fd92010-12-04 10:26:46 +0000664 result = Py_CompileStringExFlags(str, filename, start[mode], &cf, optimize);
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000665 goto finally;
666
667error:
668 result = NULL;
669finally:
670 Py_DECREF(filename_obj);
671 return result;
Guido van Rossum5b722181993-03-30 17:46:03 +0000672}
673
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000674PyDoc_STRVAR(compile_doc,
Tim Peters6cd6a822001-08-17 22:11:27 +0000675"compile(source, filename, mode[, flags[, dont_inherit]]) -> code object\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000676\n\
677Compile the source string (a Python module, statement or expression)\n\
Georg Brandl7cae87c2006-09-06 06:51:57 +0000678into a code object that can be executed by exec() or eval().\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000679The filename will be used for run-time error messages.\n\
680The mode must be 'exec' to compile a module, 'single' to compile a\n\
Tim Peters6cd6a822001-08-17 22:11:27 +0000681single (interactive) statement, or 'eval' to compile an expression.\n\
682The flags argument, if present, controls which future statements influence\n\
683the compilation of the code.\n\
684The dont_inherit argument, if non-zero, stops the compilation inheriting\n\
685the effects of any future statements in effect in the code calling\n\
686compile; if absent or zero these statements do influence the compilation,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000687in addition to any features explicitly specified.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000688
Guido van Rossum79f25d91997-04-29 20:08:16 +0000689static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000690builtin_dir(PyObject *self, PyObject *args)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000691{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000692 PyObject *arg = NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000693
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000694 if (!PyArg_UnpackTuple(args, "dir", 0, 1, &arg))
695 return NULL;
696 return PyObject_Dir(arg);
Guido van Rossum3f5da241990-12-20 15:06:42 +0000697}
698
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000699PyDoc_STRVAR(dir_doc,
Tim Peters5d2b77c2001-09-03 05:47:38 +0000700"dir([object]) -> list of strings\n"
701"\n"
Georg Brandle32b4222007-03-10 22:13:27 +0000702"If called without an argument, return the names in the current scope.\n"
703"Else, return an alphabetized list of names comprising (some of) the attributes\n"
704"of the given object, and of attributes reachable from it.\n"
705"If the object supplies a method named __dir__, it will be used; otherwise\n"
706"the default dir() logic is used and returns:\n"
707" for a module object: the module's attributes.\n"
708" for a class object: its attributes, and recursively the attributes\n"
709" of its bases.\n"
Guido van Rossumd8faa362007-04-27 19:54:29 +0000710" for any other object: its attributes, its class's attributes, and\n"
Georg Brandle32b4222007-03-10 22:13:27 +0000711" recursively the attributes of its class's base classes.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000712
Guido van Rossum79f25d91997-04-29 20:08:16 +0000713static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000714builtin_divmod(PyObject *self, PyObject *args)
Guido van Rossum6a00cd81995-01-07 12:39:01 +0000715{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000716 PyObject *v, *w;
Guido van Rossum6a00cd81995-01-07 12:39:01 +0000717
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000718 if (!PyArg_UnpackTuple(args, "divmod", 2, 2, &v, &w))
719 return NULL;
720 return PyNumber_Divmod(v, w);
Guido van Rossum3f5da241990-12-20 15:06:42 +0000721}
722
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000723PyDoc_STRVAR(divmod_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000724"divmod(x, y) -> (div, mod)\n\
725\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000726Return the tuple ((x-x%y)/y, x%y). Invariant: div*y + mod == x.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000727
728
Guido van Rossum79f25d91997-04-29 20:08:16 +0000729static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000730builtin_eval(PyObject *self, PyObject *args)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000731{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000732 PyObject *cmd, *result, *tmp = NULL;
733 PyObject *globals = Py_None, *locals = Py_None;
734 char *str;
735 PyCompilerFlags cf;
Guido van Rossum590baa41993-11-30 13:40:46 +0000736
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000737 if (!PyArg_UnpackTuple(args, "eval", 1, 3, &cmd, &globals, &locals))
738 return NULL;
739 if (locals != Py_None && !PyMapping_Check(locals)) {
740 PyErr_SetString(PyExc_TypeError, "locals must be a mapping");
741 return NULL;
742 }
743 if (globals != Py_None && !PyDict_Check(globals)) {
744 PyErr_SetString(PyExc_TypeError, PyMapping_Check(globals) ?
745 "globals must be a real dict; try eval(expr, {}, mapping)"
746 : "globals must be a dict");
747 return NULL;
748 }
749 if (globals == Py_None) {
750 globals = PyEval_GetGlobals();
751 if (locals == Py_None)
752 locals = PyEval_GetLocals();
753 }
754 else if (locals == Py_None)
755 locals = globals;
Tim Peters9fa96be2001-08-17 23:04:59 +0000756
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000757 if (globals == NULL || locals == NULL) {
758 PyErr_SetString(PyExc_TypeError,
759 "eval must be given globals and locals "
760 "when called without a frame");
761 return NULL;
762 }
Georg Brandl77c85e62005-09-15 10:46:13 +0000763
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000764 if (PyDict_GetItemString(globals, "__builtins__") == NULL) {
765 if (PyDict_SetItemString(globals, "__builtins__",
766 PyEval_GetBuiltins()) != 0)
767 return NULL;
768 }
Tim Peters9fa96be2001-08-17 23:04:59 +0000769
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000770 if (PyCode_Check(cmd)) {
771 if (PyCode_GetNumFree((PyCodeObject *)cmd) > 0) {
772 PyErr_SetString(PyExc_TypeError,
773 "code object passed to eval() may not contain free variables");
774 return NULL;
775 }
Martin v. Löwis4d0d4712010-12-03 20:14:31 +0000776 return PyEval_EvalCode(cmd, globals, locals);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000777 }
Tim Peters9fa96be2001-08-17 23:04:59 +0000778
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000779 cf.cf_flags = PyCF_SOURCE_IS_UTF8;
780 str = source_as_string(cmd, "eval", "string, bytes or code", &cf);
781 if (str == NULL)
782 return NULL;
Just van Rossum3aaf42c2003-02-10 08:21:10 +0000783
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000784 while (*str == ' ' || *str == '\t')
785 str++;
Tim Peters9fa96be2001-08-17 23:04:59 +0000786
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000787 (void)PyEval_MergeCompilerFlags(&cf);
788 result = PyRun_StringFlags(str, Py_eval_input, globals, locals, &cf);
789 Py_XDECREF(tmp);
790 return result;
Guido van Rossum3f5da241990-12-20 15:06:42 +0000791}
792
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000793PyDoc_STRVAR(eval_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000794"eval(source[, globals[, locals]]) -> value\n\
795\n\
796Evaluate the source in the context of globals and locals.\n\
797The source may be a string representing a Python expression\n\
798or a code object as returned by compile().\n\
Thomas Wouters89f507f2006-12-13 04:49:30 +0000799The globals must be a dictionary and locals can be any mapping,\n\
Raymond Hettinger214b1c32004-07-02 06:41:07 +0000800defaulting to the current globals and locals.\n\
801If only globals is given, locals defaults to it.\n");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000802
Georg Brandl7cae87c2006-09-06 06:51:57 +0000803static PyObject *
804builtin_exec(PyObject *self, PyObject *args)
805{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000806 PyObject *v;
807 PyObject *prog, *globals = Py_None, *locals = Py_None;
Georg Brandl7cae87c2006-09-06 06:51:57 +0000808
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000809 if (!PyArg_UnpackTuple(args, "exec", 1, 3, &prog, &globals, &locals))
810 return NULL;
Georg Brandl2cabc562008-08-28 07:57:16 +0000811
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000812 if (globals == Py_None) {
813 globals = PyEval_GetGlobals();
814 if (locals == Py_None) {
815 locals = PyEval_GetLocals();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000816 }
817 if (!globals || !locals) {
818 PyErr_SetString(PyExc_SystemError,
819 "globals and locals cannot be NULL");
820 return NULL;
821 }
822 }
823 else if (locals == Py_None)
824 locals = globals;
Georg Brandl7cae87c2006-09-06 06:51:57 +0000825
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000826 if (!PyDict_Check(globals)) {
827 PyErr_Format(PyExc_TypeError, "exec() arg 2 must be a dict, not %.100s",
828 globals->ob_type->tp_name);
829 return NULL;
830 }
831 if (!PyMapping_Check(locals)) {
832 PyErr_Format(PyExc_TypeError,
833 "arg 3 must be a mapping or None, not %.100s",
834 locals->ob_type->tp_name);
835 return NULL;
836 }
837 if (PyDict_GetItemString(globals, "__builtins__") == NULL) {
838 if (PyDict_SetItemString(globals, "__builtins__",
839 PyEval_GetBuiltins()) != 0)
840 return NULL;
841 }
842
843 if (PyCode_Check(prog)) {
844 if (PyCode_GetNumFree((PyCodeObject *)prog) > 0) {
845 PyErr_SetString(PyExc_TypeError,
846 "code object passed to exec() may not "
847 "contain free variables");
848 return NULL;
849 }
Martin v. Löwis4d0d4712010-12-03 20:14:31 +0000850 v = PyEval_EvalCode(prog, globals, locals);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000851 }
852 else {
853 char *str;
854 PyCompilerFlags cf;
855 cf.cf_flags = PyCF_SOURCE_IS_UTF8;
856 str = source_as_string(prog, "exec",
857 "string, bytes or code", &cf);
858 if (str == NULL)
859 return NULL;
860 if (PyEval_MergeCompilerFlags(&cf))
861 v = PyRun_StringFlags(str, Py_file_input, globals,
862 locals, &cf);
863 else
864 v = PyRun_String(str, Py_file_input, globals, locals);
865 }
866 if (v == NULL)
867 return NULL;
868 Py_DECREF(v);
869 Py_RETURN_NONE;
Georg Brandl7cae87c2006-09-06 06:51:57 +0000870}
871
872PyDoc_STRVAR(exec_doc,
873"exec(object[, globals[, locals]])\n\
874\n\
Mark Dickinson480e8e32009-12-19 21:19:35 +0000875Read and execute code from an object, which can be a string or a code\n\
Benjamin Peterson38090262009-01-04 15:30:39 +0000876object.\n\
Georg Brandl7cae87c2006-09-06 06:51:57 +0000877The globals and locals are dictionaries, defaulting to the current\n\
878globals and locals. If only globals is given, locals defaults to it.");
879
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000880
Guido van Rossum79f25d91997-04-29 20:08:16 +0000881static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000882builtin_getattr(PyObject *self, PyObject *args)
Guido van Rossum33894be1992-01-27 16:53:09 +0000883{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000884 PyObject *v, *result, *dflt = NULL;
885 PyObject *name;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000886
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000887 if (!PyArg_UnpackTuple(args, "getattr", 2, 3, &v, &name, &dflt))
888 return NULL;
Martin v. Löwis5b222132007-06-10 09:51:05 +0000889
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000890 if (!PyUnicode_Check(name)) {
891 PyErr_SetString(PyExc_TypeError,
892 "getattr(): attribute name must be string");
893 return NULL;
894 }
895 result = PyObject_GetAttr(v, name);
896 if (result == NULL && dflt != NULL &&
897 PyErr_ExceptionMatches(PyExc_AttributeError))
898 {
899 PyErr_Clear();
900 Py_INCREF(dflt);
901 result = dflt;
902 }
903 return result;
Guido van Rossum9bfef441993-03-29 10:43:31 +0000904}
905
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000906PyDoc_STRVAR(getattr_doc,
Guido van Rossum950ff291998-06-29 13:38:57 +0000907"getattr(object, name[, default]) -> value\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000908\n\
Guido van Rossum950ff291998-06-29 13:38:57 +0000909Get a named attribute from an object; getattr(x, 'y') is equivalent to x.y.\n\
910When a default argument is given, it is returned when the attribute doesn't\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000911exist; without it, an exception is raised in that case.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000912
913
Guido van Rossum79f25d91997-04-29 20:08:16 +0000914static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000915builtin_globals(PyObject *self)
Guido van Rossum872537c1995-07-07 22:43:42 +0000916{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000917 PyObject *d;
Guido van Rossum872537c1995-07-07 22:43:42 +0000918
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000919 d = PyEval_GetGlobals();
920 Py_XINCREF(d);
921 return d;
Guido van Rossum872537c1995-07-07 22:43:42 +0000922}
923
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000924PyDoc_STRVAR(globals_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000925"globals() -> dictionary\n\
926\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000927Return the dictionary containing the current scope's global variables.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000928
929
Guido van Rossum79f25d91997-04-29 20:08:16 +0000930static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000931builtin_hasattr(PyObject *self, PyObject *args)
Guido van Rossum9bfef441993-03-29 10:43:31 +0000932{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000933 PyObject *v;
934 PyObject *name;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000935
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000936 if (!PyArg_UnpackTuple(args, "hasattr", 2, 2, &v, &name))
937 return NULL;
938 if (!PyUnicode_Check(name)) {
939 PyErr_SetString(PyExc_TypeError,
940 "hasattr(): attribute name must be string");
941 return NULL;
942 }
943 v = PyObject_GetAttr(v, name);
944 if (v == NULL) {
Benjamin Peterson17689992010-08-24 03:26:23 +0000945 if (PyErr_ExceptionMatches(PyExc_AttributeError)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000946 PyErr_Clear();
Benjamin Peterson17689992010-08-24 03:26:23 +0000947 Py_RETURN_FALSE;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000948 }
Benjamin Peterson17689992010-08-24 03:26:23 +0000949 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000950 }
951 Py_DECREF(v);
Benjamin Peterson17689992010-08-24 03:26:23 +0000952 Py_RETURN_TRUE;
Guido van Rossum33894be1992-01-27 16:53:09 +0000953}
954
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000955PyDoc_STRVAR(hasattr_doc,
Guido van Rossum77f6a652002-04-03 22:41:51 +0000956"hasattr(object, name) -> bool\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000957\n\
958Return whether the object has an attribute with the given name.\n\
Benjamin Peterson17689992010-08-24 03:26:23 +0000959(This is done by calling getattr(object, name) and catching AttributeError.)");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000960
961
Guido van Rossum79f25d91997-04-29 20:08:16 +0000962static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000963builtin_id(PyObject *self, PyObject *v)
Guido van Rossum5b722181993-03-30 17:46:03 +0000964{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000965 return PyLong_FromVoidPtr(v);
Guido van Rossum5b722181993-03-30 17:46:03 +0000966}
967
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000968PyDoc_STRVAR(id_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000969"id(object) -> integer\n\
970\n\
971Return the identity of an object. This is guaranteed to be unique among\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000972simultaneously existing objects. (Hint: it's the object's memory address.)");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000973
974
Raymond Hettingera6c60372008-03-13 01:26:19 +0000975/* map object ************************************************************/
976
977typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000978 PyObject_HEAD
979 PyObject *iters;
980 PyObject *func;
Raymond Hettingera6c60372008-03-13 01:26:19 +0000981} mapobject;
982
Guido van Rossum79f25d91997-04-29 20:08:16 +0000983static PyObject *
Raymond Hettingera6c60372008-03-13 01:26:19 +0000984map_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
Guido van Rossum12d12c51993-10-26 17:58:25 +0000985{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000986 PyObject *it, *iters, *func;
987 mapobject *lz;
988 Py_ssize_t numargs, i;
Raymond Hettingera6c60372008-03-13 01:26:19 +0000989
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000990 if (type == &PyMap_Type && !_PyArg_NoKeywords("map()", kwds))
991 return NULL;
Raymond Hettingera6c60372008-03-13 01:26:19 +0000992
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000993 numargs = PyTuple_Size(args);
994 if (numargs < 2) {
995 PyErr_SetString(PyExc_TypeError,
996 "map() must have at least two arguments.");
997 return NULL;
998 }
Raymond Hettingera6c60372008-03-13 01:26:19 +0000999
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001000 iters = PyTuple_New(numargs-1);
1001 if (iters == NULL)
1002 return NULL;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001003
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001004 for (i=1 ; i<numargs ; i++) {
1005 /* Get iterator. */
1006 it = PyObject_GetIter(PyTuple_GET_ITEM(args, i));
1007 if (it == NULL) {
1008 Py_DECREF(iters);
1009 return NULL;
1010 }
1011 PyTuple_SET_ITEM(iters, i-1, it);
1012 }
Raymond Hettingera6c60372008-03-13 01:26:19 +00001013
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001014 /* create mapobject structure */
1015 lz = (mapobject *)type->tp_alloc(type, 0);
1016 if (lz == NULL) {
1017 Py_DECREF(iters);
1018 return NULL;
1019 }
1020 lz->iters = iters;
1021 func = PyTuple_GET_ITEM(args, 0);
1022 Py_INCREF(func);
1023 lz->func = func;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001024
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001025 return (PyObject *)lz;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001026}
1027
1028static void
1029map_dealloc(mapobject *lz)
1030{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001031 PyObject_GC_UnTrack(lz);
1032 Py_XDECREF(lz->iters);
1033 Py_XDECREF(lz->func);
1034 Py_TYPE(lz)->tp_free(lz);
Raymond Hettingera6c60372008-03-13 01:26:19 +00001035}
1036
1037static int
1038map_traverse(mapobject *lz, visitproc visit, void *arg)
1039{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001040 Py_VISIT(lz->iters);
1041 Py_VISIT(lz->func);
1042 return 0;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001043}
1044
1045static PyObject *
1046map_next(mapobject *lz)
1047{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001048 PyObject *val;
1049 PyObject *argtuple;
1050 PyObject *result;
1051 Py_ssize_t numargs, i;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001052
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001053 numargs = PyTuple_Size(lz->iters);
1054 argtuple = PyTuple_New(numargs);
1055 if (argtuple == NULL)
1056 return NULL;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001057
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001058 for (i=0 ; i<numargs ; i++) {
1059 val = PyIter_Next(PyTuple_GET_ITEM(lz->iters, i));
1060 if (val == NULL) {
1061 Py_DECREF(argtuple);
1062 return NULL;
1063 }
1064 PyTuple_SET_ITEM(argtuple, i, val);
1065 }
1066 result = PyObject_Call(lz->func, argtuple, NULL);
1067 Py_DECREF(argtuple);
1068 return result;
Guido van Rossum12d12c51993-10-26 17:58:25 +00001069}
1070
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001071static PyObject *
1072map_reduce(mapobject *lz)
1073{
1074 Py_ssize_t numargs = PyTuple_GET_SIZE(lz->iters);
1075 PyObject *args = PyTuple_New(numargs+1);
1076 Py_ssize_t i;
1077 if (args == NULL)
1078 return NULL;
1079 Py_INCREF(lz->func);
1080 PyTuple_SET_ITEM(args, 0, lz->func);
1081 for (i = 0; i<numargs; i++){
1082 PyObject *it = PyTuple_GET_ITEM(lz->iters, i);
1083 Py_INCREF(it);
1084 PyTuple_SET_ITEM(args, i+1, it);
1085 }
1086
1087 return Py_BuildValue("ON", Py_TYPE(lz), args);
1088}
1089
1090static PyMethodDef map_methods[] = {
1091 {"__reduce__", (PyCFunction)map_reduce, METH_NOARGS, reduce_doc},
1092 {NULL, NULL} /* sentinel */
1093};
1094
1095
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001096PyDoc_STRVAR(map_doc,
Raymond Hettingera6c60372008-03-13 01:26:19 +00001097"map(func, *iterables) --> map object\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001098\n\
Raymond Hettingera6c60372008-03-13 01:26:19 +00001099Make an iterator that computes the function using arguments from\n\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001100each of the iterables. Stops when the shortest iterable is exhausted.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001101
Raymond Hettingera6c60372008-03-13 01:26:19 +00001102PyTypeObject PyMap_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001103 PyVarObject_HEAD_INIT(&PyType_Type, 0)
1104 "map", /* tp_name */
1105 sizeof(mapobject), /* tp_basicsize */
1106 0, /* tp_itemsize */
1107 /* methods */
1108 (destructor)map_dealloc, /* tp_dealloc */
1109 0, /* tp_print */
1110 0, /* tp_getattr */
1111 0, /* tp_setattr */
1112 0, /* tp_reserved */
1113 0, /* tp_repr */
1114 0, /* tp_as_number */
1115 0, /* tp_as_sequence */
1116 0, /* tp_as_mapping */
1117 0, /* tp_hash */
1118 0, /* tp_call */
1119 0, /* tp_str */
1120 PyObject_GenericGetAttr, /* tp_getattro */
1121 0, /* tp_setattro */
1122 0, /* tp_as_buffer */
1123 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
1124 Py_TPFLAGS_BASETYPE, /* tp_flags */
1125 map_doc, /* tp_doc */
1126 (traverseproc)map_traverse, /* tp_traverse */
1127 0, /* tp_clear */
1128 0, /* tp_richcompare */
1129 0, /* tp_weaklistoffset */
1130 PyObject_SelfIter, /* tp_iter */
1131 (iternextfunc)map_next, /* tp_iternext */
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001132 map_methods, /* tp_methods */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001133 0, /* tp_members */
1134 0, /* tp_getset */
1135 0, /* tp_base */
1136 0, /* tp_dict */
1137 0, /* tp_descr_get */
1138 0, /* tp_descr_set */
1139 0, /* tp_dictoffset */
1140 0, /* tp_init */
1141 PyType_GenericAlloc, /* tp_alloc */
1142 map_new, /* tp_new */
1143 PyObject_GC_Del, /* tp_free */
Raymond Hettingera6c60372008-03-13 01:26:19 +00001144};
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001145
Guido van Rossum79f25d91997-04-29 20:08:16 +00001146static PyObject *
Georg Brandla18af4e2007-04-21 15:47:16 +00001147builtin_next(PyObject *self, PyObject *args)
1148{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001149 PyObject *it, *res;
1150 PyObject *def = NULL;
Georg Brandla18af4e2007-04-21 15:47:16 +00001151
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001152 if (!PyArg_UnpackTuple(args, "next", 1, 2, &it, &def))
1153 return NULL;
1154 if (!PyIter_Check(it)) {
1155 PyErr_Format(PyExc_TypeError,
Philip Jenvey50add042011-11-06 16:37:52 -08001156 "'%.200s' object is not an iterator",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001157 it->ob_type->tp_name);
1158 return NULL;
1159 }
1160
1161 res = (*it->ob_type->tp_iternext)(it);
1162 if (res != NULL) {
1163 return res;
1164 } else if (def != NULL) {
1165 if (PyErr_Occurred()) {
1166 if(!PyErr_ExceptionMatches(PyExc_StopIteration))
1167 return NULL;
1168 PyErr_Clear();
1169 }
1170 Py_INCREF(def);
1171 return def;
1172 } else if (PyErr_Occurred()) {
1173 return NULL;
1174 } else {
1175 PyErr_SetNone(PyExc_StopIteration);
1176 return NULL;
1177 }
Georg Brandla18af4e2007-04-21 15:47:16 +00001178}
1179
1180PyDoc_STRVAR(next_doc,
1181"next(iterator[, default])\n\
1182\n\
1183Return the next item from the iterator. If default is given and the iterator\n\
1184is exhausted, it is returned instead of raising StopIteration.");
1185
1186
1187static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001188builtin_setattr(PyObject *self, PyObject *args)
Guido van Rossum33894be1992-01-27 16:53:09 +00001189{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001190 PyObject *v;
1191 PyObject *name;
1192 PyObject *value;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001193
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001194 if (!PyArg_UnpackTuple(args, "setattr", 3, 3, &v, &name, &value))
1195 return NULL;
1196 if (PyObject_SetAttr(v, name, value) != 0)
1197 return NULL;
1198 Py_INCREF(Py_None);
1199 return Py_None;
Guido van Rossum33894be1992-01-27 16:53:09 +00001200}
1201
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001202PyDoc_STRVAR(setattr_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001203"setattr(object, name, value)\n\
1204\n\
1205Set a named attribute on an object; setattr(x, 'y', v) is equivalent to\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001206``x.y = v''.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001207
1208
Guido van Rossum79f25d91997-04-29 20:08:16 +00001209static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001210builtin_delattr(PyObject *self, PyObject *args)
Guido van Rossum14144fc1994-08-29 12:53:40 +00001211{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001212 PyObject *v;
1213 PyObject *name;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001214
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001215 if (!PyArg_UnpackTuple(args, "delattr", 2, 2, &v, &name))
1216 return NULL;
1217 if (PyObject_SetAttr(v, name, (PyObject *)NULL) != 0)
1218 return NULL;
1219 Py_INCREF(Py_None);
1220 return Py_None;
Guido van Rossum14144fc1994-08-29 12:53:40 +00001221}
1222
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001223PyDoc_STRVAR(delattr_doc,
Guido van Rossumdf12a591998-11-23 22:13:04 +00001224"delattr(object, name)\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001225\n\
1226Delete a named attribute on an object; delattr(x, 'y') is equivalent to\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001227``del x.y''.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001228
1229
Guido van Rossum79f25d91997-04-29 20:08:16 +00001230static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001231builtin_hash(PyObject *self, PyObject *v)
Guido van Rossum9bfef441993-03-29 10:43:31 +00001232{
Benjamin Peterson8f67d082010-10-17 20:54:53 +00001233 Py_hash_t x;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001234
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001235 x = PyObject_Hash(v);
1236 if (x == -1)
1237 return NULL;
Benjamin Peterson8f67d082010-10-17 20:54:53 +00001238 return PyLong_FromSsize_t(x);
Guido van Rossum9bfef441993-03-29 10:43:31 +00001239}
1240
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001241PyDoc_STRVAR(hash_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001242"hash(object) -> integer\n\
1243\n\
1244Return a hash value for the object. Two objects with the same value have\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001245the same hash value. The reverse is not necessarily true, but likely.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001246
1247
Guido van Rossum79f25d91997-04-29 20:08:16 +00001248static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001249builtin_hex(PyObject *self, PyObject *v)
Guido van Rossum006bcd41991-10-24 14:54:44 +00001250{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001251 return PyNumber_ToBase(v, 16);
Guido van Rossum006bcd41991-10-24 14:54:44 +00001252}
1253
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001254PyDoc_STRVAR(hex_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001255"hex(number) -> string\n\
1256\n\
Alexander Belopolsky12338ab2011-04-07 00:15:33 -04001257Return the hexadecimal representation of an integer.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001258
1259
Guido van Rossum79f25d91997-04-29 20:08:16 +00001260static PyObject *
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001261builtin_iter(PyObject *self, PyObject *args)
1262{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001263 PyObject *v, *w = NULL;
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001264
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001265 if (!PyArg_UnpackTuple(args, "iter", 1, 2, &v, &w))
1266 return NULL;
1267 if (w == NULL)
1268 return PyObject_GetIter(v);
1269 if (!PyCallable_Check(v)) {
1270 PyErr_SetString(PyExc_TypeError,
1271 "iter(v, w): v must be callable");
1272 return NULL;
1273 }
1274 return PyCallIter_New(v, w);
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001275}
1276
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001277PyDoc_STRVAR(iter_doc,
Georg Brandld11ae5d2008-05-16 13:27:32 +00001278"iter(iterable) -> iterator\n\
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001279iter(callable, sentinel) -> iterator\n\
1280\n\
1281Get an iterator from an object. In the first form, the argument must\n\
1282supply its own iterator, or be a sequence.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001283In the second form, the callable is called until it returns the sentinel.");
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001284
1285
1286static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001287builtin_len(PyObject *self, PyObject *v)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001288{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001289 Py_ssize_t res;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001290
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001291 res = PyObject_Size(v);
1292 if (res < 0 && PyErr_Occurred())
1293 return NULL;
1294 return PyLong_FromSsize_t(res);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001295}
1296
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001297PyDoc_STRVAR(len_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001298"len(object) -> integer\n\
1299\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001300Return the number of items of a sequence or mapping.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001301
1302
Guido van Rossum79f25d91997-04-29 20:08:16 +00001303static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001304builtin_locals(PyObject *self)
Guido van Rossum872537c1995-07-07 22:43:42 +00001305{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001306 PyObject *d;
Guido van Rossum872537c1995-07-07 22:43:42 +00001307
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001308 d = PyEval_GetLocals();
1309 Py_XINCREF(d);
1310 return d;
Guido van Rossum872537c1995-07-07 22:43:42 +00001311}
1312
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001313PyDoc_STRVAR(locals_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001314"locals() -> dictionary\n\
1315\n\
Raymond Hettinger69bf8f32003-01-04 02:16:22 +00001316Update and return a dictionary containing the current scope's local variables.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001317
1318
Guido van Rossum79f25d91997-04-29 20:08:16 +00001319static PyObject *
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001320min_max(PyObject *args, PyObject *kwds, int op)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001321{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001322 PyObject *v, *it, *item, *val, *maxitem, *maxval, *keyfunc=NULL;
1323 const char *name = op == Py_LT ? "min" : "max";
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001324
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001325 if (PyTuple_Size(args) > 1)
1326 v = args;
1327 else if (!PyArg_UnpackTuple(args, (char *)name, 1, 1, &v))
1328 return NULL;
Tim Peters67d687a2002-04-29 21:27:32 +00001329
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001330 if (kwds != NULL && PyDict_Check(kwds) && PyDict_Size(kwds)) {
1331 keyfunc = PyDict_GetItemString(kwds, "key");
1332 if (PyDict_Size(kwds)!=1 || keyfunc == NULL) {
1333 PyErr_Format(PyExc_TypeError,
1334 "%s() got an unexpected keyword argument", name);
1335 return NULL;
1336 }
1337 Py_INCREF(keyfunc);
1338 }
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001339
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001340 it = PyObject_GetIter(v);
1341 if (it == NULL) {
1342 Py_XDECREF(keyfunc);
1343 return NULL;
1344 }
Tim Petersc3074532001-05-03 07:00:32 +00001345
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001346 maxitem = NULL; /* the result */
1347 maxval = NULL; /* the value associated with the result */
1348 while (( item = PyIter_Next(it) )) {
1349 /* get the value from the key function */
1350 if (keyfunc != NULL) {
1351 val = PyObject_CallFunctionObjArgs(keyfunc, item, NULL);
1352 if (val == NULL)
1353 goto Fail_it_item;
1354 }
1355 /* no key function; the value is the item */
1356 else {
1357 val = item;
1358 Py_INCREF(val);
1359 }
Tim Petersc3074532001-05-03 07:00:32 +00001360
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001361 /* maximum value and item are unset; set them */
1362 if (maxval == NULL) {
1363 maxitem = item;
1364 maxval = val;
1365 }
1366 /* maximum value and item are set; update them as necessary */
1367 else {
1368 int cmp = PyObject_RichCompareBool(val, maxval, op);
1369 if (cmp < 0)
1370 goto Fail_it_item_and_val;
1371 else if (cmp > 0) {
1372 Py_DECREF(maxval);
1373 Py_DECREF(maxitem);
1374 maxval = val;
1375 maxitem = item;
1376 }
1377 else {
1378 Py_DECREF(item);
1379 Py_DECREF(val);
1380 }
1381 }
1382 }
1383 if (PyErr_Occurred())
1384 goto Fail_it;
1385 if (maxval == NULL) {
1386 PyErr_Format(PyExc_ValueError,
1387 "%s() arg is an empty sequence", name);
1388 assert(maxitem == NULL);
1389 }
1390 else
1391 Py_DECREF(maxval);
1392 Py_DECREF(it);
1393 Py_XDECREF(keyfunc);
1394 return maxitem;
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001395
1396Fail_it_item_and_val:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001397 Py_DECREF(val);
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001398Fail_it_item:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001399 Py_DECREF(item);
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001400Fail_it:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001401 Py_XDECREF(maxval);
1402 Py_XDECREF(maxitem);
1403 Py_DECREF(it);
1404 Py_XDECREF(keyfunc);
1405 return NULL;
Guido van Rossum3f5da241990-12-20 15:06:42 +00001406}
1407
Guido van Rossum79f25d91997-04-29 20:08:16 +00001408static PyObject *
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001409builtin_min(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001410{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001411 return min_max(args, kwds, Py_LT);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001412}
1413
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001414PyDoc_STRVAR(min_doc,
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001415"min(iterable[, key=func]) -> value\n\
1416min(a, b, c, ...[, key=func]) -> value\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001417\n\
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001418With a single iterable argument, return its smallest item.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001419With two or more arguments, return the smallest argument.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001420
1421
Guido van Rossum79f25d91997-04-29 20:08:16 +00001422static PyObject *
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001423builtin_max(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001424{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001425 return min_max(args, kwds, Py_GT);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001426}
1427
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001428PyDoc_STRVAR(max_doc,
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001429"max(iterable[, key=func]) -> value\n\
1430max(a, b, c, ...[, key=func]) -> value\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001431\n\
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001432With a single iterable argument, return its largest item.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001433With two or more arguments, return the largest argument.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001434
1435
Guido van Rossum79f25d91997-04-29 20:08:16 +00001436static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001437builtin_oct(PyObject *self, PyObject *v)
Guido van Rossum006bcd41991-10-24 14:54:44 +00001438{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001439 return PyNumber_ToBase(v, 8);
Guido van Rossum006bcd41991-10-24 14:54:44 +00001440}
1441
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001442PyDoc_STRVAR(oct_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001443"oct(number) -> string\n\
1444\n\
Alexander Belopolsky12338ab2011-04-07 00:15:33 -04001445Return the octal representation of an integer.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001446
1447
Guido van Rossum79f25d91997-04-29 20:08:16 +00001448static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001449builtin_ord(PyObject *self, PyObject* obj)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001450{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001451 long ord;
1452 Py_ssize_t size;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001453
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001454 if (PyBytes_Check(obj)) {
1455 size = PyBytes_GET_SIZE(obj);
1456 if (size == 1) {
1457 ord = (long)((unsigned char)*PyBytes_AS_STRING(obj));
1458 return PyLong_FromLong(ord);
1459 }
1460 }
1461 else if (PyUnicode_Check(obj)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001462 if (PyUnicode_READY(obj) == -1)
1463 return NULL;
1464 size = PyUnicode_GET_LENGTH(obj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001465 if (size == 1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001466 ord = (long)PyUnicode_READ_CHAR(obj, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001467 return PyLong_FromLong(ord);
1468 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001469 }
1470 else if (PyByteArray_Check(obj)) {
1471 /* XXX Hopefully this is temporary */
1472 size = PyByteArray_GET_SIZE(obj);
1473 if (size == 1) {
1474 ord = (long)((unsigned char)*PyByteArray_AS_STRING(obj));
1475 return PyLong_FromLong(ord);
1476 }
1477 }
1478 else {
1479 PyErr_Format(PyExc_TypeError,
1480 "ord() expected string of length 1, but " \
1481 "%.200s found", obj->ob_type->tp_name);
1482 return NULL;
1483 }
Guido van Rossum09095f32000-03-10 23:00:52 +00001484
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001485 PyErr_Format(PyExc_TypeError,
1486 "ord() expected a character, "
1487 "but string of length %zd found",
1488 size);
1489 return NULL;
Guido van Rossum3f5da241990-12-20 15:06:42 +00001490}
1491
Guido van Rossum307fa8c2007-07-16 20:46:27 +00001492PyDoc_VAR(ord_doc) = PyDoc_STR(
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001493"ord(c) -> integer\n\
1494\n\
Guido van Rossum8ac004e2007-07-15 13:00:05 +00001495Return the integer ordinal of a one-character string."
Antoine Pitrouedc60182012-06-23 14:19:58 +02001496);
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001497
1498
Guido van Rossum79f25d91997-04-29 20:08:16 +00001499static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001500builtin_pow(PyObject *self, PyObject *args)
Guido van Rossum6a00cd81995-01-07 12:39:01 +00001501{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001502 PyObject *v, *w, *z = Py_None;
Guido van Rossum6a00cd81995-01-07 12:39:01 +00001503
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001504 if (!PyArg_UnpackTuple(args, "pow", 2, 3, &v, &w, &z))
1505 return NULL;
1506 return PyNumber_Power(v, w, z);
Guido van Rossumd4905451991-05-05 20:00:36 +00001507}
1508
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001509PyDoc_STRVAR(pow_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001510"pow(x, y[, z]) -> number\n\
1511\n\
1512With two arguments, equivalent to x**y. With three arguments,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001513equivalent to (x**y) % z, but may be more efficient (e.g. for longs).");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001514
1515
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001516
Guido van Rossum34343512006-11-30 22:13:52 +00001517static PyObject *
1518builtin_print(PyObject *self, PyObject *args, PyObject *kwds)
1519{
Georg Brandlbc3b6822012-01-13 19:41:25 +01001520 static char *kwlist[] = {"sep", "end", "file", "flush", 0};
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001521 static PyObject *dummy_args;
Georg Brandlbc3b6822012-01-13 19:41:25 +01001522 PyObject *sep = NULL, *end = NULL, *file = NULL, *flush = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001523 int i, err;
Guido van Rossum34343512006-11-30 22:13:52 +00001524
Benjamin Peterson00102562012-01-11 21:00:16 -05001525 if (dummy_args == NULL && !(dummy_args = PyTuple_New(0)))
Georg Brandlbc3b6822012-01-13 19:41:25 +01001526 return NULL;
1527 if (!PyArg_ParseTupleAndKeywords(dummy_args, kwds, "|OOOO:print",
1528 kwlist, &sep, &end, &file, &flush))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001529 return NULL;
1530 if (file == NULL || file == Py_None) {
1531 file = PySys_GetObject("stdout");
1532 /* sys.stdout may be None when FILE* stdout isn't connected */
1533 if (file == Py_None)
1534 Py_RETURN_NONE;
1535 }
Guido van Rossum34343512006-11-30 22:13:52 +00001536
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001537 if (sep == Py_None) {
1538 sep = NULL;
1539 }
1540 else if (sep && !PyUnicode_Check(sep)) {
1541 PyErr_Format(PyExc_TypeError,
1542 "sep must be None or a string, not %.200s",
1543 sep->ob_type->tp_name);
1544 return NULL;
1545 }
1546 if (end == Py_None) {
1547 end = NULL;
1548 }
1549 else if (end && !PyUnicode_Check(end)) {
1550 PyErr_Format(PyExc_TypeError,
1551 "end must be None or a string, not %.200s",
1552 end->ob_type->tp_name);
1553 return NULL;
1554 }
Guido van Rossum34343512006-11-30 22:13:52 +00001555
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001556 for (i = 0; i < PyTuple_Size(args); i++) {
1557 if (i > 0) {
1558 if (sep == NULL)
1559 err = PyFile_WriteString(" ", file);
1560 else
1561 err = PyFile_WriteObject(sep, file,
1562 Py_PRINT_RAW);
1563 if (err)
1564 return NULL;
1565 }
1566 err = PyFile_WriteObject(PyTuple_GetItem(args, i), file,
1567 Py_PRINT_RAW);
1568 if (err)
1569 return NULL;
1570 }
Guido van Rossum34343512006-11-30 22:13:52 +00001571
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001572 if (end == NULL)
1573 err = PyFile_WriteString("\n", file);
1574 else
1575 err = PyFile_WriteObject(end, file, Py_PRINT_RAW);
1576 if (err)
1577 return NULL;
Guido van Rossum34343512006-11-30 22:13:52 +00001578
Georg Brandlbc3b6822012-01-13 19:41:25 +01001579 if (flush != NULL) {
1580 PyObject *tmp;
1581 int do_flush = PyObject_IsTrue(flush);
1582 if (do_flush == -1)
1583 return NULL;
1584 else if (do_flush) {
1585 tmp = PyObject_CallMethod(file, "flush", "");
1586 if (tmp == NULL)
1587 return NULL;
1588 else
1589 Py_DECREF(tmp);
1590 }
1591 }
1592
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001593 Py_RETURN_NONE;
Guido van Rossum34343512006-11-30 22:13:52 +00001594}
1595
1596PyDoc_STRVAR(print_doc,
Senthil Kumarane9175bd2012-08-10 13:53:45 -07001597"print(value, ..., sep=' ', end='\\n', file=sys.stdout, flush=False)\n\
Guido van Rossum34343512006-11-30 22:13:52 +00001598\n\
1599Prints the values to a stream, or to sys.stdout by default.\n\
1600Optional keyword arguments:\n\
Senthil Kumarane9175bd2012-08-10 13:53:45 -07001601file: a file-like object (stream); defaults to the current sys.stdout.\n\
1602sep: string inserted between values, default a space.\n\
1603end: string appended after the last value, default a newline.\n\
1604flush: whether to forcibly flush the stream.");
Guido van Rossum34343512006-11-30 22:13:52 +00001605
1606
Guido van Rossuma88a0332007-02-26 16:59:55 +00001607static PyObject *
1608builtin_input(PyObject *self, PyObject *args)
1609{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001610 PyObject *promptarg = NULL;
1611 PyObject *fin = PySys_GetObject("stdin");
1612 PyObject *fout = PySys_GetObject("stdout");
1613 PyObject *ferr = PySys_GetObject("stderr");
1614 PyObject *tmp;
1615 long fd;
1616 int tty;
Guido van Rossuma88a0332007-02-26 16:59:55 +00001617
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001618 /* Parse arguments */
1619 if (!PyArg_UnpackTuple(args, "input", 0, 1, &promptarg))
1620 return NULL;
Guido van Rossuma88a0332007-02-26 16:59:55 +00001621
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001622 /* Check that stdin/out/err are intact */
1623 if (fin == NULL || fin == Py_None) {
1624 PyErr_SetString(PyExc_RuntimeError,
1625 "input(): lost sys.stdin");
1626 return NULL;
1627 }
1628 if (fout == NULL || fout == Py_None) {
1629 PyErr_SetString(PyExc_RuntimeError,
1630 "input(): lost sys.stdout");
1631 return NULL;
1632 }
1633 if (ferr == NULL || ferr == Py_None) {
1634 PyErr_SetString(PyExc_RuntimeError,
1635 "input(): lost sys.stderr");
1636 return NULL;
1637 }
Guido van Rossumeba76962007-05-27 09:13:28 +00001638
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001639 /* First of all, flush stderr */
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001640 tmp = _PyObject_CallMethodId(ferr, &PyId_flush, "");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001641 if (tmp == NULL)
1642 PyErr_Clear();
1643 else
1644 Py_DECREF(tmp);
Guido van Rossumeba76962007-05-27 09:13:28 +00001645
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001646 /* We should only use (GNU) readline if Python's sys.stdin and
1647 sys.stdout are the same as C's stdin and stdout, because we
1648 need to pass it those. */
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001649 tmp = _PyObject_CallMethodId(fin, &PyId_fileno, "");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001650 if (tmp == NULL) {
1651 PyErr_Clear();
1652 tty = 0;
1653 }
1654 else {
1655 fd = PyLong_AsLong(tmp);
1656 Py_DECREF(tmp);
1657 if (fd < 0 && PyErr_Occurred())
1658 return NULL;
1659 tty = fd == fileno(stdin) && isatty(fd);
1660 }
1661 if (tty) {
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001662 tmp = _PyObject_CallMethodId(fout, &PyId_fileno, "");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001663 if (tmp == NULL)
1664 PyErr_Clear();
1665 else {
1666 fd = PyLong_AsLong(tmp);
1667 Py_DECREF(tmp);
1668 if (fd < 0 && PyErr_Occurred())
1669 return NULL;
1670 tty = fd == fileno(stdout) && isatty(fd);
1671 }
1672 }
Guido van Rossumeba76962007-05-27 09:13:28 +00001673
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001674 /* If we're interactive, use (GNU) readline */
1675 if (tty) {
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001676 PyObject *po = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001677 char *prompt;
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001678 char *s = NULL;
1679 PyObject *stdin_encoding = NULL, *stdin_errors = NULL;
1680 PyObject *stdout_encoding = NULL, *stdout_errors = NULL;
1681 char *stdin_encoding_str, *stdin_errors_str;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001682 PyObject *result;
Victor Stinnerc0f1a1a2011-02-23 12:07:37 +00001683 size_t len;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02001684 _Py_IDENTIFIER(encoding);
Antoine Pitrou5ee9d8a2011-11-06 00:38:45 +01001685 _Py_IDENTIFIER(errors);
Martin v. Löwis4a7b5d52007-09-04 05:24:49 +00001686
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02001687 stdin_encoding = _PyObject_GetAttrId(fin, &PyId_encoding);
Antoine Pitrou5ee9d8a2011-11-06 00:38:45 +01001688 stdin_errors = _PyObject_GetAttrId(fin, &PyId_errors);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001689 if (!stdin_encoding || !stdin_errors)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001690 /* stdin is a text stream, so it must have an
1691 encoding. */
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001692 goto _readline_errors;
Victor Stinner306f0102010-05-19 01:06:22 +00001693 stdin_encoding_str = _PyUnicode_AsString(stdin_encoding);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001694 stdin_errors_str = _PyUnicode_AsString(stdin_errors);
1695 if (!stdin_encoding_str || !stdin_errors_str)
1696 goto _readline_errors;
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001697 tmp = _PyObject_CallMethodId(fout, &PyId_flush, "");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001698 if (tmp == NULL)
1699 PyErr_Clear();
1700 else
1701 Py_DECREF(tmp);
1702 if (promptarg != NULL) {
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001703 /* We have a prompt, encode it as stdout would */
1704 char *stdout_encoding_str, *stdout_errors_str;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001705 PyObject *stringpo;
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02001706 stdout_encoding = _PyObject_GetAttrId(fout, &PyId_encoding);
Antoine Pitrou5ee9d8a2011-11-06 00:38:45 +01001707 stdout_errors = _PyObject_GetAttrId(fout, &PyId_errors);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001708 if (!stdout_encoding || !stdout_errors)
1709 goto _readline_errors;
Victor Stinner306f0102010-05-19 01:06:22 +00001710 stdout_encoding_str = _PyUnicode_AsString(stdout_encoding);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001711 stdout_errors_str = _PyUnicode_AsString(stdout_errors);
1712 if (!stdout_encoding_str || !stdout_errors_str)
1713 goto _readline_errors;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001714 stringpo = PyObject_Str(promptarg);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001715 if (stringpo == NULL)
1716 goto _readline_errors;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001717 po = PyUnicode_AsEncodedString(stringpo,
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001718 stdout_encoding_str, stdout_errors_str);
1719 Py_CLEAR(stdout_encoding);
1720 Py_CLEAR(stdout_errors);
1721 Py_CLEAR(stringpo);
1722 if (po == NULL)
1723 goto _readline_errors;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001724 prompt = PyBytes_AsString(po);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001725 if (prompt == NULL)
1726 goto _readline_errors;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001727 }
1728 else {
1729 po = NULL;
1730 prompt = "";
1731 }
1732 s = PyOS_Readline(stdin, stdout, prompt);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001733 if (s == NULL) {
1734 if (!PyErr_Occurred())
1735 PyErr_SetNone(PyExc_KeyboardInterrupt);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001736 goto _readline_errors;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001737 }
Victor Stinnerc0f1a1a2011-02-23 12:07:37 +00001738
1739 len = strlen(s);
1740 if (len == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001741 PyErr_SetNone(PyExc_EOFError);
1742 result = NULL;
1743 }
Victor Stinnerc0f1a1a2011-02-23 12:07:37 +00001744 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001745 if (len > PY_SSIZE_T_MAX) {
1746 PyErr_SetString(PyExc_OverflowError,
1747 "input: input too long");
1748 result = NULL;
1749 }
1750 else {
Victor Stinnerc0f1a1a2011-02-23 12:07:37 +00001751 len--; /* strip trailing '\n' */
1752 if (len != 0 && s[len-1] == '\r')
1753 len--; /* strip trailing '\r' */
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001754 result = PyUnicode_Decode(s, len, stdin_encoding_str,
1755 stdin_errors_str);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001756 }
1757 }
1758 Py_DECREF(stdin_encoding);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001759 Py_DECREF(stdin_errors);
1760 Py_XDECREF(po);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001761 PyMem_FREE(s);
1762 return result;
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001763 _readline_errors:
1764 Py_XDECREF(stdin_encoding);
1765 Py_XDECREF(stdout_encoding);
1766 Py_XDECREF(stdin_errors);
1767 Py_XDECREF(stdout_errors);
1768 Py_XDECREF(po);
1769 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001770 }
Guido van Rossumeba76962007-05-27 09:13:28 +00001771
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001772 /* Fallback if we're not interactive */
1773 if (promptarg != NULL) {
1774 if (PyFile_WriteObject(promptarg, fout, Py_PRINT_RAW) != 0)
1775 return NULL;
1776 }
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001777 tmp = _PyObject_CallMethodId(fout, &PyId_flush, "");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001778 if (tmp == NULL)
1779 PyErr_Clear();
1780 else
1781 Py_DECREF(tmp);
1782 return PyFile_GetLine(fin, -1);
Guido van Rossuma88a0332007-02-26 16:59:55 +00001783}
1784
1785PyDoc_STRVAR(input_doc,
1786"input([prompt]) -> string\n\
1787\n\
1788Read a string from standard input. The trailing newline is stripped.\n\
1789If the user hits EOF (Unix: Ctl-D, Windows: Ctl-Z+Return), raise EOFError.\n\
1790On Unix, GNU readline is used if enabled. The prompt string, if given,\n\
1791is printed without a trailing newline before reading.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001792
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001793
Guido van Rossum79f25d91997-04-29 20:08:16 +00001794static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001795builtin_repr(PyObject *self, PyObject *v)
Guido van Rossumc89705d1992-11-26 08:54:07 +00001796{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001797 return PyObject_Repr(v);
Guido van Rossumc89705d1992-11-26 08:54:07 +00001798}
1799
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001800PyDoc_STRVAR(repr_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001801"repr(object) -> string\n\
1802\n\
1803Return the canonical string representation of the object.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001804For most object types, eval(repr(object)) == object.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001805
1806
Guido van Rossum79f25d91997-04-29 20:08:16 +00001807static PyObject *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001808builtin_round(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum9e51f9b1993-02-12 16:29:05 +00001809{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001810 static PyObject *round_str = NULL;
1811 PyObject *ndigits = NULL;
1812 static char *kwlist[] = {"number", "ndigits", 0};
1813 PyObject *number, *round;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001814
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001815 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|O:round",
1816 kwlist, &number, &ndigits))
1817 return NULL;
Alex Martelliae211f92007-08-22 23:21:33 +00001818
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001819 if (Py_TYPE(number)->tp_dict == NULL) {
1820 if (PyType_Ready(Py_TYPE(number)) < 0)
1821 return NULL;
1822 }
Guido van Rossum15d3d042007-08-24 02:02:45 +00001823
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001824 if (round_str == NULL) {
1825 round_str = PyUnicode_InternFromString("__round__");
1826 if (round_str == NULL)
1827 return NULL;
1828 }
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001829
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001830 round = _PyType_Lookup(Py_TYPE(number), round_str);
1831 if (round == NULL) {
1832 PyErr_Format(PyExc_TypeError,
1833 "type %.100s doesn't define __round__ method",
1834 Py_TYPE(number)->tp_name);
1835 return NULL;
1836 }
Alex Martelliae211f92007-08-22 23:21:33 +00001837
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001838 if (ndigits == NULL)
1839 return PyObject_CallFunction(round, "O", number);
1840 else
1841 return PyObject_CallFunction(round, "OO", number, ndigits);
Guido van Rossum9e51f9b1993-02-12 16:29:05 +00001842}
1843
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001844PyDoc_STRVAR(round_doc,
Mark Dickinson1124e712009-01-28 21:25:58 +00001845"round(number[, ndigits]) -> number\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001846\n\
1847Round a number to a given precision in decimal digits (default 0 digits).\n\
Mark Dickinson0d748c22008-07-05 11:29:03 +00001848This returns an int when called with one argument, otherwise the\n\
Georg Brandl809ddaa2008-07-01 20:39:59 +00001849same type as the number. ndigits may be negative.");
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001850
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001851
Raymond Hettinger64958a12003-12-17 20:43:33 +00001852static PyObject *
1853builtin_sorted(PyObject *self, PyObject *args, PyObject *kwds)
1854{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001855 PyObject *newlist, *v, *seq, *keyfunc=NULL, *newargs;
1856 PyObject *callable;
1857 static char *kwlist[] = {"iterable", "key", "reverse", 0};
1858 int reverse;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02001859 _Py_IDENTIFIER(sort);
Raymond Hettinger64958a12003-12-17 20:43:33 +00001860
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001861 /* args 1-3 should match listsort in Objects/listobject.c */
1862 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|Oi:sorted",
1863 kwlist, &seq, &keyfunc, &reverse))
1864 return NULL;
Raymond Hettinger64958a12003-12-17 20:43:33 +00001865
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001866 newlist = PySequence_List(seq);
1867 if (newlist == NULL)
1868 return NULL;
Raymond Hettinger64958a12003-12-17 20:43:33 +00001869
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02001870 callable = _PyObject_GetAttrId(newlist, &PyId_sort);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001871 if (callable == NULL) {
1872 Py_DECREF(newlist);
1873 return NULL;
1874 }
Georg Brandl99d7e4e2005-08-31 22:21:15 +00001875
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001876 newargs = PyTuple_GetSlice(args, 1, 4);
1877 if (newargs == NULL) {
1878 Py_DECREF(newlist);
1879 Py_DECREF(callable);
1880 return NULL;
1881 }
Raymond Hettinger64958a12003-12-17 20:43:33 +00001882
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001883 v = PyObject_Call(callable, newargs, kwds);
1884 Py_DECREF(newargs);
1885 Py_DECREF(callable);
1886 if (v == NULL) {
1887 Py_DECREF(newlist);
1888 return NULL;
1889 }
1890 Py_DECREF(v);
1891 return newlist;
Raymond Hettinger64958a12003-12-17 20:43:33 +00001892}
1893
1894PyDoc_STRVAR(sorted_doc,
Raymond Hettinger70b64fc2008-01-30 20:15:17 +00001895"sorted(iterable, key=None, reverse=False) --> new sorted list");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001896
Guido van Rossum79f25d91997-04-29 20:08:16 +00001897static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001898builtin_vars(PyObject *self, PyObject *args)
Guido van Rossum2d951851994-08-29 12:52:16 +00001899{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001900 PyObject *v = NULL;
1901 PyObject *d;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001902
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001903 if (!PyArg_UnpackTuple(args, "vars", 0, 1, &v))
1904 return NULL;
1905 if (v == NULL) {
1906 d = PyEval_GetLocals();
1907 if (d == NULL) {
1908 if (!PyErr_Occurred())
1909 PyErr_SetString(PyExc_SystemError,
1910 "vars(): no locals!?");
1911 }
1912 else
1913 Py_INCREF(d);
1914 }
1915 else {
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02001916 _Py_IDENTIFIER(__dict__);
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02001917 d = _PyObject_GetAttrId(v, &PyId___dict__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001918 if (d == NULL) {
1919 PyErr_SetString(PyExc_TypeError,
1920 "vars() argument must have __dict__ attribute");
1921 return NULL;
1922 }
1923 }
1924 return d;
Guido van Rossum2d951851994-08-29 12:52:16 +00001925}
1926
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001927PyDoc_STRVAR(vars_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001928"vars([object]) -> dictionary\n\
1929\n\
1930Without arguments, equivalent to locals().\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001931With an argument, equivalent to object.__dict__.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001932
Alex Martellia70b1912003-04-22 08:12:33 +00001933static PyObject*
1934builtin_sum(PyObject *self, PyObject *args)
1935{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001936 PyObject *seq;
1937 PyObject *result = NULL;
1938 PyObject *temp, *item, *iter;
Alex Martellia70b1912003-04-22 08:12:33 +00001939
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001940 if (!PyArg_UnpackTuple(args, "sum", 1, 2, &seq, &result))
1941 return NULL;
Alex Martellia70b1912003-04-22 08:12:33 +00001942
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001943 iter = PyObject_GetIter(seq);
1944 if (iter == NULL)
1945 return NULL;
Alex Martellia70b1912003-04-22 08:12:33 +00001946
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001947 if (result == NULL) {
1948 result = PyLong_FromLong(0);
1949 if (result == NULL) {
1950 Py_DECREF(iter);
1951 return NULL;
1952 }
1953 } else {
1954 /* reject string values for 'start' parameter */
1955 if (PyUnicode_Check(result)) {
1956 PyErr_SetString(PyExc_TypeError,
1957 "sum() can't sum strings [use ''.join(seq) instead]");
1958 Py_DECREF(iter);
1959 return NULL;
1960 }
Benjamin Petersonce071ca2011-07-29 14:23:47 -05001961 if (PyBytes_Check(result)) {
1962 PyErr_SetString(PyExc_TypeError,
1963 "sum() can't sum bytes [use b''.join(seq) instead]");
Benjamin Peterson405f32c2011-07-29 22:43:45 -05001964 Py_DECREF(iter);
Benjamin Petersonce071ca2011-07-29 14:23:47 -05001965 return NULL;
1966 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001967 if (PyByteArray_Check(result)) {
1968 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson4f921c22011-07-29 14:24:29 -05001969 "sum() can't sum bytearray [use b''.join(seq) instead]");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001970 Py_DECREF(iter);
1971 return NULL;
1972 }
Guido van Rossum3172c5d2007-10-16 18:12:55 +00001973
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001974 Py_INCREF(result);
1975 }
Alex Martellia70b1912003-04-22 08:12:33 +00001976
Guido van Rossum8ce8a782007-11-01 19:42:39 +00001977#ifndef SLOW_SUM
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001978 /* Fast addition by keeping temporary sums in C instead of new Python objects.
1979 Assumes all inputs are the same type. If the assumption fails, default
1980 to the more general routine.
1981 */
1982 if (PyLong_CheckExact(result)) {
1983 int overflow;
1984 long i_result = PyLong_AsLongAndOverflow(result, &overflow);
1985 /* If this already overflowed, don't even enter the loop. */
1986 if (overflow == 0) {
1987 Py_DECREF(result);
1988 result = NULL;
1989 }
1990 while(result == NULL) {
1991 item = PyIter_Next(iter);
1992 if (item == NULL) {
1993 Py_DECREF(iter);
1994 if (PyErr_Occurred())
1995 return NULL;
1996 return PyLong_FromLong(i_result);
1997 }
1998 if (PyLong_CheckExact(item)) {
1999 long b = PyLong_AsLongAndOverflow(item, &overflow);
2000 long x = i_result + b;
2001 if (overflow == 0 && ((x^i_result) >= 0 || (x^b) >= 0)) {
2002 i_result = x;
2003 Py_DECREF(item);
2004 continue;
2005 }
2006 }
2007 /* Either overflowed or is not an int. Restore real objects and process normally */
2008 result = PyLong_FromLong(i_result);
2009 temp = PyNumber_Add(result, item);
2010 Py_DECREF(result);
2011 Py_DECREF(item);
2012 result = temp;
2013 if (result == NULL) {
2014 Py_DECREF(iter);
2015 return NULL;
2016 }
2017 }
2018 }
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002019
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002020 if (PyFloat_CheckExact(result)) {
2021 double f_result = PyFloat_AS_DOUBLE(result);
2022 Py_DECREF(result);
2023 result = NULL;
2024 while(result == NULL) {
2025 item = PyIter_Next(iter);
2026 if (item == NULL) {
2027 Py_DECREF(iter);
2028 if (PyErr_Occurred())
2029 return NULL;
2030 return PyFloat_FromDouble(f_result);
2031 }
2032 if (PyFloat_CheckExact(item)) {
2033 PyFPE_START_PROTECT("add", Py_DECREF(item); Py_DECREF(iter); return 0)
2034 f_result += PyFloat_AS_DOUBLE(item);
2035 PyFPE_END_PROTECT(f_result)
2036 Py_DECREF(item);
2037 continue;
2038 }
2039 if (PyLong_CheckExact(item)) {
2040 long value;
2041 int overflow;
2042 value = PyLong_AsLongAndOverflow(item, &overflow);
2043 if (!overflow) {
2044 PyFPE_START_PROTECT("add", Py_DECREF(item); Py_DECREF(iter); return 0)
2045 f_result += (double)value;
2046 PyFPE_END_PROTECT(f_result)
2047 Py_DECREF(item);
2048 continue;
2049 }
2050 }
2051 result = PyFloat_FromDouble(f_result);
2052 temp = PyNumber_Add(result, item);
2053 Py_DECREF(result);
2054 Py_DECREF(item);
2055 result = temp;
2056 if (result == NULL) {
2057 Py_DECREF(iter);
2058 return NULL;
2059 }
2060 }
2061 }
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002062#endif
2063
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002064 for(;;) {
2065 item = PyIter_Next(iter);
2066 if (item == NULL) {
2067 /* error, or end-of-sequence */
2068 if (PyErr_Occurred()) {
2069 Py_DECREF(result);
2070 result = NULL;
2071 }
2072 break;
2073 }
2074 /* It's tempting to use PyNumber_InPlaceAdd instead of
2075 PyNumber_Add here, to avoid quadratic running time
2076 when doing 'sum(list_of_lists, [])'. However, this
2077 would produce a change in behaviour: a snippet like
Mark Dickinson9acadc52009-10-26 14:19:42 +00002078
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002079 empty = []
2080 sum([[x] for x in range(10)], empty)
Mark Dickinson9acadc52009-10-26 14:19:42 +00002081
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002082 would change the value of empty. */
2083 temp = PyNumber_Add(result, item);
2084 Py_DECREF(result);
2085 Py_DECREF(item);
2086 result = temp;
2087 if (result == NULL)
2088 break;
2089 }
2090 Py_DECREF(iter);
2091 return result;
Alex Martellia70b1912003-04-22 08:12:33 +00002092}
2093
2094PyDoc_STRVAR(sum_doc,
Georg Brandld11ae5d2008-05-16 13:27:32 +00002095"sum(iterable[, start]) -> value\n\
Alex Martellia70b1912003-04-22 08:12:33 +00002096\n\
Georg Brandld11ae5d2008-05-16 13:27:32 +00002097Returns the sum of an iterable of numbers (NOT strings) plus the value\n\
2098of parameter 'start' (which defaults to 0). When the iterable is\n\
Thomas Wouters89f507f2006-12-13 04:49:30 +00002099empty, returns start.");
Alex Martellia70b1912003-04-22 08:12:33 +00002100
2101
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002102static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002103builtin_isinstance(PyObject *self, PyObject *args)
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002104{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002105 PyObject *inst;
2106 PyObject *cls;
2107 int retval;
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002108
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002109 if (!PyArg_UnpackTuple(args, "isinstance", 2, 2, &inst, &cls))
2110 return NULL;
Guido van Rossumf5dd9141997-12-02 19:11:45 +00002111
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002112 retval = PyObject_IsInstance(inst, cls);
2113 if (retval < 0)
2114 return NULL;
2115 return PyBool_FromLong(retval);
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002116}
2117
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002118PyDoc_STRVAR(isinstance_doc,
Guido van Rossum77f6a652002-04-03 22:41:51 +00002119"isinstance(object, class-or-type-or-tuple) -> bool\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002120\n\
2121Return whether an object is an instance of a class or of a subclass thereof.\n\
Guido van Rossum03290ec2001-10-07 20:54:12 +00002122With a type as second argument, return whether that is the object's type.\n\
2123The form using a tuple, isinstance(x, (A, B, ...)), is a shortcut for\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002124isinstance(x, A) or isinstance(x, B) or ... (etc.).");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002125
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002126
2127static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002128builtin_issubclass(PyObject *self, PyObject *args)
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002129{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002130 PyObject *derived;
2131 PyObject *cls;
2132 int retval;
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002133
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002134 if (!PyArg_UnpackTuple(args, "issubclass", 2, 2, &derived, &cls))
2135 return NULL;
Guido van Rossum668213d1999-06-16 17:28:37 +00002136
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002137 retval = PyObject_IsSubclass(derived, cls);
2138 if (retval < 0)
2139 return NULL;
2140 return PyBool_FromLong(retval);
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002141}
2142
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002143PyDoc_STRVAR(issubclass_doc,
Guido van Rossum77f6a652002-04-03 22:41:51 +00002144"issubclass(C, B) -> bool\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002145\n\
Walter Dörwaldd9a6ad32002-12-12 16:41:44 +00002146Return whether class C is a subclass (i.e., a derived class) of class B.\n\
2147When using a tuple as the second argument issubclass(X, (A, B, ...)),\n\
2148is a shortcut for issubclass(X, A) or issubclass(X, B) or ... (etc.).");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002149
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002150
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002151typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002152 PyObject_HEAD
2153 Py_ssize_t tuplesize;
2154 PyObject *ittuple; /* tuple of iterators */
2155 PyObject *result;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002156} zipobject;
2157
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002158static PyObject *
2159zip_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
Barry Warsawbd599b52000-08-03 15:45:29 +00002160{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002161 zipobject *lz;
2162 Py_ssize_t i;
2163 PyObject *ittuple; /* tuple of iterators */
2164 PyObject *result;
2165 Py_ssize_t tuplesize = PySequence_Length(args);
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002166
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002167 if (type == &PyZip_Type && !_PyArg_NoKeywords("zip()", kwds))
2168 return NULL;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002169
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002170 /* args must be a tuple */
2171 assert(PyTuple_Check(args));
Barry Warsawbd599b52000-08-03 15:45:29 +00002172
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002173 /* obtain iterators */
2174 ittuple = PyTuple_New(tuplesize);
2175 if (ittuple == NULL)
2176 return NULL;
2177 for (i=0; i < tuplesize; ++i) {
2178 PyObject *item = PyTuple_GET_ITEM(args, i);
2179 PyObject *it = PyObject_GetIter(item);
2180 if (it == NULL) {
2181 if (PyErr_ExceptionMatches(PyExc_TypeError))
2182 PyErr_Format(PyExc_TypeError,
2183 "zip argument #%zd must support iteration",
2184 i+1);
2185 Py_DECREF(ittuple);
2186 return NULL;
2187 }
2188 PyTuple_SET_ITEM(ittuple, i, it);
2189 }
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002190
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002191 /* create a result holder */
2192 result = PyTuple_New(tuplesize);
2193 if (result == NULL) {
2194 Py_DECREF(ittuple);
2195 return NULL;
2196 }
2197 for (i=0 ; i < tuplesize ; i++) {
2198 Py_INCREF(Py_None);
2199 PyTuple_SET_ITEM(result, i, Py_None);
2200 }
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002201
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002202 /* create zipobject structure */
2203 lz = (zipobject *)type->tp_alloc(type, 0);
2204 if (lz == NULL) {
2205 Py_DECREF(ittuple);
2206 Py_DECREF(result);
2207 return NULL;
2208 }
2209 lz->ittuple = ittuple;
2210 lz->tuplesize = tuplesize;
2211 lz->result = result;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002212
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002213 return (PyObject *)lz;
Barry Warsawbd599b52000-08-03 15:45:29 +00002214}
2215
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002216static void
2217zip_dealloc(zipobject *lz)
2218{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002219 PyObject_GC_UnTrack(lz);
2220 Py_XDECREF(lz->ittuple);
2221 Py_XDECREF(lz->result);
2222 Py_TYPE(lz)->tp_free(lz);
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002223}
2224
2225static int
2226zip_traverse(zipobject *lz, visitproc visit, void *arg)
2227{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002228 Py_VISIT(lz->ittuple);
2229 Py_VISIT(lz->result);
2230 return 0;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002231}
2232
2233static PyObject *
2234zip_next(zipobject *lz)
2235{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002236 Py_ssize_t i;
2237 Py_ssize_t tuplesize = lz->tuplesize;
2238 PyObject *result = lz->result;
2239 PyObject *it;
2240 PyObject *item;
2241 PyObject *olditem;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002242
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002243 if (tuplesize == 0)
2244 return NULL;
2245 if (Py_REFCNT(result) == 1) {
2246 Py_INCREF(result);
2247 for (i=0 ; i < tuplesize ; i++) {
2248 it = PyTuple_GET_ITEM(lz->ittuple, i);
2249 item = (*Py_TYPE(it)->tp_iternext)(it);
2250 if (item == NULL) {
2251 Py_DECREF(result);
2252 return NULL;
2253 }
2254 olditem = PyTuple_GET_ITEM(result, i);
2255 PyTuple_SET_ITEM(result, i, item);
2256 Py_DECREF(olditem);
2257 }
2258 } else {
2259 result = PyTuple_New(tuplesize);
2260 if (result == NULL)
2261 return NULL;
2262 for (i=0 ; i < tuplesize ; i++) {
2263 it = PyTuple_GET_ITEM(lz->ittuple, i);
2264 item = (*Py_TYPE(it)->tp_iternext)(it);
2265 if (item == NULL) {
2266 Py_DECREF(result);
2267 return NULL;
2268 }
2269 PyTuple_SET_ITEM(result, i, item);
2270 }
2271 }
2272 return result;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002273}
Barry Warsawbd599b52000-08-03 15:45:29 +00002274
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002275static PyObject *
2276zip_reduce(zipobject *lz)
2277{
2278 /* Just recreate the zip with the internal iterator tuple */
2279 return Py_BuildValue("OO", Py_TYPE(lz), lz->ittuple);
2280}
2281
2282static PyMethodDef zip_methods[] = {
2283 {"__reduce__", (PyCFunction)zip_reduce, METH_NOARGS, reduce_doc},
2284 {NULL, NULL} /* sentinel */
2285};
2286
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002287PyDoc_STRVAR(zip_doc,
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002288"zip(iter1 [,iter2 [...]]) --> zip object\n\
Barry Warsawbd599b52000-08-03 15:45:29 +00002289\n\
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002290Return a zip object whose .__next__() method returns a tuple where\n\
2291the i-th element comes from the i-th iterable argument. The .__next__()\n\
2292method continues until the shortest iterable in the argument sequence\n\
Georg Brandlced51db2008-12-04 18:28:38 +00002293is exhausted and then it raises StopIteration.");
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002294
2295PyTypeObject PyZip_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002296 PyVarObject_HEAD_INIT(&PyType_Type, 0)
2297 "zip", /* tp_name */
2298 sizeof(zipobject), /* tp_basicsize */
2299 0, /* tp_itemsize */
2300 /* methods */
2301 (destructor)zip_dealloc, /* tp_dealloc */
2302 0, /* tp_print */
2303 0, /* tp_getattr */
2304 0, /* tp_setattr */
2305 0, /* tp_reserved */
2306 0, /* tp_repr */
2307 0, /* tp_as_number */
2308 0, /* tp_as_sequence */
2309 0, /* tp_as_mapping */
2310 0, /* tp_hash */
2311 0, /* tp_call */
2312 0, /* tp_str */
2313 PyObject_GenericGetAttr, /* tp_getattro */
2314 0, /* tp_setattro */
2315 0, /* tp_as_buffer */
2316 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
2317 Py_TPFLAGS_BASETYPE, /* tp_flags */
2318 zip_doc, /* tp_doc */
2319 (traverseproc)zip_traverse, /* tp_traverse */
2320 0, /* tp_clear */
2321 0, /* tp_richcompare */
2322 0, /* tp_weaklistoffset */
2323 PyObject_SelfIter, /* tp_iter */
2324 (iternextfunc)zip_next, /* tp_iternext */
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002325 zip_methods, /* tp_methods */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002326 0, /* tp_members */
2327 0, /* tp_getset */
2328 0, /* tp_base */
2329 0, /* tp_dict */
2330 0, /* tp_descr_get */
2331 0, /* tp_descr_set */
2332 0, /* tp_dictoffset */
2333 0, /* tp_init */
2334 PyType_GenericAlloc, /* tp_alloc */
2335 zip_new, /* tp_new */
2336 PyObject_GC_Del, /* tp_free */
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002337};
Barry Warsawbd599b52000-08-03 15:45:29 +00002338
2339
Guido van Rossum79f25d91997-04-29 20:08:16 +00002340static PyMethodDef builtin_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002341 {"__build_class__", (PyCFunction)builtin___build_class__,
2342 METH_VARARGS | METH_KEYWORDS, build_class_doc},
2343 {"__import__", (PyCFunction)builtin___import__, METH_VARARGS | METH_KEYWORDS, import_doc},
2344 {"abs", builtin_abs, METH_O, abs_doc},
2345 {"all", builtin_all, METH_O, all_doc},
2346 {"any", builtin_any, METH_O, any_doc},
2347 {"ascii", builtin_ascii, METH_O, ascii_doc},
2348 {"bin", builtin_bin, METH_O, bin_doc},
Antoine Pitroue71362d2010-11-27 22:00:11 +00002349 {"callable", builtin_callable, METH_O, callable_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002350 {"chr", builtin_chr, METH_VARARGS, chr_doc},
2351 {"compile", (PyCFunction)builtin_compile, METH_VARARGS | METH_KEYWORDS, compile_doc},
2352 {"delattr", builtin_delattr, METH_VARARGS, delattr_doc},
2353 {"dir", builtin_dir, METH_VARARGS, dir_doc},
2354 {"divmod", builtin_divmod, METH_VARARGS, divmod_doc},
2355 {"eval", builtin_eval, METH_VARARGS, eval_doc},
2356 {"exec", builtin_exec, METH_VARARGS, exec_doc},
2357 {"format", builtin_format, METH_VARARGS, format_doc},
2358 {"getattr", builtin_getattr, METH_VARARGS, getattr_doc},
2359 {"globals", (PyCFunction)builtin_globals, METH_NOARGS, globals_doc},
2360 {"hasattr", builtin_hasattr, METH_VARARGS, hasattr_doc},
2361 {"hash", builtin_hash, METH_O, hash_doc},
2362 {"hex", builtin_hex, METH_O, hex_doc},
2363 {"id", builtin_id, METH_O, id_doc},
2364 {"input", builtin_input, METH_VARARGS, input_doc},
2365 {"isinstance", builtin_isinstance, METH_VARARGS, isinstance_doc},
2366 {"issubclass", builtin_issubclass, METH_VARARGS, issubclass_doc},
2367 {"iter", builtin_iter, METH_VARARGS, iter_doc},
2368 {"len", builtin_len, METH_O, len_doc},
2369 {"locals", (PyCFunction)builtin_locals, METH_NOARGS, locals_doc},
2370 {"max", (PyCFunction)builtin_max, METH_VARARGS | METH_KEYWORDS, max_doc},
2371 {"min", (PyCFunction)builtin_min, METH_VARARGS | METH_KEYWORDS, min_doc},
2372 {"next", (PyCFunction)builtin_next, METH_VARARGS, next_doc},
2373 {"oct", builtin_oct, METH_O, oct_doc},
2374 {"ord", builtin_ord, METH_O, ord_doc},
2375 {"pow", builtin_pow, METH_VARARGS, pow_doc},
2376 {"print", (PyCFunction)builtin_print, METH_VARARGS | METH_KEYWORDS, print_doc},
2377 {"repr", builtin_repr, METH_O, repr_doc},
2378 {"round", (PyCFunction)builtin_round, METH_VARARGS | METH_KEYWORDS, round_doc},
2379 {"setattr", builtin_setattr, METH_VARARGS, setattr_doc},
2380 {"sorted", (PyCFunction)builtin_sorted, METH_VARARGS | METH_KEYWORDS, sorted_doc},
2381 {"sum", builtin_sum, METH_VARARGS, sum_doc},
2382 {"vars", builtin_vars, METH_VARARGS, vars_doc},
2383 {NULL, NULL},
Guido van Rossum3f5da241990-12-20 15:06:42 +00002384};
2385
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002386PyDoc_STRVAR(builtin_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002387"Built-in functions, exceptions, and other objects.\n\
2388\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002389Noteworthy: None is the `nil' object; Ellipsis represents `...' in slices.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002390
Martin v. Löwis1a214512008-06-11 05:26:20 +00002391static struct PyModuleDef builtinsmodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002392 PyModuleDef_HEAD_INIT,
2393 "builtins",
2394 builtin_doc,
2395 -1, /* multiple "initialization" just copies the module dict. */
2396 builtin_methods,
2397 NULL,
2398 NULL,
2399 NULL,
2400 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00002401};
2402
2403
Guido van Rossum25ce5661997-08-02 03:10:38 +00002404PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002405_PyBuiltin_Init(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +00002406{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002407 PyObject *mod, *dict, *debug;
2408 mod = PyModule_Create(&builtinsmodule);
2409 if (mod == NULL)
2410 return NULL;
2411 dict = PyModule_GetDict(mod);
Tim Peters4b7625e2001-09-13 21:37:17 +00002412
Tim Peters7571a0f2003-03-23 17:52:28 +00002413#ifdef Py_TRACE_REFS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002414 /* "builtins" exposes a number of statically allocated objects
2415 * that, before this code was added in 2.3, never showed up in
2416 * the list of "all objects" maintained by Py_TRACE_REFS. As a
2417 * result, programs leaking references to None and False (etc)
2418 * couldn't be diagnosed by examining sys.getobjects(0).
2419 */
Tim Peters7571a0f2003-03-23 17:52:28 +00002420#define ADD_TO_ALL(OBJECT) _Py_AddToAllObjects((PyObject *)(OBJECT), 0)
2421#else
2422#define ADD_TO_ALL(OBJECT) (void)0
2423#endif
2424
Tim Peters4b7625e2001-09-13 21:37:17 +00002425#define SETBUILTIN(NAME, OBJECT) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002426 if (PyDict_SetItemString(dict, NAME, (PyObject *)OBJECT) < 0) \
2427 return NULL; \
2428 ADD_TO_ALL(OBJECT)
Tim Peters4b7625e2001-09-13 21:37:17 +00002429
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002430 SETBUILTIN("None", Py_None);
2431 SETBUILTIN("Ellipsis", Py_Ellipsis);
2432 SETBUILTIN("NotImplemented", Py_NotImplemented);
2433 SETBUILTIN("False", Py_False);
2434 SETBUILTIN("True", Py_True);
2435 SETBUILTIN("bool", &PyBool_Type);
2436 SETBUILTIN("memoryview", &PyMemoryView_Type);
2437 SETBUILTIN("bytearray", &PyByteArray_Type);
2438 SETBUILTIN("bytes", &PyBytes_Type);
2439 SETBUILTIN("classmethod", &PyClassMethod_Type);
2440 SETBUILTIN("complex", &PyComplex_Type);
2441 SETBUILTIN("dict", &PyDict_Type);
2442 SETBUILTIN("enumerate", &PyEnum_Type);
2443 SETBUILTIN("filter", &PyFilter_Type);
2444 SETBUILTIN("float", &PyFloat_Type);
2445 SETBUILTIN("frozenset", &PyFrozenSet_Type);
2446 SETBUILTIN("property", &PyProperty_Type);
2447 SETBUILTIN("int", &PyLong_Type);
2448 SETBUILTIN("list", &PyList_Type);
2449 SETBUILTIN("map", &PyMap_Type);
2450 SETBUILTIN("object", &PyBaseObject_Type);
2451 SETBUILTIN("range", &PyRange_Type);
2452 SETBUILTIN("reversed", &PyReversed_Type);
2453 SETBUILTIN("set", &PySet_Type);
2454 SETBUILTIN("slice", &PySlice_Type);
2455 SETBUILTIN("staticmethod", &PyStaticMethod_Type);
2456 SETBUILTIN("str", &PyUnicode_Type);
2457 SETBUILTIN("super", &PySuper_Type);
2458 SETBUILTIN("tuple", &PyTuple_Type);
2459 SETBUILTIN("type", &PyType_Type);
2460 SETBUILTIN("zip", &PyZip_Type);
2461 debug = PyBool_FromLong(Py_OptimizeFlag == 0);
2462 if (PyDict_SetItemString(dict, "__debug__", debug) < 0) {
2463 Py_XDECREF(debug);
2464 return NULL;
2465 }
2466 Py_XDECREF(debug);
Barry Warsaw757af0e1997-08-29 22:13:51 +00002467
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002468 return mod;
Tim Peters7571a0f2003-03-23 17:52:28 +00002469#undef ADD_TO_ALL
Tim Peters4b7625e2001-09-13 21:37:17 +00002470#undef SETBUILTIN
Guido van Rossum3f5da241990-12-20 15:06:42 +00002471}