blob: 88b48c0fa681b0f32ebb433b141cb13f5008802e [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 Hammond26cffde2001-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 Hammond26cffde2001-05-14 12:17:34 +000023*/
Victor Stinner99b95382011-07-04 14:23:54 +020024#ifdef HAVE_MBCS
Mark Hammond26cffde2001-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 Hammond26cffde2001-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 }
432 if (ok)
433 return item;
434 Py_DECREF(item);
435 }
Guido van Rossum12d12c51993-10-26 17:58:25 +0000436}
437
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +0000438static PyObject *
439filter_reduce(filterobject *lz)
440{
441 return Py_BuildValue("O(OO)", Py_TYPE(lz), lz->func, lz->it);
442}
443
444PyDoc_STRVAR(reduce_doc, "Return state information for pickling.");
445
446static PyMethodDef filter_methods[] = {
447 {"__reduce__", (PyCFunction)filter_reduce, METH_NOARGS, reduce_doc},
448 {NULL, NULL} /* sentinel */
449};
450
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000451PyDoc_STRVAR(filter_doc,
Georg Brandld11ae5d2008-05-16 13:27:32 +0000452"filter(function or None, iterable) --> filter object\n\
Guido van Rossumc1f779c2007-07-03 08:25:58 +0000453\n\
Georg Brandld11ae5d2008-05-16 13:27:32 +0000454Return an iterator yielding those items of iterable for which function(item)\n\
Raymond Hettinger17301e92008-03-13 00:19:26 +0000455is true. If function is None, return the items that are true.");
456
457PyTypeObject PyFilter_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000458 PyVarObject_HEAD_INIT(&PyType_Type, 0)
459 "filter", /* tp_name */
460 sizeof(filterobject), /* tp_basicsize */
461 0, /* tp_itemsize */
462 /* methods */
463 (destructor)filter_dealloc, /* tp_dealloc */
464 0, /* tp_print */
465 0, /* tp_getattr */
466 0, /* tp_setattr */
467 0, /* tp_reserved */
468 0, /* tp_repr */
469 0, /* tp_as_number */
470 0, /* tp_as_sequence */
471 0, /* tp_as_mapping */
472 0, /* tp_hash */
473 0, /* tp_call */
474 0, /* tp_str */
475 PyObject_GenericGetAttr, /* tp_getattro */
476 0, /* tp_setattro */
477 0, /* tp_as_buffer */
478 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
479 Py_TPFLAGS_BASETYPE, /* tp_flags */
480 filter_doc, /* tp_doc */
481 (traverseproc)filter_traverse, /* tp_traverse */
482 0, /* tp_clear */
483 0, /* tp_richcompare */
484 0, /* tp_weaklistoffset */
485 PyObject_SelfIter, /* tp_iter */
486 (iternextfunc)filter_next, /* tp_iternext */
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +0000487 filter_methods, /* tp_methods */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000488 0, /* tp_members */
489 0, /* tp_getset */
490 0, /* tp_base */
491 0, /* tp_dict */
492 0, /* tp_descr_get */
493 0, /* tp_descr_set */
494 0, /* tp_dictoffset */
495 0, /* tp_init */
496 PyType_GenericAlloc, /* tp_alloc */
497 filter_new, /* tp_new */
498 PyObject_GC_Del, /* tp_free */
Raymond Hettinger17301e92008-03-13 00:19:26 +0000499};
500
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000501
Eric Smith8c663262007-08-25 02:26:07 +0000502static PyObject *
503builtin_format(PyObject *self, PyObject *args)
504{
Christian Heimes94b7d3d2007-12-11 20:20:39 +0000505 PyObject *value;
Eric Smith8fd3eba2008-02-17 19:48:00 +0000506 PyObject *format_spec = NULL;
Eric Smith8c663262007-08-25 02:26:07 +0000507
Eric Smith8fd3eba2008-02-17 19:48:00 +0000508 if (!PyArg_ParseTuple(args, "O|U:format", &value, &format_spec))
Benjamin Petersona12d5c62012-01-03 16:47:22 -0600509 return NULL;
Eric Smith8c663262007-08-25 02:26:07 +0000510
Eric Smith8fd3eba2008-02-17 19:48:00 +0000511 return PyObject_Format(value, format_spec);
Eric Smith8c663262007-08-25 02:26:07 +0000512}
513
Eric Smith8c663262007-08-25 02:26:07 +0000514PyDoc_STRVAR(format_doc,
Eric Smith81936692007-08-31 01:14:01 +0000515"format(value[, format_spec]) -> string\n\
Eric Smith8c663262007-08-25 02:26:07 +0000516\n\
Eric Smith81936692007-08-31 01:14:01 +0000517Returns value.__format__(format_spec)\n\
518format_spec defaults to \"\"");
519
Guido van Rossum7fcf2242007-05-04 17:43:11 +0000520static PyObject *
Walter Dörwalde7efd592007-06-05 20:07:21 +0000521builtin_chr(PyObject *self, PyObject *args)
Guido van Rossum09095f32000-03-10 23:00:52 +0000522{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000523 int x;
Guido van Rossum09095f32000-03-10 23:00:52 +0000524
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000525 if (!PyArg_ParseTuple(args, "i:chr", &x))
526 return NULL;
Fredrik Lundh0dcf67e2001-06-26 20:01:56 +0000527
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000528 return PyUnicode_FromOrdinal(x);
Guido van Rossum09095f32000-03-10 23:00:52 +0000529}
530
Victor Stinner63ab8752011-11-22 03:31:20 +0100531PyDoc_STRVAR(chr_doc,
Guido van Rossum84fc66d2007-05-03 17:18:26 +0000532"chr(i) -> Unicode character\n\
Guido van Rossum09095f32000-03-10 23:00:52 +0000533\n\
Victor Stinner63ab8752011-11-22 03:31:20 +0100534Return a Unicode string of one character with ordinal i; 0 <= i <= 0x10ffff.");
Guido van Rossum09095f32000-03-10 23:00:52 +0000535
536
Guido van Rossumf15a29f2007-05-04 00:41:39 +0000537static char *
Benjamin Petersonf5b52242009-03-02 23:31:26 +0000538source_as_string(PyObject *cmd, char *funcname, char *what, PyCompilerFlags *cf)
Guido van Rossumf15a29f2007-05-04 00:41:39 +0000539{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000540 char *str;
541 Py_ssize_t size;
Guido van Rossumf15a29f2007-05-04 00:41:39 +0000542
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000543 if (PyUnicode_Check(cmd)) {
544 cf->cf_flags |= PyCF_IGNORE_COOKIE;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200545 str = PyUnicode_AsUTF8AndSize(cmd, &size);
546 if (str == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000547 return NULL;
548 }
549 else if (!PyObject_CheckReadBuffer(cmd)) {
550 PyErr_Format(PyExc_TypeError,
551 "%s() arg 1 must be a %s object",
552 funcname, what);
553 return NULL;
554 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200555 else if (PyObject_AsReadBuffer(cmd, (const void **)&str, &size) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000556 return NULL;
557 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200558
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000559 if (strlen(str) != size) {
560 PyErr_SetString(PyExc_TypeError,
561 "source code string cannot contain null bytes");
562 return NULL;
563 }
564 return str;
Guido van Rossumf15a29f2007-05-04 00:41:39 +0000565}
566
Guido van Rossum79f25d91997-04-29 20:08:16 +0000567static PyObject *
Guido van Rossumd8faa362007-04-27 19:54:29 +0000568builtin_compile(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum5b722181993-03-30 17:46:03 +0000569{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000570 char *str;
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000571 PyObject *filename_obj;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000572 char *filename;
573 char *startstr;
574 int mode = -1;
575 int dont_inherit = 0;
576 int supplied_flags = 0;
Georg Brandl8334fd92010-12-04 10:26:46 +0000577 int optimize = -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000578 int is_ast;
579 PyCompilerFlags cf;
580 PyObject *cmd;
581 static char *kwlist[] = {"source", "filename", "mode", "flags",
Georg Brandl8334fd92010-12-04 10:26:46 +0000582 "dont_inherit", "optimize", NULL};
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000583 int start[] = {Py_file_input, Py_eval_input, Py_single_input};
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000584 PyObject *result;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000585
Georg Brandl8334fd92010-12-04 10:26:46 +0000586 if (!PyArg_ParseTupleAndKeywords(args, kwds, "OO&s|iii:compile", kwlist,
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000587 &cmd,
588 PyUnicode_FSConverter, &filename_obj,
589 &startstr, &supplied_flags,
Georg Brandl8334fd92010-12-04 10:26:46 +0000590 &dont_inherit, &optimize))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000591 return NULL;
Tim Peters6cd6a822001-08-17 22:11:27 +0000592
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000593 filename = PyBytes_AS_STRING(filename_obj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000594 cf.cf_flags = supplied_flags | PyCF_SOURCE_IS_UTF8;
Just van Rossum3aaf42c2003-02-10 08:21:10 +0000595
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000596 if (supplied_flags &
597 ~(PyCF_MASK | PyCF_MASK_OBSOLETE | PyCF_DONT_IMPLY_DEDENT | PyCF_ONLY_AST))
598 {
599 PyErr_SetString(PyExc_ValueError,
600 "compile(): unrecognised flags");
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000601 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000602 }
603 /* XXX Warn if (supplied_flags & PyCF_MASK_OBSOLETE) != 0? */
Tim Peters6cd6a822001-08-17 22:11:27 +0000604
Georg Brandl8334fd92010-12-04 10:26:46 +0000605 if (optimize < -1 || optimize > 2) {
606 PyErr_SetString(PyExc_ValueError,
607 "compile(): invalid optimize value");
608 goto error;
609 }
610
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000611 if (!dont_inherit) {
612 PyEval_MergeCompilerFlags(&cf);
613 }
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000614
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000615 if (strcmp(startstr, "exec") == 0)
616 mode = 0;
617 else if (strcmp(startstr, "eval") == 0)
618 mode = 1;
619 else if (strcmp(startstr, "single") == 0)
620 mode = 2;
621 else {
622 PyErr_SetString(PyExc_ValueError,
623 "compile() arg 3 must be 'exec', 'eval' or 'single'");
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000624 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000625 }
Neal Norwitzdb4115f2008-03-31 04:20:05 +0000626
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000627 is_ast = PyAST_Check(cmd);
628 if (is_ast == -1)
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000629 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000630 if (is_ast) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000631 if (supplied_flags & PyCF_ONLY_AST) {
632 Py_INCREF(cmd);
633 result = cmd;
634 }
635 else {
636 PyArena *arena;
637 mod_ty mod;
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000638
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000639 arena = PyArena_New();
640 mod = PyAST_obj2mod(cmd, arena, mode);
641 if (mod == NULL) {
642 PyArena_Free(arena);
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000643 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000644 }
Benjamin Peterson832bfe22011-08-09 16:15:04 -0500645 if (!PyAST_Validate(mod)) {
646 PyArena_Free(arena);
647 goto error;
648 }
Georg Brandl8334fd92010-12-04 10:26:46 +0000649 result = (PyObject*)PyAST_CompileEx(mod, filename,
650 &cf, optimize, arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000651 PyArena_Free(arena);
652 }
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000653 goto finally;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000654 }
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000655
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000656 str = source_as_string(cmd, "compile", "string, bytes, AST or code", &cf);
657 if (str == NULL)
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000658 goto error;
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000659
Georg Brandl8334fd92010-12-04 10:26:46 +0000660 result = Py_CompileStringExFlags(str, filename, start[mode], &cf, optimize);
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000661 goto finally;
662
663error:
664 result = NULL;
665finally:
666 Py_DECREF(filename_obj);
667 return result;
Guido van Rossum5b722181993-03-30 17:46:03 +0000668}
669
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000670PyDoc_STRVAR(compile_doc,
Tim Peters6cd6a822001-08-17 22:11:27 +0000671"compile(source, filename, mode[, flags[, dont_inherit]]) -> code object\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000672\n\
673Compile the source string (a Python module, statement or expression)\n\
Georg Brandl7cae87c2006-09-06 06:51:57 +0000674into a code object that can be executed by exec() or eval().\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000675The filename will be used for run-time error messages.\n\
676The mode must be 'exec' to compile a module, 'single' to compile a\n\
Tim Peters6cd6a822001-08-17 22:11:27 +0000677single (interactive) statement, or 'eval' to compile an expression.\n\
678The flags argument, if present, controls which future statements influence\n\
679the compilation of the code.\n\
680The dont_inherit argument, if non-zero, stops the compilation inheriting\n\
681the effects of any future statements in effect in the code calling\n\
682compile; if absent or zero these statements do influence the compilation,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000683in addition to any features explicitly specified.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000684
Guido van Rossum79f25d91997-04-29 20:08:16 +0000685static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000686builtin_dir(PyObject *self, PyObject *args)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000687{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000688 PyObject *arg = NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000689
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000690 if (!PyArg_UnpackTuple(args, "dir", 0, 1, &arg))
691 return NULL;
692 return PyObject_Dir(arg);
Guido van Rossum3f5da241990-12-20 15:06:42 +0000693}
694
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000695PyDoc_STRVAR(dir_doc,
Tim Peters5d2b77c2001-09-03 05:47:38 +0000696"dir([object]) -> list of strings\n"
697"\n"
Georg Brandle32b4222007-03-10 22:13:27 +0000698"If called without an argument, return the names in the current scope.\n"
699"Else, return an alphabetized list of names comprising (some of) the attributes\n"
700"of the given object, and of attributes reachable from it.\n"
701"If the object supplies a method named __dir__, it will be used; otherwise\n"
702"the default dir() logic is used and returns:\n"
703" for a module object: the module's attributes.\n"
704" for a class object: its attributes, and recursively the attributes\n"
705" of its bases.\n"
Guido van Rossumd8faa362007-04-27 19:54:29 +0000706" for any other object: its attributes, its class's attributes, and\n"
Georg Brandle32b4222007-03-10 22:13:27 +0000707" recursively the attributes of its class's base classes.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000708
Guido van Rossum79f25d91997-04-29 20:08:16 +0000709static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000710builtin_divmod(PyObject *self, PyObject *args)
Guido van Rossum6a00cd81995-01-07 12:39:01 +0000711{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000712 PyObject *v, *w;
Guido van Rossum6a00cd81995-01-07 12:39:01 +0000713
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000714 if (!PyArg_UnpackTuple(args, "divmod", 2, 2, &v, &w))
715 return NULL;
716 return PyNumber_Divmod(v, w);
Guido van Rossum3f5da241990-12-20 15:06:42 +0000717}
718
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000719PyDoc_STRVAR(divmod_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000720"divmod(x, y) -> (div, mod)\n\
721\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000722Return the tuple ((x-x%y)/y, x%y). Invariant: div*y + mod == x.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000723
724
Guido van Rossum79f25d91997-04-29 20:08:16 +0000725static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000726builtin_eval(PyObject *self, PyObject *args)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000727{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000728 PyObject *cmd, *result, *tmp = NULL;
729 PyObject *globals = Py_None, *locals = Py_None;
730 char *str;
731 PyCompilerFlags cf;
Guido van Rossum590baa41993-11-30 13:40:46 +0000732
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000733 if (!PyArg_UnpackTuple(args, "eval", 1, 3, &cmd, &globals, &locals))
734 return NULL;
735 if (locals != Py_None && !PyMapping_Check(locals)) {
736 PyErr_SetString(PyExc_TypeError, "locals must be a mapping");
737 return NULL;
738 }
739 if (globals != Py_None && !PyDict_Check(globals)) {
740 PyErr_SetString(PyExc_TypeError, PyMapping_Check(globals) ?
741 "globals must be a real dict; try eval(expr, {}, mapping)"
742 : "globals must be a dict");
743 return NULL;
744 }
745 if (globals == Py_None) {
746 globals = PyEval_GetGlobals();
747 if (locals == Py_None)
748 locals = PyEval_GetLocals();
749 }
750 else if (locals == Py_None)
751 locals = globals;
Tim Peters9fa96be2001-08-17 23:04:59 +0000752
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000753 if (globals == NULL || locals == NULL) {
754 PyErr_SetString(PyExc_TypeError,
755 "eval must be given globals and locals "
756 "when called without a frame");
757 return NULL;
758 }
Georg Brandl77c85e62005-09-15 10:46:13 +0000759
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000760 if (PyDict_GetItemString(globals, "__builtins__") == NULL) {
761 if (PyDict_SetItemString(globals, "__builtins__",
762 PyEval_GetBuiltins()) != 0)
763 return NULL;
764 }
Tim Peters9fa96be2001-08-17 23:04:59 +0000765
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000766 if (PyCode_Check(cmd)) {
767 if (PyCode_GetNumFree((PyCodeObject *)cmd) > 0) {
768 PyErr_SetString(PyExc_TypeError,
769 "code object passed to eval() may not contain free variables");
770 return NULL;
771 }
Martin v. Löwis4d0d4712010-12-03 20:14:31 +0000772 return PyEval_EvalCode(cmd, globals, locals);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000773 }
Tim Peters9fa96be2001-08-17 23:04:59 +0000774
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000775 cf.cf_flags = PyCF_SOURCE_IS_UTF8;
776 str = source_as_string(cmd, "eval", "string, bytes or code", &cf);
777 if (str == NULL)
778 return NULL;
Just van Rossum3aaf42c2003-02-10 08:21:10 +0000779
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000780 while (*str == ' ' || *str == '\t')
781 str++;
Tim Peters9fa96be2001-08-17 23:04:59 +0000782
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000783 (void)PyEval_MergeCompilerFlags(&cf);
784 result = PyRun_StringFlags(str, Py_eval_input, globals, locals, &cf);
785 Py_XDECREF(tmp);
786 return result;
Guido van Rossum3f5da241990-12-20 15:06:42 +0000787}
788
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000789PyDoc_STRVAR(eval_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000790"eval(source[, globals[, locals]]) -> value\n\
791\n\
792Evaluate the source in the context of globals and locals.\n\
793The source may be a string representing a Python expression\n\
794or a code object as returned by compile().\n\
Thomas Wouters89f507f2006-12-13 04:49:30 +0000795The globals must be a dictionary and locals can be any mapping,\n\
Raymond Hettinger214b1c32004-07-02 06:41:07 +0000796defaulting to the current globals and locals.\n\
797If only globals is given, locals defaults to it.\n");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000798
Georg Brandl7cae87c2006-09-06 06:51:57 +0000799static PyObject *
800builtin_exec(PyObject *self, PyObject *args)
801{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000802 PyObject *v;
803 PyObject *prog, *globals = Py_None, *locals = Py_None;
Georg Brandl7cae87c2006-09-06 06:51:57 +0000804
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000805 if (!PyArg_UnpackTuple(args, "exec", 1, 3, &prog, &globals, &locals))
806 return NULL;
Georg Brandl2cabc562008-08-28 07:57:16 +0000807
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000808 if (globals == Py_None) {
809 globals = PyEval_GetGlobals();
810 if (locals == Py_None) {
811 locals = PyEval_GetLocals();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000812 }
813 if (!globals || !locals) {
814 PyErr_SetString(PyExc_SystemError,
815 "globals and locals cannot be NULL");
816 return NULL;
817 }
818 }
819 else if (locals == Py_None)
820 locals = globals;
Georg Brandl7cae87c2006-09-06 06:51:57 +0000821
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000822 if (!PyDict_Check(globals)) {
823 PyErr_Format(PyExc_TypeError, "exec() arg 2 must be a dict, not %.100s",
824 globals->ob_type->tp_name);
825 return NULL;
826 }
827 if (!PyMapping_Check(locals)) {
828 PyErr_Format(PyExc_TypeError,
829 "arg 3 must be a mapping or None, not %.100s",
830 locals->ob_type->tp_name);
831 return NULL;
832 }
833 if (PyDict_GetItemString(globals, "__builtins__") == NULL) {
834 if (PyDict_SetItemString(globals, "__builtins__",
835 PyEval_GetBuiltins()) != 0)
836 return NULL;
837 }
838
839 if (PyCode_Check(prog)) {
840 if (PyCode_GetNumFree((PyCodeObject *)prog) > 0) {
841 PyErr_SetString(PyExc_TypeError,
842 "code object passed to exec() may not "
843 "contain free variables");
844 return NULL;
845 }
Martin v. Löwis4d0d4712010-12-03 20:14:31 +0000846 v = PyEval_EvalCode(prog, globals, locals);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000847 }
848 else {
849 char *str;
850 PyCompilerFlags cf;
851 cf.cf_flags = PyCF_SOURCE_IS_UTF8;
852 str = source_as_string(prog, "exec",
853 "string, bytes or code", &cf);
854 if (str == NULL)
855 return NULL;
856 if (PyEval_MergeCompilerFlags(&cf))
857 v = PyRun_StringFlags(str, Py_file_input, globals,
858 locals, &cf);
859 else
860 v = PyRun_String(str, Py_file_input, globals, locals);
861 }
862 if (v == NULL)
863 return NULL;
864 Py_DECREF(v);
865 Py_RETURN_NONE;
Georg Brandl7cae87c2006-09-06 06:51:57 +0000866}
867
868PyDoc_STRVAR(exec_doc,
869"exec(object[, globals[, locals]])\n\
870\n\
Mark Dickinson480e8e32009-12-19 21:19:35 +0000871Read and execute code from an object, which can be a string or a code\n\
Benjamin Peterson38090262009-01-04 15:30:39 +0000872object.\n\
Georg Brandl7cae87c2006-09-06 06:51:57 +0000873The globals and locals are dictionaries, defaulting to the current\n\
874globals and locals. If only globals is given, locals defaults to it.");
875
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000876
Guido van Rossum79f25d91997-04-29 20:08:16 +0000877static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000878builtin_getattr(PyObject *self, PyObject *args)
Guido van Rossum33894be1992-01-27 16:53:09 +0000879{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000880 PyObject *v, *result, *dflt = NULL;
881 PyObject *name;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000882
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000883 if (!PyArg_UnpackTuple(args, "getattr", 2, 3, &v, &name, &dflt))
884 return NULL;
Martin v. Löwis5b222132007-06-10 09:51:05 +0000885
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000886 if (!PyUnicode_Check(name)) {
887 PyErr_SetString(PyExc_TypeError,
888 "getattr(): attribute name must be string");
889 return NULL;
890 }
891 result = PyObject_GetAttr(v, name);
892 if (result == NULL && dflt != NULL &&
893 PyErr_ExceptionMatches(PyExc_AttributeError))
894 {
895 PyErr_Clear();
896 Py_INCREF(dflt);
897 result = dflt;
898 }
899 return result;
Guido van Rossum9bfef441993-03-29 10:43:31 +0000900}
901
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000902PyDoc_STRVAR(getattr_doc,
Guido van Rossum950ff291998-06-29 13:38:57 +0000903"getattr(object, name[, default]) -> value\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000904\n\
Guido van Rossum950ff291998-06-29 13:38:57 +0000905Get a named attribute from an object; getattr(x, 'y') is equivalent to x.y.\n\
906When a default argument is given, it is returned when the attribute doesn't\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000907exist; without it, an exception is raised in that case.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000908
909
Guido van Rossum79f25d91997-04-29 20:08:16 +0000910static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000911builtin_globals(PyObject *self)
Guido van Rossum872537c1995-07-07 22:43:42 +0000912{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000913 PyObject *d;
Guido van Rossum872537c1995-07-07 22:43:42 +0000914
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000915 d = PyEval_GetGlobals();
916 Py_XINCREF(d);
917 return d;
Guido van Rossum872537c1995-07-07 22:43:42 +0000918}
919
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000920PyDoc_STRVAR(globals_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000921"globals() -> dictionary\n\
922\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000923Return the dictionary containing the current scope's global variables.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000924
925
Guido van Rossum79f25d91997-04-29 20:08:16 +0000926static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000927builtin_hasattr(PyObject *self, PyObject *args)
Guido van Rossum9bfef441993-03-29 10:43:31 +0000928{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000929 PyObject *v;
930 PyObject *name;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000931
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000932 if (!PyArg_UnpackTuple(args, "hasattr", 2, 2, &v, &name))
933 return NULL;
934 if (!PyUnicode_Check(name)) {
935 PyErr_SetString(PyExc_TypeError,
936 "hasattr(): attribute name must be string");
937 return NULL;
938 }
939 v = PyObject_GetAttr(v, name);
940 if (v == NULL) {
Benjamin Peterson17689992010-08-24 03:26:23 +0000941 if (PyErr_ExceptionMatches(PyExc_AttributeError)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000942 PyErr_Clear();
Benjamin Peterson17689992010-08-24 03:26:23 +0000943 Py_RETURN_FALSE;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000944 }
Benjamin Peterson17689992010-08-24 03:26:23 +0000945 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000946 }
947 Py_DECREF(v);
Benjamin Peterson17689992010-08-24 03:26:23 +0000948 Py_RETURN_TRUE;
Guido van Rossum33894be1992-01-27 16:53:09 +0000949}
950
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000951PyDoc_STRVAR(hasattr_doc,
Guido van Rossum77f6a652002-04-03 22:41:51 +0000952"hasattr(object, name) -> bool\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000953\n\
954Return whether the object has an attribute with the given name.\n\
Benjamin Peterson17689992010-08-24 03:26:23 +0000955(This is done by calling getattr(object, name) and catching AttributeError.)");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000956
957
Guido van Rossum79f25d91997-04-29 20:08:16 +0000958static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000959builtin_id(PyObject *self, PyObject *v)
Guido van Rossum5b722181993-03-30 17:46:03 +0000960{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000961 return PyLong_FromVoidPtr(v);
Guido van Rossum5b722181993-03-30 17:46:03 +0000962}
963
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000964PyDoc_STRVAR(id_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000965"id(object) -> integer\n\
966\n\
967Return the identity of an object. This is guaranteed to be unique among\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000968simultaneously existing objects. (Hint: it's the object's memory address.)");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000969
970
Raymond Hettingera6c60372008-03-13 01:26:19 +0000971/* map object ************************************************************/
972
973typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000974 PyObject_HEAD
975 PyObject *iters;
976 PyObject *func;
Raymond Hettingera6c60372008-03-13 01:26:19 +0000977} mapobject;
978
Guido van Rossum79f25d91997-04-29 20:08:16 +0000979static PyObject *
Raymond Hettingera6c60372008-03-13 01:26:19 +0000980map_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
Guido van Rossum12d12c51993-10-26 17:58:25 +0000981{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000982 PyObject *it, *iters, *func;
983 mapobject *lz;
984 Py_ssize_t numargs, i;
Raymond Hettingera6c60372008-03-13 01:26:19 +0000985
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000986 if (type == &PyMap_Type && !_PyArg_NoKeywords("map()", kwds))
987 return NULL;
Raymond Hettingera6c60372008-03-13 01:26:19 +0000988
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000989 numargs = PyTuple_Size(args);
990 if (numargs < 2) {
991 PyErr_SetString(PyExc_TypeError,
992 "map() must have at least two arguments.");
993 return NULL;
994 }
Raymond Hettingera6c60372008-03-13 01:26:19 +0000995
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000996 iters = PyTuple_New(numargs-1);
997 if (iters == NULL)
998 return NULL;
Raymond Hettingera6c60372008-03-13 01:26:19 +0000999
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001000 for (i=1 ; i<numargs ; i++) {
1001 /* Get iterator. */
1002 it = PyObject_GetIter(PyTuple_GET_ITEM(args, i));
1003 if (it == NULL) {
1004 Py_DECREF(iters);
1005 return NULL;
1006 }
1007 PyTuple_SET_ITEM(iters, i-1, it);
1008 }
Raymond Hettingera6c60372008-03-13 01:26:19 +00001009
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001010 /* create mapobject structure */
1011 lz = (mapobject *)type->tp_alloc(type, 0);
1012 if (lz == NULL) {
1013 Py_DECREF(iters);
1014 return NULL;
1015 }
1016 lz->iters = iters;
1017 func = PyTuple_GET_ITEM(args, 0);
1018 Py_INCREF(func);
1019 lz->func = func;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001020
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001021 return (PyObject *)lz;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001022}
1023
1024static void
1025map_dealloc(mapobject *lz)
1026{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001027 PyObject_GC_UnTrack(lz);
1028 Py_XDECREF(lz->iters);
1029 Py_XDECREF(lz->func);
1030 Py_TYPE(lz)->tp_free(lz);
Raymond Hettingera6c60372008-03-13 01:26:19 +00001031}
1032
1033static int
1034map_traverse(mapobject *lz, visitproc visit, void *arg)
1035{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001036 Py_VISIT(lz->iters);
1037 Py_VISIT(lz->func);
1038 return 0;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001039}
1040
1041static PyObject *
1042map_next(mapobject *lz)
1043{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001044 PyObject *val;
1045 PyObject *argtuple;
1046 PyObject *result;
1047 Py_ssize_t numargs, i;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001048
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001049 numargs = PyTuple_Size(lz->iters);
1050 argtuple = PyTuple_New(numargs);
1051 if (argtuple == NULL)
1052 return NULL;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001053
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001054 for (i=0 ; i<numargs ; i++) {
1055 val = PyIter_Next(PyTuple_GET_ITEM(lz->iters, i));
1056 if (val == NULL) {
1057 Py_DECREF(argtuple);
1058 return NULL;
1059 }
1060 PyTuple_SET_ITEM(argtuple, i, val);
1061 }
1062 result = PyObject_Call(lz->func, argtuple, NULL);
1063 Py_DECREF(argtuple);
1064 return result;
Guido van Rossum12d12c51993-10-26 17:58:25 +00001065}
1066
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001067static PyObject *
1068map_reduce(mapobject *lz)
1069{
1070 Py_ssize_t numargs = PyTuple_GET_SIZE(lz->iters);
1071 PyObject *args = PyTuple_New(numargs+1);
1072 Py_ssize_t i;
1073 if (args == NULL)
1074 return NULL;
1075 Py_INCREF(lz->func);
1076 PyTuple_SET_ITEM(args, 0, lz->func);
1077 for (i = 0; i<numargs; i++){
1078 PyObject *it = PyTuple_GET_ITEM(lz->iters, i);
1079 Py_INCREF(it);
1080 PyTuple_SET_ITEM(args, i+1, it);
1081 }
1082
1083 return Py_BuildValue("ON", Py_TYPE(lz), args);
1084}
1085
1086static PyMethodDef map_methods[] = {
1087 {"__reduce__", (PyCFunction)map_reduce, METH_NOARGS, reduce_doc},
1088 {NULL, NULL} /* sentinel */
1089};
1090
1091
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001092PyDoc_STRVAR(map_doc,
Raymond Hettingera6c60372008-03-13 01:26:19 +00001093"map(func, *iterables) --> map object\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001094\n\
Raymond Hettingera6c60372008-03-13 01:26:19 +00001095Make an iterator that computes the function using arguments from\n\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001096each of the iterables. Stops when the shortest iterable is exhausted.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001097
Raymond Hettingera6c60372008-03-13 01:26:19 +00001098PyTypeObject PyMap_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001099 PyVarObject_HEAD_INIT(&PyType_Type, 0)
1100 "map", /* tp_name */
1101 sizeof(mapobject), /* tp_basicsize */
1102 0, /* tp_itemsize */
1103 /* methods */
1104 (destructor)map_dealloc, /* tp_dealloc */
1105 0, /* tp_print */
1106 0, /* tp_getattr */
1107 0, /* tp_setattr */
1108 0, /* tp_reserved */
1109 0, /* tp_repr */
1110 0, /* tp_as_number */
1111 0, /* tp_as_sequence */
1112 0, /* tp_as_mapping */
1113 0, /* tp_hash */
1114 0, /* tp_call */
1115 0, /* tp_str */
1116 PyObject_GenericGetAttr, /* tp_getattro */
1117 0, /* tp_setattro */
1118 0, /* tp_as_buffer */
1119 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
1120 Py_TPFLAGS_BASETYPE, /* tp_flags */
1121 map_doc, /* tp_doc */
1122 (traverseproc)map_traverse, /* tp_traverse */
1123 0, /* tp_clear */
1124 0, /* tp_richcompare */
1125 0, /* tp_weaklistoffset */
1126 PyObject_SelfIter, /* tp_iter */
1127 (iternextfunc)map_next, /* tp_iternext */
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001128 map_methods, /* tp_methods */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001129 0, /* tp_members */
1130 0, /* tp_getset */
1131 0, /* tp_base */
1132 0, /* tp_dict */
1133 0, /* tp_descr_get */
1134 0, /* tp_descr_set */
1135 0, /* tp_dictoffset */
1136 0, /* tp_init */
1137 PyType_GenericAlloc, /* tp_alloc */
1138 map_new, /* tp_new */
1139 PyObject_GC_Del, /* tp_free */
Raymond Hettingera6c60372008-03-13 01:26:19 +00001140};
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001141
Guido van Rossum79f25d91997-04-29 20:08:16 +00001142static PyObject *
Georg Brandla18af4e2007-04-21 15:47:16 +00001143builtin_next(PyObject *self, PyObject *args)
1144{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001145 PyObject *it, *res;
1146 PyObject *def = NULL;
Georg Brandla18af4e2007-04-21 15:47:16 +00001147
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001148 if (!PyArg_UnpackTuple(args, "next", 1, 2, &it, &def))
1149 return NULL;
1150 if (!PyIter_Check(it)) {
1151 PyErr_Format(PyExc_TypeError,
Philip Jenvey50add042011-11-06 16:37:52 -08001152 "'%.200s' object is not an iterator",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001153 it->ob_type->tp_name);
1154 return NULL;
1155 }
1156
1157 res = (*it->ob_type->tp_iternext)(it);
1158 if (res != NULL) {
1159 return res;
1160 } else if (def != NULL) {
1161 if (PyErr_Occurred()) {
1162 if(!PyErr_ExceptionMatches(PyExc_StopIteration))
1163 return NULL;
1164 PyErr_Clear();
1165 }
1166 Py_INCREF(def);
1167 return def;
1168 } else if (PyErr_Occurred()) {
1169 return NULL;
1170 } else {
1171 PyErr_SetNone(PyExc_StopIteration);
1172 return NULL;
1173 }
Georg Brandla18af4e2007-04-21 15:47:16 +00001174}
1175
1176PyDoc_STRVAR(next_doc,
1177"next(iterator[, default])\n\
1178\n\
1179Return the next item from the iterator. If default is given and the iterator\n\
1180is exhausted, it is returned instead of raising StopIteration.");
1181
1182
1183static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001184builtin_setattr(PyObject *self, PyObject *args)
Guido van Rossum33894be1992-01-27 16:53:09 +00001185{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001186 PyObject *v;
1187 PyObject *name;
1188 PyObject *value;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001189
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001190 if (!PyArg_UnpackTuple(args, "setattr", 3, 3, &v, &name, &value))
1191 return NULL;
1192 if (PyObject_SetAttr(v, name, value) != 0)
1193 return NULL;
1194 Py_INCREF(Py_None);
1195 return Py_None;
Guido van Rossum33894be1992-01-27 16:53:09 +00001196}
1197
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001198PyDoc_STRVAR(setattr_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001199"setattr(object, name, value)\n\
1200\n\
1201Set a named attribute on an object; setattr(x, 'y', v) is equivalent to\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001202``x.y = v''.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001203
1204
Guido van Rossum79f25d91997-04-29 20:08:16 +00001205static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001206builtin_delattr(PyObject *self, PyObject *args)
Guido van Rossum14144fc1994-08-29 12:53:40 +00001207{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001208 PyObject *v;
1209 PyObject *name;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001210
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001211 if (!PyArg_UnpackTuple(args, "delattr", 2, 2, &v, &name))
1212 return NULL;
1213 if (PyObject_SetAttr(v, name, (PyObject *)NULL) != 0)
1214 return NULL;
1215 Py_INCREF(Py_None);
1216 return Py_None;
Guido van Rossum14144fc1994-08-29 12:53:40 +00001217}
1218
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001219PyDoc_STRVAR(delattr_doc,
Guido van Rossumdf12a591998-11-23 22:13:04 +00001220"delattr(object, name)\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001221\n\
1222Delete a named attribute on an object; delattr(x, 'y') is equivalent to\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001223``del x.y''.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001224
1225
Guido van Rossum79f25d91997-04-29 20:08:16 +00001226static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001227builtin_hash(PyObject *self, PyObject *v)
Guido van Rossum9bfef441993-03-29 10:43:31 +00001228{
Benjamin Peterson8f67d082010-10-17 20:54:53 +00001229 Py_hash_t x;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001230
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001231 x = PyObject_Hash(v);
1232 if (x == -1)
1233 return NULL;
Benjamin Peterson8f67d082010-10-17 20:54:53 +00001234 return PyLong_FromSsize_t(x);
Guido van Rossum9bfef441993-03-29 10:43:31 +00001235}
1236
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001237PyDoc_STRVAR(hash_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001238"hash(object) -> integer\n\
1239\n\
1240Return a hash value for the object. Two objects with the same value have\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001241the same hash value. The reverse is not necessarily true, but likely.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001242
1243
Guido van Rossum79f25d91997-04-29 20:08:16 +00001244static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001245builtin_hex(PyObject *self, PyObject *v)
Guido van Rossum006bcd41991-10-24 14:54:44 +00001246{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001247 return PyNumber_ToBase(v, 16);
Guido van Rossum006bcd41991-10-24 14:54:44 +00001248}
1249
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001250PyDoc_STRVAR(hex_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001251"hex(number) -> string\n\
1252\n\
Alexander Belopolsky12338ab2011-04-07 00:15:33 -04001253Return the hexadecimal representation of an integer.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001254
1255
Guido van Rossum79f25d91997-04-29 20:08:16 +00001256static PyObject *
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001257builtin_iter(PyObject *self, PyObject *args)
1258{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001259 PyObject *v, *w = NULL;
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001260
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001261 if (!PyArg_UnpackTuple(args, "iter", 1, 2, &v, &w))
1262 return NULL;
1263 if (w == NULL)
1264 return PyObject_GetIter(v);
1265 if (!PyCallable_Check(v)) {
1266 PyErr_SetString(PyExc_TypeError,
1267 "iter(v, w): v must be callable");
1268 return NULL;
1269 }
1270 return PyCallIter_New(v, w);
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001271}
1272
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001273PyDoc_STRVAR(iter_doc,
Georg Brandld11ae5d2008-05-16 13:27:32 +00001274"iter(iterable) -> iterator\n\
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001275iter(callable, sentinel) -> iterator\n\
1276\n\
1277Get an iterator from an object. In the first form, the argument must\n\
1278supply its own iterator, or be a sequence.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001279In the second form, the callable is called until it returns the sentinel.");
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001280
1281
1282static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001283builtin_len(PyObject *self, PyObject *v)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001284{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001285 Py_ssize_t res;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001286
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001287 res = PyObject_Size(v);
1288 if (res < 0 && PyErr_Occurred())
1289 return NULL;
1290 return PyLong_FromSsize_t(res);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001291}
1292
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001293PyDoc_STRVAR(len_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001294"len(object) -> integer\n\
1295\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001296Return the number of items of a sequence or mapping.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001297
1298
Guido van Rossum79f25d91997-04-29 20:08:16 +00001299static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001300builtin_locals(PyObject *self)
Guido van Rossum872537c1995-07-07 22:43:42 +00001301{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001302 PyObject *d;
Guido van Rossum872537c1995-07-07 22:43:42 +00001303
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001304 d = PyEval_GetLocals();
1305 Py_XINCREF(d);
1306 return d;
Guido van Rossum872537c1995-07-07 22:43:42 +00001307}
1308
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001309PyDoc_STRVAR(locals_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001310"locals() -> dictionary\n\
1311\n\
Raymond Hettinger69bf8f32003-01-04 02:16:22 +00001312Update and return a dictionary containing the current scope's local variables.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001313
1314
Guido van Rossum79f25d91997-04-29 20:08:16 +00001315static PyObject *
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001316min_max(PyObject *args, PyObject *kwds, int op)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001317{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001318 PyObject *v, *it, *item, *val, *maxitem, *maxval, *keyfunc=NULL;
1319 const char *name = op == Py_LT ? "min" : "max";
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001320
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001321 if (PyTuple_Size(args) > 1)
1322 v = args;
1323 else if (!PyArg_UnpackTuple(args, (char *)name, 1, 1, &v))
1324 return NULL;
Tim Peters67d687a2002-04-29 21:27:32 +00001325
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001326 if (kwds != NULL && PyDict_Check(kwds) && PyDict_Size(kwds)) {
1327 keyfunc = PyDict_GetItemString(kwds, "key");
1328 if (PyDict_Size(kwds)!=1 || keyfunc == NULL) {
1329 PyErr_Format(PyExc_TypeError,
1330 "%s() got an unexpected keyword argument", name);
1331 return NULL;
1332 }
1333 Py_INCREF(keyfunc);
1334 }
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001335
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001336 it = PyObject_GetIter(v);
1337 if (it == NULL) {
1338 Py_XDECREF(keyfunc);
1339 return NULL;
1340 }
Tim Petersc3074532001-05-03 07:00:32 +00001341
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001342 maxitem = NULL; /* the result */
1343 maxval = NULL; /* the value associated with the result */
1344 while (( item = PyIter_Next(it) )) {
1345 /* get the value from the key function */
1346 if (keyfunc != NULL) {
1347 val = PyObject_CallFunctionObjArgs(keyfunc, item, NULL);
1348 if (val == NULL)
1349 goto Fail_it_item;
1350 }
1351 /* no key function; the value is the item */
1352 else {
1353 val = item;
1354 Py_INCREF(val);
1355 }
Tim Petersc3074532001-05-03 07:00:32 +00001356
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001357 /* maximum value and item are unset; set them */
1358 if (maxval == NULL) {
1359 maxitem = item;
1360 maxval = val;
1361 }
1362 /* maximum value and item are set; update them as necessary */
1363 else {
1364 int cmp = PyObject_RichCompareBool(val, maxval, op);
1365 if (cmp < 0)
1366 goto Fail_it_item_and_val;
1367 else if (cmp > 0) {
1368 Py_DECREF(maxval);
1369 Py_DECREF(maxitem);
1370 maxval = val;
1371 maxitem = item;
1372 }
1373 else {
1374 Py_DECREF(item);
1375 Py_DECREF(val);
1376 }
1377 }
1378 }
1379 if (PyErr_Occurred())
1380 goto Fail_it;
1381 if (maxval == NULL) {
1382 PyErr_Format(PyExc_ValueError,
1383 "%s() arg is an empty sequence", name);
1384 assert(maxitem == NULL);
1385 }
1386 else
1387 Py_DECREF(maxval);
1388 Py_DECREF(it);
1389 Py_XDECREF(keyfunc);
1390 return maxitem;
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001391
1392Fail_it_item_and_val:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001393 Py_DECREF(val);
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001394Fail_it_item:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001395 Py_DECREF(item);
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001396Fail_it:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001397 Py_XDECREF(maxval);
1398 Py_XDECREF(maxitem);
1399 Py_DECREF(it);
1400 Py_XDECREF(keyfunc);
1401 return NULL;
Guido van Rossum3f5da241990-12-20 15:06:42 +00001402}
1403
Guido van Rossum79f25d91997-04-29 20:08:16 +00001404static PyObject *
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001405builtin_min(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001406{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001407 return min_max(args, kwds, Py_LT);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001408}
1409
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001410PyDoc_STRVAR(min_doc,
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001411"min(iterable[, key=func]) -> value\n\
1412min(a, b, c, ...[, key=func]) -> value\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001413\n\
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001414With a single iterable argument, return its smallest item.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001415With two or more arguments, return the smallest argument.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001416
1417
Guido van Rossum79f25d91997-04-29 20:08:16 +00001418static PyObject *
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001419builtin_max(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001420{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001421 return min_max(args, kwds, Py_GT);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001422}
1423
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001424PyDoc_STRVAR(max_doc,
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001425"max(iterable[, key=func]) -> value\n\
1426max(a, b, c, ...[, key=func]) -> value\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001427\n\
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001428With a single iterable argument, return its largest item.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001429With two or more arguments, return the largest argument.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001430
1431
Guido van Rossum79f25d91997-04-29 20:08:16 +00001432static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001433builtin_oct(PyObject *self, PyObject *v)
Guido van Rossum006bcd41991-10-24 14:54:44 +00001434{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001435 return PyNumber_ToBase(v, 8);
Guido van Rossum006bcd41991-10-24 14:54:44 +00001436}
1437
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001438PyDoc_STRVAR(oct_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001439"oct(number) -> string\n\
1440\n\
Alexander Belopolsky12338ab2011-04-07 00:15:33 -04001441Return the octal representation of an integer.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001442
1443
Guido van Rossum79f25d91997-04-29 20:08:16 +00001444static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001445builtin_ord(PyObject *self, PyObject* obj)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001446{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001447 long ord;
1448 Py_ssize_t size;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001449
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001450 if (PyBytes_Check(obj)) {
1451 size = PyBytes_GET_SIZE(obj);
1452 if (size == 1) {
1453 ord = (long)((unsigned char)*PyBytes_AS_STRING(obj));
1454 return PyLong_FromLong(ord);
1455 }
1456 }
1457 else if (PyUnicode_Check(obj)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001458 if (PyUnicode_READY(obj) == -1)
1459 return NULL;
1460 size = PyUnicode_GET_LENGTH(obj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001461 if (size == 1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001462 ord = (long)PyUnicode_READ_CHAR(obj, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001463 return PyLong_FromLong(ord);
1464 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001465 }
1466 else if (PyByteArray_Check(obj)) {
1467 /* XXX Hopefully this is temporary */
1468 size = PyByteArray_GET_SIZE(obj);
1469 if (size == 1) {
1470 ord = (long)((unsigned char)*PyByteArray_AS_STRING(obj));
1471 return PyLong_FromLong(ord);
1472 }
1473 }
1474 else {
1475 PyErr_Format(PyExc_TypeError,
1476 "ord() expected string of length 1, but " \
1477 "%.200s found", obj->ob_type->tp_name);
1478 return NULL;
1479 }
Guido van Rossum09095f32000-03-10 23:00:52 +00001480
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001481 PyErr_Format(PyExc_TypeError,
1482 "ord() expected a character, "
1483 "but string of length %zd found",
1484 size);
1485 return NULL;
Guido van Rossum3f5da241990-12-20 15:06:42 +00001486}
1487
Guido van Rossum307fa8c2007-07-16 20:46:27 +00001488PyDoc_VAR(ord_doc) = PyDoc_STR(
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001489"ord(c) -> integer\n\
1490\n\
Guido van Rossum8ac004e2007-07-15 13:00:05 +00001491Return the integer ordinal of a one-character string."
Antoine Pitrouedc60182012-06-23 14:19:58 +02001492);
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001493
1494
Guido van Rossum79f25d91997-04-29 20:08:16 +00001495static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001496builtin_pow(PyObject *self, PyObject *args)
Guido van Rossum6a00cd81995-01-07 12:39:01 +00001497{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001498 PyObject *v, *w, *z = Py_None;
Guido van Rossum6a00cd81995-01-07 12:39:01 +00001499
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001500 if (!PyArg_UnpackTuple(args, "pow", 2, 3, &v, &w, &z))
1501 return NULL;
1502 return PyNumber_Power(v, w, z);
Guido van Rossumd4905451991-05-05 20:00:36 +00001503}
1504
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001505PyDoc_STRVAR(pow_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001506"pow(x, y[, z]) -> number\n\
1507\n\
1508With two arguments, equivalent to x**y. With three arguments,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001509equivalent to (x**y) % z, but may be more efficient (e.g. for longs).");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001510
1511
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001512
Guido van Rossum34343512006-11-30 22:13:52 +00001513static PyObject *
1514builtin_print(PyObject *self, PyObject *args, PyObject *kwds)
1515{
Georg Brandlbc3b6822012-01-13 19:41:25 +01001516 static char *kwlist[] = {"sep", "end", "file", "flush", 0};
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001517 static PyObject *dummy_args;
Georg Brandlbc3b6822012-01-13 19:41:25 +01001518 PyObject *sep = NULL, *end = NULL, *file = NULL, *flush = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001519 int i, err;
Guido van Rossum34343512006-11-30 22:13:52 +00001520
Benjamin Peterson00102562012-01-11 21:00:16 -05001521 if (dummy_args == NULL && !(dummy_args = PyTuple_New(0)))
Georg Brandlbc3b6822012-01-13 19:41:25 +01001522 return NULL;
1523 if (!PyArg_ParseTupleAndKeywords(dummy_args, kwds, "|OOOO:print",
1524 kwlist, &sep, &end, &file, &flush))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001525 return NULL;
1526 if (file == NULL || file == Py_None) {
1527 file = PySys_GetObject("stdout");
1528 /* sys.stdout may be None when FILE* stdout isn't connected */
1529 if (file == Py_None)
1530 Py_RETURN_NONE;
1531 }
Guido van Rossum34343512006-11-30 22:13:52 +00001532
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001533 if (sep == Py_None) {
1534 sep = NULL;
1535 }
1536 else if (sep && !PyUnicode_Check(sep)) {
1537 PyErr_Format(PyExc_TypeError,
1538 "sep must be None or a string, not %.200s",
1539 sep->ob_type->tp_name);
1540 return NULL;
1541 }
1542 if (end == Py_None) {
1543 end = NULL;
1544 }
1545 else if (end && !PyUnicode_Check(end)) {
1546 PyErr_Format(PyExc_TypeError,
1547 "end must be None or a string, not %.200s",
1548 end->ob_type->tp_name);
1549 return NULL;
1550 }
Guido van Rossum34343512006-11-30 22:13:52 +00001551
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001552 for (i = 0; i < PyTuple_Size(args); i++) {
1553 if (i > 0) {
1554 if (sep == NULL)
1555 err = PyFile_WriteString(" ", file);
1556 else
1557 err = PyFile_WriteObject(sep, file,
1558 Py_PRINT_RAW);
1559 if (err)
1560 return NULL;
1561 }
1562 err = PyFile_WriteObject(PyTuple_GetItem(args, i), file,
1563 Py_PRINT_RAW);
1564 if (err)
1565 return NULL;
1566 }
Guido van Rossum34343512006-11-30 22:13:52 +00001567
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001568 if (end == NULL)
1569 err = PyFile_WriteString("\n", file);
1570 else
1571 err = PyFile_WriteObject(end, file, Py_PRINT_RAW);
1572 if (err)
1573 return NULL;
Guido van Rossum34343512006-11-30 22:13:52 +00001574
Georg Brandlbc3b6822012-01-13 19:41:25 +01001575 if (flush != NULL) {
1576 PyObject *tmp;
1577 int do_flush = PyObject_IsTrue(flush);
1578 if (do_flush == -1)
1579 return NULL;
1580 else if (do_flush) {
1581 tmp = PyObject_CallMethod(file, "flush", "");
1582 if (tmp == NULL)
1583 return NULL;
1584 else
1585 Py_DECREF(tmp);
1586 }
1587 }
1588
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001589 Py_RETURN_NONE;
Guido van Rossum34343512006-11-30 22:13:52 +00001590}
1591
1592PyDoc_STRVAR(print_doc,
Senthil Kumarane9175bd2012-08-10 13:53:45 -07001593"print(value, ..., sep=' ', end='\\n', file=sys.stdout, flush=False)\n\
Guido van Rossum34343512006-11-30 22:13:52 +00001594\n\
1595Prints the values to a stream, or to sys.stdout by default.\n\
1596Optional keyword arguments:\n\
Senthil Kumarane9175bd2012-08-10 13:53:45 -07001597file: a file-like object (stream); defaults to the current sys.stdout.\n\
1598sep: string inserted between values, default a space.\n\
1599end: string appended after the last value, default a newline.\n\
1600flush: whether to forcibly flush the stream.");
Guido van Rossum34343512006-11-30 22:13:52 +00001601
1602
Guido van Rossuma88a0332007-02-26 16:59:55 +00001603static PyObject *
1604builtin_input(PyObject *self, PyObject *args)
1605{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001606 PyObject *promptarg = NULL;
1607 PyObject *fin = PySys_GetObject("stdin");
1608 PyObject *fout = PySys_GetObject("stdout");
1609 PyObject *ferr = PySys_GetObject("stderr");
1610 PyObject *tmp;
1611 long fd;
1612 int tty;
Guido van Rossuma88a0332007-02-26 16:59:55 +00001613
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001614 /* Parse arguments */
1615 if (!PyArg_UnpackTuple(args, "input", 0, 1, &promptarg))
1616 return NULL;
Guido van Rossuma88a0332007-02-26 16:59:55 +00001617
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001618 /* Check that stdin/out/err are intact */
1619 if (fin == NULL || fin == Py_None) {
1620 PyErr_SetString(PyExc_RuntimeError,
1621 "input(): lost sys.stdin");
1622 return NULL;
1623 }
1624 if (fout == NULL || fout == Py_None) {
1625 PyErr_SetString(PyExc_RuntimeError,
1626 "input(): lost sys.stdout");
1627 return NULL;
1628 }
1629 if (ferr == NULL || ferr == Py_None) {
1630 PyErr_SetString(PyExc_RuntimeError,
1631 "input(): lost sys.stderr");
1632 return NULL;
1633 }
Guido van Rossumeba76962007-05-27 09:13:28 +00001634
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001635 /* First of all, flush stderr */
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001636 tmp = _PyObject_CallMethodId(ferr, &PyId_flush, "");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001637 if (tmp == NULL)
1638 PyErr_Clear();
1639 else
1640 Py_DECREF(tmp);
Guido van Rossumeba76962007-05-27 09:13:28 +00001641
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001642 /* We should only use (GNU) readline if Python's sys.stdin and
1643 sys.stdout are the same as C's stdin and stdout, because we
1644 need to pass it those. */
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001645 tmp = _PyObject_CallMethodId(fin, &PyId_fileno, "");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001646 if (tmp == NULL) {
1647 PyErr_Clear();
1648 tty = 0;
1649 }
1650 else {
1651 fd = PyLong_AsLong(tmp);
1652 Py_DECREF(tmp);
1653 if (fd < 0 && PyErr_Occurred())
1654 return NULL;
1655 tty = fd == fileno(stdin) && isatty(fd);
1656 }
1657 if (tty) {
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001658 tmp = _PyObject_CallMethodId(fout, &PyId_fileno, "");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001659 if (tmp == NULL)
1660 PyErr_Clear();
1661 else {
1662 fd = PyLong_AsLong(tmp);
1663 Py_DECREF(tmp);
1664 if (fd < 0 && PyErr_Occurred())
1665 return NULL;
1666 tty = fd == fileno(stdout) && isatty(fd);
1667 }
1668 }
Guido van Rossumeba76962007-05-27 09:13:28 +00001669
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001670 /* If we're interactive, use (GNU) readline */
1671 if (tty) {
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001672 PyObject *po = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001673 char *prompt;
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001674 char *s = NULL;
1675 PyObject *stdin_encoding = NULL, *stdin_errors = NULL;
1676 PyObject *stdout_encoding = NULL, *stdout_errors = NULL;
1677 char *stdin_encoding_str, *stdin_errors_str;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001678 PyObject *result;
Victor Stinnerc0f1a1a2011-02-23 12:07:37 +00001679 size_t len;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02001680 _Py_IDENTIFIER(encoding);
Antoine Pitrou5ee9d8a2011-11-06 00:38:45 +01001681 _Py_IDENTIFIER(errors);
Martin v. Löwis4a7b5d52007-09-04 05:24:49 +00001682
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02001683 stdin_encoding = _PyObject_GetAttrId(fin, &PyId_encoding);
Antoine Pitrou5ee9d8a2011-11-06 00:38:45 +01001684 stdin_errors = _PyObject_GetAttrId(fin, &PyId_errors);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001685 if (!stdin_encoding || !stdin_errors)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001686 /* stdin is a text stream, so it must have an
1687 encoding. */
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001688 goto _readline_errors;
Victor Stinner306f0102010-05-19 01:06:22 +00001689 stdin_encoding_str = _PyUnicode_AsString(stdin_encoding);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001690 stdin_errors_str = _PyUnicode_AsString(stdin_errors);
1691 if (!stdin_encoding_str || !stdin_errors_str)
1692 goto _readline_errors;
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001693 tmp = _PyObject_CallMethodId(fout, &PyId_flush, "");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001694 if (tmp == NULL)
1695 PyErr_Clear();
1696 else
1697 Py_DECREF(tmp);
1698 if (promptarg != NULL) {
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001699 /* We have a prompt, encode it as stdout would */
1700 char *stdout_encoding_str, *stdout_errors_str;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001701 PyObject *stringpo;
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02001702 stdout_encoding = _PyObject_GetAttrId(fout, &PyId_encoding);
Antoine Pitrou5ee9d8a2011-11-06 00:38:45 +01001703 stdout_errors = _PyObject_GetAttrId(fout, &PyId_errors);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001704 if (!stdout_encoding || !stdout_errors)
1705 goto _readline_errors;
Victor Stinner306f0102010-05-19 01:06:22 +00001706 stdout_encoding_str = _PyUnicode_AsString(stdout_encoding);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001707 stdout_errors_str = _PyUnicode_AsString(stdout_errors);
1708 if (!stdout_encoding_str || !stdout_errors_str)
1709 goto _readline_errors;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001710 stringpo = PyObject_Str(promptarg);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001711 if (stringpo == NULL)
1712 goto _readline_errors;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001713 po = PyUnicode_AsEncodedString(stringpo,
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001714 stdout_encoding_str, stdout_errors_str);
1715 Py_CLEAR(stdout_encoding);
1716 Py_CLEAR(stdout_errors);
1717 Py_CLEAR(stringpo);
1718 if (po == NULL)
1719 goto _readline_errors;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001720 prompt = PyBytes_AsString(po);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001721 if (prompt == NULL)
1722 goto _readline_errors;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001723 }
1724 else {
1725 po = NULL;
1726 prompt = "";
1727 }
1728 s = PyOS_Readline(stdin, stdout, prompt);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001729 if (s == NULL) {
1730 if (!PyErr_Occurred())
1731 PyErr_SetNone(PyExc_KeyboardInterrupt);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001732 goto _readline_errors;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001733 }
Victor Stinnerc0f1a1a2011-02-23 12:07:37 +00001734
1735 len = strlen(s);
1736 if (len == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001737 PyErr_SetNone(PyExc_EOFError);
1738 result = NULL;
1739 }
Victor Stinnerc0f1a1a2011-02-23 12:07:37 +00001740 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001741 if (len > PY_SSIZE_T_MAX) {
1742 PyErr_SetString(PyExc_OverflowError,
1743 "input: input too long");
1744 result = NULL;
1745 }
1746 else {
Victor Stinnerc0f1a1a2011-02-23 12:07:37 +00001747 len--; /* strip trailing '\n' */
1748 if (len != 0 && s[len-1] == '\r')
1749 len--; /* strip trailing '\r' */
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001750 result = PyUnicode_Decode(s, len, stdin_encoding_str,
1751 stdin_errors_str);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001752 }
1753 }
1754 Py_DECREF(stdin_encoding);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001755 Py_DECREF(stdin_errors);
1756 Py_XDECREF(po);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001757 PyMem_FREE(s);
1758 return result;
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001759 _readline_errors:
1760 Py_XDECREF(stdin_encoding);
1761 Py_XDECREF(stdout_encoding);
1762 Py_XDECREF(stdin_errors);
1763 Py_XDECREF(stdout_errors);
1764 Py_XDECREF(po);
1765 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001766 }
Guido van Rossumeba76962007-05-27 09:13:28 +00001767
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001768 /* Fallback if we're not interactive */
1769 if (promptarg != NULL) {
1770 if (PyFile_WriteObject(promptarg, fout, Py_PRINT_RAW) != 0)
1771 return NULL;
1772 }
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001773 tmp = _PyObject_CallMethodId(fout, &PyId_flush, "");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001774 if (tmp == NULL)
1775 PyErr_Clear();
1776 else
1777 Py_DECREF(tmp);
1778 return PyFile_GetLine(fin, -1);
Guido van Rossuma88a0332007-02-26 16:59:55 +00001779}
1780
1781PyDoc_STRVAR(input_doc,
1782"input([prompt]) -> string\n\
1783\n\
1784Read a string from standard input. The trailing newline is stripped.\n\
1785If the user hits EOF (Unix: Ctl-D, Windows: Ctl-Z+Return), raise EOFError.\n\
1786On Unix, GNU readline is used if enabled. The prompt string, if given,\n\
1787is printed without a trailing newline before reading.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001788
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001789
Guido van Rossum79f25d91997-04-29 20:08:16 +00001790static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001791builtin_repr(PyObject *self, PyObject *v)
Guido van Rossumc89705d1992-11-26 08:54:07 +00001792{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001793 return PyObject_Repr(v);
Guido van Rossumc89705d1992-11-26 08:54:07 +00001794}
1795
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001796PyDoc_STRVAR(repr_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001797"repr(object) -> string\n\
1798\n\
1799Return the canonical string representation of the object.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001800For most object types, eval(repr(object)) == object.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001801
1802
Guido van Rossum79f25d91997-04-29 20:08:16 +00001803static PyObject *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001804builtin_round(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum9e51f9b1993-02-12 16:29:05 +00001805{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001806 static PyObject *round_str = NULL;
1807 PyObject *ndigits = NULL;
1808 static char *kwlist[] = {"number", "ndigits", 0};
1809 PyObject *number, *round;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001810
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001811 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|O:round",
1812 kwlist, &number, &ndigits))
1813 return NULL;
Alex Martelliae211f92007-08-22 23:21:33 +00001814
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001815 if (Py_TYPE(number)->tp_dict == NULL) {
1816 if (PyType_Ready(Py_TYPE(number)) < 0)
1817 return NULL;
1818 }
Guido van Rossum15d3d042007-08-24 02:02:45 +00001819
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001820 if (round_str == NULL) {
1821 round_str = PyUnicode_InternFromString("__round__");
1822 if (round_str == NULL)
1823 return NULL;
1824 }
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001825
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001826 round = _PyType_Lookup(Py_TYPE(number), round_str);
1827 if (round == NULL) {
1828 PyErr_Format(PyExc_TypeError,
1829 "type %.100s doesn't define __round__ method",
1830 Py_TYPE(number)->tp_name);
1831 return NULL;
1832 }
Alex Martelliae211f92007-08-22 23:21:33 +00001833
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001834 if (ndigits == NULL)
1835 return PyObject_CallFunction(round, "O", number);
1836 else
1837 return PyObject_CallFunction(round, "OO", number, ndigits);
Guido van Rossum9e51f9b1993-02-12 16:29:05 +00001838}
1839
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001840PyDoc_STRVAR(round_doc,
Mark Dickinson1124e712009-01-28 21:25:58 +00001841"round(number[, ndigits]) -> number\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001842\n\
1843Round a number to a given precision in decimal digits (default 0 digits).\n\
Mark Dickinson0d748c22008-07-05 11:29:03 +00001844This returns an int when called with one argument, otherwise the\n\
Georg Brandl809ddaa2008-07-01 20:39:59 +00001845same type as the number. ndigits may be negative.");
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001846
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001847
Raymond Hettinger64958a12003-12-17 20:43:33 +00001848static PyObject *
1849builtin_sorted(PyObject *self, PyObject *args, PyObject *kwds)
1850{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001851 PyObject *newlist, *v, *seq, *keyfunc=NULL, *newargs;
1852 PyObject *callable;
1853 static char *kwlist[] = {"iterable", "key", "reverse", 0};
1854 int reverse;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02001855 _Py_IDENTIFIER(sort);
Raymond Hettinger64958a12003-12-17 20:43:33 +00001856
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001857 /* args 1-3 should match listsort in Objects/listobject.c */
1858 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|Oi:sorted",
1859 kwlist, &seq, &keyfunc, &reverse))
1860 return NULL;
Raymond Hettinger64958a12003-12-17 20:43:33 +00001861
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001862 newlist = PySequence_List(seq);
1863 if (newlist == NULL)
1864 return NULL;
Raymond Hettinger64958a12003-12-17 20:43:33 +00001865
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02001866 callable = _PyObject_GetAttrId(newlist, &PyId_sort);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001867 if (callable == NULL) {
1868 Py_DECREF(newlist);
1869 return NULL;
1870 }
Georg Brandl99d7e4e2005-08-31 22:21:15 +00001871
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001872 newargs = PyTuple_GetSlice(args, 1, 4);
1873 if (newargs == NULL) {
1874 Py_DECREF(newlist);
1875 Py_DECREF(callable);
1876 return NULL;
1877 }
Raymond Hettinger64958a12003-12-17 20:43:33 +00001878
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001879 v = PyObject_Call(callable, newargs, kwds);
1880 Py_DECREF(newargs);
1881 Py_DECREF(callable);
1882 if (v == NULL) {
1883 Py_DECREF(newlist);
1884 return NULL;
1885 }
1886 Py_DECREF(v);
1887 return newlist;
Raymond Hettinger64958a12003-12-17 20:43:33 +00001888}
1889
1890PyDoc_STRVAR(sorted_doc,
Raymond Hettinger70b64fc2008-01-30 20:15:17 +00001891"sorted(iterable, key=None, reverse=False) --> new sorted list");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001892
Guido van Rossum79f25d91997-04-29 20:08:16 +00001893static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001894builtin_vars(PyObject *self, PyObject *args)
Guido van Rossum2d951851994-08-29 12:52:16 +00001895{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001896 PyObject *v = NULL;
1897 PyObject *d;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001898
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001899 if (!PyArg_UnpackTuple(args, "vars", 0, 1, &v))
1900 return NULL;
1901 if (v == NULL) {
1902 d = PyEval_GetLocals();
1903 if (d == NULL) {
1904 if (!PyErr_Occurred())
1905 PyErr_SetString(PyExc_SystemError,
1906 "vars(): no locals!?");
1907 }
1908 else
1909 Py_INCREF(d);
1910 }
1911 else {
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02001912 _Py_IDENTIFIER(__dict__);
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02001913 d = _PyObject_GetAttrId(v, &PyId___dict__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001914 if (d == NULL) {
1915 PyErr_SetString(PyExc_TypeError,
1916 "vars() argument must have __dict__ attribute");
1917 return NULL;
1918 }
1919 }
1920 return d;
Guido van Rossum2d951851994-08-29 12:52:16 +00001921}
1922
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001923PyDoc_STRVAR(vars_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001924"vars([object]) -> dictionary\n\
1925\n\
1926Without arguments, equivalent to locals().\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001927With an argument, equivalent to object.__dict__.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001928
Alex Martellia70b1912003-04-22 08:12:33 +00001929static PyObject*
1930builtin_sum(PyObject *self, PyObject *args)
1931{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001932 PyObject *seq;
1933 PyObject *result = NULL;
1934 PyObject *temp, *item, *iter;
Alex Martellia70b1912003-04-22 08:12:33 +00001935
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001936 if (!PyArg_UnpackTuple(args, "sum", 1, 2, &seq, &result))
1937 return NULL;
Alex Martellia70b1912003-04-22 08:12:33 +00001938
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001939 iter = PyObject_GetIter(seq);
1940 if (iter == NULL)
1941 return NULL;
Alex Martellia70b1912003-04-22 08:12:33 +00001942
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001943 if (result == NULL) {
1944 result = PyLong_FromLong(0);
1945 if (result == NULL) {
1946 Py_DECREF(iter);
1947 return NULL;
1948 }
1949 } else {
1950 /* reject string values for 'start' parameter */
1951 if (PyUnicode_Check(result)) {
1952 PyErr_SetString(PyExc_TypeError,
1953 "sum() can't sum strings [use ''.join(seq) instead]");
1954 Py_DECREF(iter);
1955 return NULL;
1956 }
Benjamin Petersonce071ca2011-07-29 14:23:47 -05001957 if (PyBytes_Check(result)) {
1958 PyErr_SetString(PyExc_TypeError,
1959 "sum() can't sum bytes [use b''.join(seq) instead]");
Benjamin Peterson405f32c2011-07-29 22:43:45 -05001960 Py_DECREF(iter);
Benjamin Petersonce071ca2011-07-29 14:23:47 -05001961 return NULL;
1962 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001963 if (PyByteArray_Check(result)) {
1964 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson4f921c22011-07-29 14:24:29 -05001965 "sum() can't sum bytearray [use b''.join(seq) instead]");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001966 Py_DECREF(iter);
1967 return NULL;
1968 }
Guido van Rossum3172c5d2007-10-16 18:12:55 +00001969
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001970 Py_INCREF(result);
1971 }
Alex Martellia70b1912003-04-22 08:12:33 +00001972
Guido van Rossum8ce8a782007-11-01 19:42:39 +00001973#ifndef SLOW_SUM
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001974 /* Fast addition by keeping temporary sums in C instead of new Python objects.
1975 Assumes all inputs are the same type. If the assumption fails, default
1976 to the more general routine.
1977 */
1978 if (PyLong_CheckExact(result)) {
1979 int overflow;
1980 long i_result = PyLong_AsLongAndOverflow(result, &overflow);
1981 /* If this already overflowed, don't even enter the loop. */
1982 if (overflow == 0) {
1983 Py_DECREF(result);
1984 result = NULL;
1985 }
1986 while(result == NULL) {
1987 item = PyIter_Next(iter);
1988 if (item == NULL) {
1989 Py_DECREF(iter);
1990 if (PyErr_Occurred())
1991 return NULL;
1992 return PyLong_FromLong(i_result);
1993 }
1994 if (PyLong_CheckExact(item)) {
1995 long b = PyLong_AsLongAndOverflow(item, &overflow);
1996 long x = i_result + b;
1997 if (overflow == 0 && ((x^i_result) >= 0 || (x^b) >= 0)) {
1998 i_result = x;
1999 Py_DECREF(item);
2000 continue;
2001 }
2002 }
2003 /* Either overflowed or is not an int. Restore real objects and process normally */
2004 result = PyLong_FromLong(i_result);
2005 temp = PyNumber_Add(result, item);
2006 Py_DECREF(result);
2007 Py_DECREF(item);
2008 result = temp;
2009 if (result == NULL) {
2010 Py_DECREF(iter);
2011 return NULL;
2012 }
2013 }
2014 }
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002015
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002016 if (PyFloat_CheckExact(result)) {
2017 double f_result = PyFloat_AS_DOUBLE(result);
2018 Py_DECREF(result);
2019 result = NULL;
2020 while(result == NULL) {
2021 item = PyIter_Next(iter);
2022 if (item == NULL) {
2023 Py_DECREF(iter);
2024 if (PyErr_Occurred())
2025 return NULL;
2026 return PyFloat_FromDouble(f_result);
2027 }
2028 if (PyFloat_CheckExact(item)) {
2029 PyFPE_START_PROTECT("add", Py_DECREF(item); Py_DECREF(iter); return 0)
2030 f_result += PyFloat_AS_DOUBLE(item);
2031 PyFPE_END_PROTECT(f_result)
2032 Py_DECREF(item);
2033 continue;
2034 }
2035 if (PyLong_CheckExact(item)) {
2036 long value;
2037 int overflow;
2038 value = PyLong_AsLongAndOverflow(item, &overflow);
2039 if (!overflow) {
2040 PyFPE_START_PROTECT("add", Py_DECREF(item); Py_DECREF(iter); return 0)
2041 f_result += (double)value;
2042 PyFPE_END_PROTECT(f_result)
2043 Py_DECREF(item);
2044 continue;
2045 }
2046 }
2047 result = PyFloat_FromDouble(f_result);
2048 temp = PyNumber_Add(result, item);
2049 Py_DECREF(result);
2050 Py_DECREF(item);
2051 result = temp;
2052 if (result == NULL) {
2053 Py_DECREF(iter);
2054 return NULL;
2055 }
2056 }
2057 }
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002058#endif
2059
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002060 for(;;) {
2061 item = PyIter_Next(iter);
2062 if (item == NULL) {
2063 /* error, or end-of-sequence */
2064 if (PyErr_Occurred()) {
2065 Py_DECREF(result);
2066 result = NULL;
2067 }
2068 break;
2069 }
2070 /* It's tempting to use PyNumber_InPlaceAdd instead of
2071 PyNumber_Add here, to avoid quadratic running time
2072 when doing 'sum(list_of_lists, [])'. However, this
2073 would produce a change in behaviour: a snippet like
Mark Dickinson9acadc52009-10-26 14:19:42 +00002074
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002075 empty = []
2076 sum([[x] for x in range(10)], empty)
Mark Dickinson9acadc52009-10-26 14:19:42 +00002077
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002078 would change the value of empty. */
2079 temp = PyNumber_Add(result, item);
2080 Py_DECREF(result);
2081 Py_DECREF(item);
2082 result = temp;
2083 if (result == NULL)
2084 break;
2085 }
2086 Py_DECREF(iter);
2087 return result;
Alex Martellia70b1912003-04-22 08:12:33 +00002088}
2089
2090PyDoc_STRVAR(sum_doc,
Georg Brandld11ae5d2008-05-16 13:27:32 +00002091"sum(iterable[, start]) -> value\n\
Alex Martellia70b1912003-04-22 08:12:33 +00002092\n\
Georg Brandld11ae5d2008-05-16 13:27:32 +00002093Returns the sum of an iterable of numbers (NOT strings) plus the value\n\
2094of parameter 'start' (which defaults to 0). When the iterable is\n\
Thomas Wouters89f507f2006-12-13 04:49:30 +00002095empty, returns start.");
Alex Martellia70b1912003-04-22 08:12:33 +00002096
2097
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002098static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002099builtin_isinstance(PyObject *self, PyObject *args)
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002100{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002101 PyObject *inst;
2102 PyObject *cls;
2103 int retval;
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002104
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002105 if (!PyArg_UnpackTuple(args, "isinstance", 2, 2, &inst, &cls))
2106 return NULL;
Guido van Rossumf5dd9141997-12-02 19:11:45 +00002107
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002108 retval = PyObject_IsInstance(inst, cls);
2109 if (retval < 0)
2110 return NULL;
2111 return PyBool_FromLong(retval);
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002112}
2113
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002114PyDoc_STRVAR(isinstance_doc,
Guido van Rossum77f6a652002-04-03 22:41:51 +00002115"isinstance(object, class-or-type-or-tuple) -> bool\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002116\n\
2117Return whether an object is an instance of a class or of a subclass thereof.\n\
Guido van Rossum03290ec2001-10-07 20:54:12 +00002118With a type as second argument, return whether that is the object's type.\n\
2119The form using a tuple, isinstance(x, (A, B, ...)), is a shortcut for\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002120isinstance(x, A) or isinstance(x, B) or ... (etc.).");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002121
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002122
2123static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002124builtin_issubclass(PyObject *self, PyObject *args)
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002125{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002126 PyObject *derived;
2127 PyObject *cls;
2128 int retval;
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002129
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002130 if (!PyArg_UnpackTuple(args, "issubclass", 2, 2, &derived, &cls))
2131 return NULL;
Guido van Rossum668213d1999-06-16 17:28:37 +00002132
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002133 retval = PyObject_IsSubclass(derived, cls);
2134 if (retval < 0)
2135 return NULL;
2136 return PyBool_FromLong(retval);
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002137}
2138
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002139PyDoc_STRVAR(issubclass_doc,
Guido van Rossum77f6a652002-04-03 22:41:51 +00002140"issubclass(C, B) -> bool\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002141\n\
Walter Dörwaldd9a6ad32002-12-12 16:41:44 +00002142Return whether class C is a subclass (i.e., a derived class) of class B.\n\
2143When using a tuple as the second argument issubclass(X, (A, B, ...)),\n\
2144is a shortcut for issubclass(X, A) or issubclass(X, B) or ... (etc.).");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002145
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002146
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002147typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002148 PyObject_HEAD
2149 Py_ssize_t tuplesize;
2150 PyObject *ittuple; /* tuple of iterators */
2151 PyObject *result;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002152} zipobject;
2153
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002154static PyObject *
2155zip_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
Barry Warsawbd599b52000-08-03 15:45:29 +00002156{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002157 zipobject *lz;
2158 Py_ssize_t i;
2159 PyObject *ittuple; /* tuple of iterators */
2160 PyObject *result;
2161 Py_ssize_t tuplesize = PySequence_Length(args);
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002162
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002163 if (type == &PyZip_Type && !_PyArg_NoKeywords("zip()", kwds))
2164 return NULL;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002165
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002166 /* args must be a tuple */
2167 assert(PyTuple_Check(args));
Barry Warsawbd599b52000-08-03 15:45:29 +00002168
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002169 /* obtain iterators */
2170 ittuple = PyTuple_New(tuplesize);
2171 if (ittuple == NULL)
2172 return NULL;
2173 for (i=0; i < tuplesize; ++i) {
2174 PyObject *item = PyTuple_GET_ITEM(args, i);
2175 PyObject *it = PyObject_GetIter(item);
2176 if (it == NULL) {
2177 if (PyErr_ExceptionMatches(PyExc_TypeError))
2178 PyErr_Format(PyExc_TypeError,
2179 "zip argument #%zd must support iteration",
2180 i+1);
2181 Py_DECREF(ittuple);
2182 return NULL;
2183 }
2184 PyTuple_SET_ITEM(ittuple, i, it);
2185 }
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002186
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002187 /* create a result holder */
2188 result = PyTuple_New(tuplesize);
2189 if (result == NULL) {
2190 Py_DECREF(ittuple);
2191 return NULL;
2192 }
2193 for (i=0 ; i < tuplesize ; i++) {
2194 Py_INCREF(Py_None);
2195 PyTuple_SET_ITEM(result, i, Py_None);
2196 }
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002197
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002198 /* create zipobject structure */
2199 lz = (zipobject *)type->tp_alloc(type, 0);
2200 if (lz == NULL) {
2201 Py_DECREF(ittuple);
2202 Py_DECREF(result);
2203 return NULL;
2204 }
2205 lz->ittuple = ittuple;
2206 lz->tuplesize = tuplesize;
2207 lz->result = result;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002208
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002209 return (PyObject *)lz;
Barry Warsawbd599b52000-08-03 15:45:29 +00002210}
2211
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002212static void
2213zip_dealloc(zipobject *lz)
2214{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002215 PyObject_GC_UnTrack(lz);
2216 Py_XDECREF(lz->ittuple);
2217 Py_XDECREF(lz->result);
2218 Py_TYPE(lz)->tp_free(lz);
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002219}
2220
2221static int
2222zip_traverse(zipobject *lz, visitproc visit, void *arg)
2223{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002224 Py_VISIT(lz->ittuple);
2225 Py_VISIT(lz->result);
2226 return 0;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002227}
2228
2229static PyObject *
2230zip_next(zipobject *lz)
2231{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002232 Py_ssize_t i;
2233 Py_ssize_t tuplesize = lz->tuplesize;
2234 PyObject *result = lz->result;
2235 PyObject *it;
2236 PyObject *item;
2237 PyObject *olditem;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002238
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002239 if (tuplesize == 0)
2240 return NULL;
2241 if (Py_REFCNT(result) == 1) {
2242 Py_INCREF(result);
2243 for (i=0 ; i < tuplesize ; i++) {
2244 it = PyTuple_GET_ITEM(lz->ittuple, i);
2245 item = (*Py_TYPE(it)->tp_iternext)(it);
2246 if (item == NULL) {
2247 Py_DECREF(result);
2248 return NULL;
2249 }
2250 olditem = PyTuple_GET_ITEM(result, i);
2251 PyTuple_SET_ITEM(result, i, item);
2252 Py_DECREF(olditem);
2253 }
2254 } else {
2255 result = PyTuple_New(tuplesize);
2256 if (result == NULL)
2257 return NULL;
2258 for (i=0 ; i < tuplesize ; i++) {
2259 it = PyTuple_GET_ITEM(lz->ittuple, i);
2260 item = (*Py_TYPE(it)->tp_iternext)(it);
2261 if (item == NULL) {
2262 Py_DECREF(result);
2263 return NULL;
2264 }
2265 PyTuple_SET_ITEM(result, i, item);
2266 }
2267 }
2268 return result;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002269}
Barry Warsawbd599b52000-08-03 15:45:29 +00002270
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002271static PyObject *
2272zip_reduce(zipobject *lz)
2273{
2274 /* Just recreate the zip with the internal iterator tuple */
2275 return Py_BuildValue("OO", Py_TYPE(lz), lz->ittuple);
2276}
2277
2278static PyMethodDef zip_methods[] = {
2279 {"__reduce__", (PyCFunction)zip_reduce, METH_NOARGS, reduce_doc},
2280 {NULL, NULL} /* sentinel */
2281};
2282
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002283PyDoc_STRVAR(zip_doc,
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002284"zip(iter1 [,iter2 [...]]) --> zip object\n\
Barry Warsawbd599b52000-08-03 15:45:29 +00002285\n\
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002286Return a zip object whose .__next__() method returns a tuple where\n\
2287the i-th element comes from the i-th iterable argument. The .__next__()\n\
2288method continues until the shortest iterable in the argument sequence\n\
Georg Brandlced51db2008-12-04 18:28:38 +00002289is exhausted and then it raises StopIteration.");
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002290
2291PyTypeObject PyZip_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002292 PyVarObject_HEAD_INIT(&PyType_Type, 0)
2293 "zip", /* tp_name */
2294 sizeof(zipobject), /* tp_basicsize */
2295 0, /* tp_itemsize */
2296 /* methods */
2297 (destructor)zip_dealloc, /* tp_dealloc */
2298 0, /* tp_print */
2299 0, /* tp_getattr */
2300 0, /* tp_setattr */
2301 0, /* tp_reserved */
2302 0, /* tp_repr */
2303 0, /* tp_as_number */
2304 0, /* tp_as_sequence */
2305 0, /* tp_as_mapping */
2306 0, /* tp_hash */
2307 0, /* tp_call */
2308 0, /* tp_str */
2309 PyObject_GenericGetAttr, /* tp_getattro */
2310 0, /* tp_setattro */
2311 0, /* tp_as_buffer */
2312 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
2313 Py_TPFLAGS_BASETYPE, /* tp_flags */
2314 zip_doc, /* tp_doc */
2315 (traverseproc)zip_traverse, /* tp_traverse */
2316 0, /* tp_clear */
2317 0, /* tp_richcompare */
2318 0, /* tp_weaklistoffset */
2319 PyObject_SelfIter, /* tp_iter */
2320 (iternextfunc)zip_next, /* tp_iternext */
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002321 zip_methods, /* tp_methods */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002322 0, /* tp_members */
2323 0, /* tp_getset */
2324 0, /* tp_base */
2325 0, /* tp_dict */
2326 0, /* tp_descr_get */
2327 0, /* tp_descr_set */
2328 0, /* tp_dictoffset */
2329 0, /* tp_init */
2330 PyType_GenericAlloc, /* tp_alloc */
2331 zip_new, /* tp_new */
2332 PyObject_GC_Del, /* tp_free */
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002333};
Barry Warsawbd599b52000-08-03 15:45:29 +00002334
2335
Guido van Rossum79f25d91997-04-29 20:08:16 +00002336static PyMethodDef builtin_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002337 {"__build_class__", (PyCFunction)builtin___build_class__,
2338 METH_VARARGS | METH_KEYWORDS, build_class_doc},
2339 {"__import__", (PyCFunction)builtin___import__, METH_VARARGS | METH_KEYWORDS, import_doc},
2340 {"abs", builtin_abs, METH_O, abs_doc},
2341 {"all", builtin_all, METH_O, all_doc},
2342 {"any", builtin_any, METH_O, any_doc},
2343 {"ascii", builtin_ascii, METH_O, ascii_doc},
2344 {"bin", builtin_bin, METH_O, bin_doc},
Antoine Pitroue71362d2010-11-27 22:00:11 +00002345 {"callable", builtin_callable, METH_O, callable_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002346 {"chr", builtin_chr, METH_VARARGS, chr_doc},
2347 {"compile", (PyCFunction)builtin_compile, METH_VARARGS | METH_KEYWORDS, compile_doc},
2348 {"delattr", builtin_delattr, METH_VARARGS, delattr_doc},
2349 {"dir", builtin_dir, METH_VARARGS, dir_doc},
2350 {"divmod", builtin_divmod, METH_VARARGS, divmod_doc},
2351 {"eval", builtin_eval, METH_VARARGS, eval_doc},
2352 {"exec", builtin_exec, METH_VARARGS, exec_doc},
2353 {"format", builtin_format, METH_VARARGS, format_doc},
2354 {"getattr", builtin_getattr, METH_VARARGS, getattr_doc},
2355 {"globals", (PyCFunction)builtin_globals, METH_NOARGS, globals_doc},
2356 {"hasattr", builtin_hasattr, METH_VARARGS, hasattr_doc},
2357 {"hash", builtin_hash, METH_O, hash_doc},
2358 {"hex", builtin_hex, METH_O, hex_doc},
2359 {"id", builtin_id, METH_O, id_doc},
2360 {"input", builtin_input, METH_VARARGS, input_doc},
2361 {"isinstance", builtin_isinstance, METH_VARARGS, isinstance_doc},
2362 {"issubclass", builtin_issubclass, METH_VARARGS, issubclass_doc},
2363 {"iter", builtin_iter, METH_VARARGS, iter_doc},
2364 {"len", builtin_len, METH_O, len_doc},
2365 {"locals", (PyCFunction)builtin_locals, METH_NOARGS, locals_doc},
2366 {"max", (PyCFunction)builtin_max, METH_VARARGS | METH_KEYWORDS, max_doc},
2367 {"min", (PyCFunction)builtin_min, METH_VARARGS | METH_KEYWORDS, min_doc},
2368 {"next", (PyCFunction)builtin_next, METH_VARARGS, next_doc},
2369 {"oct", builtin_oct, METH_O, oct_doc},
2370 {"ord", builtin_ord, METH_O, ord_doc},
2371 {"pow", builtin_pow, METH_VARARGS, pow_doc},
2372 {"print", (PyCFunction)builtin_print, METH_VARARGS | METH_KEYWORDS, print_doc},
2373 {"repr", builtin_repr, METH_O, repr_doc},
2374 {"round", (PyCFunction)builtin_round, METH_VARARGS | METH_KEYWORDS, round_doc},
2375 {"setattr", builtin_setattr, METH_VARARGS, setattr_doc},
2376 {"sorted", (PyCFunction)builtin_sorted, METH_VARARGS | METH_KEYWORDS, sorted_doc},
2377 {"sum", builtin_sum, METH_VARARGS, sum_doc},
2378 {"vars", builtin_vars, METH_VARARGS, vars_doc},
2379 {NULL, NULL},
Guido van Rossum3f5da241990-12-20 15:06:42 +00002380};
2381
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002382PyDoc_STRVAR(builtin_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002383"Built-in functions, exceptions, and other objects.\n\
2384\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002385Noteworthy: None is the `nil' object; Ellipsis represents `...' in slices.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002386
Martin v. Löwis1a214512008-06-11 05:26:20 +00002387static struct PyModuleDef builtinsmodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002388 PyModuleDef_HEAD_INIT,
2389 "builtins",
2390 builtin_doc,
2391 -1, /* multiple "initialization" just copies the module dict. */
2392 builtin_methods,
2393 NULL,
2394 NULL,
2395 NULL,
2396 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00002397};
2398
2399
Guido van Rossum25ce5661997-08-02 03:10:38 +00002400PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002401_PyBuiltin_Init(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +00002402{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002403 PyObject *mod, *dict, *debug;
2404 mod = PyModule_Create(&builtinsmodule);
2405 if (mod == NULL)
2406 return NULL;
2407 dict = PyModule_GetDict(mod);
Tim Peters4b7625e2001-09-13 21:37:17 +00002408
Tim Peters7571a0f2003-03-23 17:52:28 +00002409#ifdef Py_TRACE_REFS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002410 /* "builtins" exposes a number of statically allocated objects
2411 * that, before this code was added in 2.3, never showed up in
2412 * the list of "all objects" maintained by Py_TRACE_REFS. As a
2413 * result, programs leaking references to None and False (etc)
2414 * couldn't be diagnosed by examining sys.getobjects(0).
2415 */
Tim Peters7571a0f2003-03-23 17:52:28 +00002416#define ADD_TO_ALL(OBJECT) _Py_AddToAllObjects((PyObject *)(OBJECT), 0)
2417#else
2418#define ADD_TO_ALL(OBJECT) (void)0
2419#endif
2420
Tim Peters4b7625e2001-09-13 21:37:17 +00002421#define SETBUILTIN(NAME, OBJECT) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002422 if (PyDict_SetItemString(dict, NAME, (PyObject *)OBJECT) < 0) \
2423 return NULL; \
2424 ADD_TO_ALL(OBJECT)
Tim Peters4b7625e2001-09-13 21:37:17 +00002425
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002426 SETBUILTIN("None", Py_None);
2427 SETBUILTIN("Ellipsis", Py_Ellipsis);
2428 SETBUILTIN("NotImplemented", Py_NotImplemented);
2429 SETBUILTIN("False", Py_False);
2430 SETBUILTIN("True", Py_True);
2431 SETBUILTIN("bool", &PyBool_Type);
2432 SETBUILTIN("memoryview", &PyMemoryView_Type);
2433 SETBUILTIN("bytearray", &PyByteArray_Type);
2434 SETBUILTIN("bytes", &PyBytes_Type);
2435 SETBUILTIN("classmethod", &PyClassMethod_Type);
2436 SETBUILTIN("complex", &PyComplex_Type);
2437 SETBUILTIN("dict", &PyDict_Type);
2438 SETBUILTIN("enumerate", &PyEnum_Type);
2439 SETBUILTIN("filter", &PyFilter_Type);
2440 SETBUILTIN("float", &PyFloat_Type);
2441 SETBUILTIN("frozenset", &PyFrozenSet_Type);
2442 SETBUILTIN("property", &PyProperty_Type);
2443 SETBUILTIN("int", &PyLong_Type);
2444 SETBUILTIN("list", &PyList_Type);
2445 SETBUILTIN("map", &PyMap_Type);
2446 SETBUILTIN("object", &PyBaseObject_Type);
2447 SETBUILTIN("range", &PyRange_Type);
2448 SETBUILTIN("reversed", &PyReversed_Type);
2449 SETBUILTIN("set", &PySet_Type);
2450 SETBUILTIN("slice", &PySlice_Type);
2451 SETBUILTIN("staticmethod", &PyStaticMethod_Type);
2452 SETBUILTIN("str", &PyUnicode_Type);
2453 SETBUILTIN("super", &PySuper_Type);
2454 SETBUILTIN("tuple", &PyTuple_Type);
2455 SETBUILTIN("type", &PyType_Type);
2456 SETBUILTIN("zip", &PyZip_Type);
2457 debug = PyBool_FromLong(Py_OptimizeFlag == 0);
2458 if (PyDict_SetItemString(dict, "__debug__", debug) < 0) {
2459 Py_XDECREF(debug);
2460 return NULL;
2461 }
2462 Py_XDECREF(debug);
Barry Warsaw757af0e1997-08-29 22:13:51 +00002463
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002464 return mod;
Tim Peters7571a0f2003-03-23 17:52:28 +00002465#undef ADD_TO_ALL
Tim Peters4b7625e2001-09-13 21:37:17 +00002466#undef SETBUILTIN
Guido van Rossum3f5da241990-12-20 15:06:42 +00002467}