blob: 4a98b032cfa5cdefc095f9e4f5d93ec032c882c5 [file] [log] [blame]
Guido van Rossum3f5da241990-12-20 15:06:42 +00001/* Built-in functions */
2
Guido van Rossum79f25d91997-04-29 20:08:16 +00003#include "Python.h"
Martin v. Löwis618dc5e2008-03-30 20:03:44 +00004#include "Python-ast.h"
Guido van Rossum3f5da241990-12-20 15:06:42 +00005
6#include "node.h"
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00007#include "code.h"
Guido van Rossum3f5da241990-12-20 15:06:42 +00008
Benjamin Petersonea281a52011-08-12 23:10:50 -05009#include "asdl.h"
10#include "ast.h"
11
Guido van Rossum6bf62da1997-04-11 20:37:35 +000012#include <ctype.h>
13
Victor Stinnerb744ba12010-05-15 12:27:16 +000014#ifdef HAVE_LANGINFO_H
15#include <langinfo.h> /* CODESET */
16#endif
17
Mark Hammond26cffde42001-05-14 12:17:34 +000018/* The default encoding used by the platform file system APIs
19 Can remain NULL for all platforms that don't have such a concept
Guido van Rossum00bc0e02007-10-15 02:52:41 +000020
21 Don't forget to modify PyUnicode_DecodeFSDefault() if you touch any of the
22 values for Py_FileSystemDefaultEncoding!
Mark Hammond26cffde42001-05-14 12:17:34 +000023*/
Victor Stinner99b95382011-07-04 14:23:54 +020024#ifdef HAVE_MBCS
Mark Hammond26cffde42001-05-14 12:17:34 +000025const char *Py_FileSystemDefaultEncoding = "mbcs";
Martin v. Löwis04dc25c2008-10-03 16:09:28 +000026int Py_HasFileSystemDefaultEncoding = 1;
Just van Rossumb9b8e9c2003-02-10 09:22:01 +000027#elif defined(__APPLE__)
28const char *Py_FileSystemDefaultEncoding = "utf-8";
Martin v. Löwis04dc25c2008-10-03 16:09:28 +000029int Py_HasFileSystemDefaultEncoding = 1;
Victor Stinnerd64e8a72011-07-04 13:48:30 +020030#else
Victor Stinnerb744ba12010-05-15 12:27:16 +000031const char *Py_FileSystemDefaultEncoding = NULL; /* set by initfsencoding() */
Martin v. Löwis04dc25c2008-10-03 16:09:28 +000032int Py_HasFileSystemDefaultEncoding = 0;
Mark Hammond26cffde42001-05-14 12:17:34 +000033#endif
Mark Hammondef8b6542001-05-13 08:04:26 +000034
Martin v. Löwisbd928fe2011-10-14 10:20:37 +020035_Py_IDENTIFIER(fileno);
36_Py_IDENTIFIER(flush);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +020037
Guido van Rossum79f25d91997-04-29 20:08:16 +000038static PyObject *
Guido van Rossum52cc1d82007-03-18 15:41:51 +000039builtin___build_class__(PyObject *self, PyObject *args, PyObject *kwds)
40{
Nick Coghlande31b192011-10-23 22:04:16 +100041 PyObject *func, *name, *bases, *mkw, *meta, *winner, *prep, *ns, *cell;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000042 PyObject *cls = NULL;
Florent Xicluna4d46c2a2011-10-28 15:00:50 +020043 Py_ssize_t nargs;
Nick Coghlande31b192011-10-23 22:04:16 +100044 int isclass;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +020045 _Py_IDENTIFIER(__prepare__);
Guido van Rossum52cc1d82007-03-18 15:41:51 +000046
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000047 assert(args != NULL);
48 if (!PyTuple_Check(args)) {
49 PyErr_SetString(PyExc_TypeError,
50 "__build_class__: args is not a tuple");
51 return NULL;
52 }
53 nargs = PyTuple_GET_SIZE(args);
54 if (nargs < 2) {
55 PyErr_SetString(PyExc_TypeError,
56 "__build_class__: not enough arguments");
57 return NULL;
58 }
59 func = PyTuple_GET_ITEM(args, 0); /* Better be callable */
60 name = PyTuple_GET_ITEM(args, 1);
61 if (!PyUnicode_Check(name)) {
62 PyErr_SetString(PyExc_TypeError,
63 "__build_class__: name is not a string");
64 return NULL;
65 }
66 bases = PyTuple_GetSlice(args, 2, nargs);
67 if (bases == NULL)
68 return NULL;
Guido van Rossum52cc1d82007-03-18 15:41:51 +000069
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000070 if (kwds == NULL) {
71 meta = NULL;
72 mkw = NULL;
73 }
74 else {
75 mkw = PyDict_Copy(kwds); /* Don't modify kwds passed in! */
76 if (mkw == NULL) {
77 Py_DECREF(bases);
78 return NULL;
Guido van Rossum52cc1d82007-03-18 15:41:51 +000079 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000080 meta = PyDict_GetItemString(mkw, "metaclass");
81 if (meta != NULL) {
82 Py_INCREF(meta);
83 if (PyDict_DelItemString(mkw, "metaclass") < 0) {
84 Py_DECREF(meta);
85 Py_DECREF(mkw);
86 Py_DECREF(bases);
87 return NULL;
88 }
Nick Coghlande31b192011-10-23 22:04:16 +100089 /* metaclass is explicitly given, check if it's indeed a class */
90 isclass = PyType_Check(meta);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000091 }
92 }
93 if (meta == NULL) {
Nick Coghlande31b192011-10-23 22:04:16 +100094 /* if there are no bases, use type: */
95 if (PyTuple_GET_SIZE(bases) == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000096 meta = (PyObject *) (&PyType_Type);
Nick Coghlande31b192011-10-23 22:04:16 +100097 }
98 /* else get the type of the first base */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000099 else {
100 PyObject *base0 = PyTuple_GET_ITEM(bases, 0);
101 meta = (PyObject *) (base0->ob_type);
102 }
103 Py_INCREF(meta);
Nick Coghlande31b192011-10-23 22:04:16 +1000104 isclass = 1; /* meta is really a class */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000105 }
Nick Coghlan9715d262011-10-23 22:36:42 +1000106
Nick Coghlande31b192011-10-23 22:04:16 +1000107 if (isclass) {
108 /* meta is really a class, so check for a more derived
109 metaclass, or possible metaclass conflicts: */
110 winner = (PyObject *)_PyType_CalculateMetaclass((PyTypeObject *)meta,
111 bases);
112 if (winner == NULL) {
113 Py_DECREF(meta);
114 Py_XDECREF(mkw);
115 Py_DECREF(bases);
116 return NULL;
117 }
118 if (winner != meta) {
119 Py_DECREF(meta);
120 meta = winner;
121 Py_INCREF(meta);
122 }
123 }
124 /* else: meta is not a class, so we cannot do the metaclass
125 calculation, so we will use the explicitly given object as it is */
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +0200126 prep = _PyObject_GetAttrId(meta, &PyId___prepare__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000127 if (prep == NULL) {
128 if (PyErr_ExceptionMatches(PyExc_AttributeError)) {
129 PyErr_Clear();
130 ns = PyDict_New();
131 }
132 else {
133 Py_DECREF(meta);
134 Py_XDECREF(mkw);
135 Py_DECREF(bases);
136 return NULL;
137 }
138 }
139 else {
140 PyObject *pargs = PyTuple_Pack(2, name, bases);
141 if (pargs == NULL) {
142 Py_DECREF(prep);
143 Py_DECREF(meta);
144 Py_XDECREF(mkw);
145 Py_DECREF(bases);
146 return NULL;
147 }
148 ns = PyEval_CallObjectWithKeywords(prep, pargs, mkw);
149 Py_DECREF(pargs);
150 Py_DECREF(prep);
151 }
152 if (ns == NULL) {
153 Py_DECREF(meta);
154 Py_XDECREF(mkw);
155 Py_DECREF(bases);
156 return NULL;
157 }
158 cell = PyObject_CallFunctionObjArgs(func, ns, NULL);
159 if (cell != NULL) {
160 PyObject *margs;
161 margs = PyTuple_Pack(3, name, bases, ns);
162 if (margs != NULL) {
163 cls = PyEval_CallObjectWithKeywords(meta, margs, mkw);
164 Py_DECREF(margs);
165 }
Benjamin Peterson8e8fbea2012-06-01 23:57:36 -0700166 if (cls != NULL && PyCell_Check(cell))
167 PyCell_Set(cell, cls);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000168 Py_DECREF(cell);
169 }
170 Py_DECREF(ns);
171 Py_DECREF(meta);
172 Py_XDECREF(mkw);
173 Py_DECREF(bases);
174 return cls;
Guido van Rossum52cc1d82007-03-18 15:41:51 +0000175}
176
177PyDoc_STRVAR(build_class_doc,
178"__build_class__(func, name, *bases, metaclass=None, **kwds) -> class\n\
179\n\
180Internal helper function used by the class statement.");
181
182static PyObject *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000183builtin___import__(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000184{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000185 static char *kwlist[] = {"name", "globals", "locals", "fromlist",
186 "level", 0};
Victor Stinnerfe93faf2011-03-14 15:54:52 -0400187 PyObject *name, *globals = NULL, *locals = NULL, *fromlist = NULL;
Brett Cannonfd074152012-04-14 14:10:13 -0400188 int level = 0;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000189
Victor Stinnerfe93faf2011-03-14 15:54:52 -0400190 if (!PyArg_ParseTupleAndKeywords(args, kwds, "U|OOOi:__import__",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000191 kwlist, &name, &globals, &locals, &fromlist, &level))
192 return NULL;
Victor Stinnerfe93faf2011-03-14 15:54:52 -0400193 return PyImport_ImportModuleLevelObject(name, globals, locals,
194 fromlist, level);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000195}
196
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000197PyDoc_STRVAR(import_doc,
Brett Cannoncb4996a2012-08-06 16:34:44 -0400198"__import__(name, globals=None, locals=None, fromlist=(), level=0) -> module\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000199\n\
Brett Cannon5305a992010-09-27 21:08:38 +0000200Import a module. Because this function is meant for use by the Python\n\
201interpreter and not for general use it is better to use\n\
202importlib.import_module() to programmatically import a module.\n\
203\n\
204The globals argument is only used to determine the context;\n\
205they are not modified. The locals argument is unused. The fromlist\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000206should be a list of names to emulate ``from name import ...'', or an\n\
207empty list to emulate ``import name''.\n\
208When importing a module from a package, note that __import__('A.B', ...)\n\
209returns package A when fromlist is empty, but its submodule B when\n\
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000210fromlist is not empty. Level is used to determine whether to perform \n\
Brett Cannon722d3ae2012-07-30 17:45:54 -0400211absolute or relative imports. 0 is absolute while a positive number\n\
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000212is the number of parent directories to search relative to the current module.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000213
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000214
Guido van Rossum79f25d91997-04-29 20:08:16 +0000215static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000216builtin_abs(PyObject *self, PyObject *v)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000217{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000218 return PyNumber_Absolute(v);
Guido van Rossum3f5da241990-12-20 15:06:42 +0000219}
220
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000221PyDoc_STRVAR(abs_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000222"abs(number) -> number\n\
223\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000224Return the absolute value of the argument.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000225
Raymond Hettinger96229b12005-03-11 06:49:40 +0000226static PyObject *
227builtin_all(PyObject *self, PyObject *v)
228{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000229 PyObject *it, *item;
230 PyObject *(*iternext)(PyObject *);
231 int cmp;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000232
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000233 it = PyObject_GetIter(v);
234 if (it == NULL)
235 return NULL;
236 iternext = *Py_TYPE(it)->tp_iternext;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000237
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000238 for (;;) {
239 item = iternext(it);
240 if (item == NULL)
241 break;
242 cmp = PyObject_IsTrue(item);
243 Py_DECREF(item);
244 if (cmp < 0) {
245 Py_DECREF(it);
246 return NULL;
247 }
248 if (cmp == 0) {
249 Py_DECREF(it);
250 Py_RETURN_FALSE;
251 }
252 }
253 Py_DECREF(it);
254 if (PyErr_Occurred()) {
255 if (PyErr_ExceptionMatches(PyExc_StopIteration))
256 PyErr_Clear();
257 else
258 return NULL;
259 }
260 Py_RETURN_TRUE;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000261}
262
263PyDoc_STRVAR(all_doc,
264"all(iterable) -> bool\n\
265\n\
266Return True if bool(x) is True for all values x in the iterable.");
267
268static PyObject *
269builtin_any(PyObject *self, PyObject *v)
270{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000271 PyObject *it, *item;
272 PyObject *(*iternext)(PyObject *);
273 int cmp;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000274
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000275 it = PyObject_GetIter(v);
276 if (it == NULL)
277 return NULL;
278 iternext = *Py_TYPE(it)->tp_iternext;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000279
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000280 for (;;) {
281 item = iternext(it);
282 if (item == NULL)
283 break;
284 cmp = PyObject_IsTrue(item);
285 Py_DECREF(item);
286 if (cmp < 0) {
287 Py_DECREF(it);
288 return NULL;
289 }
290 if (cmp == 1) {
291 Py_DECREF(it);
292 Py_RETURN_TRUE;
293 }
294 }
295 Py_DECREF(it);
296 if (PyErr_Occurred()) {
297 if (PyErr_ExceptionMatches(PyExc_StopIteration))
298 PyErr_Clear();
299 else
300 return NULL;
301 }
302 Py_RETURN_FALSE;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000303}
304
305PyDoc_STRVAR(any_doc,
306"any(iterable) -> bool\n\
307\n\
308Return True if bool(x) is True for any x in the iterable.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000309
Georg Brandl559e5d72008-06-11 18:37:52 +0000310static PyObject *
311builtin_ascii(PyObject *self, PyObject *v)
312{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000313 return PyObject_ASCII(v);
Georg Brandl559e5d72008-06-11 18:37:52 +0000314}
315
316PyDoc_STRVAR(ascii_doc,
317"ascii(object) -> string\n\
318\n\
319As repr(), return a string containing a printable representation of an\n\
320object, but escape the non-ASCII characters in the string returned by\n\
321repr() using \\x, \\u or \\U escapes. This generates a string similar\n\
322to that returned by repr() in Python 2.");
323
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000324
Guido van Rossum79f25d91997-04-29 20:08:16 +0000325static PyObject *
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000326builtin_bin(PyObject *self, PyObject *v)
327{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000328 return PyNumber_ToBase(v, 2);
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000329}
330
331PyDoc_STRVAR(bin_doc,
332"bin(number) -> string\n\
333\n\
Alexander Belopolsky12338ab2011-04-07 00:15:33 -0400334Return the binary representation of an integer.");
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000335
336
Antoine Pitroue71362d2010-11-27 22:00:11 +0000337static PyObject *
338builtin_callable(PyObject *self, PyObject *v)
339{
340 return PyBool_FromLong((long)PyCallable_Check(v));
341}
342
343PyDoc_STRVAR(callable_doc,
344"callable(object) -> bool\n\
345\n\
346Return whether the object is callable (i.e., some kind of function).\n\
347Note that classes are callable, as are instances of classes with a\n\
348__call__() method.");
349
350
Raymond Hettinger17301e92008-03-13 00:19:26 +0000351typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000352 PyObject_HEAD
353 PyObject *func;
354 PyObject *it;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000355} filterobject;
356
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000357static PyObject *
Raymond Hettinger17301e92008-03-13 00:19:26 +0000358filter_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
Guido van Rossum12d12c51993-10-26 17:58:25 +0000359{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000360 PyObject *func, *seq;
361 PyObject *it;
362 filterobject *lz;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000363
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000364 if (type == &PyFilter_Type && !_PyArg_NoKeywords("filter()", kwds))
365 return NULL;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000366
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000367 if (!PyArg_UnpackTuple(args, "filter", 2, 2, &func, &seq))
368 return NULL;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000369
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000370 /* Get iterator. */
371 it = PyObject_GetIter(seq);
372 if (it == NULL)
373 return NULL;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000374
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000375 /* create filterobject structure */
376 lz = (filterobject *)type->tp_alloc(type, 0);
377 if (lz == NULL) {
378 Py_DECREF(it);
379 return NULL;
380 }
381 Py_INCREF(func);
382 lz->func = func;
383 lz->it = it;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000384
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000385 return (PyObject *)lz;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000386}
387
388static void
389filter_dealloc(filterobject *lz)
390{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000391 PyObject_GC_UnTrack(lz);
392 Py_XDECREF(lz->func);
393 Py_XDECREF(lz->it);
394 Py_TYPE(lz)->tp_free(lz);
Raymond Hettinger17301e92008-03-13 00:19:26 +0000395}
396
397static int
398filter_traverse(filterobject *lz, visitproc visit, void *arg)
399{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000400 Py_VISIT(lz->it);
401 Py_VISIT(lz->func);
402 return 0;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000403}
404
405static PyObject *
406filter_next(filterobject *lz)
407{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000408 PyObject *item;
409 PyObject *it = lz->it;
410 long ok;
411 PyObject *(*iternext)(PyObject *);
Raymond Hettinger17301e92008-03-13 00:19:26 +0000412
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000413 iternext = *Py_TYPE(it)->tp_iternext;
414 for (;;) {
415 item = iternext(it);
416 if (item == NULL)
417 return NULL;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000418
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000419 if (lz->func == Py_None || lz->func == (PyObject *)&PyBool_Type) {
420 ok = PyObject_IsTrue(item);
421 } else {
422 PyObject *good;
423 good = PyObject_CallFunctionObjArgs(lz->func,
424 item, NULL);
425 if (good == NULL) {
426 Py_DECREF(item);
427 return NULL;
428 }
429 ok = PyObject_IsTrue(good);
430 Py_DECREF(good);
431 }
Antoine Pitrou6f430e42012-08-15 23:18:25 +0200432 if (ok > 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000433 return item;
434 Py_DECREF(item);
Antoine Pitrou6f430e42012-08-15 23:18:25 +0200435 if (ok < 0)
436 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000437 }
Guido van Rossum12d12c51993-10-26 17:58:25 +0000438}
439
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +0000440static PyObject *
441filter_reduce(filterobject *lz)
442{
443 return Py_BuildValue("O(OO)", Py_TYPE(lz), lz->func, lz->it);
444}
445
446PyDoc_STRVAR(reduce_doc, "Return state information for pickling.");
447
448static PyMethodDef filter_methods[] = {
449 {"__reduce__", (PyCFunction)filter_reduce, METH_NOARGS, reduce_doc},
450 {NULL, NULL} /* sentinel */
451};
452
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000453PyDoc_STRVAR(filter_doc,
Georg Brandld11ae5d2008-05-16 13:27:32 +0000454"filter(function or None, iterable) --> filter object\n\
Guido van Rossumc1f779c2007-07-03 08:25:58 +0000455\n\
Georg Brandld11ae5d2008-05-16 13:27:32 +0000456Return an iterator yielding those items of iterable for which function(item)\n\
Raymond Hettinger17301e92008-03-13 00:19:26 +0000457is true. If function is None, return the items that are true.");
458
459PyTypeObject PyFilter_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000460 PyVarObject_HEAD_INIT(&PyType_Type, 0)
461 "filter", /* tp_name */
462 sizeof(filterobject), /* tp_basicsize */
463 0, /* tp_itemsize */
464 /* methods */
465 (destructor)filter_dealloc, /* tp_dealloc */
466 0, /* tp_print */
467 0, /* tp_getattr */
468 0, /* tp_setattr */
469 0, /* tp_reserved */
470 0, /* tp_repr */
471 0, /* tp_as_number */
472 0, /* tp_as_sequence */
473 0, /* tp_as_mapping */
474 0, /* tp_hash */
475 0, /* tp_call */
476 0, /* tp_str */
477 PyObject_GenericGetAttr, /* tp_getattro */
478 0, /* tp_setattro */
479 0, /* tp_as_buffer */
480 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
481 Py_TPFLAGS_BASETYPE, /* tp_flags */
482 filter_doc, /* tp_doc */
483 (traverseproc)filter_traverse, /* tp_traverse */
484 0, /* tp_clear */
485 0, /* tp_richcompare */
486 0, /* tp_weaklistoffset */
487 PyObject_SelfIter, /* tp_iter */
488 (iternextfunc)filter_next, /* tp_iternext */
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +0000489 filter_methods, /* tp_methods */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000490 0, /* tp_members */
491 0, /* tp_getset */
492 0, /* tp_base */
493 0, /* tp_dict */
494 0, /* tp_descr_get */
495 0, /* tp_descr_set */
496 0, /* tp_dictoffset */
497 0, /* tp_init */
498 PyType_GenericAlloc, /* tp_alloc */
499 filter_new, /* tp_new */
500 PyObject_GC_Del, /* tp_free */
Raymond Hettinger17301e92008-03-13 00:19:26 +0000501};
502
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000503
Eric Smith8c663262007-08-25 02:26:07 +0000504static PyObject *
505builtin_format(PyObject *self, PyObject *args)
506{
Christian Heimes94b7d3d2007-12-11 20:20:39 +0000507 PyObject *value;
Eric Smith8fd3eba2008-02-17 19:48:00 +0000508 PyObject *format_spec = NULL;
Eric Smith8c663262007-08-25 02:26:07 +0000509
Eric Smith8fd3eba2008-02-17 19:48:00 +0000510 if (!PyArg_ParseTuple(args, "O|U:format", &value, &format_spec))
Benjamin Petersona12d5c62012-01-03 16:47:22 -0600511 return NULL;
Eric Smith8c663262007-08-25 02:26:07 +0000512
Eric Smith8fd3eba2008-02-17 19:48:00 +0000513 return PyObject_Format(value, format_spec);
Eric Smith8c663262007-08-25 02:26:07 +0000514}
515
Eric Smith8c663262007-08-25 02:26:07 +0000516PyDoc_STRVAR(format_doc,
Eric Smith81936692007-08-31 01:14:01 +0000517"format(value[, format_spec]) -> string\n\
Eric Smith8c663262007-08-25 02:26:07 +0000518\n\
Eric Smith81936692007-08-31 01:14:01 +0000519Returns value.__format__(format_spec)\n\
520format_spec defaults to \"\"");
521
Guido van Rossum7fcf2242007-05-04 17:43:11 +0000522static PyObject *
Walter Dörwalde7efd592007-06-05 20:07:21 +0000523builtin_chr(PyObject *self, PyObject *args)
Guido van Rossum09095f32000-03-10 23:00:52 +0000524{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000525 int x;
Guido van Rossum09095f32000-03-10 23:00:52 +0000526
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000527 if (!PyArg_ParseTuple(args, "i:chr", &x))
528 return NULL;
Fredrik Lundh0dcf67e2001-06-26 20:01:56 +0000529
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000530 return PyUnicode_FromOrdinal(x);
Guido van Rossum09095f32000-03-10 23:00:52 +0000531}
532
Victor Stinner63ab8752011-11-22 03:31:20 +0100533PyDoc_STRVAR(chr_doc,
Guido van Rossum84fc66d2007-05-03 17:18:26 +0000534"chr(i) -> Unicode character\n\
Guido van Rossum09095f32000-03-10 23:00:52 +0000535\n\
Victor Stinner63ab8752011-11-22 03:31:20 +0100536Return a Unicode string of one character with ordinal i; 0 <= i <= 0x10ffff.");
Guido van Rossum09095f32000-03-10 23:00:52 +0000537
538
Guido van Rossumf15a29f2007-05-04 00:41:39 +0000539static char *
Benjamin Petersonf5b52242009-03-02 23:31:26 +0000540source_as_string(PyObject *cmd, char *funcname, char *what, PyCompilerFlags *cf)
Guido van Rossumf15a29f2007-05-04 00:41:39 +0000541{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000542 char *str;
543 Py_ssize_t size;
Guido van Rossumf15a29f2007-05-04 00:41:39 +0000544
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000545 if (PyUnicode_Check(cmd)) {
546 cf->cf_flags |= PyCF_IGNORE_COOKIE;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200547 str = PyUnicode_AsUTF8AndSize(cmd, &size);
548 if (str == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000549 return NULL;
550 }
551 else if (!PyObject_CheckReadBuffer(cmd)) {
552 PyErr_Format(PyExc_TypeError,
553 "%s() arg 1 must be a %s object",
554 funcname, what);
555 return NULL;
556 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200557 else if (PyObject_AsReadBuffer(cmd, (const void **)&str, &size) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000558 return NULL;
559 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200560
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000561 if (strlen(str) != size) {
562 PyErr_SetString(PyExc_TypeError,
563 "source code string cannot contain null bytes");
564 return NULL;
565 }
566 return str;
Guido van Rossumf15a29f2007-05-04 00:41:39 +0000567}
568
Guido van Rossum79f25d91997-04-29 20:08:16 +0000569static PyObject *
Guido van Rossumd8faa362007-04-27 19:54:29 +0000570builtin_compile(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum5b722181993-03-30 17:46:03 +0000571{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000572 char *str;
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000573 PyObject *filename_obj;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000574 char *filename;
575 char *startstr;
576 int mode = -1;
577 int dont_inherit = 0;
578 int supplied_flags = 0;
Georg Brandl8334fd92010-12-04 10:26:46 +0000579 int optimize = -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000580 int is_ast;
581 PyCompilerFlags cf;
582 PyObject *cmd;
583 static char *kwlist[] = {"source", "filename", "mode", "flags",
Georg Brandl8334fd92010-12-04 10:26:46 +0000584 "dont_inherit", "optimize", NULL};
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000585 int start[] = {Py_file_input, Py_eval_input, Py_single_input};
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000586 PyObject *result;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000587
Georg Brandl8334fd92010-12-04 10:26:46 +0000588 if (!PyArg_ParseTupleAndKeywords(args, kwds, "OO&s|iii:compile", kwlist,
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000589 &cmd,
590 PyUnicode_FSConverter, &filename_obj,
591 &startstr, &supplied_flags,
Georg Brandl8334fd92010-12-04 10:26:46 +0000592 &dont_inherit, &optimize))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000593 return NULL;
Tim Peters6cd6a822001-08-17 22:11:27 +0000594
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000595 filename = PyBytes_AS_STRING(filename_obj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000596 cf.cf_flags = supplied_flags | PyCF_SOURCE_IS_UTF8;
Just van Rossum3aaf42c2003-02-10 08:21:10 +0000597
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000598 if (supplied_flags &
599 ~(PyCF_MASK | PyCF_MASK_OBSOLETE | PyCF_DONT_IMPLY_DEDENT | PyCF_ONLY_AST))
600 {
601 PyErr_SetString(PyExc_ValueError,
602 "compile(): unrecognised flags");
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000603 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000604 }
605 /* XXX Warn if (supplied_flags & PyCF_MASK_OBSOLETE) != 0? */
Tim Peters6cd6a822001-08-17 22:11:27 +0000606
Georg Brandl8334fd92010-12-04 10:26:46 +0000607 if (optimize < -1 || optimize > 2) {
608 PyErr_SetString(PyExc_ValueError,
609 "compile(): invalid optimize value");
610 goto error;
611 }
612
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000613 if (!dont_inherit) {
614 PyEval_MergeCompilerFlags(&cf);
615 }
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000616
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000617 if (strcmp(startstr, "exec") == 0)
618 mode = 0;
619 else if (strcmp(startstr, "eval") == 0)
620 mode = 1;
621 else if (strcmp(startstr, "single") == 0)
622 mode = 2;
623 else {
624 PyErr_SetString(PyExc_ValueError,
625 "compile() arg 3 must be 'exec', 'eval' or 'single'");
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000626 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000627 }
Neal Norwitzdb4115f2008-03-31 04:20:05 +0000628
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000629 is_ast = PyAST_Check(cmd);
630 if (is_ast == -1)
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000631 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000632 if (is_ast) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000633 if (supplied_flags & PyCF_ONLY_AST) {
634 Py_INCREF(cmd);
635 result = cmd;
636 }
637 else {
638 PyArena *arena;
639 mod_ty mod;
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000640
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000641 arena = PyArena_New();
642 mod = PyAST_obj2mod(cmd, arena, mode);
643 if (mod == NULL) {
644 PyArena_Free(arena);
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000645 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000646 }
Benjamin Peterson832bfe22011-08-09 16:15:04 -0500647 if (!PyAST_Validate(mod)) {
648 PyArena_Free(arena);
649 goto error;
650 }
Georg Brandl8334fd92010-12-04 10:26:46 +0000651 result = (PyObject*)PyAST_CompileEx(mod, filename,
652 &cf, optimize, arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000653 PyArena_Free(arena);
654 }
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000655 goto finally;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000656 }
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000657
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000658 str = source_as_string(cmd, "compile", "string, bytes, AST or code", &cf);
659 if (str == NULL)
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000660 goto error;
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000661
Georg Brandl8334fd92010-12-04 10:26:46 +0000662 result = Py_CompileStringExFlags(str, filename, start[mode], &cf, optimize);
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000663 goto finally;
664
665error:
666 result = NULL;
667finally:
668 Py_DECREF(filename_obj);
669 return result;
Guido van Rossum5b722181993-03-30 17:46:03 +0000670}
671
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000672PyDoc_STRVAR(compile_doc,
Tim Peters6cd6a822001-08-17 22:11:27 +0000673"compile(source, filename, mode[, flags[, dont_inherit]]) -> code object\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000674\n\
675Compile the source string (a Python module, statement or expression)\n\
Georg Brandl7cae87c2006-09-06 06:51:57 +0000676into a code object that can be executed by exec() or eval().\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000677The filename will be used for run-time error messages.\n\
678The mode must be 'exec' to compile a module, 'single' to compile a\n\
Tim Peters6cd6a822001-08-17 22:11:27 +0000679single (interactive) statement, or 'eval' to compile an expression.\n\
680The flags argument, if present, controls which future statements influence\n\
681the compilation of the code.\n\
682The dont_inherit argument, if non-zero, stops the compilation inheriting\n\
683the effects of any future statements in effect in the code calling\n\
684compile; if absent or zero these statements do influence the compilation,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000685in addition to any features explicitly specified.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000686
Guido van Rossum79f25d91997-04-29 20:08:16 +0000687static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000688builtin_dir(PyObject *self, PyObject *args)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000689{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000690 PyObject *arg = NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000691
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000692 if (!PyArg_UnpackTuple(args, "dir", 0, 1, &arg))
693 return NULL;
694 return PyObject_Dir(arg);
Guido van Rossum3f5da241990-12-20 15:06:42 +0000695}
696
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000697PyDoc_STRVAR(dir_doc,
Tim Peters5d2b77c2001-09-03 05:47:38 +0000698"dir([object]) -> list of strings\n"
699"\n"
Georg Brandle32b4222007-03-10 22:13:27 +0000700"If called without an argument, return the names in the current scope.\n"
701"Else, return an alphabetized list of names comprising (some of) the attributes\n"
702"of the given object, and of attributes reachable from it.\n"
703"If the object supplies a method named __dir__, it will be used; otherwise\n"
704"the default dir() logic is used and returns:\n"
705" for a module object: the module's attributes.\n"
706" for a class object: its attributes, and recursively the attributes\n"
707" of its bases.\n"
Guido van Rossumd8faa362007-04-27 19:54:29 +0000708" for any other object: its attributes, its class's attributes, and\n"
Georg Brandle32b4222007-03-10 22:13:27 +0000709" recursively the attributes of its class's base classes.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000710
Guido van Rossum79f25d91997-04-29 20:08:16 +0000711static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000712builtin_divmod(PyObject *self, PyObject *args)
Guido van Rossum6a00cd81995-01-07 12:39:01 +0000713{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000714 PyObject *v, *w;
Guido van Rossum6a00cd81995-01-07 12:39:01 +0000715
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000716 if (!PyArg_UnpackTuple(args, "divmod", 2, 2, &v, &w))
717 return NULL;
718 return PyNumber_Divmod(v, w);
Guido van Rossum3f5da241990-12-20 15:06:42 +0000719}
720
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000721PyDoc_STRVAR(divmod_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000722"divmod(x, y) -> (div, mod)\n\
723\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000724Return the tuple ((x-x%y)/y, x%y). Invariant: div*y + mod == x.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000725
726
Guido van Rossum79f25d91997-04-29 20:08:16 +0000727static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000728builtin_eval(PyObject *self, PyObject *args)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000729{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000730 PyObject *cmd, *result, *tmp = NULL;
731 PyObject *globals = Py_None, *locals = Py_None;
732 char *str;
733 PyCompilerFlags cf;
Guido van Rossum590baa41993-11-30 13:40:46 +0000734
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000735 if (!PyArg_UnpackTuple(args, "eval", 1, 3, &cmd, &globals, &locals))
736 return NULL;
737 if (locals != Py_None && !PyMapping_Check(locals)) {
738 PyErr_SetString(PyExc_TypeError, "locals must be a mapping");
739 return NULL;
740 }
741 if (globals != Py_None && !PyDict_Check(globals)) {
742 PyErr_SetString(PyExc_TypeError, PyMapping_Check(globals) ?
743 "globals must be a real dict; try eval(expr, {}, mapping)"
744 : "globals must be a dict");
745 return NULL;
746 }
747 if (globals == Py_None) {
748 globals = PyEval_GetGlobals();
749 if (locals == Py_None)
750 locals = PyEval_GetLocals();
751 }
752 else if (locals == Py_None)
753 locals = globals;
Tim Peters9fa96be2001-08-17 23:04:59 +0000754
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000755 if (globals == NULL || locals == NULL) {
756 PyErr_SetString(PyExc_TypeError,
757 "eval must be given globals and locals "
758 "when called without a frame");
759 return NULL;
760 }
Georg Brandl77c85e62005-09-15 10:46:13 +0000761
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000762 if (PyDict_GetItemString(globals, "__builtins__") == NULL) {
763 if (PyDict_SetItemString(globals, "__builtins__",
764 PyEval_GetBuiltins()) != 0)
765 return NULL;
766 }
Tim Peters9fa96be2001-08-17 23:04:59 +0000767
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000768 if (PyCode_Check(cmd)) {
769 if (PyCode_GetNumFree((PyCodeObject *)cmd) > 0) {
770 PyErr_SetString(PyExc_TypeError,
771 "code object passed to eval() may not contain free variables");
772 return NULL;
773 }
Martin v. Löwis4d0d4712010-12-03 20:14:31 +0000774 return PyEval_EvalCode(cmd, globals, locals);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000775 }
Tim Peters9fa96be2001-08-17 23:04:59 +0000776
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000777 cf.cf_flags = PyCF_SOURCE_IS_UTF8;
778 str = source_as_string(cmd, "eval", "string, bytes or code", &cf);
779 if (str == NULL)
780 return NULL;
Just van Rossum3aaf42c2003-02-10 08:21:10 +0000781
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000782 while (*str == ' ' || *str == '\t')
783 str++;
Tim Peters9fa96be2001-08-17 23:04:59 +0000784
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000785 (void)PyEval_MergeCompilerFlags(&cf);
786 result = PyRun_StringFlags(str, Py_eval_input, globals, locals, &cf);
787 Py_XDECREF(tmp);
788 return result;
Guido van Rossum3f5da241990-12-20 15:06:42 +0000789}
790
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000791PyDoc_STRVAR(eval_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000792"eval(source[, globals[, locals]]) -> value\n\
793\n\
794Evaluate the source in the context of globals and locals.\n\
795The source may be a string representing a Python expression\n\
796or a code object as returned by compile().\n\
Thomas Wouters89f507f2006-12-13 04:49:30 +0000797The globals must be a dictionary and locals can be any mapping,\n\
Raymond Hettinger214b1c32004-07-02 06:41:07 +0000798defaulting to the current globals and locals.\n\
799If only globals is given, locals defaults to it.\n");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000800
Georg Brandl7cae87c2006-09-06 06:51:57 +0000801static PyObject *
802builtin_exec(PyObject *self, PyObject *args)
803{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000804 PyObject *v;
805 PyObject *prog, *globals = Py_None, *locals = Py_None;
Georg Brandl7cae87c2006-09-06 06:51:57 +0000806
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000807 if (!PyArg_UnpackTuple(args, "exec", 1, 3, &prog, &globals, &locals))
808 return NULL;
Georg Brandl2cabc562008-08-28 07:57:16 +0000809
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000810 if (globals == Py_None) {
811 globals = PyEval_GetGlobals();
812 if (locals == Py_None) {
813 locals = PyEval_GetLocals();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000814 }
815 if (!globals || !locals) {
816 PyErr_SetString(PyExc_SystemError,
817 "globals and locals cannot be NULL");
818 return NULL;
819 }
820 }
821 else if (locals == Py_None)
822 locals = globals;
Georg Brandl7cae87c2006-09-06 06:51:57 +0000823
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000824 if (!PyDict_Check(globals)) {
825 PyErr_Format(PyExc_TypeError, "exec() arg 2 must be a dict, not %.100s",
826 globals->ob_type->tp_name);
827 return NULL;
828 }
829 if (!PyMapping_Check(locals)) {
830 PyErr_Format(PyExc_TypeError,
831 "arg 3 must be a mapping or None, not %.100s",
832 locals->ob_type->tp_name);
833 return NULL;
834 }
835 if (PyDict_GetItemString(globals, "__builtins__") == NULL) {
836 if (PyDict_SetItemString(globals, "__builtins__",
837 PyEval_GetBuiltins()) != 0)
838 return NULL;
839 }
840
841 if (PyCode_Check(prog)) {
842 if (PyCode_GetNumFree((PyCodeObject *)prog) > 0) {
843 PyErr_SetString(PyExc_TypeError,
844 "code object passed to exec() may not "
845 "contain free variables");
846 return NULL;
847 }
Martin v. Löwis4d0d4712010-12-03 20:14:31 +0000848 v = PyEval_EvalCode(prog, globals, locals);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000849 }
850 else {
851 char *str;
852 PyCompilerFlags cf;
853 cf.cf_flags = PyCF_SOURCE_IS_UTF8;
854 str = source_as_string(prog, "exec",
855 "string, bytes or code", &cf);
856 if (str == NULL)
857 return NULL;
858 if (PyEval_MergeCompilerFlags(&cf))
859 v = PyRun_StringFlags(str, Py_file_input, globals,
860 locals, &cf);
861 else
862 v = PyRun_String(str, Py_file_input, globals, locals);
863 }
864 if (v == NULL)
865 return NULL;
866 Py_DECREF(v);
867 Py_RETURN_NONE;
Georg Brandl7cae87c2006-09-06 06:51:57 +0000868}
869
870PyDoc_STRVAR(exec_doc,
871"exec(object[, globals[, locals]])\n\
872\n\
Mark Dickinson480e8e32009-12-19 21:19:35 +0000873Read and execute code from an object, which can be a string or a code\n\
Benjamin Peterson38090262009-01-04 15:30:39 +0000874object.\n\
Georg Brandl7cae87c2006-09-06 06:51:57 +0000875The globals and locals are dictionaries, defaulting to the current\n\
876globals and locals. If only globals is given, locals defaults to it.");
877
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000878
Guido van Rossum79f25d91997-04-29 20:08:16 +0000879static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000880builtin_getattr(PyObject *self, PyObject *args)
Guido van Rossum33894be1992-01-27 16:53:09 +0000881{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000882 PyObject *v, *result, *dflt = NULL;
883 PyObject *name;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000884
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000885 if (!PyArg_UnpackTuple(args, "getattr", 2, 3, &v, &name, &dflt))
886 return NULL;
Martin v. Löwis5b222132007-06-10 09:51:05 +0000887
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000888 if (!PyUnicode_Check(name)) {
889 PyErr_SetString(PyExc_TypeError,
890 "getattr(): attribute name must be string");
891 return NULL;
892 }
893 result = PyObject_GetAttr(v, name);
894 if (result == NULL && dflt != NULL &&
895 PyErr_ExceptionMatches(PyExc_AttributeError))
896 {
897 PyErr_Clear();
898 Py_INCREF(dflt);
899 result = dflt;
900 }
901 return result;
Guido van Rossum9bfef441993-03-29 10:43:31 +0000902}
903
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000904PyDoc_STRVAR(getattr_doc,
Guido van Rossum950ff291998-06-29 13:38:57 +0000905"getattr(object, name[, default]) -> value\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000906\n\
Guido van Rossum950ff291998-06-29 13:38:57 +0000907Get a named attribute from an object; getattr(x, 'y') is equivalent to x.y.\n\
908When a default argument is given, it is returned when the attribute doesn't\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000909exist; without it, an exception is raised in that case.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000910
911
Guido van Rossum79f25d91997-04-29 20:08:16 +0000912static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000913builtin_globals(PyObject *self)
Guido van Rossum872537c1995-07-07 22:43:42 +0000914{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000915 PyObject *d;
Guido van Rossum872537c1995-07-07 22:43:42 +0000916
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000917 d = PyEval_GetGlobals();
918 Py_XINCREF(d);
919 return d;
Guido van Rossum872537c1995-07-07 22:43:42 +0000920}
921
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000922PyDoc_STRVAR(globals_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000923"globals() -> dictionary\n\
924\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000925Return the dictionary containing the current scope's global variables.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000926
927
Guido van Rossum79f25d91997-04-29 20:08:16 +0000928static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000929builtin_hasattr(PyObject *self, PyObject *args)
Guido van Rossum9bfef441993-03-29 10:43:31 +0000930{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000931 PyObject *v;
932 PyObject *name;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000933
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000934 if (!PyArg_UnpackTuple(args, "hasattr", 2, 2, &v, &name))
935 return NULL;
936 if (!PyUnicode_Check(name)) {
937 PyErr_SetString(PyExc_TypeError,
938 "hasattr(): attribute name must be string");
939 return NULL;
940 }
941 v = PyObject_GetAttr(v, name);
942 if (v == NULL) {
Benjamin Peterson17689992010-08-24 03:26:23 +0000943 if (PyErr_ExceptionMatches(PyExc_AttributeError)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000944 PyErr_Clear();
Benjamin Peterson17689992010-08-24 03:26:23 +0000945 Py_RETURN_FALSE;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000946 }
Benjamin Peterson17689992010-08-24 03:26:23 +0000947 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000948 }
949 Py_DECREF(v);
Benjamin Peterson17689992010-08-24 03:26:23 +0000950 Py_RETURN_TRUE;
Guido van Rossum33894be1992-01-27 16:53:09 +0000951}
952
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000953PyDoc_STRVAR(hasattr_doc,
Guido van Rossum77f6a652002-04-03 22:41:51 +0000954"hasattr(object, name) -> bool\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000955\n\
956Return whether the object has an attribute with the given name.\n\
Benjamin Peterson17689992010-08-24 03:26:23 +0000957(This is done by calling getattr(object, name) and catching AttributeError.)");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000958
959
Guido van Rossum79f25d91997-04-29 20:08:16 +0000960static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000961builtin_id(PyObject *self, PyObject *v)
Guido van Rossum5b722181993-03-30 17:46:03 +0000962{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000963 return PyLong_FromVoidPtr(v);
Guido van Rossum5b722181993-03-30 17:46:03 +0000964}
965
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000966PyDoc_STRVAR(id_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000967"id(object) -> integer\n\
968\n\
969Return the identity of an object. This is guaranteed to be unique among\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000970simultaneously existing objects. (Hint: it's the object's memory address.)");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000971
972
Raymond Hettingera6c60372008-03-13 01:26:19 +0000973/* map object ************************************************************/
974
975typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000976 PyObject_HEAD
977 PyObject *iters;
978 PyObject *func;
Raymond Hettingera6c60372008-03-13 01:26:19 +0000979} mapobject;
980
Guido van Rossum79f25d91997-04-29 20:08:16 +0000981static PyObject *
Raymond Hettingera6c60372008-03-13 01:26:19 +0000982map_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
Guido van Rossum12d12c51993-10-26 17:58:25 +0000983{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000984 PyObject *it, *iters, *func;
985 mapobject *lz;
986 Py_ssize_t numargs, i;
Raymond Hettingera6c60372008-03-13 01:26:19 +0000987
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000988 if (type == &PyMap_Type && !_PyArg_NoKeywords("map()", kwds))
989 return NULL;
Raymond Hettingera6c60372008-03-13 01:26:19 +0000990
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000991 numargs = PyTuple_Size(args);
992 if (numargs < 2) {
993 PyErr_SetString(PyExc_TypeError,
994 "map() must have at least two arguments.");
995 return NULL;
996 }
Raymond Hettingera6c60372008-03-13 01:26:19 +0000997
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000998 iters = PyTuple_New(numargs-1);
999 if (iters == NULL)
1000 return NULL;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001001
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001002 for (i=1 ; i<numargs ; i++) {
1003 /* Get iterator. */
1004 it = PyObject_GetIter(PyTuple_GET_ITEM(args, i));
1005 if (it == NULL) {
1006 Py_DECREF(iters);
1007 return NULL;
1008 }
1009 PyTuple_SET_ITEM(iters, i-1, it);
1010 }
Raymond Hettingera6c60372008-03-13 01:26:19 +00001011
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001012 /* create mapobject structure */
1013 lz = (mapobject *)type->tp_alloc(type, 0);
1014 if (lz == NULL) {
1015 Py_DECREF(iters);
1016 return NULL;
1017 }
1018 lz->iters = iters;
1019 func = PyTuple_GET_ITEM(args, 0);
1020 Py_INCREF(func);
1021 lz->func = func;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001022
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001023 return (PyObject *)lz;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001024}
1025
1026static void
1027map_dealloc(mapobject *lz)
1028{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001029 PyObject_GC_UnTrack(lz);
1030 Py_XDECREF(lz->iters);
1031 Py_XDECREF(lz->func);
1032 Py_TYPE(lz)->tp_free(lz);
Raymond Hettingera6c60372008-03-13 01:26:19 +00001033}
1034
1035static int
1036map_traverse(mapobject *lz, visitproc visit, void *arg)
1037{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001038 Py_VISIT(lz->iters);
1039 Py_VISIT(lz->func);
1040 return 0;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001041}
1042
1043static PyObject *
1044map_next(mapobject *lz)
1045{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001046 PyObject *val;
1047 PyObject *argtuple;
1048 PyObject *result;
1049 Py_ssize_t numargs, i;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001050
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001051 numargs = PyTuple_Size(lz->iters);
1052 argtuple = PyTuple_New(numargs);
1053 if (argtuple == NULL)
1054 return NULL;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001055
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001056 for (i=0 ; i<numargs ; i++) {
1057 val = PyIter_Next(PyTuple_GET_ITEM(lz->iters, i));
1058 if (val == NULL) {
1059 Py_DECREF(argtuple);
1060 return NULL;
1061 }
1062 PyTuple_SET_ITEM(argtuple, i, val);
1063 }
1064 result = PyObject_Call(lz->func, argtuple, NULL);
1065 Py_DECREF(argtuple);
1066 return result;
Guido van Rossum12d12c51993-10-26 17:58:25 +00001067}
1068
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001069static PyObject *
1070map_reduce(mapobject *lz)
1071{
1072 Py_ssize_t numargs = PyTuple_GET_SIZE(lz->iters);
1073 PyObject *args = PyTuple_New(numargs+1);
1074 Py_ssize_t i;
1075 if (args == NULL)
1076 return NULL;
1077 Py_INCREF(lz->func);
1078 PyTuple_SET_ITEM(args, 0, lz->func);
1079 for (i = 0; i<numargs; i++){
1080 PyObject *it = PyTuple_GET_ITEM(lz->iters, i);
1081 Py_INCREF(it);
1082 PyTuple_SET_ITEM(args, i+1, it);
1083 }
1084
1085 return Py_BuildValue("ON", Py_TYPE(lz), args);
1086}
1087
1088static PyMethodDef map_methods[] = {
1089 {"__reduce__", (PyCFunction)map_reduce, METH_NOARGS, reduce_doc},
1090 {NULL, NULL} /* sentinel */
1091};
1092
1093
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001094PyDoc_STRVAR(map_doc,
Raymond Hettingera6c60372008-03-13 01:26:19 +00001095"map(func, *iterables) --> map object\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001096\n\
Raymond Hettingera6c60372008-03-13 01:26:19 +00001097Make an iterator that computes the function using arguments from\n\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001098each of the iterables. Stops when the shortest iterable is exhausted.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001099
Raymond Hettingera6c60372008-03-13 01:26:19 +00001100PyTypeObject PyMap_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001101 PyVarObject_HEAD_INIT(&PyType_Type, 0)
1102 "map", /* tp_name */
1103 sizeof(mapobject), /* tp_basicsize */
1104 0, /* tp_itemsize */
1105 /* methods */
1106 (destructor)map_dealloc, /* tp_dealloc */
1107 0, /* tp_print */
1108 0, /* tp_getattr */
1109 0, /* tp_setattr */
1110 0, /* tp_reserved */
1111 0, /* tp_repr */
1112 0, /* tp_as_number */
1113 0, /* tp_as_sequence */
1114 0, /* tp_as_mapping */
1115 0, /* tp_hash */
1116 0, /* tp_call */
1117 0, /* tp_str */
1118 PyObject_GenericGetAttr, /* tp_getattro */
1119 0, /* tp_setattro */
1120 0, /* tp_as_buffer */
1121 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
1122 Py_TPFLAGS_BASETYPE, /* tp_flags */
1123 map_doc, /* tp_doc */
1124 (traverseproc)map_traverse, /* tp_traverse */
1125 0, /* tp_clear */
1126 0, /* tp_richcompare */
1127 0, /* tp_weaklistoffset */
1128 PyObject_SelfIter, /* tp_iter */
1129 (iternextfunc)map_next, /* tp_iternext */
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001130 map_methods, /* tp_methods */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001131 0, /* tp_members */
1132 0, /* tp_getset */
1133 0, /* tp_base */
1134 0, /* tp_dict */
1135 0, /* tp_descr_get */
1136 0, /* tp_descr_set */
1137 0, /* tp_dictoffset */
1138 0, /* tp_init */
1139 PyType_GenericAlloc, /* tp_alloc */
1140 map_new, /* tp_new */
1141 PyObject_GC_Del, /* tp_free */
Raymond Hettingera6c60372008-03-13 01:26:19 +00001142};
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001143
Guido van Rossum79f25d91997-04-29 20:08:16 +00001144static PyObject *
Georg Brandla18af4e2007-04-21 15:47:16 +00001145builtin_next(PyObject *self, PyObject *args)
1146{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001147 PyObject *it, *res;
1148 PyObject *def = NULL;
Georg Brandla18af4e2007-04-21 15:47:16 +00001149
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001150 if (!PyArg_UnpackTuple(args, "next", 1, 2, &it, &def))
1151 return NULL;
1152 if (!PyIter_Check(it)) {
1153 PyErr_Format(PyExc_TypeError,
Philip Jenvey50add042011-11-06 16:37:52 -08001154 "'%.200s' object is not an iterator",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001155 it->ob_type->tp_name);
1156 return NULL;
1157 }
1158
1159 res = (*it->ob_type->tp_iternext)(it);
1160 if (res != NULL) {
1161 return res;
1162 } else if (def != NULL) {
1163 if (PyErr_Occurred()) {
1164 if(!PyErr_ExceptionMatches(PyExc_StopIteration))
1165 return NULL;
1166 PyErr_Clear();
1167 }
1168 Py_INCREF(def);
1169 return def;
1170 } else if (PyErr_Occurred()) {
1171 return NULL;
1172 } else {
1173 PyErr_SetNone(PyExc_StopIteration);
1174 return NULL;
1175 }
Georg Brandla18af4e2007-04-21 15:47:16 +00001176}
1177
1178PyDoc_STRVAR(next_doc,
1179"next(iterator[, default])\n\
1180\n\
1181Return the next item from the iterator. If default is given and the iterator\n\
1182is exhausted, it is returned instead of raising StopIteration.");
1183
1184
1185static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001186builtin_setattr(PyObject *self, PyObject *args)
Guido van Rossum33894be1992-01-27 16:53:09 +00001187{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001188 PyObject *v;
1189 PyObject *name;
1190 PyObject *value;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001191
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001192 if (!PyArg_UnpackTuple(args, "setattr", 3, 3, &v, &name, &value))
1193 return NULL;
1194 if (PyObject_SetAttr(v, name, value) != 0)
1195 return NULL;
1196 Py_INCREF(Py_None);
1197 return Py_None;
Guido van Rossum33894be1992-01-27 16:53:09 +00001198}
1199
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001200PyDoc_STRVAR(setattr_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001201"setattr(object, name, value)\n\
1202\n\
1203Set a named attribute on an object; setattr(x, 'y', v) is equivalent to\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001204``x.y = v''.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001205
1206
Guido van Rossum79f25d91997-04-29 20:08:16 +00001207static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001208builtin_delattr(PyObject *self, PyObject *args)
Guido van Rossum14144fc1994-08-29 12:53:40 +00001209{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001210 PyObject *v;
1211 PyObject *name;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001212
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001213 if (!PyArg_UnpackTuple(args, "delattr", 2, 2, &v, &name))
1214 return NULL;
1215 if (PyObject_SetAttr(v, name, (PyObject *)NULL) != 0)
1216 return NULL;
1217 Py_INCREF(Py_None);
1218 return Py_None;
Guido van Rossum14144fc1994-08-29 12:53:40 +00001219}
1220
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001221PyDoc_STRVAR(delattr_doc,
Guido van Rossumdf12a591998-11-23 22:13:04 +00001222"delattr(object, name)\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001223\n\
1224Delete a named attribute on an object; delattr(x, 'y') is equivalent to\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001225``del x.y''.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001226
1227
Guido van Rossum79f25d91997-04-29 20:08:16 +00001228static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001229builtin_hash(PyObject *self, PyObject *v)
Guido van Rossum9bfef441993-03-29 10:43:31 +00001230{
Benjamin Peterson8f67d082010-10-17 20:54:53 +00001231 Py_hash_t x;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001232
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001233 x = PyObject_Hash(v);
1234 if (x == -1)
1235 return NULL;
Benjamin Peterson8f67d082010-10-17 20:54:53 +00001236 return PyLong_FromSsize_t(x);
Guido van Rossum9bfef441993-03-29 10:43:31 +00001237}
1238
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001239PyDoc_STRVAR(hash_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001240"hash(object) -> integer\n\
1241\n\
1242Return a hash value for the object. Two objects with the same value have\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001243the same hash value. The reverse is not necessarily true, but likely.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001244
1245
Guido van Rossum79f25d91997-04-29 20:08:16 +00001246static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001247builtin_hex(PyObject *self, PyObject *v)
Guido van Rossum006bcd41991-10-24 14:54:44 +00001248{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001249 return PyNumber_ToBase(v, 16);
Guido van Rossum006bcd41991-10-24 14:54:44 +00001250}
1251
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001252PyDoc_STRVAR(hex_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001253"hex(number) -> string\n\
1254\n\
Alexander Belopolsky12338ab2011-04-07 00:15:33 -04001255Return the hexadecimal representation of an integer.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001256
1257
Guido van Rossum79f25d91997-04-29 20:08:16 +00001258static PyObject *
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001259builtin_iter(PyObject *self, PyObject *args)
1260{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001261 PyObject *v, *w = NULL;
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001262
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001263 if (!PyArg_UnpackTuple(args, "iter", 1, 2, &v, &w))
1264 return NULL;
1265 if (w == NULL)
1266 return PyObject_GetIter(v);
1267 if (!PyCallable_Check(v)) {
1268 PyErr_SetString(PyExc_TypeError,
1269 "iter(v, w): v must be callable");
1270 return NULL;
1271 }
1272 return PyCallIter_New(v, w);
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001273}
1274
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001275PyDoc_STRVAR(iter_doc,
Georg Brandld11ae5d2008-05-16 13:27:32 +00001276"iter(iterable) -> iterator\n\
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001277iter(callable, sentinel) -> iterator\n\
1278\n\
1279Get an iterator from an object. In the first form, the argument must\n\
1280supply its own iterator, or be a sequence.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001281In the second form, the callable is called until it returns the sentinel.");
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001282
1283
1284static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001285builtin_len(PyObject *self, PyObject *v)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001286{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001287 Py_ssize_t res;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001288
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001289 res = PyObject_Size(v);
1290 if (res < 0 && PyErr_Occurred())
1291 return NULL;
1292 return PyLong_FromSsize_t(res);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001293}
1294
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001295PyDoc_STRVAR(len_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001296"len(object) -> integer\n\
1297\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001298Return the number of items of a sequence or mapping.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001299
1300
Guido van Rossum79f25d91997-04-29 20:08:16 +00001301static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001302builtin_locals(PyObject *self)
Guido van Rossum872537c1995-07-07 22:43:42 +00001303{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001304 PyObject *d;
Guido van Rossum872537c1995-07-07 22:43:42 +00001305
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001306 d = PyEval_GetLocals();
1307 Py_XINCREF(d);
1308 return d;
Guido van Rossum872537c1995-07-07 22:43:42 +00001309}
1310
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001311PyDoc_STRVAR(locals_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001312"locals() -> dictionary\n\
1313\n\
Raymond Hettinger69bf8f32003-01-04 02:16:22 +00001314Update and return a dictionary containing the current scope's local variables.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001315
1316
Guido van Rossum79f25d91997-04-29 20:08:16 +00001317static PyObject *
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001318min_max(PyObject *args, PyObject *kwds, int op)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001319{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001320 PyObject *v, *it, *item, *val, *maxitem, *maxval, *keyfunc=NULL;
1321 const char *name = op == Py_LT ? "min" : "max";
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001322
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001323 if (PyTuple_Size(args) > 1)
1324 v = args;
1325 else if (!PyArg_UnpackTuple(args, (char *)name, 1, 1, &v))
1326 return NULL;
Tim Peters67d687a2002-04-29 21:27:32 +00001327
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001328 if (kwds != NULL && PyDict_Check(kwds) && PyDict_Size(kwds)) {
1329 keyfunc = PyDict_GetItemString(kwds, "key");
1330 if (PyDict_Size(kwds)!=1 || keyfunc == NULL) {
1331 PyErr_Format(PyExc_TypeError,
1332 "%s() got an unexpected keyword argument", name);
1333 return NULL;
1334 }
1335 Py_INCREF(keyfunc);
1336 }
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001337
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001338 it = PyObject_GetIter(v);
1339 if (it == NULL) {
1340 Py_XDECREF(keyfunc);
1341 return NULL;
1342 }
Tim Petersc3074532001-05-03 07:00:32 +00001343
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001344 maxitem = NULL; /* the result */
1345 maxval = NULL; /* the value associated with the result */
1346 while (( item = PyIter_Next(it) )) {
1347 /* get the value from the key function */
1348 if (keyfunc != NULL) {
1349 val = PyObject_CallFunctionObjArgs(keyfunc, item, NULL);
1350 if (val == NULL)
1351 goto Fail_it_item;
1352 }
1353 /* no key function; the value is the item */
1354 else {
1355 val = item;
1356 Py_INCREF(val);
1357 }
Tim Petersc3074532001-05-03 07:00:32 +00001358
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001359 /* maximum value and item are unset; set them */
1360 if (maxval == NULL) {
1361 maxitem = item;
1362 maxval = val;
1363 }
1364 /* maximum value and item are set; update them as necessary */
1365 else {
1366 int cmp = PyObject_RichCompareBool(val, maxval, op);
1367 if (cmp < 0)
1368 goto Fail_it_item_and_val;
1369 else if (cmp > 0) {
1370 Py_DECREF(maxval);
1371 Py_DECREF(maxitem);
1372 maxval = val;
1373 maxitem = item;
1374 }
1375 else {
1376 Py_DECREF(item);
1377 Py_DECREF(val);
1378 }
1379 }
1380 }
1381 if (PyErr_Occurred())
1382 goto Fail_it;
1383 if (maxval == NULL) {
1384 PyErr_Format(PyExc_ValueError,
1385 "%s() arg is an empty sequence", name);
1386 assert(maxitem == NULL);
1387 }
1388 else
1389 Py_DECREF(maxval);
1390 Py_DECREF(it);
1391 Py_XDECREF(keyfunc);
1392 return maxitem;
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001393
1394Fail_it_item_and_val:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001395 Py_DECREF(val);
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001396Fail_it_item:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001397 Py_DECREF(item);
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001398Fail_it:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001399 Py_XDECREF(maxval);
1400 Py_XDECREF(maxitem);
1401 Py_DECREF(it);
1402 Py_XDECREF(keyfunc);
1403 return NULL;
Guido van Rossum3f5da241990-12-20 15:06:42 +00001404}
1405
Guido van Rossum79f25d91997-04-29 20:08:16 +00001406static PyObject *
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001407builtin_min(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001408{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001409 return min_max(args, kwds, Py_LT);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001410}
1411
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001412PyDoc_STRVAR(min_doc,
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001413"min(iterable[, key=func]) -> value\n\
1414min(a, b, c, ...[, key=func]) -> value\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001415\n\
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001416With a single iterable argument, return its smallest item.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001417With two or more arguments, return the smallest argument.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001418
1419
Guido van Rossum79f25d91997-04-29 20:08:16 +00001420static PyObject *
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001421builtin_max(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001422{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001423 return min_max(args, kwds, Py_GT);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001424}
1425
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001426PyDoc_STRVAR(max_doc,
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001427"max(iterable[, key=func]) -> value\n\
1428max(a, b, c, ...[, key=func]) -> value\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001429\n\
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001430With a single iterable argument, return its largest item.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001431With two or more arguments, return the largest argument.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001432
1433
Guido van Rossum79f25d91997-04-29 20:08:16 +00001434static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001435builtin_oct(PyObject *self, PyObject *v)
Guido van Rossum006bcd41991-10-24 14:54:44 +00001436{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001437 return PyNumber_ToBase(v, 8);
Guido van Rossum006bcd41991-10-24 14:54:44 +00001438}
1439
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001440PyDoc_STRVAR(oct_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001441"oct(number) -> string\n\
1442\n\
Alexander Belopolsky12338ab2011-04-07 00:15:33 -04001443Return the octal representation of an integer.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001444
1445
Guido van Rossum79f25d91997-04-29 20:08:16 +00001446static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001447builtin_ord(PyObject *self, PyObject* obj)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001448{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001449 long ord;
1450 Py_ssize_t size;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001451
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001452 if (PyBytes_Check(obj)) {
1453 size = PyBytes_GET_SIZE(obj);
1454 if (size == 1) {
1455 ord = (long)((unsigned char)*PyBytes_AS_STRING(obj));
1456 return PyLong_FromLong(ord);
1457 }
1458 }
1459 else if (PyUnicode_Check(obj)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001460 if (PyUnicode_READY(obj) == -1)
1461 return NULL;
1462 size = PyUnicode_GET_LENGTH(obj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001463 if (size == 1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001464 ord = (long)PyUnicode_READ_CHAR(obj, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001465 return PyLong_FromLong(ord);
1466 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001467 }
1468 else if (PyByteArray_Check(obj)) {
1469 /* XXX Hopefully this is temporary */
1470 size = PyByteArray_GET_SIZE(obj);
1471 if (size == 1) {
1472 ord = (long)((unsigned char)*PyByteArray_AS_STRING(obj));
1473 return PyLong_FromLong(ord);
1474 }
1475 }
1476 else {
1477 PyErr_Format(PyExc_TypeError,
1478 "ord() expected string of length 1, but " \
1479 "%.200s found", obj->ob_type->tp_name);
1480 return NULL;
1481 }
Guido van Rossum09095f32000-03-10 23:00:52 +00001482
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001483 PyErr_Format(PyExc_TypeError,
1484 "ord() expected a character, "
1485 "but string of length %zd found",
1486 size);
1487 return NULL;
Guido van Rossum3f5da241990-12-20 15:06:42 +00001488}
1489
Guido van Rossum307fa8c2007-07-16 20:46:27 +00001490PyDoc_VAR(ord_doc) = PyDoc_STR(
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001491"ord(c) -> integer\n\
1492\n\
Guido van Rossum8ac004e2007-07-15 13:00:05 +00001493Return the integer ordinal of a one-character string."
Antoine Pitrouedc60182012-06-23 14:19:58 +02001494);
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001495
1496
Guido van Rossum79f25d91997-04-29 20:08:16 +00001497static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001498builtin_pow(PyObject *self, PyObject *args)
Guido van Rossum6a00cd81995-01-07 12:39:01 +00001499{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001500 PyObject *v, *w, *z = Py_None;
Guido van Rossum6a00cd81995-01-07 12:39:01 +00001501
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001502 if (!PyArg_UnpackTuple(args, "pow", 2, 3, &v, &w, &z))
1503 return NULL;
1504 return PyNumber_Power(v, w, z);
Guido van Rossumd4905451991-05-05 20:00:36 +00001505}
1506
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001507PyDoc_STRVAR(pow_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001508"pow(x, y[, z]) -> number\n\
1509\n\
1510With two arguments, equivalent to x**y. With three arguments,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001511equivalent to (x**y) % z, but may be more efficient (e.g. for longs).");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001512
1513
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001514
Guido van Rossum34343512006-11-30 22:13:52 +00001515static PyObject *
1516builtin_print(PyObject *self, PyObject *args, PyObject *kwds)
1517{
Georg Brandlbc3b6822012-01-13 19:41:25 +01001518 static char *kwlist[] = {"sep", "end", "file", "flush", 0};
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001519 static PyObject *dummy_args;
Georg Brandlbc3b6822012-01-13 19:41:25 +01001520 PyObject *sep = NULL, *end = NULL, *file = NULL, *flush = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001521 int i, err;
Guido van Rossum34343512006-11-30 22:13:52 +00001522
Benjamin Peterson00102562012-01-11 21:00:16 -05001523 if (dummy_args == NULL && !(dummy_args = PyTuple_New(0)))
Georg Brandlbc3b6822012-01-13 19:41:25 +01001524 return NULL;
1525 if (!PyArg_ParseTupleAndKeywords(dummy_args, kwds, "|OOOO:print",
1526 kwlist, &sep, &end, &file, &flush))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001527 return NULL;
1528 if (file == NULL || file == Py_None) {
1529 file = PySys_GetObject("stdout");
1530 /* sys.stdout may be None when FILE* stdout isn't connected */
1531 if (file == Py_None)
1532 Py_RETURN_NONE;
1533 }
Guido van Rossum34343512006-11-30 22:13:52 +00001534
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001535 if (sep == Py_None) {
1536 sep = NULL;
1537 }
1538 else if (sep && !PyUnicode_Check(sep)) {
1539 PyErr_Format(PyExc_TypeError,
1540 "sep must be None or a string, not %.200s",
1541 sep->ob_type->tp_name);
1542 return NULL;
1543 }
1544 if (end == Py_None) {
1545 end = NULL;
1546 }
1547 else if (end && !PyUnicode_Check(end)) {
1548 PyErr_Format(PyExc_TypeError,
1549 "end must be None or a string, not %.200s",
1550 end->ob_type->tp_name);
1551 return NULL;
1552 }
Guido van Rossum34343512006-11-30 22:13:52 +00001553
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001554 for (i = 0; i < PyTuple_Size(args); i++) {
1555 if (i > 0) {
1556 if (sep == NULL)
1557 err = PyFile_WriteString(" ", file);
1558 else
1559 err = PyFile_WriteObject(sep, file,
1560 Py_PRINT_RAW);
1561 if (err)
1562 return NULL;
1563 }
1564 err = PyFile_WriteObject(PyTuple_GetItem(args, i), file,
1565 Py_PRINT_RAW);
1566 if (err)
1567 return NULL;
1568 }
Guido van Rossum34343512006-11-30 22:13:52 +00001569
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001570 if (end == NULL)
1571 err = PyFile_WriteString("\n", file);
1572 else
1573 err = PyFile_WriteObject(end, file, Py_PRINT_RAW);
1574 if (err)
1575 return NULL;
Guido van Rossum34343512006-11-30 22:13:52 +00001576
Georg Brandlbc3b6822012-01-13 19:41:25 +01001577 if (flush != NULL) {
1578 PyObject *tmp;
1579 int do_flush = PyObject_IsTrue(flush);
1580 if (do_flush == -1)
1581 return NULL;
1582 else if (do_flush) {
1583 tmp = PyObject_CallMethod(file, "flush", "");
1584 if (tmp == NULL)
1585 return NULL;
1586 else
1587 Py_DECREF(tmp);
1588 }
1589 }
1590
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001591 Py_RETURN_NONE;
Guido van Rossum34343512006-11-30 22:13:52 +00001592}
1593
1594PyDoc_STRVAR(print_doc,
Senthil Kumarane9175bd2012-08-10 13:53:45 -07001595"print(value, ..., sep=' ', end='\\n', file=sys.stdout, flush=False)\n\
Guido van Rossum34343512006-11-30 22:13:52 +00001596\n\
1597Prints the values to a stream, or to sys.stdout by default.\n\
1598Optional keyword arguments:\n\
Senthil Kumarane9175bd2012-08-10 13:53:45 -07001599file: a file-like object (stream); defaults to the current sys.stdout.\n\
1600sep: string inserted between values, default a space.\n\
1601end: string appended after the last value, default a newline.\n\
1602flush: whether to forcibly flush the stream.");
Guido van Rossum34343512006-11-30 22:13:52 +00001603
1604
Guido van Rossuma88a0332007-02-26 16:59:55 +00001605static PyObject *
1606builtin_input(PyObject *self, PyObject *args)
1607{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001608 PyObject *promptarg = NULL;
1609 PyObject *fin = PySys_GetObject("stdin");
1610 PyObject *fout = PySys_GetObject("stdout");
1611 PyObject *ferr = PySys_GetObject("stderr");
1612 PyObject *tmp;
1613 long fd;
1614 int tty;
Guido van Rossuma88a0332007-02-26 16:59:55 +00001615
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001616 /* Parse arguments */
1617 if (!PyArg_UnpackTuple(args, "input", 0, 1, &promptarg))
1618 return NULL;
Guido van Rossuma88a0332007-02-26 16:59:55 +00001619
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001620 /* Check that stdin/out/err are intact */
1621 if (fin == NULL || fin == Py_None) {
1622 PyErr_SetString(PyExc_RuntimeError,
1623 "input(): lost sys.stdin");
1624 return NULL;
1625 }
1626 if (fout == NULL || fout == Py_None) {
1627 PyErr_SetString(PyExc_RuntimeError,
1628 "input(): lost sys.stdout");
1629 return NULL;
1630 }
1631 if (ferr == NULL || ferr == Py_None) {
1632 PyErr_SetString(PyExc_RuntimeError,
1633 "input(): lost sys.stderr");
1634 return NULL;
1635 }
Guido van Rossumeba76962007-05-27 09:13:28 +00001636
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001637 /* First of all, flush stderr */
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001638 tmp = _PyObject_CallMethodId(ferr, &PyId_flush, "");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001639 if (tmp == NULL)
1640 PyErr_Clear();
1641 else
1642 Py_DECREF(tmp);
Guido van Rossumeba76962007-05-27 09:13:28 +00001643
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001644 /* We should only use (GNU) readline if Python's sys.stdin and
1645 sys.stdout are the same as C's stdin and stdout, because we
1646 need to pass it those. */
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001647 tmp = _PyObject_CallMethodId(fin, &PyId_fileno, "");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001648 if (tmp == NULL) {
1649 PyErr_Clear();
1650 tty = 0;
1651 }
1652 else {
1653 fd = PyLong_AsLong(tmp);
1654 Py_DECREF(tmp);
1655 if (fd < 0 && PyErr_Occurred())
1656 return NULL;
1657 tty = fd == fileno(stdin) && isatty(fd);
1658 }
1659 if (tty) {
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001660 tmp = _PyObject_CallMethodId(fout, &PyId_fileno, "");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001661 if (tmp == NULL)
1662 PyErr_Clear();
1663 else {
1664 fd = PyLong_AsLong(tmp);
1665 Py_DECREF(tmp);
1666 if (fd < 0 && PyErr_Occurred())
1667 return NULL;
1668 tty = fd == fileno(stdout) && isatty(fd);
1669 }
1670 }
Guido van Rossumeba76962007-05-27 09:13:28 +00001671
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001672 /* If we're interactive, use (GNU) readline */
1673 if (tty) {
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001674 PyObject *po = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001675 char *prompt;
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001676 char *s = NULL;
1677 PyObject *stdin_encoding = NULL, *stdin_errors = NULL;
1678 PyObject *stdout_encoding = NULL, *stdout_errors = NULL;
1679 char *stdin_encoding_str, *stdin_errors_str;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001680 PyObject *result;
Victor Stinnerc0f1a1a2011-02-23 12:07:37 +00001681 size_t len;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02001682 _Py_IDENTIFIER(encoding);
Antoine Pitrou5ee9d8a2011-11-06 00:38:45 +01001683 _Py_IDENTIFIER(errors);
Martin v. Löwis4a7b5d52007-09-04 05:24:49 +00001684
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02001685 stdin_encoding = _PyObject_GetAttrId(fin, &PyId_encoding);
Antoine Pitrou5ee9d8a2011-11-06 00:38:45 +01001686 stdin_errors = _PyObject_GetAttrId(fin, &PyId_errors);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001687 if (!stdin_encoding || !stdin_errors)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001688 /* stdin is a text stream, so it must have an
1689 encoding. */
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001690 goto _readline_errors;
Victor Stinner306f0102010-05-19 01:06:22 +00001691 stdin_encoding_str = _PyUnicode_AsString(stdin_encoding);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001692 stdin_errors_str = _PyUnicode_AsString(stdin_errors);
1693 if (!stdin_encoding_str || !stdin_errors_str)
1694 goto _readline_errors;
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001695 tmp = _PyObject_CallMethodId(fout, &PyId_flush, "");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001696 if (tmp == NULL)
1697 PyErr_Clear();
1698 else
1699 Py_DECREF(tmp);
1700 if (promptarg != NULL) {
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001701 /* We have a prompt, encode it as stdout would */
1702 char *stdout_encoding_str, *stdout_errors_str;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001703 PyObject *stringpo;
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02001704 stdout_encoding = _PyObject_GetAttrId(fout, &PyId_encoding);
Antoine Pitrou5ee9d8a2011-11-06 00:38:45 +01001705 stdout_errors = _PyObject_GetAttrId(fout, &PyId_errors);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001706 if (!stdout_encoding || !stdout_errors)
1707 goto _readline_errors;
Victor Stinner306f0102010-05-19 01:06:22 +00001708 stdout_encoding_str = _PyUnicode_AsString(stdout_encoding);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001709 stdout_errors_str = _PyUnicode_AsString(stdout_errors);
1710 if (!stdout_encoding_str || !stdout_errors_str)
1711 goto _readline_errors;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001712 stringpo = PyObject_Str(promptarg);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001713 if (stringpo == NULL)
1714 goto _readline_errors;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001715 po = PyUnicode_AsEncodedString(stringpo,
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001716 stdout_encoding_str, stdout_errors_str);
1717 Py_CLEAR(stdout_encoding);
1718 Py_CLEAR(stdout_errors);
1719 Py_CLEAR(stringpo);
1720 if (po == NULL)
1721 goto _readline_errors;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001722 prompt = PyBytes_AsString(po);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001723 if (prompt == NULL)
1724 goto _readline_errors;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001725 }
1726 else {
1727 po = NULL;
1728 prompt = "";
1729 }
1730 s = PyOS_Readline(stdin, stdout, prompt);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001731 if (s == NULL) {
1732 if (!PyErr_Occurred())
1733 PyErr_SetNone(PyExc_KeyboardInterrupt);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001734 goto _readline_errors;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001735 }
Victor Stinnerc0f1a1a2011-02-23 12:07:37 +00001736
1737 len = strlen(s);
1738 if (len == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001739 PyErr_SetNone(PyExc_EOFError);
1740 result = NULL;
1741 }
Victor Stinnerc0f1a1a2011-02-23 12:07:37 +00001742 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001743 if (len > PY_SSIZE_T_MAX) {
1744 PyErr_SetString(PyExc_OverflowError,
1745 "input: input too long");
1746 result = NULL;
1747 }
1748 else {
Victor Stinnerc0f1a1a2011-02-23 12:07:37 +00001749 len--; /* strip trailing '\n' */
1750 if (len != 0 && s[len-1] == '\r')
1751 len--; /* strip trailing '\r' */
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001752 result = PyUnicode_Decode(s, len, stdin_encoding_str,
1753 stdin_errors_str);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001754 }
1755 }
1756 Py_DECREF(stdin_encoding);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001757 Py_DECREF(stdin_errors);
1758 Py_XDECREF(po);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001759 PyMem_FREE(s);
1760 return result;
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001761 _readline_errors:
1762 Py_XDECREF(stdin_encoding);
1763 Py_XDECREF(stdout_encoding);
1764 Py_XDECREF(stdin_errors);
1765 Py_XDECREF(stdout_errors);
1766 Py_XDECREF(po);
1767 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001768 }
Guido van Rossumeba76962007-05-27 09:13:28 +00001769
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001770 /* Fallback if we're not interactive */
1771 if (promptarg != NULL) {
1772 if (PyFile_WriteObject(promptarg, fout, Py_PRINT_RAW) != 0)
1773 return NULL;
1774 }
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001775 tmp = _PyObject_CallMethodId(fout, &PyId_flush, "");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001776 if (tmp == NULL)
1777 PyErr_Clear();
1778 else
1779 Py_DECREF(tmp);
1780 return PyFile_GetLine(fin, -1);
Guido van Rossuma88a0332007-02-26 16:59:55 +00001781}
1782
1783PyDoc_STRVAR(input_doc,
1784"input([prompt]) -> string\n\
1785\n\
1786Read a string from standard input. The trailing newline is stripped.\n\
1787If the user hits EOF (Unix: Ctl-D, Windows: Ctl-Z+Return), raise EOFError.\n\
1788On Unix, GNU readline is used if enabled. The prompt string, if given,\n\
1789is printed without a trailing newline before reading.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001790
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001791
Guido van Rossum79f25d91997-04-29 20:08:16 +00001792static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001793builtin_repr(PyObject *self, PyObject *v)
Guido van Rossumc89705d1992-11-26 08:54:07 +00001794{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001795 return PyObject_Repr(v);
Guido van Rossumc89705d1992-11-26 08:54:07 +00001796}
1797
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001798PyDoc_STRVAR(repr_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001799"repr(object) -> string\n\
1800\n\
1801Return the canonical string representation of the object.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001802For most object types, eval(repr(object)) == object.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001803
1804
Guido van Rossum79f25d91997-04-29 20:08:16 +00001805static PyObject *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001806builtin_round(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum9e51f9b1993-02-12 16:29:05 +00001807{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001808 static PyObject *round_str = NULL;
1809 PyObject *ndigits = NULL;
1810 static char *kwlist[] = {"number", "ndigits", 0};
1811 PyObject *number, *round;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001812
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001813 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|O:round",
1814 kwlist, &number, &ndigits))
1815 return NULL;
Alex Martelliae211f92007-08-22 23:21:33 +00001816
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001817 if (Py_TYPE(number)->tp_dict == NULL) {
1818 if (PyType_Ready(Py_TYPE(number)) < 0)
1819 return NULL;
1820 }
Guido van Rossum15d3d042007-08-24 02:02:45 +00001821
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001822 if (round_str == NULL) {
1823 round_str = PyUnicode_InternFromString("__round__");
1824 if (round_str == NULL)
1825 return NULL;
1826 }
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001827
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001828 round = _PyType_Lookup(Py_TYPE(number), round_str);
1829 if (round == NULL) {
1830 PyErr_Format(PyExc_TypeError,
1831 "type %.100s doesn't define __round__ method",
1832 Py_TYPE(number)->tp_name);
1833 return NULL;
1834 }
Alex Martelliae211f92007-08-22 23:21:33 +00001835
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001836 if (ndigits == NULL)
1837 return PyObject_CallFunction(round, "O", number);
1838 else
1839 return PyObject_CallFunction(round, "OO", number, ndigits);
Guido van Rossum9e51f9b1993-02-12 16:29:05 +00001840}
1841
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001842PyDoc_STRVAR(round_doc,
Mark Dickinson1124e712009-01-28 21:25:58 +00001843"round(number[, ndigits]) -> number\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001844\n\
1845Round a number to a given precision in decimal digits (default 0 digits).\n\
Mark Dickinson0d748c22008-07-05 11:29:03 +00001846This returns an int when called with one argument, otherwise the\n\
Georg Brandl809ddaa2008-07-01 20:39:59 +00001847same type as the number. ndigits may be negative.");
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001848
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001849
Raymond Hettinger64958a12003-12-17 20:43:33 +00001850static PyObject *
1851builtin_sorted(PyObject *self, PyObject *args, PyObject *kwds)
1852{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001853 PyObject *newlist, *v, *seq, *keyfunc=NULL, *newargs;
1854 PyObject *callable;
1855 static char *kwlist[] = {"iterable", "key", "reverse", 0};
1856 int reverse;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02001857 _Py_IDENTIFIER(sort);
Raymond Hettinger64958a12003-12-17 20:43:33 +00001858
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001859 /* args 1-3 should match listsort in Objects/listobject.c */
1860 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|Oi:sorted",
1861 kwlist, &seq, &keyfunc, &reverse))
1862 return NULL;
Raymond Hettinger64958a12003-12-17 20:43:33 +00001863
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001864 newlist = PySequence_List(seq);
1865 if (newlist == NULL)
1866 return NULL;
Raymond Hettinger64958a12003-12-17 20:43:33 +00001867
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02001868 callable = _PyObject_GetAttrId(newlist, &PyId_sort);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001869 if (callable == NULL) {
1870 Py_DECREF(newlist);
1871 return NULL;
1872 }
Georg Brandl99d7e4e2005-08-31 22:21:15 +00001873
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001874 newargs = PyTuple_GetSlice(args, 1, 4);
1875 if (newargs == NULL) {
1876 Py_DECREF(newlist);
1877 Py_DECREF(callable);
1878 return NULL;
1879 }
Raymond Hettinger64958a12003-12-17 20:43:33 +00001880
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001881 v = PyObject_Call(callable, newargs, kwds);
1882 Py_DECREF(newargs);
1883 Py_DECREF(callable);
1884 if (v == NULL) {
1885 Py_DECREF(newlist);
1886 return NULL;
1887 }
1888 Py_DECREF(v);
1889 return newlist;
Raymond Hettinger64958a12003-12-17 20:43:33 +00001890}
1891
1892PyDoc_STRVAR(sorted_doc,
Raymond Hettinger70b64fc2008-01-30 20:15:17 +00001893"sorted(iterable, key=None, reverse=False) --> new sorted list");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001894
Guido van Rossum79f25d91997-04-29 20:08:16 +00001895static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001896builtin_vars(PyObject *self, PyObject *args)
Guido van Rossum2d951851994-08-29 12:52:16 +00001897{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001898 PyObject *v = NULL;
1899 PyObject *d;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001900
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001901 if (!PyArg_UnpackTuple(args, "vars", 0, 1, &v))
1902 return NULL;
1903 if (v == NULL) {
1904 d = PyEval_GetLocals();
1905 if (d == NULL) {
1906 if (!PyErr_Occurred())
1907 PyErr_SetString(PyExc_SystemError,
1908 "vars(): no locals!?");
1909 }
1910 else
1911 Py_INCREF(d);
1912 }
1913 else {
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02001914 _Py_IDENTIFIER(__dict__);
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02001915 d = _PyObject_GetAttrId(v, &PyId___dict__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001916 if (d == NULL) {
1917 PyErr_SetString(PyExc_TypeError,
1918 "vars() argument must have __dict__ attribute");
1919 return NULL;
1920 }
1921 }
1922 return d;
Guido van Rossum2d951851994-08-29 12:52:16 +00001923}
1924
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001925PyDoc_STRVAR(vars_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001926"vars([object]) -> dictionary\n\
1927\n\
1928Without arguments, equivalent to locals().\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001929With an argument, equivalent to object.__dict__.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001930
Alex Martellia70b1912003-04-22 08:12:33 +00001931static PyObject*
1932builtin_sum(PyObject *self, PyObject *args)
1933{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001934 PyObject *seq;
1935 PyObject *result = NULL;
1936 PyObject *temp, *item, *iter;
Alex Martellia70b1912003-04-22 08:12:33 +00001937
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001938 if (!PyArg_UnpackTuple(args, "sum", 1, 2, &seq, &result))
1939 return NULL;
Alex Martellia70b1912003-04-22 08:12:33 +00001940
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001941 iter = PyObject_GetIter(seq);
1942 if (iter == NULL)
1943 return NULL;
Alex Martellia70b1912003-04-22 08:12:33 +00001944
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001945 if (result == NULL) {
1946 result = PyLong_FromLong(0);
1947 if (result == NULL) {
1948 Py_DECREF(iter);
1949 return NULL;
1950 }
1951 } else {
1952 /* reject string values for 'start' parameter */
1953 if (PyUnicode_Check(result)) {
1954 PyErr_SetString(PyExc_TypeError,
1955 "sum() can't sum strings [use ''.join(seq) instead]");
1956 Py_DECREF(iter);
1957 return NULL;
1958 }
Benjamin Petersonce071ca2011-07-29 14:23:47 -05001959 if (PyBytes_Check(result)) {
1960 PyErr_SetString(PyExc_TypeError,
1961 "sum() can't sum bytes [use b''.join(seq) instead]");
Benjamin Peterson405f32c2011-07-29 22:43:45 -05001962 Py_DECREF(iter);
Benjamin Petersonce071ca2011-07-29 14:23:47 -05001963 return NULL;
1964 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001965 if (PyByteArray_Check(result)) {
1966 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson4f921c22011-07-29 14:24:29 -05001967 "sum() can't sum bytearray [use b''.join(seq) instead]");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001968 Py_DECREF(iter);
1969 return NULL;
1970 }
Guido van Rossum3172c5d2007-10-16 18:12:55 +00001971
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001972 Py_INCREF(result);
1973 }
Alex Martellia70b1912003-04-22 08:12:33 +00001974
Guido van Rossum8ce8a782007-11-01 19:42:39 +00001975#ifndef SLOW_SUM
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001976 /* Fast addition by keeping temporary sums in C instead of new Python objects.
1977 Assumes all inputs are the same type. If the assumption fails, default
1978 to the more general routine.
1979 */
1980 if (PyLong_CheckExact(result)) {
1981 int overflow;
1982 long i_result = PyLong_AsLongAndOverflow(result, &overflow);
1983 /* If this already overflowed, don't even enter the loop. */
1984 if (overflow == 0) {
1985 Py_DECREF(result);
1986 result = NULL;
1987 }
1988 while(result == NULL) {
1989 item = PyIter_Next(iter);
1990 if (item == NULL) {
1991 Py_DECREF(iter);
1992 if (PyErr_Occurred())
1993 return NULL;
1994 return PyLong_FromLong(i_result);
1995 }
1996 if (PyLong_CheckExact(item)) {
1997 long b = PyLong_AsLongAndOverflow(item, &overflow);
1998 long x = i_result + b;
1999 if (overflow == 0 && ((x^i_result) >= 0 || (x^b) >= 0)) {
2000 i_result = x;
2001 Py_DECREF(item);
2002 continue;
2003 }
2004 }
2005 /* Either overflowed or is not an int. Restore real objects and process normally */
2006 result = PyLong_FromLong(i_result);
2007 temp = PyNumber_Add(result, item);
2008 Py_DECREF(result);
2009 Py_DECREF(item);
2010 result = temp;
2011 if (result == NULL) {
2012 Py_DECREF(iter);
2013 return NULL;
2014 }
2015 }
2016 }
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002017
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002018 if (PyFloat_CheckExact(result)) {
2019 double f_result = PyFloat_AS_DOUBLE(result);
2020 Py_DECREF(result);
2021 result = NULL;
2022 while(result == NULL) {
2023 item = PyIter_Next(iter);
2024 if (item == NULL) {
2025 Py_DECREF(iter);
2026 if (PyErr_Occurred())
2027 return NULL;
2028 return PyFloat_FromDouble(f_result);
2029 }
2030 if (PyFloat_CheckExact(item)) {
2031 PyFPE_START_PROTECT("add", Py_DECREF(item); Py_DECREF(iter); return 0)
2032 f_result += PyFloat_AS_DOUBLE(item);
2033 PyFPE_END_PROTECT(f_result)
2034 Py_DECREF(item);
2035 continue;
2036 }
2037 if (PyLong_CheckExact(item)) {
2038 long value;
2039 int overflow;
2040 value = PyLong_AsLongAndOverflow(item, &overflow);
2041 if (!overflow) {
2042 PyFPE_START_PROTECT("add", Py_DECREF(item); Py_DECREF(iter); return 0)
2043 f_result += (double)value;
2044 PyFPE_END_PROTECT(f_result)
2045 Py_DECREF(item);
2046 continue;
2047 }
2048 }
2049 result = PyFloat_FromDouble(f_result);
2050 temp = PyNumber_Add(result, item);
2051 Py_DECREF(result);
2052 Py_DECREF(item);
2053 result = temp;
2054 if (result == NULL) {
2055 Py_DECREF(iter);
2056 return NULL;
2057 }
2058 }
2059 }
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002060#endif
2061
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002062 for(;;) {
2063 item = PyIter_Next(iter);
2064 if (item == NULL) {
2065 /* error, or end-of-sequence */
2066 if (PyErr_Occurred()) {
2067 Py_DECREF(result);
2068 result = NULL;
2069 }
2070 break;
2071 }
2072 /* It's tempting to use PyNumber_InPlaceAdd instead of
2073 PyNumber_Add here, to avoid quadratic running time
2074 when doing 'sum(list_of_lists, [])'. However, this
2075 would produce a change in behaviour: a snippet like
Mark Dickinson9acadc52009-10-26 14:19:42 +00002076
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002077 empty = []
2078 sum([[x] for x in range(10)], empty)
Mark Dickinson9acadc52009-10-26 14:19:42 +00002079
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002080 would change the value of empty. */
2081 temp = PyNumber_Add(result, item);
2082 Py_DECREF(result);
2083 Py_DECREF(item);
2084 result = temp;
2085 if (result == NULL)
2086 break;
2087 }
2088 Py_DECREF(iter);
2089 return result;
Alex Martellia70b1912003-04-22 08:12:33 +00002090}
2091
2092PyDoc_STRVAR(sum_doc,
Georg Brandld11ae5d2008-05-16 13:27:32 +00002093"sum(iterable[, start]) -> value\n\
Alex Martellia70b1912003-04-22 08:12:33 +00002094\n\
Georg Brandld11ae5d2008-05-16 13:27:32 +00002095Returns the sum of an iterable of numbers (NOT strings) plus the value\n\
2096of parameter 'start' (which defaults to 0). When the iterable is\n\
Thomas Wouters89f507f2006-12-13 04:49:30 +00002097empty, returns start.");
Alex Martellia70b1912003-04-22 08:12:33 +00002098
2099
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002100static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002101builtin_isinstance(PyObject *self, PyObject *args)
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002102{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002103 PyObject *inst;
2104 PyObject *cls;
2105 int retval;
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002106
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002107 if (!PyArg_UnpackTuple(args, "isinstance", 2, 2, &inst, &cls))
2108 return NULL;
Guido van Rossumf5dd9141997-12-02 19:11:45 +00002109
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002110 retval = PyObject_IsInstance(inst, cls);
2111 if (retval < 0)
2112 return NULL;
2113 return PyBool_FromLong(retval);
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002114}
2115
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002116PyDoc_STRVAR(isinstance_doc,
Guido van Rossum77f6a652002-04-03 22:41:51 +00002117"isinstance(object, class-or-type-or-tuple) -> bool\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002118\n\
2119Return whether an object is an instance of a class or of a subclass thereof.\n\
Guido van Rossum03290ec2001-10-07 20:54:12 +00002120With a type as second argument, return whether that is the object's type.\n\
2121The form using a tuple, isinstance(x, (A, B, ...)), is a shortcut for\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002122isinstance(x, A) or isinstance(x, B) or ... (etc.).");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002123
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002124
2125static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002126builtin_issubclass(PyObject *self, PyObject *args)
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002127{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002128 PyObject *derived;
2129 PyObject *cls;
2130 int retval;
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002131
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002132 if (!PyArg_UnpackTuple(args, "issubclass", 2, 2, &derived, &cls))
2133 return NULL;
Guido van Rossum668213d1999-06-16 17:28:37 +00002134
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002135 retval = PyObject_IsSubclass(derived, cls);
2136 if (retval < 0)
2137 return NULL;
2138 return PyBool_FromLong(retval);
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002139}
2140
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002141PyDoc_STRVAR(issubclass_doc,
Guido van Rossum77f6a652002-04-03 22:41:51 +00002142"issubclass(C, B) -> bool\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002143\n\
Walter Dörwaldd9a6ad32002-12-12 16:41:44 +00002144Return whether class C is a subclass (i.e., a derived class) of class B.\n\
2145When using a tuple as the second argument issubclass(X, (A, B, ...)),\n\
2146is a shortcut for issubclass(X, A) or issubclass(X, B) or ... (etc.).");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002147
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002148
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002149typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002150 PyObject_HEAD
2151 Py_ssize_t tuplesize;
2152 PyObject *ittuple; /* tuple of iterators */
2153 PyObject *result;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002154} zipobject;
2155
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002156static PyObject *
2157zip_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
Barry Warsawbd599b52000-08-03 15:45:29 +00002158{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002159 zipobject *lz;
2160 Py_ssize_t i;
2161 PyObject *ittuple; /* tuple of iterators */
2162 PyObject *result;
2163 Py_ssize_t tuplesize = PySequence_Length(args);
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002164
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002165 if (type == &PyZip_Type && !_PyArg_NoKeywords("zip()", kwds))
2166 return NULL;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002167
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002168 /* args must be a tuple */
2169 assert(PyTuple_Check(args));
Barry Warsawbd599b52000-08-03 15:45:29 +00002170
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002171 /* obtain iterators */
2172 ittuple = PyTuple_New(tuplesize);
2173 if (ittuple == NULL)
2174 return NULL;
2175 for (i=0; i < tuplesize; ++i) {
2176 PyObject *item = PyTuple_GET_ITEM(args, i);
2177 PyObject *it = PyObject_GetIter(item);
2178 if (it == NULL) {
2179 if (PyErr_ExceptionMatches(PyExc_TypeError))
2180 PyErr_Format(PyExc_TypeError,
2181 "zip argument #%zd must support iteration",
2182 i+1);
2183 Py_DECREF(ittuple);
2184 return NULL;
2185 }
2186 PyTuple_SET_ITEM(ittuple, i, it);
2187 }
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002188
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002189 /* create a result holder */
2190 result = PyTuple_New(tuplesize);
2191 if (result == NULL) {
2192 Py_DECREF(ittuple);
2193 return NULL;
2194 }
2195 for (i=0 ; i < tuplesize ; i++) {
2196 Py_INCREF(Py_None);
2197 PyTuple_SET_ITEM(result, i, Py_None);
2198 }
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002199
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002200 /* create zipobject structure */
2201 lz = (zipobject *)type->tp_alloc(type, 0);
2202 if (lz == NULL) {
2203 Py_DECREF(ittuple);
2204 Py_DECREF(result);
2205 return NULL;
2206 }
2207 lz->ittuple = ittuple;
2208 lz->tuplesize = tuplesize;
2209 lz->result = result;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002210
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002211 return (PyObject *)lz;
Barry Warsawbd599b52000-08-03 15:45:29 +00002212}
2213
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002214static void
2215zip_dealloc(zipobject *lz)
2216{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002217 PyObject_GC_UnTrack(lz);
2218 Py_XDECREF(lz->ittuple);
2219 Py_XDECREF(lz->result);
2220 Py_TYPE(lz)->tp_free(lz);
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002221}
2222
2223static int
2224zip_traverse(zipobject *lz, visitproc visit, void *arg)
2225{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002226 Py_VISIT(lz->ittuple);
2227 Py_VISIT(lz->result);
2228 return 0;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002229}
2230
2231static PyObject *
2232zip_next(zipobject *lz)
2233{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002234 Py_ssize_t i;
2235 Py_ssize_t tuplesize = lz->tuplesize;
2236 PyObject *result = lz->result;
2237 PyObject *it;
2238 PyObject *item;
2239 PyObject *olditem;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002240
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002241 if (tuplesize == 0)
2242 return NULL;
2243 if (Py_REFCNT(result) == 1) {
2244 Py_INCREF(result);
2245 for (i=0 ; i < tuplesize ; i++) {
2246 it = PyTuple_GET_ITEM(lz->ittuple, i);
2247 item = (*Py_TYPE(it)->tp_iternext)(it);
2248 if (item == NULL) {
2249 Py_DECREF(result);
2250 return NULL;
2251 }
2252 olditem = PyTuple_GET_ITEM(result, i);
2253 PyTuple_SET_ITEM(result, i, item);
2254 Py_DECREF(olditem);
2255 }
2256 } else {
2257 result = PyTuple_New(tuplesize);
2258 if (result == NULL)
2259 return NULL;
2260 for (i=0 ; i < tuplesize ; i++) {
2261 it = PyTuple_GET_ITEM(lz->ittuple, i);
2262 item = (*Py_TYPE(it)->tp_iternext)(it);
2263 if (item == NULL) {
2264 Py_DECREF(result);
2265 return NULL;
2266 }
2267 PyTuple_SET_ITEM(result, i, item);
2268 }
2269 }
2270 return result;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002271}
Barry Warsawbd599b52000-08-03 15:45:29 +00002272
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002273static PyObject *
2274zip_reduce(zipobject *lz)
2275{
2276 /* Just recreate the zip with the internal iterator tuple */
2277 return Py_BuildValue("OO", Py_TYPE(lz), lz->ittuple);
2278}
2279
2280static PyMethodDef zip_methods[] = {
2281 {"__reduce__", (PyCFunction)zip_reduce, METH_NOARGS, reduce_doc},
2282 {NULL, NULL} /* sentinel */
2283};
2284
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002285PyDoc_STRVAR(zip_doc,
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002286"zip(iter1 [,iter2 [...]]) --> zip object\n\
Barry Warsawbd599b52000-08-03 15:45:29 +00002287\n\
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002288Return a zip object whose .__next__() method returns a tuple where\n\
2289the i-th element comes from the i-th iterable argument. The .__next__()\n\
2290method continues until the shortest iterable in the argument sequence\n\
Georg Brandlced51db2008-12-04 18:28:38 +00002291is exhausted and then it raises StopIteration.");
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002292
2293PyTypeObject PyZip_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002294 PyVarObject_HEAD_INIT(&PyType_Type, 0)
2295 "zip", /* tp_name */
2296 sizeof(zipobject), /* tp_basicsize */
2297 0, /* tp_itemsize */
2298 /* methods */
2299 (destructor)zip_dealloc, /* tp_dealloc */
2300 0, /* tp_print */
2301 0, /* tp_getattr */
2302 0, /* tp_setattr */
2303 0, /* tp_reserved */
2304 0, /* tp_repr */
2305 0, /* tp_as_number */
2306 0, /* tp_as_sequence */
2307 0, /* tp_as_mapping */
2308 0, /* tp_hash */
2309 0, /* tp_call */
2310 0, /* tp_str */
2311 PyObject_GenericGetAttr, /* tp_getattro */
2312 0, /* tp_setattro */
2313 0, /* tp_as_buffer */
2314 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
2315 Py_TPFLAGS_BASETYPE, /* tp_flags */
2316 zip_doc, /* tp_doc */
2317 (traverseproc)zip_traverse, /* tp_traverse */
2318 0, /* tp_clear */
2319 0, /* tp_richcompare */
2320 0, /* tp_weaklistoffset */
2321 PyObject_SelfIter, /* tp_iter */
2322 (iternextfunc)zip_next, /* tp_iternext */
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002323 zip_methods, /* tp_methods */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002324 0, /* tp_members */
2325 0, /* tp_getset */
2326 0, /* tp_base */
2327 0, /* tp_dict */
2328 0, /* tp_descr_get */
2329 0, /* tp_descr_set */
2330 0, /* tp_dictoffset */
2331 0, /* tp_init */
2332 PyType_GenericAlloc, /* tp_alloc */
2333 zip_new, /* tp_new */
2334 PyObject_GC_Del, /* tp_free */
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002335};
Barry Warsawbd599b52000-08-03 15:45:29 +00002336
2337
Guido van Rossum79f25d91997-04-29 20:08:16 +00002338static PyMethodDef builtin_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002339 {"__build_class__", (PyCFunction)builtin___build_class__,
2340 METH_VARARGS | METH_KEYWORDS, build_class_doc},
2341 {"__import__", (PyCFunction)builtin___import__, METH_VARARGS | METH_KEYWORDS, import_doc},
2342 {"abs", builtin_abs, METH_O, abs_doc},
2343 {"all", builtin_all, METH_O, all_doc},
2344 {"any", builtin_any, METH_O, any_doc},
2345 {"ascii", builtin_ascii, METH_O, ascii_doc},
2346 {"bin", builtin_bin, METH_O, bin_doc},
Antoine Pitroue71362d2010-11-27 22:00:11 +00002347 {"callable", builtin_callable, METH_O, callable_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002348 {"chr", builtin_chr, METH_VARARGS, chr_doc},
2349 {"compile", (PyCFunction)builtin_compile, METH_VARARGS | METH_KEYWORDS, compile_doc},
2350 {"delattr", builtin_delattr, METH_VARARGS, delattr_doc},
2351 {"dir", builtin_dir, METH_VARARGS, dir_doc},
2352 {"divmod", builtin_divmod, METH_VARARGS, divmod_doc},
2353 {"eval", builtin_eval, METH_VARARGS, eval_doc},
2354 {"exec", builtin_exec, METH_VARARGS, exec_doc},
2355 {"format", builtin_format, METH_VARARGS, format_doc},
2356 {"getattr", builtin_getattr, METH_VARARGS, getattr_doc},
2357 {"globals", (PyCFunction)builtin_globals, METH_NOARGS, globals_doc},
2358 {"hasattr", builtin_hasattr, METH_VARARGS, hasattr_doc},
2359 {"hash", builtin_hash, METH_O, hash_doc},
2360 {"hex", builtin_hex, METH_O, hex_doc},
2361 {"id", builtin_id, METH_O, id_doc},
2362 {"input", builtin_input, METH_VARARGS, input_doc},
2363 {"isinstance", builtin_isinstance, METH_VARARGS, isinstance_doc},
2364 {"issubclass", builtin_issubclass, METH_VARARGS, issubclass_doc},
2365 {"iter", builtin_iter, METH_VARARGS, iter_doc},
2366 {"len", builtin_len, METH_O, len_doc},
2367 {"locals", (PyCFunction)builtin_locals, METH_NOARGS, locals_doc},
2368 {"max", (PyCFunction)builtin_max, METH_VARARGS | METH_KEYWORDS, max_doc},
2369 {"min", (PyCFunction)builtin_min, METH_VARARGS | METH_KEYWORDS, min_doc},
2370 {"next", (PyCFunction)builtin_next, METH_VARARGS, next_doc},
2371 {"oct", builtin_oct, METH_O, oct_doc},
2372 {"ord", builtin_ord, METH_O, ord_doc},
2373 {"pow", builtin_pow, METH_VARARGS, pow_doc},
2374 {"print", (PyCFunction)builtin_print, METH_VARARGS | METH_KEYWORDS, print_doc},
2375 {"repr", builtin_repr, METH_O, repr_doc},
2376 {"round", (PyCFunction)builtin_round, METH_VARARGS | METH_KEYWORDS, round_doc},
2377 {"setattr", builtin_setattr, METH_VARARGS, setattr_doc},
2378 {"sorted", (PyCFunction)builtin_sorted, METH_VARARGS | METH_KEYWORDS, sorted_doc},
2379 {"sum", builtin_sum, METH_VARARGS, sum_doc},
2380 {"vars", builtin_vars, METH_VARARGS, vars_doc},
2381 {NULL, NULL},
Guido van Rossum3f5da241990-12-20 15:06:42 +00002382};
2383
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002384PyDoc_STRVAR(builtin_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002385"Built-in functions, exceptions, and other objects.\n\
2386\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002387Noteworthy: None is the `nil' object; Ellipsis represents `...' in slices.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002388
Martin v. Löwis1a214512008-06-11 05:26:20 +00002389static struct PyModuleDef builtinsmodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002390 PyModuleDef_HEAD_INIT,
2391 "builtins",
2392 builtin_doc,
2393 -1, /* multiple "initialization" just copies the module dict. */
2394 builtin_methods,
2395 NULL,
2396 NULL,
2397 NULL,
2398 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00002399};
2400
2401
Guido van Rossum25ce5661997-08-02 03:10:38 +00002402PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002403_PyBuiltin_Init(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +00002404{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002405 PyObject *mod, *dict, *debug;
2406 mod = PyModule_Create(&builtinsmodule);
2407 if (mod == NULL)
2408 return NULL;
2409 dict = PyModule_GetDict(mod);
Tim Peters4b7625e2001-09-13 21:37:17 +00002410
Tim Peters7571a0f2003-03-23 17:52:28 +00002411#ifdef Py_TRACE_REFS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002412 /* "builtins" exposes a number of statically allocated objects
2413 * that, before this code was added in 2.3, never showed up in
2414 * the list of "all objects" maintained by Py_TRACE_REFS. As a
2415 * result, programs leaking references to None and False (etc)
2416 * couldn't be diagnosed by examining sys.getobjects(0).
2417 */
Tim Peters7571a0f2003-03-23 17:52:28 +00002418#define ADD_TO_ALL(OBJECT) _Py_AddToAllObjects((PyObject *)(OBJECT), 0)
2419#else
2420#define ADD_TO_ALL(OBJECT) (void)0
2421#endif
2422
Tim Peters4b7625e2001-09-13 21:37:17 +00002423#define SETBUILTIN(NAME, OBJECT) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002424 if (PyDict_SetItemString(dict, NAME, (PyObject *)OBJECT) < 0) \
2425 return NULL; \
2426 ADD_TO_ALL(OBJECT)
Tim Peters4b7625e2001-09-13 21:37:17 +00002427
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002428 SETBUILTIN("None", Py_None);
2429 SETBUILTIN("Ellipsis", Py_Ellipsis);
2430 SETBUILTIN("NotImplemented", Py_NotImplemented);
2431 SETBUILTIN("False", Py_False);
2432 SETBUILTIN("True", Py_True);
2433 SETBUILTIN("bool", &PyBool_Type);
2434 SETBUILTIN("memoryview", &PyMemoryView_Type);
2435 SETBUILTIN("bytearray", &PyByteArray_Type);
2436 SETBUILTIN("bytes", &PyBytes_Type);
2437 SETBUILTIN("classmethod", &PyClassMethod_Type);
2438 SETBUILTIN("complex", &PyComplex_Type);
2439 SETBUILTIN("dict", &PyDict_Type);
2440 SETBUILTIN("enumerate", &PyEnum_Type);
2441 SETBUILTIN("filter", &PyFilter_Type);
2442 SETBUILTIN("float", &PyFloat_Type);
2443 SETBUILTIN("frozenset", &PyFrozenSet_Type);
2444 SETBUILTIN("property", &PyProperty_Type);
2445 SETBUILTIN("int", &PyLong_Type);
2446 SETBUILTIN("list", &PyList_Type);
2447 SETBUILTIN("map", &PyMap_Type);
2448 SETBUILTIN("object", &PyBaseObject_Type);
2449 SETBUILTIN("range", &PyRange_Type);
2450 SETBUILTIN("reversed", &PyReversed_Type);
2451 SETBUILTIN("set", &PySet_Type);
2452 SETBUILTIN("slice", &PySlice_Type);
2453 SETBUILTIN("staticmethod", &PyStaticMethod_Type);
2454 SETBUILTIN("str", &PyUnicode_Type);
2455 SETBUILTIN("super", &PySuper_Type);
2456 SETBUILTIN("tuple", &PyTuple_Type);
2457 SETBUILTIN("type", &PyType_Type);
2458 SETBUILTIN("zip", &PyZip_Type);
2459 debug = PyBool_FromLong(Py_OptimizeFlag == 0);
2460 if (PyDict_SetItemString(dict, "__debug__", debug) < 0) {
2461 Py_XDECREF(debug);
2462 return NULL;
2463 }
2464 Py_XDECREF(debug);
Barry Warsaw757af0e1997-08-29 22:13:51 +00002465
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002466 return mod;
Tim Peters7571a0f2003-03-23 17:52:28 +00002467#undef ADD_TO_ALL
Tim Peters4b7625e2001-09-13 21:37:17 +00002468#undef SETBUILTIN
Guido van Rossum3f5da241990-12-20 15:06:42 +00002469}