blob: 80ac7f1293634bb406766d3d057cc5566e5bd943 [file] [log] [blame]
Guido van Rossum3f5da241990-12-20 15:06:42 +00001/* Built-in functions */
2
Guido van Rossum79f25d91997-04-29 20:08:16 +00003#include "Python.h"
Martin v. Löwis618dc5e2008-03-30 20:03:44 +00004#include "Python-ast.h"
Guido van Rossum3f5da241990-12-20 15:06:42 +00005
6#include "node.h"
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00007#include "code.h"
Guido van Rossum3f5da241990-12-20 15:06:42 +00008
Benjamin Petersonea281a52011-08-12 23:10:50 -05009#include "asdl.h"
10#include "ast.h"
11
Guido van Rossum6bf62da1997-04-11 20:37:35 +000012#include <ctype.h>
13
Victor Stinnerb744ba12010-05-15 12:27:16 +000014#ifdef HAVE_LANGINFO_H
15#include <langinfo.h> /* CODESET */
16#endif
17
Mark Hammond26cffde2001-05-14 12:17:34 +000018/* The default encoding used by the platform file system APIs
19 Can remain NULL for all platforms that don't have such a concept
Guido van Rossum00bc0e02007-10-15 02:52:41 +000020
21 Don't forget to modify PyUnicode_DecodeFSDefault() if you touch any of the
22 values for Py_FileSystemDefaultEncoding!
Mark Hammond26cffde2001-05-14 12:17:34 +000023*/
Victor Stinner99b95382011-07-04 14:23:54 +020024#ifdef HAVE_MBCS
Mark Hammond26cffde2001-05-14 12:17:34 +000025const char *Py_FileSystemDefaultEncoding = "mbcs";
Martin v. Löwis04dc25c2008-10-03 16:09:28 +000026int Py_HasFileSystemDefaultEncoding = 1;
Just van Rossumb9b8e9c2003-02-10 09:22:01 +000027#elif defined(__APPLE__)
28const char *Py_FileSystemDefaultEncoding = "utf-8";
Martin v. Löwis04dc25c2008-10-03 16:09:28 +000029int Py_HasFileSystemDefaultEncoding = 1;
Victor Stinnerd64e8a72011-07-04 13:48:30 +020030#else
Victor Stinnerb744ba12010-05-15 12:27:16 +000031const char *Py_FileSystemDefaultEncoding = NULL; /* set by initfsencoding() */
Martin v. Löwis04dc25c2008-10-03 16:09:28 +000032int Py_HasFileSystemDefaultEncoding = 0;
Mark Hammond26cffde2001-05-14 12:17:34 +000033#endif
Mark Hammondef8b6542001-05-13 08:04:26 +000034
Martin v. Löwisbd928fe2011-10-14 10:20:37 +020035_Py_IDENTIFIER(fileno);
36_Py_IDENTIFIER(flush);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +020037
Guido van Rossum79f25d91997-04-29 20:08:16 +000038static PyObject *
Guido van Rossum52cc1d82007-03-18 15:41:51 +000039builtin___build_class__(PyObject *self, PyObject *args, PyObject *kwds)
40{
Nick Coghlande31b192011-10-23 22:04:16 +100041 PyObject *func, *name, *bases, *mkw, *meta, *winner, *prep, *ns, *cell;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000042 PyObject *cls = NULL;
Florent Xicluna4d46c2a2011-10-28 15:00:50 +020043 Py_ssize_t nargs;
Nick Coghlande31b192011-10-23 22:04:16 +100044 int isclass;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +020045 _Py_IDENTIFIER(__prepare__);
Guido van Rossum52cc1d82007-03-18 15:41:51 +000046
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000047 assert(args != NULL);
48 if (!PyTuple_Check(args)) {
49 PyErr_SetString(PyExc_TypeError,
50 "__build_class__: args is not a tuple");
51 return NULL;
52 }
53 nargs = PyTuple_GET_SIZE(args);
54 if (nargs < 2) {
55 PyErr_SetString(PyExc_TypeError,
56 "__build_class__: not enough arguments");
57 return NULL;
58 }
59 func = PyTuple_GET_ITEM(args, 0); /* Better be callable */
60 name = PyTuple_GET_ITEM(args, 1);
61 if (!PyUnicode_Check(name)) {
62 PyErr_SetString(PyExc_TypeError,
63 "__build_class__: name is not a string");
64 return NULL;
65 }
66 bases = PyTuple_GetSlice(args, 2, nargs);
67 if (bases == NULL)
68 return NULL;
Guido van Rossum52cc1d82007-03-18 15:41:51 +000069
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000070 if (kwds == NULL) {
71 meta = NULL;
72 mkw = NULL;
73 }
74 else {
75 mkw = PyDict_Copy(kwds); /* Don't modify kwds passed in! */
76 if (mkw == NULL) {
77 Py_DECREF(bases);
78 return NULL;
Guido van Rossum52cc1d82007-03-18 15:41:51 +000079 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000080 meta = PyDict_GetItemString(mkw, "metaclass");
81 if (meta != NULL) {
82 Py_INCREF(meta);
83 if (PyDict_DelItemString(mkw, "metaclass") < 0) {
84 Py_DECREF(meta);
85 Py_DECREF(mkw);
86 Py_DECREF(bases);
87 return NULL;
88 }
Nick Coghlande31b192011-10-23 22:04:16 +100089 /* metaclass is explicitly given, check if it's indeed a class */
90 isclass = PyType_Check(meta);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000091 }
92 }
93 if (meta == NULL) {
Nick Coghlande31b192011-10-23 22:04:16 +100094 /* if there are no bases, use type: */
95 if (PyTuple_GET_SIZE(bases) == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000096 meta = (PyObject *) (&PyType_Type);
Nick Coghlande31b192011-10-23 22:04:16 +100097 }
98 /* else get the type of the first base */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000099 else {
100 PyObject *base0 = PyTuple_GET_ITEM(bases, 0);
101 meta = (PyObject *) (base0->ob_type);
102 }
103 Py_INCREF(meta);
Nick Coghlande31b192011-10-23 22:04:16 +1000104 isclass = 1; /* meta is really a class */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000105 }
Nick Coghlan9715d262011-10-23 22:36:42 +1000106
Nick Coghlande31b192011-10-23 22:04:16 +1000107 if (isclass) {
108 /* meta is really a class, so check for a more derived
109 metaclass, or possible metaclass conflicts: */
110 winner = (PyObject *)_PyType_CalculateMetaclass((PyTypeObject *)meta,
111 bases);
112 if (winner == NULL) {
113 Py_DECREF(meta);
114 Py_XDECREF(mkw);
115 Py_DECREF(bases);
116 return NULL;
117 }
118 if (winner != meta) {
119 Py_DECREF(meta);
120 meta = winner;
121 Py_INCREF(meta);
122 }
123 }
124 /* else: meta is not a class, so we cannot do the metaclass
125 calculation, so we will use the explicitly given object as it is */
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +0200126 prep = _PyObject_GetAttrId(meta, &PyId___prepare__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000127 if (prep == NULL) {
128 if (PyErr_ExceptionMatches(PyExc_AttributeError)) {
129 PyErr_Clear();
130 ns = PyDict_New();
131 }
132 else {
133 Py_DECREF(meta);
134 Py_XDECREF(mkw);
135 Py_DECREF(bases);
136 return NULL;
137 }
138 }
139 else {
140 PyObject *pargs = PyTuple_Pack(2, name, bases);
141 if (pargs == NULL) {
142 Py_DECREF(prep);
143 Py_DECREF(meta);
144 Py_XDECREF(mkw);
145 Py_DECREF(bases);
146 return NULL;
147 }
148 ns = PyEval_CallObjectWithKeywords(prep, pargs, mkw);
149 Py_DECREF(pargs);
150 Py_DECREF(prep);
151 }
152 if (ns == NULL) {
153 Py_DECREF(meta);
154 Py_XDECREF(mkw);
155 Py_DECREF(bases);
156 return NULL;
157 }
158 cell = PyObject_CallFunctionObjArgs(func, ns, NULL);
159 if (cell != NULL) {
160 PyObject *margs;
161 margs = PyTuple_Pack(3, name, bases, ns);
162 if (margs != NULL) {
163 cls = PyEval_CallObjectWithKeywords(meta, margs, mkw);
164 Py_DECREF(margs);
165 }
Benjamin Peterson8e8fbea2012-06-01 23:57:36 -0700166 if (cls != NULL && PyCell_Check(cell))
167 PyCell_Set(cell, cls);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000168 Py_DECREF(cell);
169 }
170 Py_DECREF(ns);
171 Py_DECREF(meta);
172 Py_XDECREF(mkw);
173 Py_DECREF(bases);
174 return cls;
Guido van Rossum52cc1d82007-03-18 15:41:51 +0000175}
176
177PyDoc_STRVAR(build_class_doc,
178"__build_class__(func, name, *bases, metaclass=None, **kwds) -> class\n\
179\n\
180Internal helper function used by the class statement.");
181
182static PyObject *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000183builtin___import__(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000184{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000185 static char *kwlist[] = {"name", "globals", "locals", "fromlist",
186 "level", 0};
Victor Stinnerfe93faf2011-03-14 15:54:52 -0400187 PyObject *name, *globals = NULL, *locals = NULL, *fromlist = NULL;
Brett Cannonfd074152012-04-14 14:10:13 -0400188 int level = 0;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000189
Victor Stinnerfe93faf2011-03-14 15:54:52 -0400190 if (!PyArg_ParseTupleAndKeywords(args, kwds, "U|OOOi:__import__",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000191 kwlist, &name, &globals, &locals, &fromlist, &level))
192 return NULL;
Victor Stinnerfe93faf2011-03-14 15:54:52 -0400193 return PyImport_ImportModuleLevelObject(name, globals, locals,
194 fromlist, level);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000195}
196
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000197PyDoc_STRVAR(import_doc,
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000198"__import__(name, globals={}, locals={}, fromlist=[], level=-1) -> 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\
211absolute or relative imports. -1 is the original strategy of attempting\n\
212both absolute and relative imports, 0 is absolute, a positive number\n\
213is the number of parent directories to search relative to the current module.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000214
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000215
Guido van Rossum79f25d91997-04-29 20:08:16 +0000216static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000217builtin_abs(PyObject *self, PyObject *v)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000218{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000219 return PyNumber_Absolute(v);
Guido van Rossum3f5da241990-12-20 15:06:42 +0000220}
221
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000222PyDoc_STRVAR(abs_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000223"abs(number) -> number\n\
224\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000225Return the absolute value of the argument.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000226
Raymond Hettinger96229b12005-03-11 06:49:40 +0000227static PyObject *
228builtin_all(PyObject *self, PyObject *v)
229{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000230 PyObject *it, *item;
231 PyObject *(*iternext)(PyObject *);
232 int cmp;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000233
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000234 it = PyObject_GetIter(v);
235 if (it == NULL)
236 return NULL;
237 iternext = *Py_TYPE(it)->tp_iternext;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000238
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000239 for (;;) {
240 item = iternext(it);
241 if (item == NULL)
242 break;
243 cmp = PyObject_IsTrue(item);
244 Py_DECREF(item);
245 if (cmp < 0) {
246 Py_DECREF(it);
247 return NULL;
248 }
249 if (cmp == 0) {
250 Py_DECREF(it);
251 Py_RETURN_FALSE;
252 }
253 }
254 Py_DECREF(it);
255 if (PyErr_Occurred()) {
256 if (PyErr_ExceptionMatches(PyExc_StopIteration))
257 PyErr_Clear();
258 else
259 return NULL;
260 }
261 Py_RETURN_TRUE;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000262}
263
264PyDoc_STRVAR(all_doc,
265"all(iterable) -> bool\n\
266\n\
267Return True if bool(x) is True for all values x in the iterable.");
268
269static PyObject *
270builtin_any(PyObject *self, PyObject *v)
271{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000272 PyObject *it, *item;
273 PyObject *(*iternext)(PyObject *);
274 int cmp;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000275
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000276 it = PyObject_GetIter(v);
277 if (it == NULL)
278 return NULL;
279 iternext = *Py_TYPE(it)->tp_iternext;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000280
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000281 for (;;) {
282 item = iternext(it);
283 if (item == NULL)
284 break;
285 cmp = PyObject_IsTrue(item);
286 Py_DECREF(item);
287 if (cmp < 0) {
288 Py_DECREF(it);
289 return NULL;
290 }
291 if (cmp == 1) {
292 Py_DECREF(it);
293 Py_RETURN_TRUE;
294 }
295 }
296 Py_DECREF(it);
297 if (PyErr_Occurred()) {
298 if (PyErr_ExceptionMatches(PyExc_StopIteration))
299 PyErr_Clear();
300 else
301 return NULL;
302 }
303 Py_RETURN_FALSE;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000304}
305
306PyDoc_STRVAR(any_doc,
307"any(iterable) -> bool\n\
308\n\
309Return True if bool(x) is True for any x in the iterable.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000310
Georg Brandl559e5d72008-06-11 18:37:52 +0000311static PyObject *
312builtin_ascii(PyObject *self, PyObject *v)
313{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000314 return PyObject_ASCII(v);
Georg Brandl559e5d72008-06-11 18:37:52 +0000315}
316
317PyDoc_STRVAR(ascii_doc,
318"ascii(object) -> string\n\
319\n\
320As repr(), return a string containing a printable representation of an\n\
321object, but escape the non-ASCII characters in the string returned by\n\
322repr() using \\x, \\u or \\U escapes. This generates a string similar\n\
323to that returned by repr() in Python 2.");
324
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000325
Guido van Rossum79f25d91997-04-29 20:08:16 +0000326static PyObject *
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000327builtin_bin(PyObject *self, PyObject *v)
328{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000329 return PyNumber_ToBase(v, 2);
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000330}
331
332PyDoc_STRVAR(bin_doc,
333"bin(number) -> string\n\
334\n\
Alexander Belopolsky12338ab2011-04-07 00:15:33 -0400335Return the binary representation of an integer.");
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000336
337
Antoine Pitroue71362d2010-11-27 22:00:11 +0000338static PyObject *
339builtin_callable(PyObject *self, PyObject *v)
340{
341 return PyBool_FromLong((long)PyCallable_Check(v));
342}
343
344PyDoc_STRVAR(callable_doc,
345"callable(object) -> bool\n\
346\n\
347Return whether the object is callable (i.e., some kind of function).\n\
348Note that classes are callable, as are instances of classes with a\n\
349__call__() method.");
350
351
Raymond Hettinger17301e92008-03-13 00:19:26 +0000352typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000353 PyObject_HEAD
354 PyObject *func;
355 PyObject *it;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000356} filterobject;
357
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000358static PyObject *
Raymond Hettinger17301e92008-03-13 00:19:26 +0000359filter_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
Guido van Rossum12d12c51993-10-26 17:58:25 +0000360{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000361 PyObject *func, *seq;
362 PyObject *it;
363 filterobject *lz;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000364
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000365 if (type == &PyFilter_Type && !_PyArg_NoKeywords("filter()", kwds))
366 return NULL;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000367
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000368 if (!PyArg_UnpackTuple(args, "filter", 2, 2, &func, &seq))
369 return NULL;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000370
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000371 /* Get iterator. */
372 it = PyObject_GetIter(seq);
373 if (it == NULL)
374 return NULL;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000375
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000376 /* create filterobject structure */
377 lz = (filterobject *)type->tp_alloc(type, 0);
378 if (lz == NULL) {
379 Py_DECREF(it);
380 return NULL;
381 }
382 Py_INCREF(func);
383 lz->func = func;
384 lz->it = it;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000385
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000386 return (PyObject *)lz;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000387}
388
389static void
390filter_dealloc(filterobject *lz)
391{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000392 PyObject_GC_UnTrack(lz);
393 Py_XDECREF(lz->func);
394 Py_XDECREF(lz->it);
395 Py_TYPE(lz)->tp_free(lz);
Raymond Hettinger17301e92008-03-13 00:19:26 +0000396}
397
398static int
399filter_traverse(filterobject *lz, visitproc visit, void *arg)
400{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000401 Py_VISIT(lz->it);
402 Py_VISIT(lz->func);
403 return 0;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000404}
405
406static PyObject *
407filter_next(filterobject *lz)
408{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000409 PyObject *item;
410 PyObject *it = lz->it;
411 long ok;
412 PyObject *(*iternext)(PyObject *);
Raymond Hettinger17301e92008-03-13 00:19:26 +0000413
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000414 iternext = *Py_TYPE(it)->tp_iternext;
415 for (;;) {
416 item = iternext(it);
417 if (item == NULL)
418 return NULL;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000419
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000420 if (lz->func == Py_None || lz->func == (PyObject *)&PyBool_Type) {
421 ok = PyObject_IsTrue(item);
422 } else {
423 PyObject *good;
424 good = PyObject_CallFunctionObjArgs(lz->func,
425 item, NULL);
426 if (good == NULL) {
427 Py_DECREF(item);
428 return NULL;
429 }
430 ok = PyObject_IsTrue(good);
431 Py_DECREF(good);
432 }
433 if (ok)
434 return item;
435 Py_DECREF(item);
436 }
Guido van Rossum12d12c51993-10-26 17:58:25 +0000437}
438
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +0000439static PyObject *
440filter_reduce(filterobject *lz)
441{
442 return Py_BuildValue("O(OO)", Py_TYPE(lz), lz->func, lz->it);
443}
444
445PyDoc_STRVAR(reduce_doc, "Return state information for pickling.");
446
447static PyMethodDef filter_methods[] = {
448 {"__reduce__", (PyCFunction)filter_reduce, METH_NOARGS, reduce_doc},
449 {NULL, NULL} /* sentinel */
450};
451
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000452PyDoc_STRVAR(filter_doc,
Georg Brandld11ae5d2008-05-16 13:27:32 +0000453"filter(function or None, iterable) --> filter object\n\
Guido van Rossumc1f779c2007-07-03 08:25:58 +0000454\n\
Georg Brandld11ae5d2008-05-16 13:27:32 +0000455Return an iterator yielding those items of iterable for which function(item)\n\
Raymond Hettinger17301e92008-03-13 00:19:26 +0000456is true. If function is None, return the items that are true.");
457
458PyTypeObject PyFilter_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000459 PyVarObject_HEAD_INIT(&PyType_Type, 0)
460 "filter", /* tp_name */
461 sizeof(filterobject), /* tp_basicsize */
462 0, /* tp_itemsize */
463 /* methods */
464 (destructor)filter_dealloc, /* tp_dealloc */
465 0, /* tp_print */
466 0, /* tp_getattr */
467 0, /* tp_setattr */
468 0, /* tp_reserved */
469 0, /* tp_repr */
470 0, /* tp_as_number */
471 0, /* tp_as_sequence */
472 0, /* tp_as_mapping */
473 0, /* tp_hash */
474 0, /* tp_call */
475 0, /* tp_str */
476 PyObject_GenericGetAttr, /* tp_getattro */
477 0, /* tp_setattro */
478 0, /* tp_as_buffer */
479 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
480 Py_TPFLAGS_BASETYPE, /* tp_flags */
481 filter_doc, /* tp_doc */
482 (traverseproc)filter_traverse, /* tp_traverse */
483 0, /* tp_clear */
484 0, /* tp_richcompare */
485 0, /* tp_weaklistoffset */
486 PyObject_SelfIter, /* tp_iter */
487 (iternextfunc)filter_next, /* tp_iternext */
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +0000488 filter_methods, /* tp_methods */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000489 0, /* tp_members */
490 0, /* tp_getset */
491 0, /* tp_base */
492 0, /* tp_dict */
493 0, /* tp_descr_get */
494 0, /* tp_descr_set */
495 0, /* tp_dictoffset */
496 0, /* tp_init */
497 PyType_GenericAlloc, /* tp_alloc */
498 filter_new, /* tp_new */
499 PyObject_GC_Del, /* tp_free */
Raymond Hettinger17301e92008-03-13 00:19:26 +0000500};
501
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000502
Eric Smith8c663262007-08-25 02:26:07 +0000503static PyObject *
504builtin_format(PyObject *self, PyObject *args)
505{
Christian Heimes94b7d3d2007-12-11 20:20:39 +0000506 PyObject *value;
Eric Smith8fd3eba2008-02-17 19:48:00 +0000507 PyObject *format_spec = NULL;
Eric Smith8c663262007-08-25 02:26:07 +0000508
Eric Smith8fd3eba2008-02-17 19:48:00 +0000509 if (!PyArg_ParseTuple(args, "O|U:format", &value, &format_spec))
Benjamin Petersona12d5c62012-01-03 16:47:22 -0600510 return NULL;
Eric Smith8c663262007-08-25 02:26:07 +0000511
Eric Smith8fd3eba2008-02-17 19:48:00 +0000512 return PyObject_Format(value, format_spec);
Eric Smith8c663262007-08-25 02:26:07 +0000513}
514
Eric Smith8c663262007-08-25 02:26:07 +0000515PyDoc_STRVAR(format_doc,
Eric Smith81936692007-08-31 01:14:01 +0000516"format(value[, format_spec]) -> string\n\
Eric Smith8c663262007-08-25 02:26:07 +0000517\n\
Eric Smith81936692007-08-31 01:14:01 +0000518Returns value.__format__(format_spec)\n\
519format_spec defaults to \"\"");
520
Guido van Rossum7fcf2242007-05-04 17:43:11 +0000521static PyObject *
Walter Dörwalde7efd592007-06-05 20:07:21 +0000522builtin_chr(PyObject *self, PyObject *args)
Guido van Rossum09095f32000-03-10 23:00:52 +0000523{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000524 int x;
Guido van Rossum09095f32000-03-10 23:00:52 +0000525
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000526 if (!PyArg_ParseTuple(args, "i:chr", &x))
527 return NULL;
Fredrik Lundh0dcf67e2001-06-26 20:01:56 +0000528
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000529 return PyUnicode_FromOrdinal(x);
Guido van Rossum09095f32000-03-10 23:00:52 +0000530}
531
Victor Stinner63ab8752011-11-22 03:31:20 +0100532PyDoc_STRVAR(chr_doc,
Guido van Rossum84fc66d2007-05-03 17:18:26 +0000533"chr(i) -> Unicode character\n\
Guido van Rossum09095f32000-03-10 23:00:52 +0000534\n\
Victor Stinner63ab8752011-11-22 03:31:20 +0100535Return a Unicode string of one character with ordinal i; 0 <= i <= 0x10ffff.");
Guido van Rossum09095f32000-03-10 23:00:52 +0000536
537
Guido van Rossumf15a29f2007-05-04 00:41:39 +0000538static char *
Benjamin Petersonf5b52242009-03-02 23:31:26 +0000539source_as_string(PyObject *cmd, char *funcname, char *what, PyCompilerFlags *cf)
Guido van Rossumf15a29f2007-05-04 00:41:39 +0000540{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000541 char *str;
542 Py_ssize_t size;
Guido van Rossumf15a29f2007-05-04 00:41:39 +0000543
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000544 if (PyUnicode_Check(cmd)) {
545 cf->cf_flags |= PyCF_IGNORE_COOKIE;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200546 str = PyUnicode_AsUTF8AndSize(cmd, &size);
547 if (str == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000548 return NULL;
549 }
550 else if (!PyObject_CheckReadBuffer(cmd)) {
551 PyErr_Format(PyExc_TypeError,
552 "%s() arg 1 must be a %s object",
553 funcname, what);
554 return NULL;
555 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200556 else if (PyObject_AsReadBuffer(cmd, (const void **)&str, &size) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000557 return NULL;
558 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200559
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000560 if (strlen(str) != size) {
561 PyErr_SetString(PyExc_TypeError,
562 "source code string cannot contain null bytes");
563 return NULL;
564 }
565 return str;
Guido van Rossumf15a29f2007-05-04 00:41:39 +0000566}
567
Guido van Rossum79f25d91997-04-29 20:08:16 +0000568static PyObject *
Guido van Rossumd8faa362007-04-27 19:54:29 +0000569builtin_compile(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum5b722181993-03-30 17:46:03 +0000570{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000571 char *str;
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000572 PyObject *filename_obj;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000573 char *filename;
574 char *startstr;
575 int mode = -1;
576 int dont_inherit = 0;
577 int supplied_flags = 0;
Georg Brandl8334fd92010-12-04 10:26:46 +0000578 int optimize = -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000579 int is_ast;
580 PyCompilerFlags cf;
581 PyObject *cmd;
582 static char *kwlist[] = {"source", "filename", "mode", "flags",
Georg Brandl8334fd92010-12-04 10:26:46 +0000583 "dont_inherit", "optimize", NULL};
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000584 int start[] = {Py_file_input, Py_eval_input, Py_single_input};
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000585 PyObject *result;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000586
Georg Brandl8334fd92010-12-04 10:26:46 +0000587 if (!PyArg_ParseTupleAndKeywords(args, kwds, "OO&s|iii:compile", kwlist,
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000588 &cmd,
589 PyUnicode_FSConverter, &filename_obj,
590 &startstr, &supplied_flags,
Georg Brandl8334fd92010-12-04 10:26:46 +0000591 &dont_inherit, &optimize))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000592 return NULL;
Tim Peters6cd6a822001-08-17 22:11:27 +0000593
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000594 filename = PyBytes_AS_STRING(filename_obj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000595 cf.cf_flags = supplied_flags | PyCF_SOURCE_IS_UTF8;
Just van Rossum3aaf42c2003-02-10 08:21:10 +0000596
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000597 if (supplied_flags &
598 ~(PyCF_MASK | PyCF_MASK_OBSOLETE | PyCF_DONT_IMPLY_DEDENT | PyCF_ONLY_AST))
599 {
600 PyErr_SetString(PyExc_ValueError,
601 "compile(): unrecognised flags");
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000602 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000603 }
604 /* XXX Warn if (supplied_flags & PyCF_MASK_OBSOLETE) != 0? */
Tim Peters6cd6a822001-08-17 22:11:27 +0000605
Georg Brandl8334fd92010-12-04 10:26:46 +0000606 if (optimize < -1 || optimize > 2) {
607 PyErr_SetString(PyExc_ValueError,
608 "compile(): invalid optimize value");
609 goto error;
610 }
611
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000612 if (!dont_inherit) {
613 PyEval_MergeCompilerFlags(&cf);
614 }
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000615
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000616 if (strcmp(startstr, "exec") == 0)
617 mode = 0;
618 else if (strcmp(startstr, "eval") == 0)
619 mode = 1;
620 else if (strcmp(startstr, "single") == 0)
621 mode = 2;
622 else {
623 PyErr_SetString(PyExc_ValueError,
624 "compile() arg 3 must be 'exec', 'eval' or 'single'");
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000625 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000626 }
Neal Norwitzdb4115f2008-03-31 04:20:05 +0000627
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000628 is_ast = PyAST_Check(cmd);
629 if (is_ast == -1)
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000630 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000631 if (is_ast) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000632 if (supplied_flags & PyCF_ONLY_AST) {
633 Py_INCREF(cmd);
634 result = cmd;
635 }
636 else {
637 PyArena *arena;
638 mod_ty mod;
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000639
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000640 arena = PyArena_New();
641 mod = PyAST_obj2mod(cmd, arena, mode);
642 if (mod == NULL) {
643 PyArena_Free(arena);
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000644 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000645 }
Benjamin Peterson832bfe22011-08-09 16:15:04 -0500646 if (!PyAST_Validate(mod)) {
647 PyArena_Free(arena);
648 goto error;
649 }
Georg Brandl8334fd92010-12-04 10:26:46 +0000650 result = (PyObject*)PyAST_CompileEx(mod, filename,
651 &cf, optimize, arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000652 PyArena_Free(arena);
653 }
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000654 goto finally;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000655 }
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000656
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000657 str = source_as_string(cmd, "compile", "string, bytes, AST or code", &cf);
658 if (str == NULL)
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000659 goto error;
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000660
Georg Brandl8334fd92010-12-04 10:26:46 +0000661 result = Py_CompileStringExFlags(str, filename, start[mode], &cf, optimize);
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000662 goto finally;
663
664error:
665 result = NULL;
666finally:
667 Py_DECREF(filename_obj);
668 return result;
Guido van Rossum5b722181993-03-30 17:46:03 +0000669}
670
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000671PyDoc_STRVAR(compile_doc,
Tim Peters6cd6a822001-08-17 22:11:27 +0000672"compile(source, filename, mode[, flags[, dont_inherit]]) -> code object\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000673\n\
674Compile the source string (a Python module, statement or expression)\n\
Georg Brandl7cae87c2006-09-06 06:51:57 +0000675into a code object that can be executed by exec() or eval().\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000676The filename will be used for run-time error messages.\n\
677The mode must be 'exec' to compile a module, 'single' to compile a\n\
Tim Peters6cd6a822001-08-17 22:11:27 +0000678single (interactive) statement, or 'eval' to compile an expression.\n\
679The flags argument, if present, controls which future statements influence\n\
680the compilation of the code.\n\
681The dont_inherit argument, if non-zero, stops the compilation inheriting\n\
682the effects of any future statements in effect in the code calling\n\
683compile; if absent or zero these statements do influence the compilation,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000684in addition to any features explicitly specified.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000685
Guido van Rossum79f25d91997-04-29 20:08:16 +0000686static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000687builtin_dir(PyObject *self, PyObject *args)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000688{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000689 PyObject *arg = NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000690
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000691 if (!PyArg_UnpackTuple(args, "dir", 0, 1, &arg))
692 return NULL;
693 return PyObject_Dir(arg);
Guido van Rossum3f5da241990-12-20 15:06:42 +0000694}
695
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000696PyDoc_STRVAR(dir_doc,
Tim Peters5d2b77c2001-09-03 05:47:38 +0000697"dir([object]) -> list of strings\n"
698"\n"
Georg Brandle32b4222007-03-10 22:13:27 +0000699"If called without an argument, return the names in the current scope.\n"
700"Else, return an alphabetized list of names comprising (some of) the attributes\n"
701"of the given object, and of attributes reachable from it.\n"
702"If the object supplies a method named __dir__, it will be used; otherwise\n"
703"the default dir() logic is used and returns:\n"
704" for a module object: the module's attributes.\n"
705" for a class object: its attributes, and recursively the attributes\n"
706" of its bases.\n"
Guido van Rossumd8faa362007-04-27 19:54:29 +0000707" for any other object: its attributes, its class's attributes, and\n"
Georg Brandle32b4222007-03-10 22:13:27 +0000708" recursively the attributes of its class's base classes.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000709
Guido van Rossum79f25d91997-04-29 20:08:16 +0000710static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000711builtin_divmod(PyObject *self, PyObject *args)
Guido van Rossum6a00cd81995-01-07 12:39:01 +0000712{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000713 PyObject *v, *w;
Guido van Rossum6a00cd81995-01-07 12:39:01 +0000714
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000715 if (!PyArg_UnpackTuple(args, "divmod", 2, 2, &v, &w))
716 return NULL;
717 return PyNumber_Divmod(v, w);
Guido van Rossum3f5da241990-12-20 15:06:42 +0000718}
719
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000720PyDoc_STRVAR(divmod_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000721"divmod(x, y) -> (div, mod)\n\
722\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000723Return the tuple ((x-x%y)/y, x%y). Invariant: div*y + mod == x.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000724
725
Guido van Rossum79f25d91997-04-29 20:08:16 +0000726static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000727builtin_eval(PyObject *self, PyObject *args)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000728{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000729 PyObject *cmd, *result, *tmp = NULL;
730 PyObject *globals = Py_None, *locals = Py_None;
731 char *str;
732 PyCompilerFlags cf;
Guido van Rossum590baa41993-11-30 13:40:46 +0000733
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000734 if (!PyArg_UnpackTuple(args, "eval", 1, 3, &cmd, &globals, &locals))
735 return NULL;
736 if (locals != Py_None && !PyMapping_Check(locals)) {
737 PyErr_SetString(PyExc_TypeError, "locals must be a mapping");
738 return NULL;
739 }
740 if (globals != Py_None && !PyDict_Check(globals)) {
741 PyErr_SetString(PyExc_TypeError, PyMapping_Check(globals) ?
742 "globals must be a real dict; try eval(expr, {}, mapping)"
743 : "globals must be a dict");
744 return NULL;
745 }
746 if (globals == Py_None) {
747 globals = PyEval_GetGlobals();
748 if (locals == Py_None)
749 locals = PyEval_GetLocals();
750 }
751 else if (locals == Py_None)
752 locals = globals;
Tim Peters9fa96be2001-08-17 23:04:59 +0000753
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000754 if (globals == NULL || locals == NULL) {
755 PyErr_SetString(PyExc_TypeError,
756 "eval must be given globals and locals "
757 "when called without a frame");
758 return NULL;
759 }
Georg Brandl77c85e62005-09-15 10:46:13 +0000760
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000761 if (PyDict_GetItemString(globals, "__builtins__") == NULL) {
762 if (PyDict_SetItemString(globals, "__builtins__",
763 PyEval_GetBuiltins()) != 0)
764 return NULL;
765 }
Tim Peters9fa96be2001-08-17 23:04:59 +0000766
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000767 if (PyCode_Check(cmd)) {
768 if (PyCode_GetNumFree((PyCodeObject *)cmd) > 0) {
769 PyErr_SetString(PyExc_TypeError,
770 "code object passed to eval() may not contain free variables");
771 return NULL;
772 }
Martin v. Löwis4d0d4712010-12-03 20:14:31 +0000773 return PyEval_EvalCode(cmd, globals, locals);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000774 }
Tim Peters9fa96be2001-08-17 23:04:59 +0000775
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000776 cf.cf_flags = PyCF_SOURCE_IS_UTF8;
777 str = source_as_string(cmd, "eval", "string, bytes or code", &cf);
778 if (str == NULL)
779 return NULL;
Just van Rossum3aaf42c2003-02-10 08:21:10 +0000780
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000781 while (*str == ' ' || *str == '\t')
782 str++;
Tim Peters9fa96be2001-08-17 23:04:59 +0000783
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000784 (void)PyEval_MergeCompilerFlags(&cf);
785 result = PyRun_StringFlags(str, Py_eval_input, globals, locals, &cf);
786 Py_XDECREF(tmp);
787 return result;
Guido van Rossum3f5da241990-12-20 15:06:42 +0000788}
789
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000790PyDoc_STRVAR(eval_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000791"eval(source[, globals[, locals]]) -> value\n\
792\n\
793Evaluate the source in the context of globals and locals.\n\
794The source may be a string representing a Python expression\n\
795or a code object as returned by compile().\n\
Thomas Wouters89f507f2006-12-13 04:49:30 +0000796The globals must be a dictionary and locals can be any mapping,\n\
Raymond Hettinger214b1c32004-07-02 06:41:07 +0000797defaulting to the current globals and locals.\n\
798If only globals is given, locals defaults to it.\n");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000799
Georg Brandl7cae87c2006-09-06 06:51:57 +0000800static PyObject *
801builtin_exec(PyObject *self, PyObject *args)
802{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000803 PyObject *v;
804 PyObject *prog, *globals = Py_None, *locals = Py_None;
Georg Brandl7cae87c2006-09-06 06:51:57 +0000805
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000806 if (!PyArg_UnpackTuple(args, "exec", 1, 3, &prog, &globals, &locals))
807 return NULL;
Georg Brandl2cabc562008-08-28 07:57:16 +0000808
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000809 if (globals == Py_None) {
810 globals = PyEval_GetGlobals();
811 if (locals == Py_None) {
812 locals = PyEval_GetLocals();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000813 }
814 if (!globals || !locals) {
815 PyErr_SetString(PyExc_SystemError,
816 "globals and locals cannot be NULL");
817 return NULL;
818 }
819 }
820 else if (locals == Py_None)
821 locals = globals;
Georg Brandl7cae87c2006-09-06 06:51:57 +0000822
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000823 if (!PyDict_Check(globals)) {
824 PyErr_Format(PyExc_TypeError, "exec() arg 2 must be a dict, not %.100s",
825 globals->ob_type->tp_name);
826 return NULL;
827 }
828 if (!PyMapping_Check(locals)) {
829 PyErr_Format(PyExc_TypeError,
830 "arg 3 must be a mapping or None, not %.100s",
831 locals->ob_type->tp_name);
832 return NULL;
833 }
834 if (PyDict_GetItemString(globals, "__builtins__") == NULL) {
835 if (PyDict_SetItemString(globals, "__builtins__",
836 PyEval_GetBuiltins()) != 0)
837 return NULL;
838 }
839
840 if (PyCode_Check(prog)) {
841 if (PyCode_GetNumFree((PyCodeObject *)prog) > 0) {
842 PyErr_SetString(PyExc_TypeError,
843 "code object passed to exec() may not "
844 "contain free variables");
845 return NULL;
846 }
Martin v. Löwis4d0d4712010-12-03 20:14:31 +0000847 v = PyEval_EvalCode(prog, globals, locals);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000848 }
849 else {
850 char *str;
851 PyCompilerFlags cf;
852 cf.cf_flags = PyCF_SOURCE_IS_UTF8;
853 str = source_as_string(prog, "exec",
854 "string, bytes or code", &cf);
855 if (str == NULL)
856 return NULL;
857 if (PyEval_MergeCompilerFlags(&cf))
858 v = PyRun_StringFlags(str, Py_file_input, globals,
859 locals, &cf);
860 else
861 v = PyRun_String(str, Py_file_input, globals, locals);
862 }
863 if (v == NULL)
864 return NULL;
865 Py_DECREF(v);
866 Py_RETURN_NONE;
Georg Brandl7cae87c2006-09-06 06:51:57 +0000867}
868
869PyDoc_STRVAR(exec_doc,
870"exec(object[, globals[, locals]])\n\
871\n\
Mark Dickinson480e8e32009-12-19 21:19:35 +0000872Read and execute code from an object, which can be a string or a code\n\
Benjamin Peterson38090262009-01-04 15:30:39 +0000873object.\n\
Georg Brandl7cae87c2006-09-06 06:51:57 +0000874The globals and locals are dictionaries, defaulting to the current\n\
875globals and locals. If only globals is given, locals defaults to it.");
876
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000877
Guido van Rossum79f25d91997-04-29 20:08:16 +0000878static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000879builtin_getattr(PyObject *self, PyObject *args)
Guido van Rossum33894be1992-01-27 16:53:09 +0000880{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000881 PyObject *v, *result, *dflt = NULL;
882 PyObject *name;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000883
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000884 if (!PyArg_UnpackTuple(args, "getattr", 2, 3, &v, &name, &dflt))
885 return NULL;
Martin v. Löwis5b222132007-06-10 09:51:05 +0000886
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000887 if (!PyUnicode_Check(name)) {
888 PyErr_SetString(PyExc_TypeError,
889 "getattr(): attribute name must be string");
890 return NULL;
891 }
892 result = PyObject_GetAttr(v, name);
893 if (result == NULL && dflt != NULL &&
894 PyErr_ExceptionMatches(PyExc_AttributeError))
895 {
896 PyErr_Clear();
897 Py_INCREF(dflt);
898 result = dflt;
899 }
900 return result;
Guido van Rossum9bfef441993-03-29 10:43:31 +0000901}
902
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000903PyDoc_STRVAR(getattr_doc,
Guido van Rossum950ff291998-06-29 13:38:57 +0000904"getattr(object, name[, default]) -> value\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000905\n\
Guido van Rossum950ff291998-06-29 13:38:57 +0000906Get a named attribute from an object; getattr(x, 'y') is equivalent to x.y.\n\
907When a default argument is given, it is returned when the attribute doesn't\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000908exist; without it, an exception is raised in that case.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000909
910
Guido van Rossum79f25d91997-04-29 20:08:16 +0000911static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000912builtin_globals(PyObject *self)
Guido van Rossum872537c1995-07-07 22:43:42 +0000913{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000914 PyObject *d;
Guido van Rossum872537c1995-07-07 22:43:42 +0000915
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000916 d = PyEval_GetGlobals();
917 Py_XINCREF(d);
918 return d;
Guido van Rossum872537c1995-07-07 22:43:42 +0000919}
920
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000921PyDoc_STRVAR(globals_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000922"globals() -> dictionary\n\
923\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000924Return the dictionary containing the current scope's global variables.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000925
926
Guido van Rossum79f25d91997-04-29 20:08:16 +0000927static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000928builtin_hasattr(PyObject *self, PyObject *args)
Guido van Rossum9bfef441993-03-29 10:43:31 +0000929{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000930 PyObject *v;
931 PyObject *name;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000932
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000933 if (!PyArg_UnpackTuple(args, "hasattr", 2, 2, &v, &name))
934 return NULL;
935 if (!PyUnicode_Check(name)) {
936 PyErr_SetString(PyExc_TypeError,
937 "hasattr(): attribute name must be string");
938 return NULL;
939 }
940 v = PyObject_GetAttr(v, name);
941 if (v == NULL) {
Benjamin Peterson17689992010-08-24 03:26:23 +0000942 if (PyErr_ExceptionMatches(PyExc_AttributeError)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000943 PyErr_Clear();
Benjamin Peterson17689992010-08-24 03:26:23 +0000944 Py_RETURN_FALSE;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000945 }
Benjamin Peterson17689992010-08-24 03:26:23 +0000946 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000947 }
948 Py_DECREF(v);
Benjamin Peterson17689992010-08-24 03:26:23 +0000949 Py_RETURN_TRUE;
Guido van Rossum33894be1992-01-27 16:53:09 +0000950}
951
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000952PyDoc_STRVAR(hasattr_doc,
Guido van Rossum77f6a652002-04-03 22:41:51 +0000953"hasattr(object, name) -> bool\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000954\n\
955Return whether the object has an attribute with the given name.\n\
Benjamin Peterson17689992010-08-24 03:26:23 +0000956(This is done by calling getattr(object, name) and catching AttributeError.)");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000957
958
Guido van Rossum79f25d91997-04-29 20:08:16 +0000959static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000960builtin_id(PyObject *self, PyObject *v)
Guido van Rossum5b722181993-03-30 17:46:03 +0000961{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000962 return PyLong_FromVoidPtr(v);
Guido van Rossum5b722181993-03-30 17:46:03 +0000963}
964
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000965PyDoc_STRVAR(id_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000966"id(object) -> integer\n\
967\n\
968Return the identity of an object. This is guaranteed to be unique among\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000969simultaneously existing objects. (Hint: it's the object's memory address.)");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000970
971
Raymond Hettingera6c60372008-03-13 01:26:19 +0000972/* map object ************************************************************/
973
974typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000975 PyObject_HEAD
976 PyObject *iters;
977 PyObject *func;
Raymond Hettingera6c60372008-03-13 01:26:19 +0000978} mapobject;
979
Guido van Rossum79f25d91997-04-29 20:08:16 +0000980static PyObject *
Raymond Hettingera6c60372008-03-13 01:26:19 +0000981map_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
Guido van Rossum12d12c51993-10-26 17:58:25 +0000982{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000983 PyObject *it, *iters, *func;
984 mapobject *lz;
985 Py_ssize_t numargs, i;
Raymond Hettingera6c60372008-03-13 01:26:19 +0000986
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000987 if (type == &PyMap_Type && !_PyArg_NoKeywords("map()", kwds))
988 return NULL;
Raymond Hettingera6c60372008-03-13 01:26:19 +0000989
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000990 numargs = PyTuple_Size(args);
991 if (numargs < 2) {
992 PyErr_SetString(PyExc_TypeError,
993 "map() must have at least two arguments.");
994 return NULL;
995 }
Raymond Hettingera6c60372008-03-13 01:26:19 +0000996
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000997 iters = PyTuple_New(numargs-1);
998 if (iters == NULL)
999 return NULL;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001000
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001001 for (i=1 ; i<numargs ; i++) {
1002 /* Get iterator. */
1003 it = PyObject_GetIter(PyTuple_GET_ITEM(args, i));
1004 if (it == NULL) {
1005 Py_DECREF(iters);
1006 return NULL;
1007 }
1008 PyTuple_SET_ITEM(iters, i-1, it);
1009 }
Raymond Hettingera6c60372008-03-13 01:26:19 +00001010
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001011 /* create mapobject structure */
1012 lz = (mapobject *)type->tp_alloc(type, 0);
1013 if (lz == NULL) {
1014 Py_DECREF(iters);
1015 return NULL;
1016 }
1017 lz->iters = iters;
1018 func = PyTuple_GET_ITEM(args, 0);
1019 Py_INCREF(func);
1020 lz->func = func;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001021
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001022 return (PyObject *)lz;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001023}
1024
1025static void
1026map_dealloc(mapobject *lz)
1027{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001028 PyObject_GC_UnTrack(lz);
1029 Py_XDECREF(lz->iters);
1030 Py_XDECREF(lz->func);
1031 Py_TYPE(lz)->tp_free(lz);
Raymond Hettingera6c60372008-03-13 01:26:19 +00001032}
1033
1034static int
1035map_traverse(mapobject *lz, visitproc visit, void *arg)
1036{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001037 Py_VISIT(lz->iters);
1038 Py_VISIT(lz->func);
1039 return 0;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001040}
1041
1042static PyObject *
1043map_next(mapobject *lz)
1044{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001045 PyObject *val;
1046 PyObject *argtuple;
1047 PyObject *result;
1048 Py_ssize_t numargs, i;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001049
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001050 numargs = PyTuple_Size(lz->iters);
1051 argtuple = PyTuple_New(numargs);
1052 if (argtuple == NULL)
1053 return NULL;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001054
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001055 for (i=0 ; i<numargs ; i++) {
1056 val = PyIter_Next(PyTuple_GET_ITEM(lz->iters, i));
1057 if (val == NULL) {
1058 Py_DECREF(argtuple);
1059 return NULL;
1060 }
1061 PyTuple_SET_ITEM(argtuple, i, val);
1062 }
1063 result = PyObject_Call(lz->func, argtuple, NULL);
1064 Py_DECREF(argtuple);
1065 return result;
Guido van Rossum12d12c51993-10-26 17:58:25 +00001066}
1067
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001068static PyObject *
1069map_reduce(mapobject *lz)
1070{
1071 Py_ssize_t numargs = PyTuple_GET_SIZE(lz->iters);
1072 PyObject *args = PyTuple_New(numargs+1);
1073 Py_ssize_t i;
1074 if (args == NULL)
1075 return NULL;
1076 Py_INCREF(lz->func);
1077 PyTuple_SET_ITEM(args, 0, lz->func);
1078 for (i = 0; i<numargs; i++){
1079 PyObject *it = PyTuple_GET_ITEM(lz->iters, i);
1080 Py_INCREF(it);
1081 PyTuple_SET_ITEM(args, i+1, it);
1082 }
1083
1084 return Py_BuildValue("ON", Py_TYPE(lz), args);
1085}
1086
1087static PyMethodDef map_methods[] = {
1088 {"__reduce__", (PyCFunction)map_reduce, METH_NOARGS, reduce_doc},
1089 {NULL, NULL} /* sentinel */
1090};
1091
1092
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001093PyDoc_STRVAR(map_doc,
Raymond Hettingera6c60372008-03-13 01:26:19 +00001094"map(func, *iterables) --> map object\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001095\n\
Raymond Hettingera6c60372008-03-13 01:26:19 +00001096Make an iterator that computes the function using arguments from\n\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001097each of the iterables. Stops when the shortest iterable is exhausted.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001098
Raymond Hettingera6c60372008-03-13 01:26:19 +00001099PyTypeObject PyMap_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001100 PyVarObject_HEAD_INIT(&PyType_Type, 0)
1101 "map", /* tp_name */
1102 sizeof(mapobject), /* tp_basicsize */
1103 0, /* tp_itemsize */
1104 /* methods */
1105 (destructor)map_dealloc, /* tp_dealloc */
1106 0, /* tp_print */
1107 0, /* tp_getattr */
1108 0, /* tp_setattr */
1109 0, /* tp_reserved */
1110 0, /* tp_repr */
1111 0, /* tp_as_number */
1112 0, /* tp_as_sequence */
1113 0, /* tp_as_mapping */
1114 0, /* tp_hash */
1115 0, /* tp_call */
1116 0, /* tp_str */
1117 PyObject_GenericGetAttr, /* tp_getattro */
1118 0, /* tp_setattro */
1119 0, /* tp_as_buffer */
1120 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
1121 Py_TPFLAGS_BASETYPE, /* tp_flags */
1122 map_doc, /* tp_doc */
1123 (traverseproc)map_traverse, /* tp_traverse */
1124 0, /* tp_clear */
1125 0, /* tp_richcompare */
1126 0, /* tp_weaklistoffset */
1127 PyObject_SelfIter, /* tp_iter */
1128 (iternextfunc)map_next, /* tp_iternext */
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001129 map_methods, /* tp_methods */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001130 0, /* tp_members */
1131 0, /* tp_getset */
1132 0, /* tp_base */
1133 0, /* tp_dict */
1134 0, /* tp_descr_get */
1135 0, /* tp_descr_set */
1136 0, /* tp_dictoffset */
1137 0, /* tp_init */
1138 PyType_GenericAlloc, /* tp_alloc */
1139 map_new, /* tp_new */
1140 PyObject_GC_Del, /* tp_free */
Raymond Hettingera6c60372008-03-13 01:26:19 +00001141};
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001142
Guido van Rossum79f25d91997-04-29 20:08:16 +00001143static PyObject *
Georg Brandla18af4e2007-04-21 15:47:16 +00001144builtin_next(PyObject *self, PyObject *args)
1145{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001146 PyObject *it, *res;
1147 PyObject *def = NULL;
Georg Brandla18af4e2007-04-21 15:47:16 +00001148
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001149 if (!PyArg_UnpackTuple(args, "next", 1, 2, &it, &def))
1150 return NULL;
1151 if (!PyIter_Check(it)) {
1152 PyErr_Format(PyExc_TypeError,
Philip Jenvey50add042011-11-06 16:37:52 -08001153 "'%.200s' object is not an iterator",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001154 it->ob_type->tp_name);
1155 return NULL;
1156 }
1157
1158 res = (*it->ob_type->tp_iternext)(it);
1159 if (res != NULL) {
1160 return res;
1161 } else if (def != NULL) {
1162 if (PyErr_Occurred()) {
1163 if(!PyErr_ExceptionMatches(PyExc_StopIteration))
1164 return NULL;
1165 PyErr_Clear();
1166 }
1167 Py_INCREF(def);
1168 return def;
1169 } else if (PyErr_Occurred()) {
1170 return NULL;
1171 } else {
1172 PyErr_SetNone(PyExc_StopIteration);
1173 return NULL;
1174 }
Georg Brandla18af4e2007-04-21 15:47:16 +00001175}
1176
1177PyDoc_STRVAR(next_doc,
1178"next(iterator[, default])\n\
1179\n\
1180Return the next item from the iterator. If default is given and the iterator\n\
1181is exhausted, it is returned instead of raising StopIteration.");
1182
1183
1184static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001185builtin_setattr(PyObject *self, PyObject *args)
Guido van Rossum33894be1992-01-27 16:53:09 +00001186{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001187 PyObject *v;
1188 PyObject *name;
1189 PyObject *value;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001190
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001191 if (!PyArg_UnpackTuple(args, "setattr", 3, 3, &v, &name, &value))
1192 return NULL;
1193 if (PyObject_SetAttr(v, name, value) != 0)
1194 return NULL;
1195 Py_INCREF(Py_None);
1196 return Py_None;
Guido van Rossum33894be1992-01-27 16:53:09 +00001197}
1198
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001199PyDoc_STRVAR(setattr_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001200"setattr(object, name, value)\n\
1201\n\
1202Set a named attribute on an object; setattr(x, 'y', v) is equivalent to\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001203``x.y = v''.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001204
1205
Guido van Rossum79f25d91997-04-29 20:08:16 +00001206static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001207builtin_delattr(PyObject *self, PyObject *args)
Guido van Rossum14144fc1994-08-29 12:53:40 +00001208{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001209 PyObject *v;
1210 PyObject *name;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001211
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001212 if (!PyArg_UnpackTuple(args, "delattr", 2, 2, &v, &name))
1213 return NULL;
1214 if (PyObject_SetAttr(v, name, (PyObject *)NULL) != 0)
1215 return NULL;
1216 Py_INCREF(Py_None);
1217 return Py_None;
Guido van Rossum14144fc1994-08-29 12:53:40 +00001218}
1219
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001220PyDoc_STRVAR(delattr_doc,
Guido van Rossumdf12a591998-11-23 22:13:04 +00001221"delattr(object, name)\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001222\n\
1223Delete a named attribute on an object; delattr(x, 'y') is equivalent to\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001224``del x.y''.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001225
1226
Guido van Rossum79f25d91997-04-29 20:08:16 +00001227static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001228builtin_hash(PyObject *self, PyObject *v)
Guido van Rossum9bfef441993-03-29 10:43:31 +00001229{
Benjamin Peterson8f67d082010-10-17 20:54:53 +00001230 Py_hash_t x;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001231
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001232 x = PyObject_Hash(v);
1233 if (x == -1)
1234 return NULL;
Benjamin Peterson8f67d082010-10-17 20:54:53 +00001235 return PyLong_FromSsize_t(x);
Guido van Rossum9bfef441993-03-29 10:43:31 +00001236}
1237
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001238PyDoc_STRVAR(hash_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001239"hash(object) -> integer\n\
1240\n\
1241Return a hash value for the object. Two objects with the same value have\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001242the same hash value. The reverse is not necessarily true, but likely.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001243
1244
Guido van Rossum79f25d91997-04-29 20:08:16 +00001245static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001246builtin_hex(PyObject *self, PyObject *v)
Guido van Rossum006bcd41991-10-24 14:54:44 +00001247{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001248 return PyNumber_ToBase(v, 16);
Guido van Rossum006bcd41991-10-24 14:54:44 +00001249}
1250
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001251PyDoc_STRVAR(hex_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001252"hex(number) -> string\n\
1253\n\
Alexander Belopolsky12338ab2011-04-07 00:15:33 -04001254Return the hexadecimal representation of an integer.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001255
1256
Guido van Rossum79f25d91997-04-29 20:08:16 +00001257static PyObject *
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001258builtin_iter(PyObject *self, PyObject *args)
1259{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001260 PyObject *v, *w = NULL;
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001261
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001262 if (!PyArg_UnpackTuple(args, "iter", 1, 2, &v, &w))
1263 return NULL;
1264 if (w == NULL)
1265 return PyObject_GetIter(v);
1266 if (!PyCallable_Check(v)) {
1267 PyErr_SetString(PyExc_TypeError,
1268 "iter(v, w): v must be callable");
1269 return NULL;
1270 }
1271 return PyCallIter_New(v, w);
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001272}
1273
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001274PyDoc_STRVAR(iter_doc,
Georg Brandld11ae5d2008-05-16 13:27:32 +00001275"iter(iterable) -> iterator\n\
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001276iter(callable, sentinel) -> iterator\n\
1277\n\
1278Get an iterator from an object. In the first form, the argument must\n\
1279supply its own iterator, or be a sequence.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001280In the second form, the callable is called until it returns the sentinel.");
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001281
1282
1283static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001284builtin_len(PyObject *self, PyObject *v)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001285{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001286 Py_ssize_t res;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001287
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001288 res = PyObject_Size(v);
1289 if (res < 0 && PyErr_Occurred())
1290 return NULL;
1291 return PyLong_FromSsize_t(res);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001292}
1293
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001294PyDoc_STRVAR(len_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001295"len(object) -> integer\n\
1296\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001297Return the number of items of a sequence or mapping.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001298
1299
Guido van Rossum79f25d91997-04-29 20:08:16 +00001300static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001301builtin_locals(PyObject *self)
Guido van Rossum872537c1995-07-07 22:43:42 +00001302{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001303 PyObject *d;
Guido van Rossum872537c1995-07-07 22:43:42 +00001304
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001305 d = PyEval_GetLocals();
1306 Py_XINCREF(d);
1307 return d;
Guido van Rossum872537c1995-07-07 22:43:42 +00001308}
1309
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001310PyDoc_STRVAR(locals_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001311"locals() -> dictionary\n\
1312\n\
Raymond Hettinger69bf8f32003-01-04 02:16:22 +00001313Update and return a dictionary containing the current scope's local variables.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001314
1315
Guido van Rossum79f25d91997-04-29 20:08:16 +00001316static PyObject *
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001317min_max(PyObject *args, PyObject *kwds, int op)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001318{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001319 PyObject *v, *it, *item, *val, *maxitem, *maxval, *keyfunc=NULL;
1320 const char *name = op == Py_LT ? "min" : "max";
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001321
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001322 if (PyTuple_Size(args) > 1)
1323 v = args;
1324 else if (!PyArg_UnpackTuple(args, (char *)name, 1, 1, &v))
1325 return NULL;
Tim Peters67d687a2002-04-29 21:27:32 +00001326
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001327 if (kwds != NULL && PyDict_Check(kwds) && PyDict_Size(kwds)) {
1328 keyfunc = PyDict_GetItemString(kwds, "key");
1329 if (PyDict_Size(kwds)!=1 || keyfunc == NULL) {
1330 PyErr_Format(PyExc_TypeError,
1331 "%s() got an unexpected keyword argument", name);
1332 return NULL;
1333 }
1334 Py_INCREF(keyfunc);
1335 }
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001336
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001337 it = PyObject_GetIter(v);
1338 if (it == NULL) {
1339 Py_XDECREF(keyfunc);
1340 return NULL;
1341 }
Tim Petersc3074532001-05-03 07:00:32 +00001342
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001343 maxitem = NULL; /* the result */
1344 maxval = NULL; /* the value associated with the result */
1345 while (( item = PyIter_Next(it) )) {
1346 /* get the value from the key function */
1347 if (keyfunc != NULL) {
1348 val = PyObject_CallFunctionObjArgs(keyfunc, item, NULL);
1349 if (val == NULL)
1350 goto Fail_it_item;
1351 }
1352 /* no key function; the value is the item */
1353 else {
1354 val = item;
1355 Py_INCREF(val);
1356 }
Tim Petersc3074532001-05-03 07:00:32 +00001357
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001358 /* maximum value and item are unset; set them */
1359 if (maxval == NULL) {
1360 maxitem = item;
1361 maxval = val;
1362 }
1363 /* maximum value and item are set; update them as necessary */
1364 else {
1365 int cmp = PyObject_RichCompareBool(val, maxval, op);
1366 if (cmp < 0)
1367 goto Fail_it_item_and_val;
1368 else if (cmp > 0) {
1369 Py_DECREF(maxval);
1370 Py_DECREF(maxitem);
1371 maxval = val;
1372 maxitem = item;
1373 }
1374 else {
1375 Py_DECREF(item);
1376 Py_DECREF(val);
1377 }
1378 }
1379 }
1380 if (PyErr_Occurred())
1381 goto Fail_it;
1382 if (maxval == NULL) {
1383 PyErr_Format(PyExc_ValueError,
1384 "%s() arg is an empty sequence", name);
1385 assert(maxitem == NULL);
1386 }
1387 else
1388 Py_DECREF(maxval);
1389 Py_DECREF(it);
1390 Py_XDECREF(keyfunc);
1391 return maxitem;
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001392
1393Fail_it_item_and_val:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001394 Py_DECREF(val);
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001395Fail_it_item:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001396 Py_DECREF(item);
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001397Fail_it:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001398 Py_XDECREF(maxval);
1399 Py_XDECREF(maxitem);
1400 Py_DECREF(it);
1401 Py_XDECREF(keyfunc);
1402 return NULL;
Guido van Rossum3f5da241990-12-20 15:06:42 +00001403}
1404
Guido van Rossum79f25d91997-04-29 20:08:16 +00001405static PyObject *
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001406builtin_min(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001407{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001408 return min_max(args, kwds, Py_LT);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001409}
1410
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001411PyDoc_STRVAR(min_doc,
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001412"min(iterable[, key=func]) -> value\n\
1413min(a, b, c, ...[, key=func]) -> value\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001414\n\
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001415With a single iterable argument, return its smallest item.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001416With two or more arguments, return the smallest argument.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001417
1418
Guido van Rossum79f25d91997-04-29 20:08:16 +00001419static PyObject *
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001420builtin_max(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001421{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001422 return min_max(args, kwds, Py_GT);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001423}
1424
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001425PyDoc_STRVAR(max_doc,
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001426"max(iterable[, key=func]) -> value\n\
1427max(a, b, c, ...[, key=func]) -> value\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001428\n\
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001429With a single iterable argument, return its largest item.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001430With two or more arguments, return the largest argument.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001431
1432
Guido van Rossum79f25d91997-04-29 20:08:16 +00001433static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001434builtin_oct(PyObject *self, PyObject *v)
Guido van Rossum006bcd41991-10-24 14:54:44 +00001435{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001436 return PyNumber_ToBase(v, 8);
Guido van Rossum006bcd41991-10-24 14:54:44 +00001437}
1438
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001439PyDoc_STRVAR(oct_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001440"oct(number) -> string\n\
1441\n\
Alexander Belopolsky12338ab2011-04-07 00:15:33 -04001442Return the octal representation of an integer.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001443
1444
Guido van Rossum79f25d91997-04-29 20:08:16 +00001445static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001446builtin_ord(PyObject *self, PyObject* obj)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001447{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001448 long ord;
1449 Py_ssize_t size;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001450
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001451 if (PyBytes_Check(obj)) {
1452 size = PyBytes_GET_SIZE(obj);
1453 if (size == 1) {
1454 ord = (long)((unsigned char)*PyBytes_AS_STRING(obj));
1455 return PyLong_FromLong(ord);
1456 }
1457 }
1458 else if (PyUnicode_Check(obj)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001459 if (PyUnicode_READY(obj) == -1)
1460 return NULL;
1461 size = PyUnicode_GET_LENGTH(obj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001462 if (size == 1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001463 ord = (long)PyUnicode_READ_CHAR(obj, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001464 return PyLong_FromLong(ord);
1465 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001466 }
1467 else if (PyByteArray_Check(obj)) {
1468 /* XXX Hopefully this is temporary */
1469 size = PyByteArray_GET_SIZE(obj);
1470 if (size == 1) {
1471 ord = (long)((unsigned char)*PyByteArray_AS_STRING(obj));
1472 return PyLong_FromLong(ord);
1473 }
1474 }
1475 else {
1476 PyErr_Format(PyExc_TypeError,
1477 "ord() expected string of length 1, but " \
1478 "%.200s found", obj->ob_type->tp_name);
1479 return NULL;
1480 }
Guido van Rossum09095f32000-03-10 23:00:52 +00001481
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001482 PyErr_Format(PyExc_TypeError,
1483 "ord() expected a character, "
1484 "but string of length %zd found",
1485 size);
1486 return NULL;
Guido van Rossum3f5da241990-12-20 15:06:42 +00001487}
1488
Guido van Rossum307fa8c2007-07-16 20:46:27 +00001489PyDoc_VAR(ord_doc) = PyDoc_STR(
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001490"ord(c) -> integer\n\
1491\n\
Guido van Rossum8ac004e2007-07-15 13:00:05 +00001492Return the integer ordinal of a one-character string."
Antoine Pitrouedc60182012-06-23 14:19:58 +02001493);
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001494
1495
Guido van Rossum79f25d91997-04-29 20:08:16 +00001496static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001497builtin_pow(PyObject *self, PyObject *args)
Guido van Rossum6a00cd81995-01-07 12:39:01 +00001498{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001499 PyObject *v, *w, *z = Py_None;
Guido van Rossum6a00cd81995-01-07 12:39:01 +00001500
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001501 if (!PyArg_UnpackTuple(args, "pow", 2, 3, &v, &w, &z))
1502 return NULL;
1503 return PyNumber_Power(v, w, z);
Guido van Rossumd4905451991-05-05 20:00:36 +00001504}
1505
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001506PyDoc_STRVAR(pow_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001507"pow(x, y[, z]) -> number\n\
1508\n\
1509With two arguments, equivalent to x**y. With three arguments,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001510equivalent to (x**y) % z, but may be more efficient (e.g. for longs).");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001511
1512
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001513
Guido van Rossum34343512006-11-30 22:13:52 +00001514static PyObject *
1515builtin_print(PyObject *self, PyObject *args, PyObject *kwds)
1516{
Georg Brandlbc3b6822012-01-13 19:41:25 +01001517 static char *kwlist[] = {"sep", "end", "file", "flush", 0};
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001518 static PyObject *dummy_args;
Georg Brandlbc3b6822012-01-13 19:41:25 +01001519 PyObject *sep = NULL, *end = NULL, *file = NULL, *flush = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001520 int i, err;
Guido van Rossum34343512006-11-30 22:13:52 +00001521
Benjamin Peterson00102562012-01-11 21:00:16 -05001522 if (dummy_args == NULL && !(dummy_args = PyTuple_New(0)))
Georg Brandlbc3b6822012-01-13 19:41:25 +01001523 return NULL;
1524 if (!PyArg_ParseTupleAndKeywords(dummy_args, kwds, "|OOOO:print",
1525 kwlist, &sep, &end, &file, &flush))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001526 return NULL;
1527 if (file == NULL || file == Py_None) {
1528 file = PySys_GetObject("stdout");
1529 /* sys.stdout may be None when FILE* stdout isn't connected */
1530 if (file == Py_None)
1531 Py_RETURN_NONE;
1532 }
Guido van Rossum34343512006-11-30 22:13:52 +00001533
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001534 if (sep == Py_None) {
1535 sep = NULL;
1536 }
1537 else if (sep && !PyUnicode_Check(sep)) {
1538 PyErr_Format(PyExc_TypeError,
1539 "sep must be None or a string, not %.200s",
1540 sep->ob_type->tp_name);
1541 return NULL;
1542 }
1543 if (end == Py_None) {
1544 end = NULL;
1545 }
1546 else if (end && !PyUnicode_Check(end)) {
1547 PyErr_Format(PyExc_TypeError,
1548 "end must be None or a string, not %.200s",
1549 end->ob_type->tp_name);
1550 return NULL;
1551 }
Guido van Rossum34343512006-11-30 22:13:52 +00001552
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001553 for (i = 0; i < PyTuple_Size(args); i++) {
1554 if (i > 0) {
1555 if (sep == NULL)
1556 err = PyFile_WriteString(" ", file);
1557 else
1558 err = PyFile_WriteObject(sep, file,
1559 Py_PRINT_RAW);
1560 if (err)
1561 return NULL;
1562 }
1563 err = PyFile_WriteObject(PyTuple_GetItem(args, i), file,
1564 Py_PRINT_RAW);
1565 if (err)
1566 return NULL;
1567 }
Guido van Rossum34343512006-11-30 22:13:52 +00001568
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001569 if (end == NULL)
1570 err = PyFile_WriteString("\n", file);
1571 else
1572 err = PyFile_WriteObject(end, file, Py_PRINT_RAW);
1573 if (err)
1574 return NULL;
Guido van Rossum34343512006-11-30 22:13:52 +00001575
Georg Brandlbc3b6822012-01-13 19:41:25 +01001576 if (flush != NULL) {
1577 PyObject *tmp;
1578 int do_flush = PyObject_IsTrue(flush);
1579 if (do_flush == -1)
1580 return NULL;
1581 else if (do_flush) {
1582 tmp = PyObject_CallMethod(file, "flush", "");
1583 if (tmp == NULL)
1584 return NULL;
1585 else
1586 Py_DECREF(tmp);
1587 }
1588 }
1589
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001590 Py_RETURN_NONE;
Guido van Rossum34343512006-11-30 22:13:52 +00001591}
1592
1593PyDoc_STRVAR(print_doc,
Georg Brandlcd5da7d2008-02-01 15:47:37 +00001594"print(value, ..., sep=' ', end='\\n', file=sys.stdout)\n\
Guido van Rossum34343512006-11-30 22:13:52 +00001595\n\
1596Prints the values to a stream, or to sys.stdout by default.\n\
1597Optional keyword arguments:\n\
1598file: a file-like object (stream); defaults to the current sys.stdout.\n\
1599sep: string inserted between values, default a space.\n\
1600end: string appended after the last value, default a newline.");
1601
1602
Guido van Rossuma88a0332007-02-26 16:59:55 +00001603static PyObject *
1604builtin_input(PyObject *self, PyObject *args)
1605{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001606 PyObject *promptarg = NULL;
1607 PyObject *fin = PySys_GetObject("stdin");
1608 PyObject *fout = PySys_GetObject("stdout");
1609 PyObject *ferr = PySys_GetObject("stderr");
1610 PyObject *tmp;
1611 long fd;
1612 int tty;
Guido van Rossuma88a0332007-02-26 16:59:55 +00001613
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001614 /* Parse arguments */
1615 if (!PyArg_UnpackTuple(args, "input", 0, 1, &promptarg))
1616 return NULL;
Guido van Rossuma88a0332007-02-26 16:59:55 +00001617
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001618 /* Check that stdin/out/err are intact */
1619 if (fin == NULL || fin == Py_None) {
1620 PyErr_SetString(PyExc_RuntimeError,
1621 "input(): lost sys.stdin");
1622 return NULL;
1623 }
1624 if (fout == NULL || fout == Py_None) {
1625 PyErr_SetString(PyExc_RuntimeError,
1626 "input(): lost sys.stdout");
1627 return NULL;
1628 }
1629 if (ferr == NULL || ferr == Py_None) {
1630 PyErr_SetString(PyExc_RuntimeError,
1631 "input(): lost sys.stderr");
1632 return NULL;
1633 }
Guido van Rossumeba76962007-05-27 09:13:28 +00001634
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001635 /* First of all, flush stderr */
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001636 tmp = _PyObject_CallMethodId(ferr, &PyId_flush, "");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001637 if (tmp == NULL)
1638 PyErr_Clear();
1639 else
1640 Py_DECREF(tmp);
Guido van Rossumeba76962007-05-27 09:13:28 +00001641
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001642 /* We should only use (GNU) readline if Python's sys.stdin and
1643 sys.stdout are the same as C's stdin and stdout, because we
1644 need to pass it those. */
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001645 tmp = _PyObject_CallMethodId(fin, &PyId_fileno, "");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001646 if (tmp == NULL) {
1647 PyErr_Clear();
1648 tty = 0;
1649 }
1650 else {
1651 fd = PyLong_AsLong(tmp);
1652 Py_DECREF(tmp);
1653 if (fd < 0 && PyErr_Occurred())
1654 return NULL;
1655 tty = fd == fileno(stdin) && isatty(fd);
1656 }
1657 if (tty) {
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001658 tmp = _PyObject_CallMethodId(fout, &PyId_fileno, "");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001659 if (tmp == NULL)
1660 PyErr_Clear();
1661 else {
1662 fd = PyLong_AsLong(tmp);
1663 Py_DECREF(tmp);
1664 if (fd < 0 && PyErr_Occurred())
1665 return NULL;
1666 tty = fd == fileno(stdout) && isatty(fd);
1667 }
1668 }
Guido van Rossumeba76962007-05-27 09:13:28 +00001669
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001670 /* If we're interactive, use (GNU) readline */
1671 if (tty) {
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001672 PyObject *po = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001673 char *prompt;
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001674 char *s = NULL;
1675 PyObject *stdin_encoding = NULL, *stdin_errors = NULL;
1676 PyObject *stdout_encoding = NULL, *stdout_errors = NULL;
1677 char *stdin_encoding_str, *stdin_errors_str;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001678 PyObject *result;
Victor Stinnerc0f1a1a2011-02-23 12:07:37 +00001679 size_t len;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02001680 _Py_IDENTIFIER(encoding);
Antoine Pitrou5ee9d8a2011-11-06 00:38:45 +01001681 _Py_IDENTIFIER(errors);
Martin v. Löwis4a7b5d52007-09-04 05:24:49 +00001682
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02001683 stdin_encoding = _PyObject_GetAttrId(fin, &PyId_encoding);
Antoine Pitrou5ee9d8a2011-11-06 00:38:45 +01001684 stdin_errors = _PyObject_GetAttrId(fin, &PyId_errors);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001685 if (!stdin_encoding || !stdin_errors)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001686 /* stdin is a text stream, so it must have an
1687 encoding. */
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001688 goto _readline_errors;
Victor Stinner306f0102010-05-19 01:06:22 +00001689 stdin_encoding_str = _PyUnicode_AsString(stdin_encoding);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001690 stdin_errors_str = _PyUnicode_AsString(stdin_errors);
1691 if (!stdin_encoding_str || !stdin_errors_str)
1692 goto _readline_errors;
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001693 tmp = _PyObject_CallMethodId(fout, &PyId_flush, "");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001694 if (tmp == NULL)
1695 PyErr_Clear();
1696 else
1697 Py_DECREF(tmp);
1698 if (promptarg != NULL) {
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001699 /* We have a prompt, encode it as stdout would */
1700 char *stdout_encoding_str, *stdout_errors_str;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001701 PyObject *stringpo;
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02001702 stdout_encoding = _PyObject_GetAttrId(fout, &PyId_encoding);
Antoine Pitrou5ee9d8a2011-11-06 00:38:45 +01001703 stdout_errors = _PyObject_GetAttrId(fout, &PyId_errors);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001704 if (!stdout_encoding || !stdout_errors)
1705 goto _readline_errors;
Victor Stinner306f0102010-05-19 01:06:22 +00001706 stdout_encoding_str = _PyUnicode_AsString(stdout_encoding);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001707 stdout_errors_str = _PyUnicode_AsString(stdout_errors);
1708 if (!stdout_encoding_str || !stdout_errors_str)
1709 goto _readline_errors;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001710 stringpo = PyObject_Str(promptarg);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001711 if (stringpo == NULL)
1712 goto _readline_errors;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001713 po = PyUnicode_AsEncodedString(stringpo,
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001714 stdout_encoding_str, stdout_errors_str);
1715 Py_CLEAR(stdout_encoding);
1716 Py_CLEAR(stdout_errors);
1717 Py_CLEAR(stringpo);
1718 if (po == NULL)
1719 goto _readline_errors;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001720 prompt = PyBytes_AsString(po);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001721 if (prompt == NULL)
1722 goto _readline_errors;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001723 }
1724 else {
1725 po = NULL;
1726 prompt = "";
1727 }
1728 s = PyOS_Readline(stdin, stdout, prompt);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001729 if (s == NULL) {
1730 if (!PyErr_Occurred())
1731 PyErr_SetNone(PyExc_KeyboardInterrupt);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001732 goto _readline_errors;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001733 }
Victor Stinnerc0f1a1a2011-02-23 12:07:37 +00001734
1735 len = strlen(s);
1736 if (len == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001737 PyErr_SetNone(PyExc_EOFError);
1738 result = NULL;
1739 }
Victor Stinnerc0f1a1a2011-02-23 12:07:37 +00001740 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001741 if (len > PY_SSIZE_T_MAX) {
1742 PyErr_SetString(PyExc_OverflowError,
1743 "input: input too long");
1744 result = NULL;
1745 }
1746 else {
Victor Stinnerc0f1a1a2011-02-23 12:07:37 +00001747 len--; /* strip trailing '\n' */
1748 if (len != 0 && s[len-1] == '\r')
1749 len--; /* strip trailing '\r' */
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001750 result = PyUnicode_Decode(s, len, stdin_encoding_str,
1751 stdin_errors_str);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001752 }
1753 }
1754 Py_DECREF(stdin_encoding);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001755 Py_DECREF(stdin_errors);
1756 Py_XDECREF(po);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001757 PyMem_FREE(s);
1758 return result;
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001759 _readline_errors:
1760 Py_XDECREF(stdin_encoding);
1761 Py_XDECREF(stdout_encoding);
1762 Py_XDECREF(stdin_errors);
1763 Py_XDECREF(stdout_errors);
1764 Py_XDECREF(po);
1765 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001766 }
Guido van Rossumeba76962007-05-27 09:13:28 +00001767
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001768 /* Fallback if we're not interactive */
1769 if (promptarg != NULL) {
1770 if (PyFile_WriteObject(promptarg, fout, Py_PRINT_RAW) != 0)
1771 return NULL;
1772 }
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001773 tmp = _PyObject_CallMethodId(fout, &PyId_flush, "");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001774 if (tmp == NULL)
1775 PyErr_Clear();
1776 else
1777 Py_DECREF(tmp);
1778 return PyFile_GetLine(fin, -1);
Guido van Rossuma88a0332007-02-26 16:59:55 +00001779}
1780
1781PyDoc_STRVAR(input_doc,
1782"input([prompt]) -> string\n\
1783\n\
1784Read a string from standard input. The trailing newline is stripped.\n\
1785If the user hits EOF (Unix: Ctl-D, Windows: Ctl-Z+Return), raise EOFError.\n\
1786On Unix, GNU readline is used if enabled. The prompt string, if given,\n\
1787is printed without a trailing newline before reading.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001788
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001789
Guido van Rossum79f25d91997-04-29 20:08:16 +00001790static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001791builtin_repr(PyObject *self, PyObject *v)
Guido van Rossumc89705d1992-11-26 08:54:07 +00001792{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001793 return PyObject_Repr(v);
Guido van Rossumc89705d1992-11-26 08:54:07 +00001794}
1795
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001796PyDoc_STRVAR(repr_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001797"repr(object) -> string\n\
1798\n\
1799Return the canonical string representation of the object.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001800For most object types, eval(repr(object)) == object.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001801
1802
Guido van Rossum79f25d91997-04-29 20:08:16 +00001803static PyObject *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001804builtin_round(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum9e51f9b1993-02-12 16:29:05 +00001805{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001806 static PyObject *round_str = NULL;
1807 PyObject *ndigits = NULL;
1808 static char *kwlist[] = {"number", "ndigits", 0};
1809 PyObject *number, *round;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001810
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001811 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|O:round",
1812 kwlist, &number, &ndigits))
1813 return NULL;
Alex Martelliae211f92007-08-22 23:21:33 +00001814
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001815 if (Py_TYPE(number)->tp_dict == NULL) {
1816 if (PyType_Ready(Py_TYPE(number)) < 0)
1817 return NULL;
1818 }
Guido van Rossum15d3d042007-08-24 02:02:45 +00001819
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001820 if (round_str == NULL) {
1821 round_str = PyUnicode_InternFromString("__round__");
1822 if (round_str == NULL)
1823 return NULL;
1824 }
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001825
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001826 round = _PyType_Lookup(Py_TYPE(number), round_str);
1827 if (round == NULL) {
1828 PyErr_Format(PyExc_TypeError,
1829 "type %.100s doesn't define __round__ method",
1830 Py_TYPE(number)->tp_name);
1831 return NULL;
1832 }
Alex Martelliae211f92007-08-22 23:21:33 +00001833
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001834 if (ndigits == NULL)
1835 return PyObject_CallFunction(round, "O", number);
1836 else
1837 return PyObject_CallFunction(round, "OO", number, ndigits);
Guido van Rossum9e51f9b1993-02-12 16:29:05 +00001838}
1839
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001840PyDoc_STRVAR(round_doc,
Mark Dickinson1124e712009-01-28 21:25:58 +00001841"round(number[, ndigits]) -> number\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001842\n\
1843Round a number to a given precision in decimal digits (default 0 digits).\n\
Mark Dickinson0d748c22008-07-05 11:29:03 +00001844This returns an int when called with one argument, otherwise the\n\
Georg Brandl809ddaa2008-07-01 20:39:59 +00001845same type as the number. ndigits may be negative.");
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001846
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001847
Raymond Hettinger64958a12003-12-17 20:43:33 +00001848static PyObject *
1849builtin_sorted(PyObject *self, PyObject *args, PyObject *kwds)
1850{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001851 PyObject *newlist, *v, *seq, *keyfunc=NULL, *newargs;
1852 PyObject *callable;
1853 static char *kwlist[] = {"iterable", "key", "reverse", 0};
1854 int reverse;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02001855 _Py_IDENTIFIER(sort);
Raymond Hettinger64958a12003-12-17 20:43:33 +00001856
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001857 /* args 1-3 should match listsort in Objects/listobject.c */
1858 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|Oi:sorted",
1859 kwlist, &seq, &keyfunc, &reverse))
1860 return NULL;
Raymond Hettinger64958a12003-12-17 20:43:33 +00001861
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001862 newlist = PySequence_List(seq);
1863 if (newlist == NULL)
1864 return NULL;
Raymond Hettinger64958a12003-12-17 20:43:33 +00001865
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02001866 callable = _PyObject_GetAttrId(newlist, &PyId_sort);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001867 if (callable == NULL) {
1868 Py_DECREF(newlist);
1869 return NULL;
1870 }
Georg Brandl99d7e4e2005-08-31 22:21:15 +00001871
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001872 newargs = PyTuple_GetSlice(args, 1, 4);
1873 if (newargs == NULL) {
1874 Py_DECREF(newlist);
1875 Py_DECREF(callable);
1876 return NULL;
1877 }
Raymond Hettinger64958a12003-12-17 20:43:33 +00001878
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001879 v = PyObject_Call(callable, newargs, kwds);
1880 Py_DECREF(newargs);
1881 Py_DECREF(callable);
1882 if (v == NULL) {
1883 Py_DECREF(newlist);
1884 return NULL;
1885 }
1886 Py_DECREF(v);
1887 return newlist;
Raymond Hettinger64958a12003-12-17 20:43:33 +00001888}
1889
1890PyDoc_STRVAR(sorted_doc,
Raymond Hettinger70b64fc2008-01-30 20:15:17 +00001891"sorted(iterable, key=None, reverse=False) --> new sorted list");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001892
Guido van Rossum79f25d91997-04-29 20:08:16 +00001893static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001894builtin_vars(PyObject *self, PyObject *args)
Guido van Rossum2d951851994-08-29 12:52:16 +00001895{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001896 PyObject *v = NULL;
1897 PyObject *d;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001898
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001899 if (!PyArg_UnpackTuple(args, "vars", 0, 1, &v))
1900 return NULL;
1901 if (v == NULL) {
1902 d = PyEval_GetLocals();
1903 if (d == NULL) {
1904 if (!PyErr_Occurred())
1905 PyErr_SetString(PyExc_SystemError,
1906 "vars(): no locals!?");
1907 }
1908 else
1909 Py_INCREF(d);
1910 }
1911 else {
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02001912 _Py_IDENTIFIER(__dict__);
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02001913 d = _PyObject_GetAttrId(v, &PyId___dict__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001914 if (d == NULL) {
1915 PyErr_SetString(PyExc_TypeError,
1916 "vars() argument must have __dict__ attribute");
1917 return NULL;
1918 }
1919 }
1920 return d;
Guido van Rossum2d951851994-08-29 12:52:16 +00001921}
1922
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001923PyDoc_STRVAR(vars_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001924"vars([object]) -> dictionary\n\
1925\n\
1926Without arguments, equivalent to locals().\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001927With an argument, equivalent to object.__dict__.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001928
Alex Martellia70b1912003-04-22 08:12:33 +00001929static PyObject*
1930builtin_sum(PyObject *self, PyObject *args)
1931{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001932 PyObject *seq;
1933 PyObject *result = NULL;
1934 PyObject *temp, *item, *iter;
Alex Martellia70b1912003-04-22 08:12:33 +00001935
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001936 if (!PyArg_UnpackTuple(args, "sum", 1, 2, &seq, &result))
1937 return NULL;
Alex Martellia70b1912003-04-22 08:12:33 +00001938
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001939 iter = PyObject_GetIter(seq);
1940 if (iter == NULL)
1941 return NULL;
Alex Martellia70b1912003-04-22 08:12:33 +00001942
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001943 if (result == NULL) {
1944 result = PyLong_FromLong(0);
1945 if (result == NULL) {
1946 Py_DECREF(iter);
1947 return NULL;
1948 }
1949 } else {
1950 /* reject string values for 'start' parameter */
1951 if (PyUnicode_Check(result)) {
1952 PyErr_SetString(PyExc_TypeError,
1953 "sum() can't sum strings [use ''.join(seq) instead]");
1954 Py_DECREF(iter);
1955 return NULL;
1956 }
Benjamin Petersonce071ca2011-07-29 14:23:47 -05001957 if (PyBytes_Check(result)) {
1958 PyErr_SetString(PyExc_TypeError,
1959 "sum() can't sum bytes [use b''.join(seq) instead]");
Benjamin Peterson405f32c2011-07-29 22:43:45 -05001960 Py_DECREF(iter);
Benjamin Petersonce071ca2011-07-29 14:23:47 -05001961 return NULL;
1962 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001963 if (PyByteArray_Check(result)) {
1964 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson4f921c22011-07-29 14:24:29 -05001965 "sum() can't sum bytearray [use b''.join(seq) instead]");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001966 Py_DECREF(iter);
1967 return NULL;
1968 }
Guido van Rossum3172c5d2007-10-16 18:12:55 +00001969
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001970 Py_INCREF(result);
1971 }
Alex Martellia70b1912003-04-22 08:12:33 +00001972
Guido van Rossum8ce8a782007-11-01 19:42:39 +00001973#ifndef SLOW_SUM
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001974 /* Fast addition by keeping temporary sums in C instead of new Python objects.
1975 Assumes all inputs are the same type. If the assumption fails, default
1976 to the more general routine.
1977 */
1978 if (PyLong_CheckExact(result)) {
1979 int overflow;
1980 long i_result = PyLong_AsLongAndOverflow(result, &overflow);
1981 /* If this already overflowed, don't even enter the loop. */
1982 if (overflow == 0) {
1983 Py_DECREF(result);
1984 result = NULL;
1985 }
1986 while(result == NULL) {
1987 item = PyIter_Next(iter);
1988 if (item == NULL) {
1989 Py_DECREF(iter);
1990 if (PyErr_Occurred())
1991 return NULL;
1992 return PyLong_FromLong(i_result);
1993 }
1994 if (PyLong_CheckExact(item)) {
1995 long b = PyLong_AsLongAndOverflow(item, &overflow);
1996 long x = i_result + b;
1997 if (overflow == 0 && ((x^i_result) >= 0 || (x^b) >= 0)) {
1998 i_result = x;
1999 Py_DECREF(item);
2000 continue;
2001 }
2002 }
2003 /* Either overflowed or is not an int. Restore real objects and process normally */
2004 result = PyLong_FromLong(i_result);
2005 temp = PyNumber_Add(result, item);
2006 Py_DECREF(result);
2007 Py_DECREF(item);
2008 result = temp;
2009 if (result == NULL) {
2010 Py_DECREF(iter);
2011 return NULL;
2012 }
2013 }
2014 }
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002015
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002016 if (PyFloat_CheckExact(result)) {
2017 double f_result = PyFloat_AS_DOUBLE(result);
2018 Py_DECREF(result);
2019 result = NULL;
2020 while(result == NULL) {
2021 item = PyIter_Next(iter);
2022 if (item == NULL) {
2023 Py_DECREF(iter);
2024 if (PyErr_Occurred())
2025 return NULL;
2026 return PyFloat_FromDouble(f_result);
2027 }
2028 if (PyFloat_CheckExact(item)) {
2029 PyFPE_START_PROTECT("add", Py_DECREF(item); Py_DECREF(iter); return 0)
2030 f_result += PyFloat_AS_DOUBLE(item);
2031 PyFPE_END_PROTECT(f_result)
2032 Py_DECREF(item);
2033 continue;
2034 }
2035 if (PyLong_CheckExact(item)) {
2036 long value;
2037 int overflow;
2038 value = PyLong_AsLongAndOverflow(item, &overflow);
2039 if (!overflow) {
2040 PyFPE_START_PROTECT("add", Py_DECREF(item); Py_DECREF(iter); return 0)
2041 f_result += (double)value;
2042 PyFPE_END_PROTECT(f_result)
2043 Py_DECREF(item);
2044 continue;
2045 }
2046 }
2047 result = PyFloat_FromDouble(f_result);
2048 temp = PyNumber_Add(result, item);
2049 Py_DECREF(result);
2050 Py_DECREF(item);
2051 result = temp;
2052 if (result == NULL) {
2053 Py_DECREF(iter);
2054 return NULL;
2055 }
2056 }
2057 }
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002058#endif
2059
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002060 for(;;) {
2061 item = PyIter_Next(iter);
2062 if (item == NULL) {
2063 /* error, or end-of-sequence */
2064 if (PyErr_Occurred()) {
2065 Py_DECREF(result);
2066 result = NULL;
2067 }
2068 break;
2069 }
2070 /* It's tempting to use PyNumber_InPlaceAdd instead of
2071 PyNumber_Add here, to avoid quadratic running time
2072 when doing 'sum(list_of_lists, [])'. However, this
2073 would produce a change in behaviour: a snippet like
Mark Dickinson9acadc52009-10-26 14:19:42 +00002074
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002075 empty = []
2076 sum([[x] for x in range(10)], empty)
Mark Dickinson9acadc52009-10-26 14:19:42 +00002077
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002078 would change the value of empty. */
2079 temp = PyNumber_Add(result, item);
2080 Py_DECREF(result);
2081 Py_DECREF(item);
2082 result = temp;
2083 if (result == NULL)
2084 break;
2085 }
2086 Py_DECREF(iter);
2087 return result;
Alex Martellia70b1912003-04-22 08:12:33 +00002088}
2089
2090PyDoc_STRVAR(sum_doc,
Georg Brandld11ae5d2008-05-16 13:27:32 +00002091"sum(iterable[, start]) -> value\n\
Alex Martellia70b1912003-04-22 08:12:33 +00002092\n\
Georg Brandld11ae5d2008-05-16 13:27:32 +00002093Returns the sum of an iterable of numbers (NOT strings) plus the value\n\
2094of parameter 'start' (which defaults to 0). When the iterable is\n\
Thomas Wouters89f507f2006-12-13 04:49:30 +00002095empty, returns start.");
Alex Martellia70b1912003-04-22 08:12:33 +00002096
2097
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002098static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002099builtin_isinstance(PyObject *self, PyObject *args)
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002100{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002101 PyObject *inst;
2102 PyObject *cls;
2103 int retval;
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002104
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002105 if (!PyArg_UnpackTuple(args, "isinstance", 2, 2, &inst, &cls))
2106 return NULL;
Guido van Rossumf5dd9141997-12-02 19:11:45 +00002107
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002108 retval = PyObject_IsInstance(inst, cls);
2109 if (retval < 0)
2110 return NULL;
2111 return PyBool_FromLong(retval);
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002112}
2113
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002114PyDoc_STRVAR(isinstance_doc,
Guido van Rossum77f6a652002-04-03 22:41:51 +00002115"isinstance(object, class-or-type-or-tuple) -> bool\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002116\n\
2117Return whether an object is an instance of a class or of a subclass thereof.\n\
Guido van Rossum03290ec2001-10-07 20:54:12 +00002118With a type as second argument, return whether that is the object's type.\n\
2119The form using a tuple, isinstance(x, (A, B, ...)), is a shortcut for\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002120isinstance(x, A) or isinstance(x, B) or ... (etc.).");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002121
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002122
2123static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002124builtin_issubclass(PyObject *self, PyObject *args)
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002125{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002126 PyObject *derived;
2127 PyObject *cls;
2128 int retval;
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002129
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002130 if (!PyArg_UnpackTuple(args, "issubclass", 2, 2, &derived, &cls))
2131 return NULL;
Guido van Rossum668213d1999-06-16 17:28:37 +00002132
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002133 retval = PyObject_IsSubclass(derived, cls);
2134 if (retval < 0)
2135 return NULL;
2136 return PyBool_FromLong(retval);
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002137}
2138
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002139PyDoc_STRVAR(issubclass_doc,
Guido van Rossum77f6a652002-04-03 22:41:51 +00002140"issubclass(C, B) -> bool\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002141\n\
Walter Dörwaldd9a6ad32002-12-12 16:41:44 +00002142Return whether class C is a subclass (i.e., a derived class) of class B.\n\
2143When using a tuple as the second argument issubclass(X, (A, B, ...)),\n\
2144is a shortcut for issubclass(X, A) or issubclass(X, B) or ... (etc.).");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002145
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002146
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002147typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002148 PyObject_HEAD
2149 Py_ssize_t tuplesize;
2150 PyObject *ittuple; /* tuple of iterators */
2151 PyObject *result;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002152} zipobject;
2153
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002154static PyObject *
2155zip_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
Barry Warsawbd599b52000-08-03 15:45:29 +00002156{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002157 zipobject *lz;
2158 Py_ssize_t i;
2159 PyObject *ittuple; /* tuple of iterators */
2160 PyObject *result;
2161 Py_ssize_t tuplesize = PySequence_Length(args);
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002162
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002163 if (type == &PyZip_Type && !_PyArg_NoKeywords("zip()", kwds))
2164 return NULL;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002165
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002166 /* args must be a tuple */
2167 assert(PyTuple_Check(args));
Barry Warsawbd599b52000-08-03 15:45:29 +00002168
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002169 /* obtain iterators */
2170 ittuple = PyTuple_New(tuplesize);
2171 if (ittuple == NULL)
2172 return NULL;
2173 for (i=0; i < tuplesize; ++i) {
2174 PyObject *item = PyTuple_GET_ITEM(args, i);
2175 PyObject *it = PyObject_GetIter(item);
2176 if (it == NULL) {
2177 if (PyErr_ExceptionMatches(PyExc_TypeError))
2178 PyErr_Format(PyExc_TypeError,
2179 "zip argument #%zd must support iteration",
2180 i+1);
2181 Py_DECREF(ittuple);
2182 return NULL;
2183 }
2184 PyTuple_SET_ITEM(ittuple, i, it);
2185 }
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002186
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002187 /* create a result holder */
2188 result = PyTuple_New(tuplesize);
2189 if (result == NULL) {
2190 Py_DECREF(ittuple);
2191 return NULL;
2192 }
2193 for (i=0 ; i < tuplesize ; i++) {
2194 Py_INCREF(Py_None);
2195 PyTuple_SET_ITEM(result, i, Py_None);
2196 }
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002197
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002198 /* create zipobject structure */
2199 lz = (zipobject *)type->tp_alloc(type, 0);
2200 if (lz == NULL) {
2201 Py_DECREF(ittuple);
2202 Py_DECREF(result);
2203 return NULL;
2204 }
2205 lz->ittuple = ittuple;
2206 lz->tuplesize = tuplesize;
2207 lz->result = result;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002208
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002209 return (PyObject *)lz;
Barry Warsawbd599b52000-08-03 15:45:29 +00002210}
2211
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002212static void
2213zip_dealloc(zipobject *lz)
2214{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002215 PyObject_GC_UnTrack(lz);
2216 Py_XDECREF(lz->ittuple);
2217 Py_XDECREF(lz->result);
2218 Py_TYPE(lz)->tp_free(lz);
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002219}
2220
2221static int
2222zip_traverse(zipobject *lz, visitproc visit, void *arg)
2223{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002224 Py_VISIT(lz->ittuple);
2225 Py_VISIT(lz->result);
2226 return 0;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002227}
2228
2229static PyObject *
2230zip_next(zipobject *lz)
2231{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002232 Py_ssize_t i;
2233 Py_ssize_t tuplesize = lz->tuplesize;
2234 PyObject *result = lz->result;
2235 PyObject *it;
2236 PyObject *item;
2237 PyObject *olditem;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002238
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002239 if (tuplesize == 0)
2240 return NULL;
2241 if (Py_REFCNT(result) == 1) {
2242 Py_INCREF(result);
2243 for (i=0 ; i < tuplesize ; i++) {
2244 it = PyTuple_GET_ITEM(lz->ittuple, i);
2245 item = (*Py_TYPE(it)->tp_iternext)(it);
2246 if (item == NULL) {
2247 Py_DECREF(result);
2248 return NULL;
2249 }
2250 olditem = PyTuple_GET_ITEM(result, i);
2251 PyTuple_SET_ITEM(result, i, item);
2252 Py_DECREF(olditem);
2253 }
2254 } else {
2255 result = PyTuple_New(tuplesize);
2256 if (result == NULL)
2257 return NULL;
2258 for (i=0 ; i < tuplesize ; i++) {
2259 it = PyTuple_GET_ITEM(lz->ittuple, i);
2260 item = (*Py_TYPE(it)->tp_iternext)(it);
2261 if (item == NULL) {
2262 Py_DECREF(result);
2263 return NULL;
2264 }
2265 PyTuple_SET_ITEM(result, i, item);
2266 }
2267 }
2268 return result;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002269}
Barry Warsawbd599b52000-08-03 15:45:29 +00002270
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002271static PyObject *
2272zip_reduce(zipobject *lz)
2273{
2274 /* Just recreate the zip with the internal iterator tuple */
2275 return Py_BuildValue("OO", Py_TYPE(lz), lz->ittuple);
2276}
2277
2278static PyMethodDef zip_methods[] = {
2279 {"__reduce__", (PyCFunction)zip_reduce, METH_NOARGS, reduce_doc},
2280 {NULL, NULL} /* sentinel */
2281};
2282
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002283PyDoc_STRVAR(zip_doc,
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002284"zip(iter1 [,iter2 [...]]) --> zip object\n\
Barry Warsawbd599b52000-08-03 15:45:29 +00002285\n\
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002286Return a zip object whose .__next__() method returns a tuple where\n\
2287the i-th element comes from the i-th iterable argument. The .__next__()\n\
2288method continues until the shortest iterable in the argument sequence\n\
Georg Brandlced51db2008-12-04 18:28:38 +00002289is exhausted and then it raises StopIteration.");
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002290
2291PyTypeObject PyZip_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002292 PyVarObject_HEAD_INIT(&PyType_Type, 0)
2293 "zip", /* tp_name */
2294 sizeof(zipobject), /* tp_basicsize */
2295 0, /* tp_itemsize */
2296 /* methods */
2297 (destructor)zip_dealloc, /* tp_dealloc */
2298 0, /* tp_print */
2299 0, /* tp_getattr */
2300 0, /* tp_setattr */
2301 0, /* tp_reserved */
2302 0, /* tp_repr */
2303 0, /* tp_as_number */
2304 0, /* tp_as_sequence */
2305 0, /* tp_as_mapping */
2306 0, /* tp_hash */
2307 0, /* tp_call */
2308 0, /* tp_str */
2309 PyObject_GenericGetAttr, /* tp_getattro */
2310 0, /* tp_setattro */
2311 0, /* tp_as_buffer */
2312 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
2313 Py_TPFLAGS_BASETYPE, /* tp_flags */
2314 zip_doc, /* tp_doc */
2315 (traverseproc)zip_traverse, /* tp_traverse */
2316 0, /* tp_clear */
2317 0, /* tp_richcompare */
2318 0, /* tp_weaklistoffset */
2319 PyObject_SelfIter, /* tp_iter */
2320 (iternextfunc)zip_next, /* tp_iternext */
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002321 zip_methods, /* tp_methods */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002322 0, /* tp_members */
2323 0, /* tp_getset */
2324 0, /* tp_base */
2325 0, /* tp_dict */
2326 0, /* tp_descr_get */
2327 0, /* tp_descr_set */
2328 0, /* tp_dictoffset */
2329 0, /* tp_init */
2330 PyType_GenericAlloc, /* tp_alloc */
2331 zip_new, /* tp_new */
2332 PyObject_GC_Del, /* tp_free */
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002333};
Barry Warsawbd599b52000-08-03 15:45:29 +00002334
2335
Guido van Rossum79f25d91997-04-29 20:08:16 +00002336static PyMethodDef builtin_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002337 {"__build_class__", (PyCFunction)builtin___build_class__,
2338 METH_VARARGS | METH_KEYWORDS, build_class_doc},
2339 {"__import__", (PyCFunction)builtin___import__, METH_VARARGS | METH_KEYWORDS, import_doc},
2340 {"abs", builtin_abs, METH_O, abs_doc},
2341 {"all", builtin_all, METH_O, all_doc},
2342 {"any", builtin_any, METH_O, any_doc},
2343 {"ascii", builtin_ascii, METH_O, ascii_doc},
2344 {"bin", builtin_bin, METH_O, bin_doc},
Antoine Pitroue71362d2010-11-27 22:00:11 +00002345 {"callable", builtin_callable, METH_O, callable_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002346 {"chr", builtin_chr, METH_VARARGS, chr_doc},
2347 {"compile", (PyCFunction)builtin_compile, METH_VARARGS | METH_KEYWORDS, compile_doc},
2348 {"delattr", builtin_delattr, METH_VARARGS, delattr_doc},
2349 {"dir", builtin_dir, METH_VARARGS, dir_doc},
2350 {"divmod", builtin_divmod, METH_VARARGS, divmod_doc},
2351 {"eval", builtin_eval, METH_VARARGS, eval_doc},
2352 {"exec", builtin_exec, METH_VARARGS, exec_doc},
2353 {"format", builtin_format, METH_VARARGS, format_doc},
2354 {"getattr", builtin_getattr, METH_VARARGS, getattr_doc},
2355 {"globals", (PyCFunction)builtin_globals, METH_NOARGS, globals_doc},
2356 {"hasattr", builtin_hasattr, METH_VARARGS, hasattr_doc},
2357 {"hash", builtin_hash, METH_O, hash_doc},
2358 {"hex", builtin_hex, METH_O, hex_doc},
2359 {"id", builtin_id, METH_O, id_doc},
2360 {"input", builtin_input, METH_VARARGS, input_doc},
2361 {"isinstance", builtin_isinstance, METH_VARARGS, isinstance_doc},
2362 {"issubclass", builtin_issubclass, METH_VARARGS, issubclass_doc},
2363 {"iter", builtin_iter, METH_VARARGS, iter_doc},
2364 {"len", builtin_len, METH_O, len_doc},
2365 {"locals", (PyCFunction)builtin_locals, METH_NOARGS, locals_doc},
2366 {"max", (PyCFunction)builtin_max, METH_VARARGS | METH_KEYWORDS, max_doc},
2367 {"min", (PyCFunction)builtin_min, METH_VARARGS | METH_KEYWORDS, min_doc},
2368 {"next", (PyCFunction)builtin_next, METH_VARARGS, next_doc},
2369 {"oct", builtin_oct, METH_O, oct_doc},
2370 {"ord", builtin_ord, METH_O, ord_doc},
2371 {"pow", builtin_pow, METH_VARARGS, pow_doc},
2372 {"print", (PyCFunction)builtin_print, METH_VARARGS | METH_KEYWORDS, print_doc},
2373 {"repr", builtin_repr, METH_O, repr_doc},
2374 {"round", (PyCFunction)builtin_round, METH_VARARGS | METH_KEYWORDS, round_doc},
2375 {"setattr", builtin_setattr, METH_VARARGS, setattr_doc},
2376 {"sorted", (PyCFunction)builtin_sorted, METH_VARARGS | METH_KEYWORDS, sorted_doc},
2377 {"sum", builtin_sum, METH_VARARGS, sum_doc},
2378 {"vars", builtin_vars, METH_VARARGS, vars_doc},
2379 {NULL, NULL},
Guido van Rossum3f5da241990-12-20 15:06:42 +00002380};
2381
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002382PyDoc_STRVAR(builtin_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002383"Built-in functions, exceptions, and other objects.\n\
2384\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002385Noteworthy: None is the `nil' object; Ellipsis represents `...' in slices.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002386
Martin v. Löwis1a214512008-06-11 05:26:20 +00002387static struct PyModuleDef builtinsmodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002388 PyModuleDef_HEAD_INIT,
2389 "builtins",
2390 builtin_doc,
2391 -1, /* multiple "initialization" just copies the module dict. */
2392 builtin_methods,
2393 NULL,
2394 NULL,
2395 NULL,
2396 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00002397};
2398
2399
Guido van Rossum25ce5661997-08-02 03:10:38 +00002400PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002401_PyBuiltin_Init(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +00002402{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002403 PyObject *mod, *dict, *debug;
2404 mod = PyModule_Create(&builtinsmodule);
2405 if (mod == NULL)
2406 return NULL;
2407 dict = PyModule_GetDict(mod);
Tim Peters4b7625e2001-09-13 21:37:17 +00002408
Tim Peters7571a0f2003-03-23 17:52:28 +00002409#ifdef Py_TRACE_REFS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002410 /* "builtins" exposes a number of statically allocated objects
2411 * that, before this code was added in 2.3, never showed up in
2412 * the list of "all objects" maintained by Py_TRACE_REFS. As a
2413 * result, programs leaking references to None and False (etc)
2414 * couldn't be diagnosed by examining sys.getobjects(0).
2415 */
Tim Peters7571a0f2003-03-23 17:52:28 +00002416#define ADD_TO_ALL(OBJECT) _Py_AddToAllObjects((PyObject *)(OBJECT), 0)
2417#else
2418#define ADD_TO_ALL(OBJECT) (void)0
2419#endif
2420
Tim Peters4b7625e2001-09-13 21:37:17 +00002421#define SETBUILTIN(NAME, OBJECT) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002422 if (PyDict_SetItemString(dict, NAME, (PyObject *)OBJECT) < 0) \
2423 return NULL; \
2424 ADD_TO_ALL(OBJECT)
Tim Peters4b7625e2001-09-13 21:37:17 +00002425
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002426 SETBUILTIN("None", Py_None);
2427 SETBUILTIN("Ellipsis", Py_Ellipsis);
2428 SETBUILTIN("NotImplemented", Py_NotImplemented);
2429 SETBUILTIN("False", Py_False);
2430 SETBUILTIN("True", Py_True);
2431 SETBUILTIN("bool", &PyBool_Type);
2432 SETBUILTIN("memoryview", &PyMemoryView_Type);
2433 SETBUILTIN("bytearray", &PyByteArray_Type);
2434 SETBUILTIN("bytes", &PyBytes_Type);
2435 SETBUILTIN("classmethod", &PyClassMethod_Type);
2436 SETBUILTIN("complex", &PyComplex_Type);
2437 SETBUILTIN("dict", &PyDict_Type);
2438 SETBUILTIN("enumerate", &PyEnum_Type);
2439 SETBUILTIN("filter", &PyFilter_Type);
2440 SETBUILTIN("float", &PyFloat_Type);
2441 SETBUILTIN("frozenset", &PyFrozenSet_Type);
2442 SETBUILTIN("property", &PyProperty_Type);
2443 SETBUILTIN("int", &PyLong_Type);
2444 SETBUILTIN("list", &PyList_Type);
2445 SETBUILTIN("map", &PyMap_Type);
2446 SETBUILTIN("object", &PyBaseObject_Type);
2447 SETBUILTIN("range", &PyRange_Type);
2448 SETBUILTIN("reversed", &PyReversed_Type);
2449 SETBUILTIN("set", &PySet_Type);
2450 SETBUILTIN("slice", &PySlice_Type);
2451 SETBUILTIN("staticmethod", &PyStaticMethod_Type);
2452 SETBUILTIN("str", &PyUnicode_Type);
2453 SETBUILTIN("super", &PySuper_Type);
2454 SETBUILTIN("tuple", &PyTuple_Type);
2455 SETBUILTIN("type", &PyType_Type);
2456 SETBUILTIN("zip", &PyZip_Type);
2457 debug = PyBool_FromLong(Py_OptimizeFlag == 0);
2458 if (PyDict_SetItemString(dict, "__debug__", debug) < 0) {
2459 Py_XDECREF(debug);
2460 return NULL;
2461 }
2462 Py_XDECREF(debug);
Barry Warsaw757af0e1997-08-29 22:13:51 +00002463
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002464 return mod;
Tim Peters7571a0f2003-03-23 17:52:28 +00002465#undef ADD_TO_ALL
Tim Peters4b7625e2001-09-13 21:37:17 +00002466#undef SETBUILTIN
Guido van Rossum3f5da241990-12-20 15:06:42 +00002467}