blob: e6511a1ae6bdc262e211cd51aa7bbb71092d6247 [file] [log] [blame]
Guido van Rossum3f5da241990-12-20 15:06:42 +00001/* Built-in functions */
2
Guido van Rossum79f25d91997-04-29 20:08:16 +00003#include "Python.h"
Martin v. Löwis618dc5e2008-03-30 20:03:44 +00004#include "Python-ast.h"
Guido van Rossum3f5da241990-12-20 15:06:42 +00005
6#include "node.h"
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00007#include "code.h"
Guido van Rossum3f5da241990-12-20 15:06:42 +00008
Benjamin Petersonea281a52011-08-12 23:10:50 -05009#include "asdl.h"
10#include "ast.h"
11
Guido van Rossum6bf62da1997-04-11 20:37:35 +000012#include <ctype.h>
13
Victor Stinnerb744ba12010-05-15 12:27:16 +000014#ifdef HAVE_LANGINFO_H
15#include <langinfo.h> /* CODESET */
16#endif
17
Mark Hammond26cffde42001-05-14 12:17:34 +000018/* The default encoding used by the platform file system APIs
19 Can remain NULL for all platforms that don't have such a concept
Guido van Rossum00bc0e02007-10-15 02:52:41 +000020
21 Don't forget to modify PyUnicode_DecodeFSDefault() if you touch any of the
22 values for Py_FileSystemDefaultEncoding!
Mark Hammond26cffde42001-05-14 12:17:34 +000023*/
Victor Stinner99b95382011-07-04 14:23:54 +020024#ifdef HAVE_MBCS
Mark Hammond26cffde42001-05-14 12:17:34 +000025const char *Py_FileSystemDefaultEncoding = "mbcs";
Martin v. Löwis04dc25c2008-10-03 16:09:28 +000026int Py_HasFileSystemDefaultEncoding = 1;
Just van Rossumb9b8e9c2003-02-10 09:22:01 +000027#elif defined(__APPLE__)
28const char *Py_FileSystemDefaultEncoding = "utf-8";
Martin v. Löwis04dc25c2008-10-03 16:09:28 +000029int Py_HasFileSystemDefaultEncoding = 1;
Victor Stinnerd64e8a72011-07-04 13:48:30 +020030#else
Victor Stinnerb744ba12010-05-15 12:27:16 +000031const char *Py_FileSystemDefaultEncoding = NULL; /* set by initfsencoding() */
Martin v. Löwis04dc25c2008-10-03 16:09:28 +000032int Py_HasFileSystemDefaultEncoding = 0;
Mark Hammond26cffde42001-05-14 12:17:34 +000033#endif
Mark Hammondef8b6542001-05-13 08:04:26 +000034
Martin v. Löwisbd928fe2011-10-14 10:20:37 +020035_Py_IDENTIFIER(fileno);
36_Py_IDENTIFIER(flush);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +020037
Guido van Rossum79f25d91997-04-29 20:08:16 +000038static PyObject *
Guido van Rossum52cc1d82007-03-18 15:41:51 +000039builtin___build_class__(PyObject *self, PyObject *args, PyObject *kwds)
40{
Nick Coghlande31b192011-10-23 22:04:16 +100041 PyObject *func, *name, *bases, *mkw, *meta, *winner, *prep, *ns, *cell;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000042 PyObject *cls = NULL;
Florent Xicluna4d46c2a2011-10-28 15:00:50 +020043 Py_ssize_t nargs;
Nick Coghlande31b192011-10-23 22:04:16 +100044 int isclass;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +020045 _Py_IDENTIFIER(__prepare__);
Guido van Rossum52cc1d82007-03-18 15:41:51 +000046
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000047 assert(args != NULL);
48 if (!PyTuple_Check(args)) {
49 PyErr_SetString(PyExc_TypeError,
50 "__build_class__: args is not a tuple");
51 return NULL;
52 }
53 nargs = PyTuple_GET_SIZE(args);
54 if (nargs < 2) {
55 PyErr_SetString(PyExc_TypeError,
56 "__build_class__: not enough arguments");
57 return NULL;
58 }
59 func = PyTuple_GET_ITEM(args, 0); /* Better be callable */
60 name = PyTuple_GET_ITEM(args, 1);
61 if (!PyUnicode_Check(name)) {
62 PyErr_SetString(PyExc_TypeError,
63 "__build_class__: name is not a string");
64 return NULL;
65 }
66 bases = PyTuple_GetSlice(args, 2, nargs);
67 if (bases == NULL)
68 return NULL;
Guido van Rossum52cc1d82007-03-18 15:41:51 +000069
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000070 if (kwds == NULL) {
71 meta = NULL;
72 mkw = NULL;
73 }
74 else {
75 mkw = PyDict_Copy(kwds); /* Don't modify kwds passed in! */
76 if (mkw == NULL) {
77 Py_DECREF(bases);
78 return NULL;
Guido van Rossum52cc1d82007-03-18 15:41:51 +000079 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000080 meta = PyDict_GetItemString(mkw, "metaclass");
81 if (meta != NULL) {
82 Py_INCREF(meta);
83 if (PyDict_DelItemString(mkw, "metaclass") < 0) {
84 Py_DECREF(meta);
85 Py_DECREF(mkw);
86 Py_DECREF(bases);
87 return NULL;
88 }
Nick Coghlande31b192011-10-23 22:04:16 +100089 /* metaclass is explicitly given, check if it's indeed a class */
90 isclass = PyType_Check(meta);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000091 }
92 }
93 if (meta == NULL) {
Nick Coghlande31b192011-10-23 22:04:16 +100094 /* if there are no bases, use type: */
95 if (PyTuple_GET_SIZE(bases) == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000096 meta = (PyObject *) (&PyType_Type);
Nick Coghlande31b192011-10-23 22:04:16 +100097 }
98 /* else get the type of the first base */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000099 else {
100 PyObject *base0 = PyTuple_GET_ITEM(bases, 0);
101 meta = (PyObject *) (base0->ob_type);
102 }
103 Py_INCREF(meta);
Nick Coghlande31b192011-10-23 22:04:16 +1000104 isclass = 1; /* meta is really a class */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000105 }
Nick Coghlan9715d262011-10-23 22:36:42 +1000106
Nick Coghlande31b192011-10-23 22:04:16 +1000107 if (isclass) {
108 /* meta is really a class, so check for a more derived
109 metaclass, or possible metaclass conflicts: */
110 winner = (PyObject *)_PyType_CalculateMetaclass((PyTypeObject *)meta,
111 bases);
112 if (winner == NULL) {
113 Py_DECREF(meta);
114 Py_XDECREF(mkw);
115 Py_DECREF(bases);
116 return NULL;
117 }
118 if (winner != meta) {
119 Py_DECREF(meta);
120 meta = winner;
121 Py_INCREF(meta);
122 }
123 }
124 /* else: meta is not a class, so we cannot do the metaclass
125 calculation, so we will use the explicitly given object as it is */
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +0200126 prep = _PyObject_GetAttrId(meta, &PyId___prepare__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000127 if (prep == NULL) {
128 if (PyErr_ExceptionMatches(PyExc_AttributeError)) {
129 PyErr_Clear();
130 ns = PyDict_New();
131 }
132 else {
133 Py_DECREF(meta);
134 Py_XDECREF(mkw);
135 Py_DECREF(bases);
136 return NULL;
137 }
138 }
139 else {
140 PyObject *pargs = PyTuple_Pack(2, name, bases);
141 if (pargs == NULL) {
142 Py_DECREF(prep);
143 Py_DECREF(meta);
144 Py_XDECREF(mkw);
145 Py_DECREF(bases);
146 return NULL;
147 }
148 ns = PyEval_CallObjectWithKeywords(prep, pargs, mkw);
149 Py_DECREF(pargs);
150 Py_DECREF(prep);
151 }
152 if (ns == NULL) {
153 Py_DECREF(meta);
154 Py_XDECREF(mkw);
155 Py_DECREF(bases);
156 return NULL;
157 }
158 cell = PyObject_CallFunctionObjArgs(func, ns, NULL);
159 if (cell != NULL) {
160 PyObject *margs;
161 margs = PyTuple_Pack(3, name, bases, ns);
162 if (margs != NULL) {
163 cls = PyEval_CallObjectWithKeywords(meta, margs, mkw);
164 Py_DECREF(margs);
165 }
Benjamin Peterson8e8fbea2012-06-01 23:57:36 -0700166 if (cls != NULL && PyCell_Check(cell))
167 PyCell_Set(cell, cls);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000168 Py_DECREF(cell);
169 }
170 Py_DECREF(ns);
171 Py_DECREF(meta);
172 Py_XDECREF(mkw);
173 Py_DECREF(bases);
174 return cls;
Guido van Rossum52cc1d82007-03-18 15:41:51 +0000175}
176
177PyDoc_STRVAR(build_class_doc,
178"__build_class__(func, name, *bases, metaclass=None, **kwds) -> class\n\
179\n\
180Internal helper function used by the class statement.");
181
182static PyObject *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000183builtin___import__(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000184{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000185 static char *kwlist[] = {"name", "globals", "locals", "fromlist",
186 "level", 0};
Victor Stinnerfe93faf2011-03-14 15:54:52 -0400187 PyObject *name, *globals = NULL, *locals = NULL, *fromlist = NULL;
Brett Cannonfd074152012-04-14 14:10:13 -0400188 int level = 0;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000189
Victor Stinnerfe93faf2011-03-14 15:54:52 -0400190 if (!PyArg_ParseTupleAndKeywords(args, kwds, "U|OOOi:__import__",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000191 kwlist, &name, &globals, &locals, &fromlist, &level))
192 return NULL;
Victor Stinnerfe93faf2011-03-14 15:54:52 -0400193 return PyImport_ImportModuleLevelObject(name, globals, locals,
194 fromlist, level);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000195}
196
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000197PyDoc_STRVAR(import_doc,
Brett Cannoncb4996a2012-08-06 16:34:44 -0400198"__import__(name, globals=None, locals=None, fromlist=(), level=0) -> module\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000199\n\
Brett Cannon5305a992010-09-27 21:08:38 +0000200Import a module. Because this function is meant for use by the Python\n\
201interpreter and not for general use it is better to use\n\
202importlib.import_module() to programmatically import a module.\n\
203\n\
204The globals argument is only used to determine the context;\n\
205they are not modified. The locals argument is unused. The fromlist\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000206should be a list of names to emulate ``from name import ...'', or an\n\
207empty list to emulate ``import name''.\n\
208When importing a module from a package, note that __import__('A.B', ...)\n\
209returns package A when fromlist is empty, but its submodule B when\n\
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000210fromlist is not empty. Level is used to determine whether to perform \n\
Brett Cannon722d3ae2012-07-30 17:45:54 -0400211absolute or relative imports. 0 is absolute while a positive number\n\
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000212is the number of parent directories to search relative to the current module.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000213
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000214
Guido van Rossum79f25d91997-04-29 20:08:16 +0000215static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000216builtin_abs(PyObject *self, PyObject *v)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000217{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000218 return PyNumber_Absolute(v);
Guido van Rossum3f5da241990-12-20 15:06:42 +0000219}
220
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000221PyDoc_STRVAR(abs_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000222"abs(number) -> number\n\
223\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000224Return the absolute value of the argument.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000225
Raymond Hettinger96229b12005-03-11 06:49:40 +0000226static PyObject *
227builtin_all(PyObject *self, PyObject *v)
228{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000229 PyObject *it, *item;
230 PyObject *(*iternext)(PyObject *);
231 int cmp;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000232
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000233 it = PyObject_GetIter(v);
234 if (it == NULL)
235 return NULL;
236 iternext = *Py_TYPE(it)->tp_iternext;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000237
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000238 for (;;) {
239 item = iternext(it);
240 if (item == NULL)
241 break;
242 cmp = PyObject_IsTrue(item);
243 Py_DECREF(item);
244 if (cmp < 0) {
245 Py_DECREF(it);
246 return NULL;
247 }
248 if (cmp == 0) {
249 Py_DECREF(it);
250 Py_RETURN_FALSE;
251 }
252 }
253 Py_DECREF(it);
254 if (PyErr_Occurred()) {
255 if (PyErr_ExceptionMatches(PyExc_StopIteration))
256 PyErr_Clear();
257 else
258 return NULL;
259 }
260 Py_RETURN_TRUE;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000261}
262
263PyDoc_STRVAR(all_doc,
264"all(iterable) -> bool\n\
265\n\
266Return True if bool(x) is True for all values x in the iterable.");
267
268static PyObject *
269builtin_any(PyObject *self, PyObject *v)
270{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000271 PyObject *it, *item;
272 PyObject *(*iternext)(PyObject *);
273 int cmp;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000274
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000275 it = PyObject_GetIter(v);
276 if (it == NULL)
277 return NULL;
278 iternext = *Py_TYPE(it)->tp_iternext;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000279
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000280 for (;;) {
281 item = iternext(it);
282 if (item == NULL)
283 break;
284 cmp = PyObject_IsTrue(item);
285 Py_DECREF(item);
286 if (cmp < 0) {
287 Py_DECREF(it);
288 return NULL;
289 }
290 if (cmp == 1) {
291 Py_DECREF(it);
292 Py_RETURN_TRUE;
293 }
294 }
295 Py_DECREF(it);
296 if (PyErr_Occurred()) {
297 if (PyErr_ExceptionMatches(PyExc_StopIteration))
298 PyErr_Clear();
299 else
300 return NULL;
301 }
302 Py_RETURN_FALSE;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000303}
304
305PyDoc_STRVAR(any_doc,
306"any(iterable) -> bool\n\
307\n\
308Return True if bool(x) is True for any x in the iterable.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000309
Georg Brandl559e5d72008-06-11 18:37:52 +0000310static PyObject *
311builtin_ascii(PyObject *self, PyObject *v)
312{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000313 return PyObject_ASCII(v);
Georg Brandl559e5d72008-06-11 18:37:52 +0000314}
315
316PyDoc_STRVAR(ascii_doc,
317"ascii(object) -> string\n\
318\n\
319As repr(), return a string containing a printable representation of an\n\
320object, but escape the non-ASCII characters in the string returned by\n\
321repr() using \\x, \\u or \\U escapes. This generates a string similar\n\
322to that returned by repr() in Python 2.");
323
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000324
Guido van Rossum79f25d91997-04-29 20:08:16 +0000325static PyObject *
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000326builtin_bin(PyObject *self, PyObject *v)
327{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000328 return PyNumber_ToBase(v, 2);
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000329}
330
331PyDoc_STRVAR(bin_doc,
332"bin(number) -> string\n\
333\n\
Alexander Belopolsky12338ab2011-04-07 00:15:33 -0400334Return the binary representation of an integer.");
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000335
336
Antoine Pitroue71362d2010-11-27 22:00:11 +0000337static PyObject *
338builtin_callable(PyObject *self, PyObject *v)
339{
340 return PyBool_FromLong((long)PyCallable_Check(v));
341}
342
343PyDoc_STRVAR(callable_doc,
344"callable(object) -> bool\n\
345\n\
346Return whether the object is callable (i.e., some kind of function).\n\
347Note that classes are callable, as are instances of classes with a\n\
348__call__() method.");
349
350
Raymond Hettinger17301e92008-03-13 00:19:26 +0000351typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000352 PyObject_HEAD
353 PyObject *func;
354 PyObject *it;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000355} filterobject;
356
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000357static PyObject *
Raymond Hettinger17301e92008-03-13 00:19:26 +0000358filter_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
Guido van Rossum12d12c51993-10-26 17:58:25 +0000359{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000360 PyObject *func, *seq;
361 PyObject *it;
362 filterobject *lz;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000363
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000364 if (type == &PyFilter_Type && !_PyArg_NoKeywords("filter()", kwds))
365 return NULL;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000366
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000367 if (!PyArg_UnpackTuple(args, "filter", 2, 2, &func, &seq))
368 return NULL;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000369
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000370 /* Get iterator. */
371 it = PyObject_GetIter(seq);
372 if (it == NULL)
373 return NULL;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000374
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000375 /* create filterobject structure */
376 lz = (filterobject *)type->tp_alloc(type, 0);
377 if (lz == NULL) {
378 Py_DECREF(it);
379 return NULL;
380 }
381 Py_INCREF(func);
382 lz->func = func;
383 lz->it = it;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000384
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000385 return (PyObject *)lz;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000386}
387
388static void
389filter_dealloc(filterobject *lz)
390{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000391 PyObject_GC_UnTrack(lz);
392 Py_XDECREF(lz->func);
393 Py_XDECREF(lz->it);
394 Py_TYPE(lz)->tp_free(lz);
Raymond Hettinger17301e92008-03-13 00:19:26 +0000395}
396
397static int
398filter_traverse(filterobject *lz, visitproc visit, void *arg)
399{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000400 Py_VISIT(lz->it);
401 Py_VISIT(lz->func);
402 return 0;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000403}
404
405static PyObject *
406filter_next(filterobject *lz)
407{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000408 PyObject *item;
409 PyObject *it = lz->it;
410 long ok;
411 PyObject *(*iternext)(PyObject *);
Raymond Hettinger17301e92008-03-13 00:19:26 +0000412
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000413 iternext = *Py_TYPE(it)->tp_iternext;
414 for (;;) {
415 item = iternext(it);
416 if (item == NULL)
417 return NULL;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000418
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000419 if (lz->func == Py_None || lz->func == (PyObject *)&PyBool_Type) {
420 ok = PyObject_IsTrue(item);
421 } else {
422 PyObject *good;
423 good = PyObject_CallFunctionObjArgs(lz->func,
424 item, NULL);
425 if (good == NULL) {
426 Py_DECREF(item);
427 return NULL;
428 }
429 ok = PyObject_IsTrue(good);
430 Py_DECREF(good);
431 }
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,
Georg Brandlcd5da7d2008-02-01 15:47:37 +00001593"print(value, ..., sep=' ', end='\\n', file=sys.stdout)\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\
1597file: 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.");
1600
1601
Guido van Rossuma88a0332007-02-26 16:59:55 +00001602static PyObject *
1603builtin_input(PyObject *self, PyObject *args)
1604{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001605 PyObject *promptarg = NULL;
1606 PyObject *fin = PySys_GetObject("stdin");
1607 PyObject *fout = PySys_GetObject("stdout");
1608 PyObject *ferr = PySys_GetObject("stderr");
1609 PyObject *tmp;
1610 long fd;
1611 int tty;
Guido van Rossuma88a0332007-02-26 16:59:55 +00001612
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001613 /* Parse arguments */
1614 if (!PyArg_UnpackTuple(args, "input", 0, 1, &promptarg))
1615 return NULL;
Guido van Rossuma88a0332007-02-26 16:59:55 +00001616
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001617 /* Check that stdin/out/err are intact */
1618 if (fin == NULL || fin == Py_None) {
1619 PyErr_SetString(PyExc_RuntimeError,
1620 "input(): lost sys.stdin");
1621 return NULL;
1622 }
1623 if (fout == NULL || fout == Py_None) {
1624 PyErr_SetString(PyExc_RuntimeError,
1625 "input(): lost sys.stdout");
1626 return NULL;
1627 }
1628 if (ferr == NULL || ferr == Py_None) {
1629 PyErr_SetString(PyExc_RuntimeError,
1630 "input(): lost sys.stderr");
1631 return NULL;
1632 }
Guido van Rossumeba76962007-05-27 09:13:28 +00001633
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001634 /* First of all, flush stderr */
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001635 tmp = _PyObject_CallMethodId(ferr, &PyId_flush, "");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001636 if (tmp == NULL)
1637 PyErr_Clear();
1638 else
1639 Py_DECREF(tmp);
Guido van Rossumeba76962007-05-27 09:13:28 +00001640
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001641 /* We should only use (GNU) readline if Python's sys.stdin and
1642 sys.stdout are the same as C's stdin and stdout, because we
1643 need to pass it those. */
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001644 tmp = _PyObject_CallMethodId(fin, &PyId_fileno, "");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001645 if (tmp == NULL) {
1646 PyErr_Clear();
1647 tty = 0;
1648 }
1649 else {
1650 fd = PyLong_AsLong(tmp);
1651 Py_DECREF(tmp);
1652 if (fd < 0 && PyErr_Occurred())
1653 return NULL;
1654 tty = fd == fileno(stdin) && isatty(fd);
1655 }
1656 if (tty) {
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001657 tmp = _PyObject_CallMethodId(fout, &PyId_fileno, "");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001658 if (tmp == NULL)
1659 PyErr_Clear();
1660 else {
1661 fd = PyLong_AsLong(tmp);
1662 Py_DECREF(tmp);
1663 if (fd < 0 && PyErr_Occurred())
1664 return NULL;
1665 tty = fd == fileno(stdout) && isatty(fd);
1666 }
1667 }
Guido van Rossumeba76962007-05-27 09:13:28 +00001668
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001669 /* If we're interactive, use (GNU) readline */
1670 if (tty) {
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001671 PyObject *po = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001672 char *prompt;
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001673 char *s = NULL;
1674 PyObject *stdin_encoding = NULL, *stdin_errors = NULL;
1675 PyObject *stdout_encoding = NULL, *stdout_errors = NULL;
1676 char *stdin_encoding_str, *stdin_errors_str;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001677 PyObject *result;
Victor Stinnerc0f1a1a2011-02-23 12:07:37 +00001678 size_t len;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02001679 _Py_IDENTIFIER(encoding);
Antoine Pitrou5ee9d8a2011-11-06 00:38:45 +01001680 _Py_IDENTIFIER(errors);
Martin v. Löwis4a7b5d52007-09-04 05:24:49 +00001681
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02001682 stdin_encoding = _PyObject_GetAttrId(fin, &PyId_encoding);
Antoine Pitrou5ee9d8a2011-11-06 00:38:45 +01001683 stdin_errors = _PyObject_GetAttrId(fin, &PyId_errors);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001684 if (!stdin_encoding || !stdin_errors)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001685 /* stdin is a text stream, so it must have an
1686 encoding. */
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001687 goto _readline_errors;
Victor Stinner306f0102010-05-19 01:06:22 +00001688 stdin_encoding_str = _PyUnicode_AsString(stdin_encoding);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001689 stdin_errors_str = _PyUnicode_AsString(stdin_errors);
1690 if (!stdin_encoding_str || !stdin_errors_str)
1691 goto _readline_errors;
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001692 tmp = _PyObject_CallMethodId(fout, &PyId_flush, "");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001693 if (tmp == NULL)
1694 PyErr_Clear();
1695 else
1696 Py_DECREF(tmp);
1697 if (promptarg != NULL) {
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001698 /* We have a prompt, encode it as stdout would */
1699 char *stdout_encoding_str, *stdout_errors_str;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001700 PyObject *stringpo;
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02001701 stdout_encoding = _PyObject_GetAttrId(fout, &PyId_encoding);
Antoine Pitrou5ee9d8a2011-11-06 00:38:45 +01001702 stdout_errors = _PyObject_GetAttrId(fout, &PyId_errors);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001703 if (!stdout_encoding || !stdout_errors)
1704 goto _readline_errors;
Victor Stinner306f0102010-05-19 01:06:22 +00001705 stdout_encoding_str = _PyUnicode_AsString(stdout_encoding);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001706 stdout_errors_str = _PyUnicode_AsString(stdout_errors);
1707 if (!stdout_encoding_str || !stdout_errors_str)
1708 goto _readline_errors;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001709 stringpo = PyObject_Str(promptarg);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001710 if (stringpo == NULL)
1711 goto _readline_errors;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001712 po = PyUnicode_AsEncodedString(stringpo,
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001713 stdout_encoding_str, stdout_errors_str);
1714 Py_CLEAR(stdout_encoding);
1715 Py_CLEAR(stdout_errors);
1716 Py_CLEAR(stringpo);
1717 if (po == NULL)
1718 goto _readline_errors;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001719 prompt = PyBytes_AsString(po);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001720 if (prompt == NULL)
1721 goto _readline_errors;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001722 }
1723 else {
1724 po = NULL;
1725 prompt = "";
1726 }
1727 s = PyOS_Readline(stdin, stdout, prompt);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001728 if (s == NULL) {
1729 if (!PyErr_Occurred())
1730 PyErr_SetNone(PyExc_KeyboardInterrupt);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001731 goto _readline_errors;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001732 }
Victor Stinnerc0f1a1a2011-02-23 12:07:37 +00001733
1734 len = strlen(s);
1735 if (len == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001736 PyErr_SetNone(PyExc_EOFError);
1737 result = NULL;
1738 }
Victor Stinnerc0f1a1a2011-02-23 12:07:37 +00001739 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001740 if (len > PY_SSIZE_T_MAX) {
1741 PyErr_SetString(PyExc_OverflowError,
1742 "input: input too long");
1743 result = NULL;
1744 }
1745 else {
Victor Stinnerc0f1a1a2011-02-23 12:07:37 +00001746 len--; /* strip trailing '\n' */
1747 if (len != 0 && s[len-1] == '\r')
1748 len--; /* strip trailing '\r' */
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001749 result = PyUnicode_Decode(s, len, stdin_encoding_str,
1750 stdin_errors_str);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001751 }
1752 }
1753 Py_DECREF(stdin_encoding);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001754 Py_DECREF(stdin_errors);
1755 Py_XDECREF(po);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001756 PyMem_FREE(s);
1757 return result;
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001758 _readline_errors:
1759 Py_XDECREF(stdin_encoding);
1760 Py_XDECREF(stdout_encoding);
1761 Py_XDECREF(stdin_errors);
1762 Py_XDECREF(stdout_errors);
1763 Py_XDECREF(po);
1764 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001765 }
Guido van Rossumeba76962007-05-27 09:13:28 +00001766
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001767 /* Fallback if we're not interactive */
1768 if (promptarg != NULL) {
1769 if (PyFile_WriteObject(promptarg, fout, Py_PRINT_RAW) != 0)
1770 return NULL;
1771 }
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001772 tmp = _PyObject_CallMethodId(fout, &PyId_flush, "");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001773 if (tmp == NULL)
1774 PyErr_Clear();
1775 else
1776 Py_DECREF(tmp);
1777 return PyFile_GetLine(fin, -1);
Guido van Rossuma88a0332007-02-26 16:59:55 +00001778}
1779
1780PyDoc_STRVAR(input_doc,
1781"input([prompt]) -> string\n\
1782\n\
1783Read a string from standard input. The trailing newline is stripped.\n\
1784If the user hits EOF (Unix: Ctl-D, Windows: Ctl-Z+Return), raise EOFError.\n\
1785On Unix, GNU readline is used if enabled. The prompt string, if given,\n\
1786is printed without a trailing newline before reading.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001787
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001788
Guido van Rossum79f25d91997-04-29 20:08:16 +00001789static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001790builtin_repr(PyObject *self, PyObject *v)
Guido van Rossumc89705d1992-11-26 08:54:07 +00001791{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001792 return PyObject_Repr(v);
Guido van Rossumc89705d1992-11-26 08:54:07 +00001793}
1794
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001795PyDoc_STRVAR(repr_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001796"repr(object) -> string\n\
1797\n\
1798Return the canonical string representation of the object.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001799For most object types, eval(repr(object)) == object.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001800
1801
Guido van Rossum79f25d91997-04-29 20:08:16 +00001802static PyObject *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001803builtin_round(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum9e51f9b1993-02-12 16:29:05 +00001804{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001805 static PyObject *round_str = NULL;
1806 PyObject *ndigits = NULL;
1807 static char *kwlist[] = {"number", "ndigits", 0};
1808 PyObject *number, *round;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001809
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001810 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|O:round",
1811 kwlist, &number, &ndigits))
1812 return NULL;
Alex Martelliae211f92007-08-22 23:21:33 +00001813
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001814 if (Py_TYPE(number)->tp_dict == NULL) {
1815 if (PyType_Ready(Py_TYPE(number)) < 0)
1816 return NULL;
1817 }
Guido van Rossum15d3d042007-08-24 02:02:45 +00001818
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001819 if (round_str == NULL) {
1820 round_str = PyUnicode_InternFromString("__round__");
1821 if (round_str == NULL)
1822 return NULL;
1823 }
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001824
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001825 round = _PyType_Lookup(Py_TYPE(number), round_str);
1826 if (round == NULL) {
1827 PyErr_Format(PyExc_TypeError,
1828 "type %.100s doesn't define __round__ method",
1829 Py_TYPE(number)->tp_name);
1830 return NULL;
1831 }
Alex Martelliae211f92007-08-22 23:21:33 +00001832
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001833 if (ndigits == NULL)
1834 return PyObject_CallFunction(round, "O", number);
1835 else
1836 return PyObject_CallFunction(round, "OO", number, ndigits);
Guido van Rossum9e51f9b1993-02-12 16:29:05 +00001837}
1838
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001839PyDoc_STRVAR(round_doc,
Mark Dickinson1124e712009-01-28 21:25:58 +00001840"round(number[, ndigits]) -> number\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001841\n\
1842Round a number to a given precision in decimal digits (default 0 digits).\n\
Mark Dickinson0d748c22008-07-05 11:29:03 +00001843This returns an int when called with one argument, otherwise the\n\
Georg Brandl809ddaa2008-07-01 20:39:59 +00001844same type as the number. ndigits may be negative.");
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001845
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001846
Raymond Hettinger64958a12003-12-17 20:43:33 +00001847static PyObject *
1848builtin_sorted(PyObject *self, PyObject *args, PyObject *kwds)
1849{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001850 PyObject *newlist, *v, *seq, *keyfunc=NULL, *newargs;
1851 PyObject *callable;
1852 static char *kwlist[] = {"iterable", "key", "reverse", 0};
1853 int reverse;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02001854 _Py_IDENTIFIER(sort);
Raymond Hettinger64958a12003-12-17 20:43:33 +00001855
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001856 /* args 1-3 should match listsort in Objects/listobject.c */
1857 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|Oi:sorted",
1858 kwlist, &seq, &keyfunc, &reverse))
1859 return NULL;
Raymond Hettinger64958a12003-12-17 20:43:33 +00001860
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001861 newlist = PySequence_List(seq);
1862 if (newlist == NULL)
1863 return NULL;
Raymond Hettinger64958a12003-12-17 20:43:33 +00001864
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02001865 callable = _PyObject_GetAttrId(newlist, &PyId_sort);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001866 if (callable == NULL) {
1867 Py_DECREF(newlist);
1868 return NULL;
1869 }
Georg Brandl99d7e4e2005-08-31 22:21:15 +00001870
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001871 newargs = PyTuple_GetSlice(args, 1, 4);
1872 if (newargs == NULL) {
1873 Py_DECREF(newlist);
1874 Py_DECREF(callable);
1875 return NULL;
1876 }
Raymond Hettinger64958a12003-12-17 20:43:33 +00001877
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001878 v = PyObject_Call(callable, newargs, kwds);
1879 Py_DECREF(newargs);
1880 Py_DECREF(callable);
1881 if (v == NULL) {
1882 Py_DECREF(newlist);
1883 return NULL;
1884 }
1885 Py_DECREF(v);
1886 return newlist;
Raymond Hettinger64958a12003-12-17 20:43:33 +00001887}
1888
1889PyDoc_STRVAR(sorted_doc,
Raymond Hettinger70b64fc2008-01-30 20:15:17 +00001890"sorted(iterable, key=None, reverse=False) --> new sorted list");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001891
Guido van Rossum79f25d91997-04-29 20:08:16 +00001892static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001893builtin_vars(PyObject *self, PyObject *args)
Guido van Rossum2d951851994-08-29 12:52:16 +00001894{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001895 PyObject *v = NULL;
1896 PyObject *d;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001897
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001898 if (!PyArg_UnpackTuple(args, "vars", 0, 1, &v))
1899 return NULL;
1900 if (v == NULL) {
1901 d = PyEval_GetLocals();
1902 if (d == NULL) {
1903 if (!PyErr_Occurred())
1904 PyErr_SetString(PyExc_SystemError,
1905 "vars(): no locals!?");
1906 }
1907 else
1908 Py_INCREF(d);
1909 }
1910 else {
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02001911 _Py_IDENTIFIER(__dict__);
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02001912 d = _PyObject_GetAttrId(v, &PyId___dict__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001913 if (d == NULL) {
1914 PyErr_SetString(PyExc_TypeError,
1915 "vars() argument must have __dict__ attribute");
1916 return NULL;
1917 }
1918 }
1919 return d;
Guido van Rossum2d951851994-08-29 12:52:16 +00001920}
1921
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001922PyDoc_STRVAR(vars_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001923"vars([object]) -> dictionary\n\
1924\n\
1925Without arguments, equivalent to locals().\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001926With an argument, equivalent to object.__dict__.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001927
Alex Martellia70b1912003-04-22 08:12:33 +00001928static PyObject*
1929builtin_sum(PyObject *self, PyObject *args)
1930{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001931 PyObject *seq;
1932 PyObject *result = NULL;
1933 PyObject *temp, *item, *iter;
Alex Martellia70b1912003-04-22 08:12:33 +00001934
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001935 if (!PyArg_UnpackTuple(args, "sum", 1, 2, &seq, &result))
1936 return NULL;
Alex Martellia70b1912003-04-22 08:12:33 +00001937
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001938 iter = PyObject_GetIter(seq);
1939 if (iter == NULL)
1940 return NULL;
Alex Martellia70b1912003-04-22 08:12:33 +00001941
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001942 if (result == NULL) {
1943 result = PyLong_FromLong(0);
1944 if (result == NULL) {
1945 Py_DECREF(iter);
1946 return NULL;
1947 }
1948 } else {
1949 /* reject string values for 'start' parameter */
1950 if (PyUnicode_Check(result)) {
1951 PyErr_SetString(PyExc_TypeError,
1952 "sum() can't sum strings [use ''.join(seq) instead]");
1953 Py_DECREF(iter);
1954 return NULL;
1955 }
Benjamin Petersonce071ca2011-07-29 14:23:47 -05001956 if (PyBytes_Check(result)) {
1957 PyErr_SetString(PyExc_TypeError,
1958 "sum() can't sum bytes [use b''.join(seq) instead]");
Benjamin Peterson405f32c2011-07-29 22:43:45 -05001959 Py_DECREF(iter);
Benjamin Petersonce071ca2011-07-29 14:23:47 -05001960 return NULL;
1961 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001962 if (PyByteArray_Check(result)) {
1963 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson4f921c22011-07-29 14:24:29 -05001964 "sum() can't sum bytearray [use b''.join(seq) instead]");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001965 Py_DECREF(iter);
1966 return NULL;
1967 }
Guido van Rossum3172c5d2007-10-16 18:12:55 +00001968
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001969 Py_INCREF(result);
1970 }
Alex Martellia70b1912003-04-22 08:12:33 +00001971
Guido van Rossum8ce8a782007-11-01 19:42:39 +00001972#ifndef SLOW_SUM
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001973 /* Fast addition by keeping temporary sums in C instead of new Python objects.
1974 Assumes all inputs are the same type. If the assumption fails, default
1975 to the more general routine.
1976 */
1977 if (PyLong_CheckExact(result)) {
1978 int overflow;
1979 long i_result = PyLong_AsLongAndOverflow(result, &overflow);
1980 /* If this already overflowed, don't even enter the loop. */
1981 if (overflow == 0) {
1982 Py_DECREF(result);
1983 result = NULL;
1984 }
1985 while(result == NULL) {
1986 item = PyIter_Next(iter);
1987 if (item == NULL) {
1988 Py_DECREF(iter);
1989 if (PyErr_Occurred())
1990 return NULL;
1991 return PyLong_FromLong(i_result);
1992 }
1993 if (PyLong_CheckExact(item)) {
1994 long b = PyLong_AsLongAndOverflow(item, &overflow);
1995 long x = i_result + b;
1996 if (overflow == 0 && ((x^i_result) >= 0 || (x^b) >= 0)) {
1997 i_result = x;
1998 Py_DECREF(item);
1999 continue;
2000 }
2001 }
2002 /* Either overflowed or is not an int. Restore real objects and process normally */
2003 result = PyLong_FromLong(i_result);
2004 temp = PyNumber_Add(result, item);
2005 Py_DECREF(result);
2006 Py_DECREF(item);
2007 result = temp;
2008 if (result == NULL) {
2009 Py_DECREF(iter);
2010 return NULL;
2011 }
2012 }
2013 }
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002014
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002015 if (PyFloat_CheckExact(result)) {
2016 double f_result = PyFloat_AS_DOUBLE(result);
2017 Py_DECREF(result);
2018 result = NULL;
2019 while(result == NULL) {
2020 item = PyIter_Next(iter);
2021 if (item == NULL) {
2022 Py_DECREF(iter);
2023 if (PyErr_Occurred())
2024 return NULL;
2025 return PyFloat_FromDouble(f_result);
2026 }
2027 if (PyFloat_CheckExact(item)) {
2028 PyFPE_START_PROTECT("add", Py_DECREF(item); Py_DECREF(iter); return 0)
2029 f_result += PyFloat_AS_DOUBLE(item);
2030 PyFPE_END_PROTECT(f_result)
2031 Py_DECREF(item);
2032 continue;
2033 }
2034 if (PyLong_CheckExact(item)) {
2035 long value;
2036 int overflow;
2037 value = PyLong_AsLongAndOverflow(item, &overflow);
2038 if (!overflow) {
2039 PyFPE_START_PROTECT("add", Py_DECREF(item); Py_DECREF(iter); return 0)
2040 f_result += (double)value;
2041 PyFPE_END_PROTECT(f_result)
2042 Py_DECREF(item);
2043 continue;
2044 }
2045 }
2046 result = PyFloat_FromDouble(f_result);
2047 temp = PyNumber_Add(result, item);
2048 Py_DECREF(result);
2049 Py_DECREF(item);
2050 result = temp;
2051 if (result == NULL) {
2052 Py_DECREF(iter);
2053 return NULL;
2054 }
2055 }
2056 }
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002057#endif
2058
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002059 for(;;) {
2060 item = PyIter_Next(iter);
2061 if (item == NULL) {
2062 /* error, or end-of-sequence */
2063 if (PyErr_Occurred()) {
2064 Py_DECREF(result);
2065 result = NULL;
2066 }
2067 break;
2068 }
2069 /* It's tempting to use PyNumber_InPlaceAdd instead of
2070 PyNumber_Add here, to avoid quadratic running time
2071 when doing 'sum(list_of_lists, [])'. However, this
2072 would produce a change in behaviour: a snippet like
Mark Dickinson9acadc52009-10-26 14:19:42 +00002073
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002074 empty = []
2075 sum([[x] for x in range(10)], empty)
Mark Dickinson9acadc52009-10-26 14:19:42 +00002076
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002077 would change the value of empty. */
2078 temp = PyNumber_Add(result, item);
2079 Py_DECREF(result);
2080 Py_DECREF(item);
2081 result = temp;
2082 if (result == NULL)
2083 break;
2084 }
2085 Py_DECREF(iter);
2086 return result;
Alex Martellia70b1912003-04-22 08:12:33 +00002087}
2088
2089PyDoc_STRVAR(sum_doc,
Georg Brandld11ae5d2008-05-16 13:27:32 +00002090"sum(iterable[, start]) -> value\n\
Alex Martellia70b1912003-04-22 08:12:33 +00002091\n\
Georg Brandld11ae5d2008-05-16 13:27:32 +00002092Returns the sum of an iterable of numbers (NOT strings) plus the value\n\
2093of parameter 'start' (which defaults to 0). When the iterable is\n\
Thomas Wouters89f507f2006-12-13 04:49:30 +00002094empty, returns start.");
Alex Martellia70b1912003-04-22 08:12:33 +00002095
2096
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002097static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002098builtin_isinstance(PyObject *self, PyObject *args)
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002099{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002100 PyObject *inst;
2101 PyObject *cls;
2102 int retval;
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002103
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002104 if (!PyArg_UnpackTuple(args, "isinstance", 2, 2, &inst, &cls))
2105 return NULL;
Guido van Rossumf5dd9141997-12-02 19:11:45 +00002106
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002107 retval = PyObject_IsInstance(inst, cls);
2108 if (retval < 0)
2109 return NULL;
2110 return PyBool_FromLong(retval);
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002111}
2112
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002113PyDoc_STRVAR(isinstance_doc,
Guido van Rossum77f6a652002-04-03 22:41:51 +00002114"isinstance(object, class-or-type-or-tuple) -> bool\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002115\n\
2116Return whether an object is an instance of a class or of a subclass thereof.\n\
Guido van Rossum03290ec2001-10-07 20:54:12 +00002117With a type as second argument, return whether that is the object's type.\n\
2118The form using a tuple, isinstance(x, (A, B, ...)), is a shortcut for\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002119isinstance(x, A) or isinstance(x, B) or ... (etc.).");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002120
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002121
2122static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002123builtin_issubclass(PyObject *self, PyObject *args)
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002124{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002125 PyObject *derived;
2126 PyObject *cls;
2127 int retval;
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002128
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002129 if (!PyArg_UnpackTuple(args, "issubclass", 2, 2, &derived, &cls))
2130 return NULL;
Guido van Rossum668213d1999-06-16 17:28:37 +00002131
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002132 retval = PyObject_IsSubclass(derived, cls);
2133 if (retval < 0)
2134 return NULL;
2135 return PyBool_FromLong(retval);
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002136}
2137
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002138PyDoc_STRVAR(issubclass_doc,
Guido van Rossum77f6a652002-04-03 22:41:51 +00002139"issubclass(C, B) -> bool\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002140\n\
Walter Dörwaldd9a6ad32002-12-12 16:41:44 +00002141Return whether class C is a subclass (i.e., a derived class) of class B.\n\
2142When using a tuple as the second argument issubclass(X, (A, B, ...)),\n\
2143is a shortcut for issubclass(X, A) or issubclass(X, B) or ... (etc.).");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002144
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002145
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002146typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002147 PyObject_HEAD
2148 Py_ssize_t tuplesize;
2149 PyObject *ittuple; /* tuple of iterators */
2150 PyObject *result;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002151} zipobject;
2152
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002153static PyObject *
2154zip_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
Barry Warsawbd599b52000-08-03 15:45:29 +00002155{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002156 zipobject *lz;
2157 Py_ssize_t i;
2158 PyObject *ittuple; /* tuple of iterators */
2159 PyObject *result;
2160 Py_ssize_t tuplesize = PySequence_Length(args);
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002161
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002162 if (type == &PyZip_Type && !_PyArg_NoKeywords("zip()", kwds))
2163 return NULL;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002164
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002165 /* args must be a tuple */
2166 assert(PyTuple_Check(args));
Barry Warsawbd599b52000-08-03 15:45:29 +00002167
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002168 /* obtain iterators */
2169 ittuple = PyTuple_New(tuplesize);
2170 if (ittuple == NULL)
2171 return NULL;
2172 for (i=0; i < tuplesize; ++i) {
2173 PyObject *item = PyTuple_GET_ITEM(args, i);
2174 PyObject *it = PyObject_GetIter(item);
2175 if (it == NULL) {
2176 if (PyErr_ExceptionMatches(PyExc_TypeError))
2177 PyErr_Format(PyExc_TypeError,
2178 "zip argument #%zd must support iteration",
2179 i+1);
2180 Py_DECREF(ittuple);
2181 return NULL;
2182 }
2183 PyTuple_SET_ITEM(ittuple, i, it);
2184 }
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002185
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002186 /* create a result holder */
2187 result = PyTuple_New(tuplesize);
2188 if (result == NULL) {
2189 Py_DECREF(ittuple);
2190 return NULL;
2191 }
2192 for (i=0 ; i < tuplesize ; i++) {
2193 Py_INCREF(Py_None);
2194 PyTuple_SET_ITEM(result, i, Py_None);
2195 }
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002196
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002197 /* create zipobject structure */
2198 lz = (zipobject *)type->tp_alloc(type, 0);
2199 if (lz == NULL) {
2200 Py_DECREF(ittuple);
2201 Py_DECREF(result);
2202 return NULL;
2203 }
2204 lz->ittuple = ittuple;
2205 lz->tuplesize = tuplesize;
2206 lz->result = result;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002207
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002208 return (PyObject *)lz;
Barry Warsawbd599b52000-08-03 15:45:29 +00002209}
2210
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002211static void
2212zip_dealloc(zipobject *lz)
2213{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002214 PyObject_GC_UnTrack(lz);
2215 Py_XDECREF(lz->ittuple);
2216 Py_XDECREF(lz->result);
2217 Py_TYPE(lz)->tp_free(lz);
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002218}
2219
2220static int
2221zip_traverse(zipobject *lz, visitproc visit, void *arg)
2222{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002223 Py_VISIT(lz->ittuple);
2224 Py_VISIT(lz->result);
2225 return 0;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002226}
2227
2228static PyObject *
2229zip_next(zipobject *lz)
2230{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002231 Py_ssize_t i;
2232 Py_ssize_t tuplesize = lz->tuplesize;
2233 PyObject *result = lz->result;
2234 PyObject *it;
2235 PyObject *item;
2236 PyObject *olditem;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002237
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002238 if (tuplesize == 0)
2239 return NULL;
2240 if (Py_REFCNT(result) == 1) {
2241 Py_INCREF(result);
2242 for (i=0 ; i < tuplesize ; i++) {
2243 it = PyTuple_GET_ITEM(lz->ittuple, i);
2244 item = (*Py_TYPE(it)->tp_iternext)(it);
2245 if (item == NULL) {
2246 Py_DECREF(result);
2247 return NULL;
2248 }
2249 olditem = PyTuple_GET_ITEM(result, i);
2250 PyTuple_SET_ITEM(result, i, item);
2251 Py_DECREF(olditem);
2252 }
2253 } else {
2254 result = PyTuple_New(tuplesize);
2255 if (result == NULL)
2256 return NULL;
2257 for (i=0 ; i < tuplesize ; i++) {
2258 it = PyTuple_GET_ITEM(lz->ittuple, i);
2259 item = (*Py_TYPE(it)->tp_iternext)(it);
2260 if (item == NULL) {
2261 Py_DECREF(result);
2262 return NULL;
2263 }
2264 PyTuple_SET_ITEM(result, i, item);
2265 }
2266 }
2267 return result;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002268}
Barry Warsawbd599b52000-08-03 15:45:29 +00002269
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002270static PyObject *
2271zip_reduce(zipobject *lz)
2272{
2273 /* Just recreate the zip with the internal iterator tuple */
2274 return Py_BuildValue("OO", Py_TYPE(lz), lz->ittuple);
2275}
2276
2277static PyMethodDef zip_methods[] = {
2278 {"__reduce__", (PyCFunction)zip_reduce, METH_NOARGS, reduce_doc},
2279 {NULL, NULL} /* sentinel */
2280};
2281
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002282PyDoc_STRVAR(zip_doc,
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002283"zip(iter1 [,iter2 [...]]) --> zip object\n\
Barry Warsawbd599b52000-08-03 15:45:29 +00002284\n\
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002285Return a zip object whose .__next__() method returns a tuple where\n\
2286the i-th element comes from the i-th iterable argument. The .__next__()\n\
2287method continues until the shortest iterable in the argument sequence\n\
Georg Brandlced51db2008-12-04 18:28:38 +00002288is exhausted and then it raises StopIteration.");
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002289
2290PyTypeObject PyZip_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002291 PyVarObject_HEAD_INIT(&PyType_Type, 0)
2292 "zip", /* tp_name */
2293 sizeof(zipobject), /* tp_basicsize */
2294 0, /* tp_itemsize */
2295 /* methods */
2296 (destructor)zip_dealloc, /* tp_dealloc */
2297 0, /* tp_print */
2298 0, /* tp_getattr */
2299 0, /* tp_setattr */
2300 0, /* tp_reserved */
2301 0, /* tp_repr */
2302 0, /* tp_as_number */
2303 0, /* tp_as_sequence */
2304 0, /* tp_as_mapping */
2305 0, /* tp_hash */
2306 0, /* tp_call */
2307 0, /* tp_str */
2308 PyObject_GenericGetAttr, /* tp_getattro */
2309 0, /* tp_setattro */
2310 0, /* tp_as_buffer */
2311 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
2312 Py_TPFLAGS_BASETYPE, /* tp_flags */
2313 zip_doc, /* tp_doc */
2314 (traverseproc)zip_traverse, /* tp_traverse */
2315 0, /* tp_clear */
2316 0, /* tp_richcompare */
2317 0, /* tp_weaklistoffset */
2318 PyObject_SelfIter, /* tp_iter */
2319 (iternextfunc)zip_next, /* tp_iternext */
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002320 zip_methods, /* tp_methods */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002321 0, /* tp_members */
2322 0, /* tp_getset */
2323 0, /* tp_base */
2324 0, /* tp_dict */
2325 0, /* tp_descr_get */
2326 0, /* tp_descr_set */
2327 0, /* tp_dictoffset */
2328 0, /* tp_init */
2329 PyType_GenericAlloc, /* tp_alloc */
2330 zip_new, /* tp_new */
2331 PyObject_GC_Del, /* tp_free */
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002332};
Barry Warsawbd599b52000-08-03 15:45:29 +00002333
2334
Guido van Rossum79f25d91997-04-29 20:08:16 +00002335static PyMethodDef builtin_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002336 {"__build_class__", (PyCFunction)builtin___build_class__,
2337 METH_VARARGS | METH_KEYWORDS, build_class_doc},
2338 {"__import__", (PyCFunction)builtin___import__, METH_VARARGS | METH_KEYWORDS, import_doc},
2339 {"abs", builtin_abs, METH_O, abs_doc},
2340 {"all", builtin_all, METH_O, all_doc},
2341 {"any", builtin_any, METH_O, any_doc},
2342 {"ascii", builtin_ascii, METH_O, ascii_doc},
2343 {"bin", builtin_bin, METH_O, bin_doc},
Antoine Pitroue71362d2010-11-27 22:00:11 +00002344 {"callable", builtin_callable, METH_O, callable_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002345 {"chr", builtin_chr, METH_VARARGS, chr_doc},
2346 {"compile", (PyCFunction)builtin_compile, METH_VARARGS | METH_KEYWORDS, compile_doc},
2347 {"delattr", builtin_delattr, METH_VARARGS, delattr_doc},
2348 {"dir", builtin_dir, METH_VARARGS, dir_doc},
2349 {"divmod", builtin_divmod, METH_VARARGS, divmod_doc},
2350 {"eval", builtin_eval, METH_VARARGS, eval_doc},
2351 {"exec", builtin_exec, METH_VARARGS, exec_doc},
2352 {"format", builtin_format, METH_VARARGS, format_doc},
2353 {"getattr", builtin_getattr, METH_VARARGS, getattr_doc},
2354 {"globals", (PyCFunction)builtin_globals, METH_NOARGS, globals_doc},
2355 {"hasattr", builtin_hasattr, METH_VARARGS, hasattr_doc},
2356 {"hash", builtin_hash, METH_O, hash_doc},
2357 {"hex", builtin_hex, METH_O, hex_doc},
2358 {"id", builtin_id, METH_O, id_doc},
2359 {"input", builtin_input, METH_VARARGS, input_doc},
2360 {"isinstance", builtin_isinstance, METH_VARARGS, isinstance_doc},
2361 {"issubclass", builtin_issubclass, METH_VARARGS, issubclass_doc},
2362 {"iter", builtin_iter, METH_VARARGS, iter_doc},
2363 {"len", builtin_len, METH_O, len_doc},
2364 {"locals", (PyCFunction)builtin_locals, METH_NOARGS, locals_doc},
2365 {"max", (PyCFunction)builtin_max, METH_VARARGS | METH_KEYWORDS, max_doc},
2366 {"min", (PyCFunction)builtin_min, METH_VARARGS | METH_KEYWORDS, min_doc},
2367 {"next", (PyCFunction)builtin_next, METH_VARARGS, next_doc},
2368 {"oct", builtin_oct, METH_O, oct_doc},
2369 {"ord", builtin_ord, METH_O, ord_doc},
2370 {"pow", builtin_pow, METH_VARARGS, pow_doc},
2371 {"print", (PyCFunction)builtin_print, METH_VARARGS | METH_KEYWORDS, print_doc},
2372 {"repr", builtin_repr, METH_O, repr_doc},
2373 {"round", (PyCFunction)builtin_round, METH_VARARGS | METH_KEYWORDS, round_doc},
2374 {"setattr", builtin_setattr, METH_VARARGS, setattr_doc},
2375 {"sorted", (PyCFunction)builtin_sorted, METH_VARARGS | METH_KEYWORDS, sorted_doc},
2376 {"sum", builtin_sum, METH_VARARGS, sum_doc},
2377 {"vars", builtin_vars, METH_VARARGS, vars_doc},
2378 {NULL, NULL},
Guido van Rossum3f5da241990-12-20 15:06:42 +00002379};
2380
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002381PyDoc_STRVAR(builtin_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002382"Built-in functions, exceptions, and other objects.\n\
2383\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002384Noteworthy: None is the `nil' object; Ellipsis represents `...' in slices.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002385
Martin v. Löwis1a214512008-06-11 05:26:20 +00002386static struct PyModuleDef builtinsmodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002387 PyModuleDef_HEAD_INIT,
2388 "builtins",
2389 builtin_doc,
2390 -1, /* multiple "initialization" just copies the module dict. */
2391 builtin_methods,
2392 NULL,
2393 NULL,
2394 NULL,
2395 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00002396};
2397
2398
Guido van Rossum25ce5661997-08-02 03:10:38 +00002399PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002400_PyBuiltin_Init(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +00002401{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002402 PyObject *mod, *dict, *debug;
2403 mod = PyModule_Create(&builtinsmodule);
2404 if (mod == NULL)
2405 return NULL;
2406 dict = PyModule_GetDict(mod);
Tim Peters4b7625e2001-09-13 21:37:17 +00002407
Tim Peters7571a0f2003-03-23 17:52:28 +00002408#ifdef Py_TRACE_REFS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002409 /* "builtins" exposes a number of statically allocated objects
2410 * that, before this code was added in 2.3, never showed up in
2411 * the list of "all objects" maintained by Py_TRACE_REFS. As a
2412 * result, programs leaking references to None and False (etc)
2413 * couldn't be diagnosed by examining sys.getobjects(0).
2414 */
Tim Peters7571a0f2003-03-23 17:52:28 +00002415#define ADD_TO_ALL(OBJECT) _Py_AddToAllObjects((PyObject *)(OBJECT), 0)
2416#else
2417#define ADD_TO_ALL(OBJECT) (void)0
2418#endif
2419
Tim Peters4b7625e2001-09-13 21:37:17 +00002420#define SETBUILTIN(NAME, OBJECT) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002421 if (PyDict_SetItemString(dict, NAME, (PyObject *)OBJECT) < 0) \
2422 return NULL; \
2423 ADD_TO_ALL(OBJECT)
Tim Peters4b7625e2001-09-13 21:37:17 +00002424
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002425 SETBUILTIN("None", Py_None);
2426 SETBUILTIN("Ellipsis", Py_Ellipsis);
2427 SETBUILTIN("NotImplemented", Py_NotImplemented);
2428 SETBUILTIN("False", Py_False);
2429 SETBUILTIN("True", Py_True);
2430 SETBUILTIN("bool", &PyBool_Type);
2431 SETBUILTIN("memoryview", &PyMemoryView_Type);
2432 SETBUILTIN("bytearray", &PyByteArray_Type);
2433 SETBUILTIN("bytes", &PyBytes_Type);
2434 SETBUILTIN("classmethod", &PyClassMethod_Type);
2435 SETBUILTIN("complex", &PyComplex_Type);
2436 SETBUILTIN("dict", &PyDict_Type);
2437 SETBUILTIN("enumerate", &PyEnum_Type);
2438 SETBUILTIN("filter", &PyFilter_Type);
2439 SETBUILTIN("float", &PyFloat_Type);
2440 SETBUILTIN("frozenset", &PyFrozenSet_Type);
2441 SETBUILTIN("property", &PyProperty_Type);
2442 SETBUILTIN("int", &PyLong_Type);
2443 SETBUILTIN("list", &PyList_Type);
2444 SETBUILTIN("map", &PyMap_Type);
2445 SETBUILTIN("object", &PyBaseObject_Type);
2446 SETBUILTIN("range", &PyRange_Type);
2447 SETBUILTIN("reversed", &PyReversed_Type);
2448 SETBUILTIN("set", &PySet_Type);
2449 SETBUILTIN("slice", &PySlice_Type);
2450 SETBUILTIN("staticmethod", &PyStaticMethod_Type);
2451 SETBUILTIN("str", &PyUnicode_Type);
2452 SETBUILTIN("super", &PySuper_Type);
2453 SETBUILTIN("tuple", &PyTuple_Type);
2454 SETBUILTIN("type", &PyType_Type);
2455 SETBUILTIN("zip", &PyZip_Type);
2456 debug = PyBool_FromLong(Py_OptimizeFlag == 0);
2457 if (PyDict_SetItemString(dict, "__debug__", debug) < 0) {
2458 Py_XDECREF(debug);
2459 return NULL;
2460 }
2461 Py_XDECREF(debug);
Barry Warsaw757af0e1997-08-29 22:13:51 +00002462
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002463 return mod;
Tim Peters7571a0f2003-03-23 17:52:28 +00002464#undef ADD_TO_ALL
Tim Peters4b7625e2001-09-13 21:37:17 +00002465#undef SETBUILTIN
Guido van Rossum3f5da241990-12-20 15:06:42 +00002466}