blob: a2fb1d9a7758eb80e7e16aba5180689d741d28b7 [file] [log] [blame]
Guido van Rossum3f5da241990-12-20 15:06:42 +00001/* Built-in functions */
2
Guido van Rossum79f25d91997-04-29 20:08:16 +00003#include "Python.h"
Martin v. Löwis618dc5e2008-03-30 20:03:44 +00004#include "Python-ast.h"
Guido van Rossum3f5da241990-12-20 15:06:42 +00005
6#include "node.h"
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00007#include "code.h"
Guido van Rossum3f5da241990-12-20 15:06:42 +00008
Benjamin Petersonea281a52011-08-12 23:10:50 -05009#include "asdl.h"
10#include "ast.h"
11
Guido van Rossum6bf62da1997-04-11 20:37:35 +000012#include <ctype.h>
13
Victor Stinnerb744ba12010-05-15 12:27:16 +000014#ifdef HAVE_LANGINFO_H
15#include <langinfo.h> /* CODESET */
16#endif
17
Mark Hammond26cffde42001-05-14 12:17:34 +000018/* The default encoding used by the platform file system APIs
19 Can remain NULL for all platforms that don't have such a concept
Guido van Rossum00bc0e02007-10-15 02:52:41 +000020
21 Don't forget to modify PyUnicode_DecodeFSDefault() if you touch any of the
22 values for Py_FileSystemDefaultEncoding!
Mark Hammond26cffde42001-05-14 12:17:34 +000023*/
Victor Stinner99b95382011-07-04 14:23:54 +020024#ifdef HAVE_MBCS
Mark Hammond26cffde42001-05-14 12:17:34 +000025const char *Py_FileSystemDefaultEncoding = "mbcs";
Martin v. Löwis04dc25c2008-10-03 16:09:28 +000026int Py_HasFileSystemDefaultEncoding = 1;
Just van Rossumb9b8e9c2003-02-10 09:22:01 +000027#elif defined(__APPLE__)
28const char *Py_FileSystemDefaultEncoding = "utf-8";
Martin v. Löwis04dc25c2008-10-03 16:09:28 +000029int Py_HasFileSystemDefaultEncoding = 1;
Victor Stinnerd64e8a72011-07-04 13:48:30 +020030#else
Victor Stinnerb744ba12010-05-15 12:27:16 +000031const char *Py_FileSystemDefaultEncoding = NULL; /* set by initfsencoding() */
Martin v. Löwis04dc25c2008-10-03 16:09:28 +000032int Py_HasFileSystemDefaultEncoding = 0;
Mark Hammond26cffde42001-05-14 12:17:34 +000033#endif
Mark Hammondef8b6542001-05-13 08:04:26 +000034
Martin v. Löwisbd928fe2011-10-14 10:20:37 +020035_Py_IDENTIFIER(fileno);
36_Py_IDENTIFIER(flush);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +020037
Guido van Rossum79f25d91997-04-29 20:08:16 +000038static PyObject *
Guido van Rossum52cc1d82007-03-18 15:41:51 +000039builtin___build_class__(PyObject *self, PyObject *args, PyObject *kwds)
40{
Nick Coghlande31b192011-10-23 22:04:16 +100041 PyObject *func, *name, *bases, *mkw, *meta, *winner, *prep, *ns, *cell;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000042 PyObject *cls = NULL;
Florent Xicluna4d46c2a2011-10-28 15:00:50 +020043 Py_ssize_t nargs;
Nick Coghlande31b192011-10-23 22:04:16 +100044 int isclass;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +020045 _Py_IDENTIFIER(__prepare__);
Guido van Rossum52cc1d82007-03-18 15:41:51 +000046
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000047 assert(args != NULL);
48 if (!PyTuple_Check(args)) {
49 PyErr_SetString(PyExc_TypeError,
50 "__build_class__: args is not a tuple");
51 return NULL;
52 }
53 nargs = PyTuple_GET_SIZE(args);
54 if (nargs < 2) {
55 PyErr_SetString(PyExc_TypeError,
56 "__build_class__: not enough arguments");
57 return NULL;
58 }
59 func = PyTuple_GET_ITEM(args, 0); /* Better be callable */
60 name = PyTuple_GET_ITEM(args, 1);
61 if (!PyUnicode_Check(name)) {
62 PyErr_SetString(PyExc_TypeError,
63 "__build_class__: name is not a string");
64 return NULL;
65 }
66 bases = PyTuple_GetSlice(args, 2, nargs);
67 if (bases == NULL)
68 return NULL;
Guido van Rossum52cc1d82007-03-18 15:41:51 +000069
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000070 if (kwds == NULL) {
71 meta = NULL;
72 mkw = NULL;
73 }
74 else {
75 mkw = PyDict_Copy(kwds); /* Don't modify kwds passed in! */
76 if (mkw == NULL) {
77 Py_DECREF(bases);
78 return NULL;
Guido van Rossum52cc1d82007-03-18 15:41:51 +000079 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000080 meta = PyDict_GetItemString(mkw, "metaclass");
81 if (meta != NULL) {
82 Py_INCREF(meta);
83 if (PyDict_DelItemString(mkw, "metaclass") < 0) {
84 Py_DECREF(meta);
85 Py_DECREF(mkw);
86 Py_DECREF(bases);
87 return NULL;
88 }
Nick Coghlande31b192011-10-23 22:04:16 +100089 /* metaclass is explicitly given, check if it's indeed a class */
90 isclass = PyType_Check(meta);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000091 }
92 }
93 if (meta == NULL) {
Nick Coghlande31b192011-10-23 22:04:16 +100094 /* if there are no bases, use type: */
95 if (PyTuple_GET_SIZE(bases) == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000096 meta = (PyObject *) (&PyType_Type);
Nick Coghlande31b192011-10-23 22:04:16 +100097 }
98 /* else get the type of the first base */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000099 else {
100 PyObject *base0 = PyTuple_GET_ITEM(bases, 0);
101 meta = (PyObject *) (base0->ob_type);
102 }
103 Py_INCREF(meta);
Nick Coghlande31b192011-10-23 22:04:16 +1000104 isclass = 1; /* meta is really a class */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000105 }
Nick Coghlan9715d262011-10-23 22:36:42 +1000106
Nick Coghlande31b192011-10-23 22:04:16 +1000107 if (isclass) {
108 /* meta is really a class, so check for a more derived
109 metaclass, or possible metaclass conflicts: */
110 winner = (PyObject *)_PyType_CalculateMetaclass((PyTypeObject *)meta,
111 bases);
112 if (winner == NULL) {
113 Py_DECREF(meta);
114 Py_XDECREF(mkw);
115 Py_DECREF(bases);
116 return NULL;
117 }
118 if (winner != meta) {
119 Py_DECREF(meta);
120 meta = winner;
121 Py_INCREF(meta);
122 }
123 }
124 /* else: meta is not a class, so we cannot do the metaclass
125 calculation, so we will use the explicitly given object as it is */
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +0200126 prep = _PyObject_GetAttrId(meta, &PyId___prepare__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000127 if (prep == NULL) {
128 if (PyErr_ExceptionMatches(PyExc_AttributeError)) {
129 PyErr_Clear();
130 ns = PyDict_New();
131 }
132 else {
133 Py_DECREF(meta);
134 Py_XDECREF(mkw);
135 Py_DECREF(bases);
136 return NULL;
137 }
138 }
139 else {
140 PyObject *pargs = PyTuple_Pack(2, name, bases);
141 if (pargs == NULL) {
142 Py_DECREF(prep);
143 Py_DECREF(meta);
144 Py_XDECREF(mkw);
145 Py_DECREF(bases);
146 return NULL;
147 }
148 ns = PyEval_CallObjectWithKeywords(prep, pargs, mkw);
149 Py_DECREF(pargs);
150 Py_DECREF(prep);
151 }
152 if (ns == NULL) {
153 Py_DECREF(meta);
154 Py_XDECREF(mkw);
155 Py_DECREF(bases);
156 return NULL;
157 }
158 cell = PyObject_CallFunctionObjArgs(func, ns, NULL);
159 if (cell != NULL) {
160 PyObject *margs;
161 margs = PyTuple_Pack(3, name, bases, ns);
162 if (margs != NULL) {
163 cls = PyEval_CallObjectWithKeywords(meta, margs, mkw);
164 Py_DECREF(margs);
165 }
166 if (cls != NULL && PyCell_Check(cell)) {
167 Py_INCREF(cls);
168 PyCell_SET(cell, cls);
169 }
170 Py_DECREF(cell);
171 }
172 Py_DECREF(ns);
173 Py_DECREF(meta);
174 Py_XDECREF(mkw);
175 Py_DECREF(bases);
176 return cls;
Guido van Rossum52cc1d82007-03-18 15:41:51 +0000177}
178
179PyDoc_STRVAR(build_class_doc,
180"__build_class__(func, name, *bases, metaclass=None, **kwds) -> class\n\
181\n\
182Internal helper function used by the class statement.");
183
184static PyObject *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000185builtin___import__(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000186{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000187 static char *kwlist[] = {"name", "globals", "locals", "fromlist",
188 "level", 0};
Victor Stinnerfe93faf2011-03-14 15:54:52 -0400189 PyObject *name, *globals = NULL, *locals = NULL, *fromlist = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000190 int level = -1;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000191
Victor Stinnerfe93faf2011-03-14 15:54:52 -0400192 if (!PyArg_ParseTupleAndKeywords(args, kwds, "U|OOOi:__import__",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000193 kwlist, &name, &globals, &locals, &fromlist, &level))
194 return NULL;
Victor Stinnerfe93faf2011-03-14 15:54:52 -0400195 return PyImport_ImportModuleLevelObject(name, globals, locals,
196 fromlist, level);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000197}
198
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000199PyDoc_STRVAR(import_doc,
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000200"__import__(name, globals={}, locals={}, fromlist=[], level=-1) -> module\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000201\n\
Brett Cannon5305a992010-09-27 21:08:38 +0000202Import a module. Because this function is meant for use by the Python\n\
203interpreter and not for general use it is better to use\n\
204importlib.import_module() to programmatically import a module.\n\
205\n\
206The globals argument is only used to determine the context;\n\
207they are not modified. The locals argument is unused. The fromlist\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000208should be a list of names to emulate ``from name import ...'', or an\n\
209empty list to emulate ``import name''.\n\
210When importing a module from a package, note that __import__('A.B', ...)\n\
211returns package A when fromlist is empty, but its submodule B when\n\
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000212fromlist is not empty. Level is used to determine whether to perform \n\
213absolute or relative imports. -1 is the original strategy of attempting\n\
214both absolute and relative imports, 0 is absolute, a positive number\n\
215is the number of parent directories to search relative to the current module.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000216
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000217
Guido van Rossum79f25d91997-04-29 20:08:16 +0000218static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000219builtin_abs(PyObject *self, PyObject *v)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000220{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000221 return PyNumber_Absolute(v);
Guido van Rossum3f5da241990-12-20 15:06:42 +0000222}
223
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000224PyDoc_STRVAR(abs_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000225"abs(number) -> number\n\
226\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000227Return the absolute value of the argument.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000228
Raymond Hettinger96229b12005-03-11 06:49:40 +0000229static PyObject *
230builtin_all(PyObject *self, PyObject *v)
231{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000232 PyObject *it, *item;
233 PyObject *(*iternext)(PyObject *);
234 int cmp;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000235
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000236 it = PyObject_GetIter(v);
237 if (it == NULL)
238 return NULL;
239 iternext = *Py_TYPE(it)->tp_iternext;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000240
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000241 for (;;) {
242 item = iternext(it);
243 if (item == NULL)
244 break;
245 cmp = PyObject_IsTrue(item);
246 Py_DECREF(item);
247 if (cmp < 0) {
248 Py_DECREF(it);
249 return NULL;
250 }
251 if (cmp == 0) {
252 Py_DECREF(it);
253 Py_RETURN_FALSE;
254 }
255 }
256 Py_DECREF(it);
257 if (PyErr_Occurred()) {
258 if (PyErr_ExceptionMatches(PyExc_StopIteration))
259 PyErr_Clear();
260 else
261 return NULL;
262 }
263 Py_RETURN_TRUE;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000264}
265
266PyDoc_STRVAR(all_doc,
267"all(iterable) -> bool\n\
268\n\
269Return True if bool(x) is True for all values x in the iterable.");
270
271static PyObject *
272builtin_any(PyObject *self, PyObject *v)
273{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000274 PyObject *it, *item;
275 PyObject *(*iternext)(PyObject *);
276 int cmp;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000277
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000278 it = PyObject_GetIter(v);
279 if (it == NULL)
280 return NULL;
281 iternext = *Py_TYPE(it)->tp_iternext;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000282
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000283 for (;;) {
284 item = iternext(it);
285 if (item == NULL)
286 break;
287 cmp = PyObject_IsTrue(item);
288 Py_DECREF(item);
289 if (cmp < 0) {
290 Py_DECREF(it);
291 return NULL;
292 }
293 if (cmp == 1) {
294 Py_DECREF(it);
295 Py_RETURN_TRUE;
296 }
297 }
298 Py_DECREF(it);
299 if (PyErr_Occurred()) {
300 if (PyErr_ExceptionMatches(PyExc_StopIteration))
301 PyErr_Clear();
302 else
303 return NULL;
304 }
305 Py_RETURN_FALSE;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000306}
307
308PyDoc_STRVAR(any_doc,
309"any(iterable) -> bool\n\
310\n\
311Return True if bool(x) is True for any x in the iterable.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000312
Georg Brandl559e5d72008-06-11 18:37:52 +0000313static PyObject *
314builtin_ascii(PyObject *self, PyObject *v)
315{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000316 return PyObject_ASCII(v);
Georg Brandl559e5d72008-06-11 18:37:52 +0000317}
318
319PyDoc_STRVAR(ascii_doc,
320"ascii(object) -> string\n\
321\n\
322As repr(), return a string containing a printable representation of an\n\
323object, but escape the non-ASCII characters in the string returned by\n\
324repr() using \\x, \\u or \\U escapes. This generates a string similar\n\
325to that returned by repr() in Python 2.");
326
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000327
Guido van Rossum79f25d91997-04-29 20:08:16 +0000328static PyObject *
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000329builtin_bin(PyObject *self, PyObject *v)
330{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000331 return PyNumber_ToBase(v, 2);
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000332}
333
334PyDoc_STRVAR(bin_doc,
335"bin(number) -> string\n\
336\n\
Alexander Belopolsky12338ab2011-04-07 00:15:33 -0400337Return the binary representation of an integer.");
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000338
339
Antoine Pitroue71362d2010-11-27 22:00:11 +0000340static PyObject *
341builtin_callable(PyObject *self, PyObject *v)
342{
343 return PyBool_FromLong((long)PyCallable_Check(v));
344}
345
346PyDoc_STRVAR(callable_doc,
347"callable(object) -> bool\n\
348\n\
349Return whether the object is callable (i.e., some kind of function).\n\
350Note that classes are callable, as are instances of classes with a\n\
351__call__() method.");
352
353
Raymond Hettinger17301e92008-03-13 00:19:26 +0000354typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000355 PyObject_HEAD
356 PyObject *func;
357 PyObject *it;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000358} filterobject;
359
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000360static PyObject *
Raymond Hettinger17301e92008-03-13 00:19:26 +0000361filter_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
Guido van Rossum12d12c51993-10-26 17:58:25 +0000362{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000363 PyObject *func, *seq;
364 PyObject *it;
365 filterobject *lz;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000366
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000367 if (type == &PyFilter_Type && !_PyArg_NoKeywords("filter()", kwds))
368 return NULL;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000369
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000370 if (!PyArg_UnpackTuple(args, "filter", 2, 2, &func, &seq))
371 return NULL;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000372
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000373 /* Get iterator. */
374 it = PyObject_GetIter(seq);
375 if (it == NULL)
376 return NULL;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000377
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000378 /* create filterobject structure */
379 lz = (filterobject *)type->tp_alloc(type, 0);
380 if (lz == NULL) {
381 Py_DECREF(it);
382 return NULL;
383 }
384 Py_INCREF(func);
385 lz->func = func;
386 lz->it = it;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000387
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000388 return (PyObject *)lz;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000389}
390
391static void
392filter_dealloc(filterobject *lz)
393{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000394 PyObject_GC_UnTrack(lz);
395 Py_XDECREF(lz->func);
396 Py_XDECREF(lz->it);
397 Py_TYPE(lz)->tp_free(lz);
Raymond Hettinger17301e92008-03-13 00:19:26 +0000398}
399
400static int
401filter_traverse(filterobject *lz, visitproc visit, void *arg)
402{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000403 Py_VISIT(lz->it);
404 Py_VISIT(lz->func);
405 return 0;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000406}
407
408static PyObject *
409filter_next(filterobject *lz)
410{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000411 PyObject *item;
412 PyObject *it = lz->it;
413 long ok;
414 PyObject *(*iternext)(PyObject *);
Raymond Hettinger17301e92008-03-13 00:19:26 +0000415
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000416 iternext = *Py_TYPE(it)->tp_iternext;
417 for (;;) {
418 item = iternext(it);
419 if (item == NULL)
420 return NULL;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000421
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000422 if (lz->func == Py_None || lz->func == (PyObject *)&PyBool_Type) {
423 ok = PyObject_IsTrue(item);
424 } else {
425 PyObject *good;
426 good = PyObject_CallFunctionObjArgs(lz->func,
427 item, NULL);
428 if (good == NULL) {
429 Py_DECREF(item);
430 return NULL;
431 }
432 ok = PyObject_IsTrue(good);
433 Py_DECREF(good);
434 }
435 if (ok)
436 return item;
437 Py_DECREF(item);
438 }
Guido van Rossum12d12c51993-10-26 17:58:25 +0000439}
440
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +0000441static PyObject *
442filter_reduce(filterobject *lz)
443{
444 return Py_BuildValue("O(OO)", Py_TYPE(lz), lz->func, lz->it);
445}
446
447PyDoc_STRVAR(reduce_doc, "Return state information for pickling.");
448
449static PyMethodDef filter_methods[] = {
450 {"__reduce__", (PyCFunction)filter_reduce, METH_NOARGS, reduce_doc},
451 {NULL, NULL} /* sentinel */
452};
453
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000454PyDoc_STRVAR(filter_doc,
Georg Brandld11ae5d2008-05-16 13:27:32 +0000455"filter(function or None, iterable) --> filter object\n\
Guido van Rossumc1f779c2007-07-03 08:25:58 +0000456\n\
Georg Brandld11ae5d2008-05-16 13:27:32 +0000457Return an iterator yielding those items of iterable for which function(item)\n\
Raymond Hettinger17301e92008-03-13 00:19:26 +0000458is true. If function is None, return the items that are true.");
459
460PyTypeObject PyFilter_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000461 PyVarObject_HEAD_INIT(&PyType_Type, 0)
462 "filter", /* tp_name */
463 sizeof(filterobject), /* tp_basicsize */
464 0, /* tp_itemsize */
465 /* methods */
466 (destructor)filter_dealloc, /* tp_dealloc */
467 0, /* tp_print */
468 0, /* tp_getattr */
469 0, /* tp_setattr */
470 0, /* tp_reserved */
471 0, /* tp_repr */
472 0, /* tp_as_number */
473 0, /* tp_as_sequence */
474 0, /* tp_as_mapping */
475 0, /* tp_hash */
476 0, /* tp_call */
477 0, /* tp_str */
478 PyObject_GenericGetAttr, /* tp_getattro */
479 0, /* tp_setattro */
480 0, /* tp_as_buffer */
481 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
482 Py_TPFLAGS_BASETYPE, /* tp_flags */
483 filter_doc, /* tp_doc */
484 (traverseproc)filter_traverse, /* tp_traverse */
485 0, /* tp_clear */
486 0, /* tp_richcompare */
487 0, /* tp_weaklistoffset */
488 PyObject_SelfIter, /* tp_iter */
489 (iternextfunc)filter_next, /* tp_iternext */
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +0000490 filter_methods, /* tp_methods */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000491 0, /* tp_members */
492 0, /* tp_getset */
493 0, /* tp_base */
494 0, /* tp_dict */
495 0, /* tp_descr_get */
496 0, /* tp_descr_set */
497 0, /* tp_dictoffset */
498 0, /* tp_init */
499 PyType_GenericAlloc, /* tp_alloc */
500 filter_new, /* tp_new */
501 PyObject_GC_Del, /* tp_free */
Raymond Hettinger17301e92008-03-13 00:19:26 +0000502};
503
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000504
Eric Smith8c663262007-08-25 02:26:07 +0000505static PyObject *
506builtin_format(PyObject *self, PyObject *args)
507{
Christian Heimes94b7d3d2007-12-11 20:20:39 +0000508 PyObject *value;
Eric Smith8fd3eba2008-02-17 19:48:00 +0000509 PyObject *format_spec = NULL;
Eric Smith8c663262007-08-25 02:26:07 +0000510
Eric Smith8fd3eba2008-02-17 19:48:00 +0000511 if (!PyArg_ParseTuple(args, "O|U:format", &value, &format_spec))
Benjamin Petersona12d5c62012-01-03 16:47:22 -0600512 return NULL;
Eric Smith8c663262007-08-25 02:26:07 +0000513
Eric Smith8fd3eba2008-02-17 19:48:00 +0000514 return PyObject_Format(value, format_spec);
Eric Smith8c663262007-08-25 02:26:07 +0000515}
516
Eric Smith8c663262007-08-25 02:26:07 +0000517PyDoc_STRVAR(format_doc,
Eric Smith81936692007-08-31 01:14:01 +0000518"format(value[, format_spec]) -> string\n\
Eric Smith8c663262007-08-25 02:26:07 +0000519\n\
Eric Smith81936692007-08-31 01:14:01 +0000520Returns value.__format__(format_spec)\n\
521format_spec defaults to \"\"");
522
Guido van Rossum7fcf2242007-05-04 17:43:11 +0000523static PyObject *
Walter Dörwalde7efd592007-06-05 20:07:21 +0000524builtin_chr(PyObject *self, PyObject *args)
Guido van Rossum09095f32000-03-10 23:00:52 +0000525{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000526 int x;
Guido van Rossum09095f32000-03-10 23:00:52 +0000527
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000528 if (!PyArg_ParseTuple(args, "i:chr", &x))
529 return NULL;
Fredrik Lundh0dcf67e2001-06-26 20:01:56 +0000530
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000531 return PyUnicode_FromOrdinal(x);
Guido van Rossum09095f32000-03-10 23:00:52 +0000532}
533
Victor Stinner63ab8752011-11-22 03:31:20 +0100534PyDoc_STRVAR(chr_doc,
Guido van Rossum84fc66d2007-05-03 17:18:26 +0000535"chr(i) -> Unicode character\n\
Guido van Rossum09095f32000-03-10 23:00:52 +0000536\n\
Victor Stinner63ab8752011-11-22 03:31:20 +0100537Return a Unicode string of one character with ordinal i; 0 <= i <= 0x10ffff.");
Guido van Rossum09095f32000-03-10 23:00:52 +0000538
539
Guido van Rossumf15a29f2007-05-04 00:41:39 +0000540static char *
Benjamin Petersonf5b52242009-03-02 23:31:26 +0000541source_as_string(PyObject *cmd, char *funcname, char *what, PyCompilerFlags *cf)
Guido van Rossumf15a29f2007-05-04 00:41:39 +0000542{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000543 char *str;
544 Py_ssize_t size;
Guido van Rossumf15a29f2007-05-04 00:41:39 +0000545
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000546 if (PyUnicode_Check(cmd)) {
547 cf->cf_flags |= PyCF_IGNORE_COOKIE;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200548 str = PyUnicode_AsUTF8AndSize(cmd, &size);
549 if (str == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000550 return NULL;
551 }
552 else if (!PyObject_CheckReadBuffer(cmd)) {
553 PyErr_Format(PyExc_TypeError,
554 "%s() arg 1 must be a %s object",
555 funcname, what);
556 return NULL;
557 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200558 else if (PyObject_AsReadBuffer(cmd, (const void **)&str, &size) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000559 return NULL;
560 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200561
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000562 if (strlen(str) != size) {
563 PyErr_SetString(PyExc_TypeError,
564 "source code string cannot contain null bytes");
565 return NULL;
566 }
567 return str;
Guido van Rossumf15a29f2007-05-04 00:41:39 +0000568}
569
Guido van Rossum79f25d91997-04-29 20:08:16 +0000570static PyObject *
Guido van Rossumd8faa362007-04-27 19:54:29 +0000571builtin_compile(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum5b722181993-03-30 17:46:03 +0000572{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000573 char *str;
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000574 PyObject *filename_obj;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000575 char *filename;
576 char *startstr;
577 int mode = -1;
578 int dont_inherit = 0;
579 int supplied_flags = 0;
Georg Brandl8334fd92010-12-04 10:26:46 +0000580 int optimize = -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000581 int is_ast;
582 PyCompilerFlags cf;
583 PyObject *cmd;
584 static char *kwlist[] = {"source", "filename", "mode", "flags",
Georg Brandl8334fd92010-12-04 10:26:46 +0000585 "dont_inherit", "optimize", NULL};
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000586 int start[] = {Py_file_input, Py_eval_input, Py_single_input};
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000587 PyObject *result;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000588
Georg Brandl8334fd92010-12-04 10:26:46 +0000589 if (!PyArg_ParseTupleAndKeywords(args, kwds, "OO&s|iii:compile", kwlist,
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000590 &cmd,
591 PyUnicode_FSConverter, &filename_obj,
592 &startstr, &supplied_flags,
Georg Brandl8334fd92010-12-04 10:26:46 +0000593 &dont_inherit, &optimize))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000594 return NULL;
Tim Peters6cd6a822001-08-17 22:11:27 +0000595
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000596 filename = PyBytes_AS_STRING(filename_obj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000597 cf.cf_flags = supplied_flags | PyCF_SOURCE_IS_UTF8;
Just van Rossum3aaf42c2003-02-10 08:21:10 +0000598
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000599 if (supplied_flags &
600 ~(PyCF_MASK | PyCF_MASK_OBSOLETE | PyCF_DONT_IMPLY_DEDENT | PyCF_ONLY_AST))
601 {
602 PyErr_SetString(PyExc_ValueError,
603 "compile(): unrecognised flags");
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000604 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000605 }
606 /* XXX Warn if (supplied_flags & PyCF_MASK_OBSOLETE) != 0? */
Tim Peters6cd6a822001-08-17 22:11:27 +0000607
Georg Brandl8334fd92010-12-04 10:26:46 +0000608 if (optimize < -1 || optimize > 2) {
609 PyErr_SetString(PyExc_ValueError,
610 "compile(): invalid optimize value");
611 goto error;
612 }
613
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000614 if (!dont_inherit) {
615 PyEval_MergeCompilerFlags(&cf);
616 }
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000617
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000618 if (strcmp(startstr, "exec") == 0)
619 mode = 0;
620 else if (strcmp(startstr, "eval") == 0)
621 mode = 1;
622 else if (strcmp(startstr, "single") == 0)
623 mode = 2;
624 else {
625 PyErr_SetString(PyExc_ValueError,
626 "compile() arg 3 must be 'exec', 'eval' or 'single'");
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000627 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000628 }
Neal Norwitzdb4115f2008-03-31 04:20:05 +0000629
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000630 is_ast = PyAST_Check(cmd);
631 if (is_ast == -1)
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000632 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000633 if (is_ast) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000634 if (supplied_flags & PyCF_ONLY_AST) {
635 Py_INCREF(cmd);
636 result = cmd;
637 }
638 else {
639 PyArena *arena;
640 mod_ty mod;
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000641
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000642 arena = PyArena_New();
643 mod = PyAST_obj2mod(cmd, arena, mode);
644 if (mod == NULL) {
645 PyArena_Free(arena);
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000646 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000647 }
Benjamin Peterson832bfe22011-08-09 16:15:04 -0500648 if (!PyAST_Validate(mod)) {
649 PyArena_Free(arena);
650 goto error;
651 }
Georg Brandl8334fd92010-12-04 10:26:46 +0000652 result = (PyObject*)PyAST_CompileEx(mod, filename,
653 &cf, optimize, arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000654 PyArena_Free(arena);
655 }
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000656 goto finally;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000657 }
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000658
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000659 str = source_as_string(cmd, "compile", "string, bytes, AST or code", &cf);
660 if (str == NULL)
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000661 goto error;
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000662
Georg Brandl8334fd92010-12-04 10:26:46 +0000663 result = Py_CompileStringExFlags(str, filename, start[mode], &cf, optimize);
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000664 goto finally;
665
666error:
667 result = NULL;
668finally:
669 Py_DECREF(filename_obj);
670 return result;
Guido van Rossum5b722181993-03-30 17:46:03 +0000671}
672
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000673PyDoc_STRVAR(compile_doc,
Tim Peters6cd6a822001-08-17 22:11:27 +0000674"compile(source, filename, mode[, flags[, dont_inherit]]) -> code object\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000675\n\
676Compile the source string (a Python module, statement or expression)\n\
Georg Brandl7cae87c2006-09-06 06:51:57 +0000677into a code object that can be executed by exec() or eval().\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000678The filename will be used for run-time error messages.\n\
679The mode must be 'exec' to compile a module, 'single' to compile a\n\
Tim Peters6cd6a822001-08-17 22:11:27 +0000680single (interactive) statement, or 'eval' to compile an expression.\n\
681The flags argument, if present, controls which future statements influence\n\
682the compilation of the code.\n\
683The dont_inherit argument, if non-zero, stops the compilation inheriting\n\
684the effects of any future statements in effect in the code calling\n\
685compile; if absent or zero these statements do influence the compilation,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000686in addition to any features explicitly specified.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000687
Guido van Rossum79f25d91997-04-29 20:08:16 +0000688static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000689builtin_dir(PyObject *self, PyObject *args)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000690{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000691 PyObject *arg = NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000692
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000693 if (!PyArg_UnpackTuple(args, "dir", 0, 1, &arg))
694 return NULL;
695 return PyObject_Dir(arg);
Guido van Rossum3f5da241990-12-20 15:06:42 +0000696}
697
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000698PyDoc_STRVAR(dir_doc,
Tim Peters5d2b77c2001-09-03 05:47:38 +0000699"dir([object]) -> list of strings\n"
700"\n"
Georg Brandle32b4222007-03-10 22:13:27 +0000701"If called without an argument, return the names in the current scope.\n"
702"Else, return an alphabetized list of names comprising (some of) the attributes\n"
703"of the given object, and of attributes reachable from it.\n"
704"If the object supplies a method named __dir__, it will be used; otherwise\n"
705"the default dir() logic is used and returns:\n"
706" for a module object: the module's attributes.\n"
707" for a class object: its attributes, and recursively the attributes\n"
708" of its bases.\n"
Guido van Rossumd8faa362007-04-27 19:54:29 +0000709" for any other object: its attributes, its class's attributes, and\n"
Georg Brandle32b4222007-03-10 22:13:27 +0000710" recursively the attributes of its class's base classes.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000711
Guido van Rossum79f25d91997-04-29 20:08:16 +0000712static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000713builtin_divmod(PyObject *self, PyObject *args)
Guido van Rossum6a00cd81995-01-07 12:39:01 +0000714{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000715 PyObject *v, *w;
Guido van Rossum6a00cd81995-01-07 12:39:01 +0000716
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000717 if (!PyArg_UnpackTuple(args, "divmod", 2, 2, &v, &w))
718 return NULL;
719 return PyNumber_Divmod(v, w);
Guido van Rossum3f5da241990-12-20 15:06:42 +0000720}
721
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000722PyDoc_STRVAR(divmod_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000723"divmod(x, y) -> (div, mod)\n\
724\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000725Return the tuple ((x-x%y)/y, x%y). Invariant: div*y + mod == x.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000726
727
Guido van Rossum79f25d91997-04-29 20:08:16 +0000728static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000729builtin_eval(PyObject *self, PyObject *args)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000730{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000731 PyObject *cmd, *result, *tmp = NULL;
732 PyObject *globals = Py_None, *locals = Py_None;
733 char *str;
734 PyCompilerFlags cf;
Guido van Rossum590baa41993-11-30 13:40:46 +0000735
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000736 if (!PyArg_UnpackTuple(args, "eval", 1, 3, &cmd, &globals, &locals))
737 return NULL;
738 if (locals != Py_None && !PyMapping_Check(locals)) {
739 PyErr_SetString(PyExc_TypeError, "locals must be a mapping");
740 return NULL;
741 }
742 if (globals != Py_None && !PyDict_Check(globals)) {
743 PyErr_SetString(PyExc_TypeError, PyMapping_Check(globals) ?
744 "globals must be a real dict; try eval(expr, {}, mapping)"
745 : "globals must be a dict");
746 return NULL;
747 }
748 if (globals == Py_None) {
749 globals = PyEval_GetGlobals();
750 if (locals == Py_None)
751 locals = PyEval_GetLocals();
752 }
753 else if (locals == Py_None)
754 locals = globals;
Tim Peters9fa96be2001-08-17 23:04:59 +0000755
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000756 if (globals == NULL || locals == NULL) {
757 PyErr_SetString(PyExc_TypeError,
758 "eval must be given globals and locals "
759 "when called without a frame");
760 return NULL;
761 }
Georg Brandl77c85e62005-09-15 10:46:13 +0000762
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000763 if (PyDict_GetItemString(globals, "__builtins__") == NULL) {
764 if (PyDict_SetItemString(globals, "__builtins__",
765 PyEval_GetBuiltins()) != 0)
766 return NULL;
767 }
Tim Peters9fa96be2001-08-17 23:04:59 +0000768
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000769 if (PyCode_Check(cmd)) {
770 if (PyCode_GetNumFree((PyCodeObject *)cmd) > 0) {
771 PyErr_SetString(PyExc_TypeError,
772 "code object passed to eval() may not contain free variables");
773 return NULL;
774 }
Martin v. Löwis4d0d4712010-12-03 20:14:31 +0000775 return PyEval_EvalCode(cmd, globals, locals);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000776 }
Tim Peters9fa96be2001-08-17 23:04:59 +0000777
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000778 cf.cf_flags = PyCF_SOURCE_IS_UTF8;
779 str = source_as_string(cmd, "eval", "string, bytes or code", &cf);
780 if (str == NULL)
781 return NULL;
Just van Rossum3aaf42c2003-02-10 08:21:10 +0000782
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000783 while (*str == ' ' || *str == '\t')
784 str++;
Tim Peters9fa96be2001-08-17 23:04:59 +0000785
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000786 (void)PyEval_MergeCompilerFlags(&cf);
787 result = PyRun_StringFlags(str, Py_eval_input, globals, locals, &cf);
788 Py_XDECREF(tmp);
789 return result;
Guido van Rossum3f5da241990-12-20 15:06:42 +0000790}
791
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000792PyDoc_STRVAR(eval_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000793"eval(source[, globals[, locals]]) -> value\n\
794\n\
795Evaluate the source in the context of globals and locals.\n\
796The source may be a string representing a Python expression\n\
797or a code object as returned by compile().\n\
Thomas Wouters89f507f2006-12-13 04:49:30 +0000798The globals must be a dictionary and locals can be any mapping,\n\
Raymond Hettinger214b1c32004-07-02 06:41:07 +0000799defaulting to the current globals and locals.\n\
800If only globals is given, locals defaults to it.\n");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000801
Georg Brandl7cae87c2006-09-06 06:51:57 +0000802static PyObject *
803builtin_exec(PyObject *self, PyObject *args)
804{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000805 PyObject *v;
806 PyObject *prog, *globals = Py_None, *locals = Py_None;
Georg Brandl7cae87c2006-09-06 06:51:57 +0000807
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000808 if (!PyArg_UnpackTuple(args, "exec", 1, 3, &prog, &globals, &locals))
809 return NULL;
Georg Brandl2cabc562008-08-28 07:57:16 +0000810
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000811 if (globals == Py_None) {
812 globals = PyEval_GetGlobals();
813 if (locals == Py_None) {
814 locals = PyEval_GetLocals();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000815 }
816 if (!globals || !locals) {
817 PyErr_SetString(PyExc_SystemError,
818 "globals and locals cannot be NULL");
819 return NULL;
820 }
821 }
822 else if (locals == Py_None)
823 locals = globals;
Georg Brandl7cae87c2006-09-06 06:51:57 +0000824
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000825 if (!PyDict_Check(globals)) {
826 PyErr_Format(PyExc_TypeError, "exec() arg 2 must be a dict, not %.100s",
827 globals->ob_type->tp_name);
828 return NULL;
829 }
830 if (!PyMapping_Check(locals)) {
831 PyErr_Format(PyExc_TypeError,
832 "arg 3 must be a mapping or None, not %.100s",
833 locals->ob_type->tp_name);
834 return NULL;
835 }
836 if (PyDict_GetItemString(globals, "__builtins__") == NULL) {
837 if (PyDict_SetItemString(globals, "__builtins__",
838 PyEval_GetBuiltins()) != 0)
839 return NULL;
840 }
841
842 if (PyCode_Check(prog)) {
843 if (PyCode_GetNumFree((PyCodeObject *)prog) > 0) {
844 PyErr_SetString(PyExc_TypeError,
845 "code object passed to exec() may not "
846 "contain free variables");
847 return NULL;
848 }
Martin v. Löwis4d0d4712010-12-03 20:14:31 +0000849 v = PyEval_EvalCode(prog, globals, locals);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000850 }
851 else {
852 char *str;
853 PyCompilerFlags cf;
854 cf.cf_flags = PyCF_SOURCE_IS_UTF8;
855 str = source_as_string(prog, "exec",
856 "string, bytes or code", &cf);
857 if (str == NULL)
858 return NULL;
859 if (PyEval_MergeCompilerFlags(&cf))
860 v = PyRun_StringFlags(str, Py_file_input, globals,
861 locals, &cf);
862 else
863 v = PyRun_String(str, Py_file_input, globals, locals);
864 }
865 if (v == NULL)
866 return NULL;
867 Py_DECREF(v);
868 Py_RETURN_NONE;
Georg Brandl7cae87c2006-09-06 06:51:57 +0000869}
870
871PyDoc_STRVAR(exec_doc,
872"exec(object[, globals[, locals]])\n\
873\n\
Mark Dickinson480e8e32009-12-19 21:19:35 +0000874Read and execute code from an object, which can be a string or a code\n\
Benjamin Peterson38090262009-01-04 15:30:39 +0000875object.\n\
Georg Brandl7cae87c2006-09-06 06:51:57 +0000876The globals and locals are dictionaries, defaulting to the current\n\
877globals and locals. If only globals is given, locals defaults to it.");
878
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000879
Guido van Rossum79f25d91997-04-29 20:08:16 +0000880static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000881builtin_getattr(PyObject *self, PyObject *args)
Guido van Rossum33894be1992-01-27 16:53:09 +0000882{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000883 PyObject *v, *result, *dflt = NULL;
884 PyObject *name;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000885
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000886 if (!PyArg_UnpackTuple(args, "getattr", 2, 3, &v, &name, &dflt))
887 return NULL;
Martin v. Löwis5b222132007-06-10 09:51:05 +0000888
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000889 if (!PyUnicode_Check(name)) {
890 PyErr_SetString(PyExc_TypeError,
891 "getattr(): attribute name must be string");
892 return NULL;
893 }
894 result = PyObject_GetAttr(v, name);
895 if (result == NULL && dflt != NULL &&
896 PyErr_ExceptionMatches(PyExc_AttributeError))
897 {
898 PyErr_Clear();
899 Py_INCREF(dflt);
900 result = dflt;
901 }
902 return result;
Guido van Rossum9bfef441993-03-29 10:43:31 +0000903}
904
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000905PyDoc_STRVAR(getattr_doc,
Guido van Rossum950ff291998-06-29 13:38:57 +0000906"getattr(object, name[, default]) -> value\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000907\n\
Guido van Rossum950ff291998-06-29 13:38:57 +0000908Get a named attribute from an object; getattr(x, 'y') is equivalent to x.y.\n\
909When a default argument is given, it is returned when the attribute doesn't\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000910exist; without it, an exception is raised in that case.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000911
912
Guido van Rossum79f25d91997-04-29 20:08:16 +0000913static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000914builtin_globals(PyObject *self)
Guido van Rossum872537c1995-07-07 22:43:42 +0000915{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000916 PyObject *d;
Guido van Rossum872537c1995-07-07 22:43:42 +0000917
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000918 d = PyEval_GetGlobals();
919 Py_XINCREF(d);
920 return d;
Guido van Rossum872537c1995-07-07 22:43:42 +0000921}
922
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000923PyDoc_STRVAR(globals_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000924"globals() -> dictionary\n\
925\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000926Return the dictionary containing the current scope's global variables.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000927
928
Guido van Rossum79f25d91997-04-29 20:08:16 +0000929static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000930builtin_hasattr(PyObject *self, PyObject *args)
Guido van Rossum9bfef441993-03-29 10:43:31 +0000931{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000932 PyObject *v;
933 PyObject *name;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000934
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000935 if (!PyArg_UnpackTuple(args, "hasattr", 2, 2, &v, &name))
936 return NULL;
937 if (!PyUnicode_Check(name)) {
938 PyErr_SetString(PyExc_TypeError,
939 "hasattr(): attribute name must be string");
940 return NULL;
941 }
942 v = PyObject_GetAttr(v, name);
943 if (v == NULL) {
Benjamin Peterson17689992010-08-24 03:26:23 +0000944 if (PyErr_ExceptionMatches(PyExc_AttributeError)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000945 PyErr_Clear();
Benjamin Peterson17689992010-08-24 03:26:23 +0000946 Py_RETURN_FALSE;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000947 }
Benjamin Peterson17689992010-08-24 03:26:23 +0000948 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000949 }
950 Py_DECREF(v);
Benjamin Peterson17689992010-08-24 03:26:23 +0000951 Py_RETURN_TRUE;
Guido van Rossum33894be1992-01-27 16:53:09 +0000952}
953
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000954PyDoc_STRVAR(hasattr_doc,
Guido van Rossum77f6a652002-04-03 22:41:51 +0000955"hasattr(object, name) -> bool\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000956\n\
957Return whether the object has an attribute with the given name.\n\
Benjamin Peterson17689992010-08-24 03:26:23 +0000958(This is done by calling getattr(object, name) and catching AttributeError.)");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000959
960
Guido van Rossum79f25d91997-04-29 20:08:16 +0000961static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000962builtin_id(PyObject *self, PyObject *v)
Guido van Rossum5b722181993-03-30 17:46:03 +0000963{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000964 return PyLong_FromVoidPtr(v);
Guido van Rossum5b722181993-03-30 17:46:03 +0000965}
966
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000967PyDoc_STRVAR(id_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000968"id(object) -> integer\n\
969\n\
970Return the identity of an object. This is guaranteed to be unique among\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000971simultaneously existing objects. (Hint: it's the object's memory address.)");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000972
973
Raymond Hettingera6c60372008-03-13 01:26:19 +0000974/* map object ************************************************************/
975
976typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000977 PyObject_HEAD
978 PyObject *iters;
979 PyObject *func;
Raymond Hettingera6c60372008-03-13 01:26:19 +0000980} mapobject;
981
Guido van Rossum79f25d91997-04-29 20:08:16 +0000982static PyObject *
Raymond Hettingera6c60372008-03-13 01:26:19 +0000983map_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
Guido van Rossum12d12c51993-10-26 17:58:25 +0000984{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000985 PyObject *it, *iters, *func;
986 mapobject *lz;
987 Py_ssize_t numargs, i;
Raymond Hettingera6c60372008-03-13 01:26:19 +0000988
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000989 if (type == &PyMap_Type && !_PyArg_NoKeywords("map()", kwds))
990 return NULL;
Raymond Hettingera6c60372008-03-13 01:26:19 +0000991
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000992 numargs = PyTuple_Size(args);
993 if (numargs < 2) {
994 PyErr_SetString(PyExc_TypeError,
995 "map() must have at least two arguments.");
996 return NULL;
997 }
Raymond Hettingera6c60372008-03-13 01:26:19 +0000998
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000999 iters = PyTuple_New(numargs-1);
1000 if (iters == NULL)
1001 return NULL;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001002
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001003 for (i=1 ; i<numargs ; i++) {
1004 /* Get iterator. */
1005 it = PyObject_GetIter(PyTuple_GET_ITEM(args, i));
1006 if (it == NULL) {
1007 Py_DECREF(iters);
1008 return NULL;
1009 }
1010 PyTuple_SET_ITEM(iters, i-1, it);
1011 }
Raymond Hettingera6c60372008-03-13 01:26:19 +00001012
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001013 /* create mapobject structure */
1014 lz = (mapobject *)type->tp_alloc(type, 0);
1015 if (lz == NULL) {
1016 Py_DECREF(iters);
1017 return NULL;
1018 }
1019 lz->iters = iters;
1020 func = PyTuple_GET_ITEM(args, 0);
1021 Py_INCREF(func);
1022 lz->func = func;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001023
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001024 return (PyObject *)lz;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001025}
1026
1027static void
1028map_dealloc(mapobject *lz)
1029{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001030 PyObject_GC_UnTrack(lz);
1031 Py_XDECREF(lz->iters);
1032 Py_XDECREF(lz->func);
1033 Py_TYPE(lz)->tp_free(lz);
Raymond Hettingera6c60372008-03-13 01:26:19 +00001034}
1035
1036static int
1037map_traverse(mapobject *lz, visitproc visit, void *arg)
1038{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001039 Py_VISIT(lz->iters);
1040 Py_VISIT(lz->func);
1041 return 0;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001042}
1043
1044static PyObject *
1045map_next(mapobject *lz)
1046{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001047 PyObject *val;
1048 PyObject *argtuple;
1049 PyObject *result;
1050 Py_ssize_t numargs, i;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001051
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001052 numargs = PyTuple_Size(lz->iters);
1053 argtuple = PyTuple_New(numargs);
1054 if (argtuple == NULL)
1055 return NULL;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001056
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001057 for (i=0 ; i<numargs ; i++) {
1058 val = PyIter_Next(PyTuple_GET_ITEM(lz->iters, i));
1059 if (val == NULL) {
1060 Py_DECREF(argtuple);
1061 return NULL;
1062 }
1063 PyTuple_SET_ITEM(argtuple, i, val);
1064 }
1065 result = PyObject_Call(lz->func, argtuple, NULL);
1066 Py_DECREF(argtuple);
1067 return result;
Guido van Rossum12d12c51993-10-26 17:58:25 +00001068}
1069
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001070static PyObject *
1071map_reduce(mapobject *lz)
1072{
1073 Py_ssize_t numargs = PyTuple_GET_SIZE(lz->iters);
1074 PyObject *args = PyTuple_New(numargs+1);
1075 Py_ssize_t i;
1076 if (args == NULL)
1077 return NULL;
1078 Py_INCREF(lz->func);
1079 PyTuple_SET_ITEM(args, 0, lz->func);
1080 for (i = 0; i<numargs; i++){
1081 PyObject *it = PyTuple_GET_ITEM(lz->iters, i);
1082 Py_INCREF(it);
1083 PyTuple_SET_ITEM(args, i+1, it);
1084 }
1085
1086 return Py_BuildValue("ON", Py_TYPE(lz), args);
1087}
1088
1089static PyMethodDef map_methods[] = {
1090 {"__reduce__", (PyCFunction)map_reduce, METH_NOARGS, reduce_doc},
1091 {NULL, NULL} /* sentinel */
1092};
1093
1094
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001095PyDoc_STRVAR(map_doc,
Raymond Hettingera6c60372008-03-13 01:26:19 +00001096"map(func, *iterables) --> map object\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001097\n\
Raymond Hettingera6c60372008-03-13 01:26:19 +00001098Make an iterator that computes the function using arguments from\n\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001099each of the iterables. Stops when the shortest iterable is exhausted.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001100
Raymond Hettingera6c60372008-03-13 01:26:19 +00001101PyTypeObject PyMap_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001102 PyVarObject_HEAD_INIT(&PyType_Type, 0)
1103 "map", /* tp_name */
1104 sizeof(mapobject), /* tp_basicsize */
1105 0, /* tp_itemsize */
1106 /* methods */
1107 (destructor)map_dealloc, /* tp_dealloc */
1108 0, /* tp_print */
1109 0, /* tp_getattr */
1110 0, /* tp_setattr */
1111 0, /* tp_reserved */
1112 0, /* tp_repr */
1113 0, /* tp_as_number */
1114 0, /* tp_as_sequence */
1115 0, /* tp_as_mapping */
1116 0, /* tp_hash */
1117 0, /* tp_call */
1118 0, /* tp_str */
1119 PyObject_GenericGetAttr, /* tp_getattro */
1120 0, /* tp_setattro */
1121 0, /* tp_as_buffer */
1122 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
1123 Py_TPFLAGS_BASETYPE, /* tp_flags */
1124 map_doc, /* tp_doc */
1125 (traverseproc)map_traverse, /* tp_traverse */
1126 0, /* tp_clear */
1127 0, /* tp_richcompare */
1128 0, /* tp_weaklistoffset */
1129 PyObject_SelfIter, /* tp_iter */
1130 (iternextfunc)map_next, /* tp_iternext */
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001131 map_methods, /* tp_methods */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001132 0, /* tp_members */
1133 0, /* tp_getset */
1134 0, /* tp_base */
1135 0, /* tp_dict */
1136 0, /* tp_descr_get */
1137 0, /* tp_descr_set */
1138 0, /* tp_dictoffset */
1139 0, /* tp_init */
1140 PyType_GenericAlloc, /* tp_alloc */
1141 map_new, /* tp_new */
1142 PyObject_GC_Del, /* tp_free */
Raymond Hettingera6c60372008-03-13 01:26:19 +00001143};
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001144
Guido van Rossum79f25d91997-04-29 20:08:16 +00001145static PyObject *
Georg Brandla18af4e2007-04-21 15:47:16 +00001146builtin_next(PyObject *self, PyObject *args)
1147{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001148 PyObject *it, *res;
1149 PyObject *def = NULL;
Georg Brandla18af4e2007-04-21 15:47:16 +00001150
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001151 if (!PyArg_UnpackTuple(args, "next", 1, 2, &it, &def))
1152 return NULL;
1153 if (!PyIter_Check(it)) {
1154 PyErr_Format(PyExc_TypeError,
Philip Jenvey50add042011-11-06 16:37:52 -08001155 "'%.200s' object is not an iterator",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001156 it->ob_type->tp_name);
1157 return NULL;
1158 }
1159
1160 res = (*it->ob_type->tp_iternext)(it);
1161 if (res != NULL) {
1162 return res;
1163 } else if (def != NULL) {
1164 if (PyErr_Occurred()) {
1165 if(!PyErr_ExceptionMatches(PyExc_StopIteration))
1166 return NULL;
1167 PyErr_Clear();
1168 }
1169 Py_INCREF(def);
1170 return def;
1171 } else if (PyErr_Occurred()) {
1172 return NULL;
1173 } else {
1174 PyErr_SetNone(PyExc_StopIteration);
1175 return NULL;
1176 }
Georg Brandla18af4e2007-04-21 15:47:16 +00001177}
1178
1179PyDoc_STRVAR(next_doc,
1180"next(iterator[, default])\n\
1181\n\
1182Return the next item from the iterator. If default is given and the iterator\n\
1183is exhausted, it is returned instead of raising StopIteration.");
1184
1185
1186static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001187builtin_setattr(PyObject *self, PyObject *args)
Guido van Rossum33894be1992-01-27 16:53:09 +00001188{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001189 PyObject *v;
1190 PyObject *name;
1191 PyObject *value;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001192
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001193 if (!PyArg_UnpackTuple(args, "setattr", 3, 3, &v, &name, &value))
1194 return NULL;
1195 if (PyObject_SetAttr(v, name, value) != 0)
1196 return NULL;
1197 Py_INCREF(Py_None);
1198 return Py_None;
Guido van Rossum33894be1992-01-27 16:53:09 +00001199}
1200
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001201PyDoc_STRVAR(setattr_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001202"setattr(object, name, value)\n\
1203\n\
1204Set a named attribute on an object; setattr(x, 'y', v) is equivalent to\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001205``x.y = v''.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001206
1207
Guido van Rossum79f25d91997-04-29 20:08:16 +00001208static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001209builtin_delattr(PyObject *self, PyObject *args)
Guido van Rossum14144fc1994-08-29 12:53:40 +00001210{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001211 PyObject *v;
1212 PyObject *name;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001213
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001214 if (!PyArg_UnpackTuple(args, "delattr", 2, 2, &v, &name))
1215 return NULL;
1216 if (PyObject_SetAttr(v, name, (PyObject *)NULL) != 0)
1217 return NULL;
1218 Py_INCREF(Py_None);
1219 return Py_None;
Guido van Rossum14144fc1994-08-29 12:53:40 +00001220}
1221
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001222PyDoc_STRVAR(delattr_doc,
Guido van Rossumdf12a591998-11-23 22:13:04 +00001223"delattr(object, name)\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001224\n\
1225Delete a named attribute on an object; delattr(x, 'y') is equivalent to\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001226``del x.y''.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001227
1228
Guido van Rossum79f25d91997-04-29 20:08:16 +00001229static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001230builtin_hash(PyObject *self, PyObject *v)
Guido van Rossum9bfef441993-03-29 10:43:31 +00001231{
Benjamin Peterson8f67d082010-10-17 20:54:53 +00001232 Py_hash_t x;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001233
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001234 x = PyObject_Hash(v);
1235 if (x == -1)
1236 return NULL;
Benjamin Peterson8f67d082010-10-17 20:54:53 +00001237 return PyLong_FromSsize_t(x);
Guido van Rossum9bfef441993-03-29 10:43:31 +00001238}
1239
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001240PyDoc_STRVAR(hash_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001241"hash(object) -> integer\n\
1242\n\
1243Return a hash value for the object. Two objects with the same value have\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001244the same hash value. The reverse is not necessarily true, but likely.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001245
1246
Guido van Rossum79f25d91997-04-29 20:08:16 +00001247static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001248builtin_hex(PyObject *self, PyObject *v)
Guido van Rossum006bcd41991-10-24 14:54:44 +00001249{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001250 return PyNumber_ToBase(v, 16);
Guido van Rossum006bcd41991-10-24 14:54:44 +00001251}
1252
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001253PyDoc_STRVAR(hex_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001254"hex(number) -> string\n\
1255\n\
Alexander Belopolsky12338ab2011-04-07 00:15:33 -04001256Return the hexadecimal representation of an integer.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001257
1258
Guido van Rossum79f25d91997-04-29 20:08:16 +00001259static PyObject *
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001260builtin_iter(PyObject *self, PyObject *args)
1261{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001262 PyObject *v, *w = NULL;
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001263
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001264 if (!PyArg_UnpackTuple(args, "iter", 1, 2, &v, &w))
1265 return NULL;
1266 if (w == NULL)
1267 return PyObject_GetIter(v);
1268 if (!PyCallable_Check(v)) {
1269 PyErr_SetString(PyExc_TypeError,
1270 "iter(v, w): v must be callable");
1271 return NULL;
1272 }
1273 return PyCallIter_New(v, w);
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001274}
1275
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001276PyDoc_STRVAR(iter_doc,
Georg Brandld11ae5d2008-05-16 13:27:32 +00001277"iter(iterable) -> iterator\n\
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001278iter(callable, sentinel) -> iterator\n\
1279\n\
1280Get an iterator from an object. In the first form, the argument must\n\
1281supply its own iterator, or be a sequence.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001282In the second form, the callable is called until it returns the sentinel.");
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001283
1284
1285static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001286builtin_len(PyObject *self, PyObject *v)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001287{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001288 Py_ssize_t res;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001289
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001290 res = PyObject_Size(v);
1291 if (res < 0 && PyErr_Occurred())
1292 return NULL;
1293 return PyLong_FromSsize_t(res);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001294}
1295
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001296PyDoc_STRVAR(len_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001297"len(object) -> integer\n\
1298\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001299Return the number of items of a sequence or mapping.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001300
1301
Guido van Rossum79f25d91997-04-29 20:08:16 +00001302static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001303builtin_locals(PyObject *self)
Guido van Rossum872537c1995-07-07 22:43:42 +00001304{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001305 PyObject *d;
Guido van Rossum872537c1995-07-07 22:43:42 +00001306
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001307 d = PyEval_GetLocals();
1308 Py_XINCREF(d);
1309 return d;
Guido van Rossum872537c1995-07-07 22:43:42 +00001310}
1311
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001312PyDoc_STRVAR(locals_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001313"locals() -> dictionary\n\
1314\n\
Raymond Hettinger69bf8f32003-01-04 02:16:22 +00001315Update and return a dictionary containing the current scope's local variables.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001316
1317
Guido van Rossum79f25d91997-04-29 20:08:16 +00001318static PyObject *
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001319min_max(PyObject *args, PyObject *kwds, int op)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001320{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001321 PyObject *v, *it, *item, *val, *maxitem, *maxval, *keyfunc=NULL;
1322 const char *name = op == Py_LT ? "min" : "max";
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001323
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001324 if (PyTuple_Size(args) > 1)
1325 v = args;
1326 else if (!PyArg_UnpackTuple(args, (char *)name, 1, 1, &v))
1327 return NULL;
Tim Peters67d687a2002-04-29 21:27:32 +00001328
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001329 if (kwds != NULL && PyDict_Check(kwds) && PyDict_Size(kwds)) {
1330 keyfunc = PyDict_GetItemString(kwds, "key");
1331 if (PyDict_Size(kwds)!=1 || keyfunc == NULL) {
1332 PyErr_Format(PyExc_TypeError,
1333 "%s() got an unexpected keyword argument", name);
1334 return NULL;
1335 }
1336 Py_INCREF(keyfunc);
1337 }
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001338
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001339 it = PyObject_GetIter(v);
1340 if (it == NULL) {
1341 Py_XDECREF(keyfunc);
1342 return NULL;
1343 }
Tim Petersc3074532001-05-03 07:00:32 +00001344
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001345 maxitem = NULL; /* the result */
1346 maxval = NULL; /* the value associated with the result */
1347 while (( item = PyIter_Next(it) )) {
1348 /* get the value from the key function */
1349 if (keyfunc != NULL) {
1350 val = PyObject_CallFunctionObjArgs(keyfunc, item, NULL);
1351 if (val == NULL)
1352 goto Fail_it_item;
1353 }
1354 /* no key function; the value is the item */
1355 else {
1356 val = item;
1357 Py_INCREF(val);
1358 }
Tim Petersc3074532001-05-03 07:00:32 +00001359
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001360 /* maximum value and item are unset; set them */
1361 if (maxval == NULL) {
1362 maxitem = item;
1363 maxval = val;
1364 }
1365 /* maximum value and item are set; update them as necessary */
1366 else {
1367 int cmp = PyObject_RichCompareBool(val, maxval, op);
1368 if (cmp < 0)
1369 goto Fail_it_item_and_val;
1370 else if (cmp > 0) {
1371 Py_DECREF(maxval);
1372 Py_DECREF(maxitem);
1373 maxval = val;
1374 maxitem = item;
1375 }
1376 else {
1377 Py_DECREF(item);
1378 Py_DECREF(val);
1379 }
1380 }
1381 }
1382 if (PyErr_Occurred())
1383 goto Fail_it;
1384 if (maxval == NULL) {
1385 PyErr_Format(PyExc_ValueError,
1386 "%s() arg is an empty sequence", name);
1387 assert(maxitem == NULL);
1388 }
1389 else
1390 Py_DECREF(maxval);
1391 Py_DECREF(it);
1392 Py_XDECREF(keyfunc);
1393 return maxitem;
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001394
1395Fail_it_item_and_val:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001396 Py_DECREF(val);
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001397Fail_it_item:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001398 Py_DECREF(item);
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001399Fail_it:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001400 Py_XDECREF(maxval);
1401 Py_XDECREF(maxitem);
1402 Py_DECREF(it);
1403 Py_XDECREF(keyfunc);
1404 return NULL;
Guido van Rossum3f5da241990-12-20 15:06:42 +00001405}
1406
Guido van Rossum79f25d91997-04-29 20:08:16 +00001407static PyObject *
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001408builtin_min(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001409{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001410 return min_max(args, kwds, Py_LT);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001411}
1412
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001413PyDoc_STRVAR(min_doc,
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001414"min(iterable[, key=func]) -> value\n\
1415min(a, b, c, ...[, key=func]) -> value\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001416\n\
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001417With a single iterable argument, return its smallest item.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001418With two or more arguments, return the smallest argument.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001419
1420
Guido van Rossum79f25d91997-04-29 20:08:16 +00001421static PyObject *
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001422builtin_max(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001423{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001424 return min_max(args, kwds, Py_GT);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001425}
1426
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001427PyDoc_STRVAR(max_doc,
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001428"max(iterable[, key=func]) -> value\n\
1429max(a, b, c, ...[, key=func]) -> value\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001430\n\
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001431With a single iterable argument, return its largest item.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001432With two or more arguments, return the largest argument.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001433
1434
Guido van Rossum79f25d91997-04-29 20:08:16 +00001435static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001436builtin_oct(PyObject *self, PyObject *v)
Guido van Rossum006bcd41991-10-24 14:54:44 +00001437{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001438 return PyNumber_ToBase(v, 8);
Guido van Rossum006bcd41991-10-24 14:54:44 +00001439}
1440
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001441PyDoc_STRVAR(oct_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001442"oct(number) -> string\n\
1443\n\
Alexander Belopolsky12338ab2011-04-07 00:15:33 -04001444Return the octal representation of an integer.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001445
1446
Guido van Rossum79f25d91997-04-29 20:08:16 +00001447static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001448builtin_ord(PyObject *self, PyObject* obj)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001449{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001450 long ord;
1451 Py_ssize_t size;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001452
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001453 if (PyBytes_Check(obj)) {
1454 size = PyBytes_GET_SIZE(obj);
1455 if (size == 1) {
1456 ord = (long)((unsigned char)*PyBytes_AS_STRING(obj));
1457 return PyLong_FromLong(ord);
1458 }
1459 }
1460 else if (PyUnicode_Check(obj)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001461 if (PyUnicode_READY(obj) == -1)
1462 return NULL;
1463 size = PyUnicode_GET_LENGTH(obj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001464 if (size == 1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001465 ord = (long)PyUnicode_READ_CHAR(obj, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001466 return PyLong_FromLong(ord);
1467 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001468 }
1469 else if (PyByteArray_Check(obj)) {
1470 /* XXX Hopefully this is temporary */
1471 size = PyByteArray_GET_SIZE(obj);
1472 if (size == 1) {
1473 ord = (long)((unsigned char)*PyByteArray_AS_STRING(obj));
1474 return PyLong_FromLong(ord);
1475 }
1476 }
1477 else {
1478 PyErr_Format(PyExc_TypeError,
1479 "ord() expected string of length 1, but " \
1480 "%.200s found", obj->ob_type->tp_name);
1481 return NULL;
1482 }
Guido van Rossum09095f32000-03-10 23:00:52 +00001483
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001484 PyErr_Format(PyExc_TypeError,
1485 "ord() expected a character, "
1486 "but string of length %zd found",
1487 size);
1488 return NULL;
Guido van Rossum3f5da241990-12-20 15:06:42 +00001489}
1490
Guido van Rossum307fa8c2007-07-16 20:46:27 +00001491PyDoc_VAR(ord_doc) = PyDoc_STR(
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001492"ord(c) -> integer\n\
1493\n\
Guido van Rossum8ac004e2007-07-15 13:00:05 +00001494Return the integer ordinal of a one-character string."
Guido van Rossum307fa8c2007-07-16 20:46:27 +00001495)
Guido van Rossum8ac004e2007-07-15 13:00:05 +00001496#ifndef Py_UNICODE_WIDE
Guido van Rossum307fa8c2007-07-16 20:46:27 +00001497PyDoc_STR(
Guido van Rossum8ac004e2007-07-15 13:00:05 +00001498"\nA valid surrogate pair is also accepted."
Guido van Rossum307fa8c2007-07-16 20:46:27 +00001499)
Guido van Rossum8ac004e2007-07-15 13:00:05 +00001500#endif
Guido van Rossum307fa8c2007-07-16 20:46:27 +00001501;
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001502
1503
Guido van Rossum79f25d91997-04-29 20:08:16 +00001504static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001505builtin_pow(PyObject *self, PyObject *args)
Guido van Rossum6a00cd81995-01-07 12:39:01 +00001506{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001507 PyObject *v, *w, *z = Py_None;
Guido van Rossum6a00cd81995-01-07 12:39:01 +00001508
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001509 if (!PyArg_UnpackTuple(args, "pow", 2, 3, &v, &w, &z))
1510 return NULL;
1511 return PyNumber_Power(v, w, z);
Guido van Rossumd4905451991-05-05 20:00:36 +00001512}
1513
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001514PyDoc_STRVAR(pow_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001515"pow(x, y[, z]) -> number\n\
1516\n\
1517With two arguments, equivalent to x**y. With three arguments,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001518equivalent to (x**y) % z, but may be more efficient (e.g. for longs).");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001519
1520
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001521
Guido van Rossum34343512006-11-30 22:13:52 +00001522static PyObject *
1523builtin_print(PyObject *self, PyObject *args, PyObject *kwds)
1524{
Georg Brandlbc3b6822012-01-13 19:41:25 +01001525 static char *kwlist[] = {"sep", "end", "file", "flush", 0};
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001526 static PyObject *dummy_args;
Georg Brandlbc3b6822012-01-13 19:41:25 +01001527 PyObject *sep = NULL, *end = NULL, *file = NULL, *flush = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001528 int i, err;
Guido van Rossum34343512006-11-30 22:13:52 +00001529
Benjamin Peterson00102562012-01-11 21:00:16 -05001530 if (dummy_args == NULL && !(dummy_args = PyTuple_New(0)))
Georg Brandlbc3b6822012-01-13 19:41:25 +01001531 return NULL;
1532 if (!PyArg_ParseTupleAndKeywords(dummy_args, kwds, "|OOOO:print",
1533 kwlist, &sep, &end, &file, &flush))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001534 return NULL;
1535 if (file == NULL || file == Py_None) {
1536 file = PySys_GetObject("stdout");
1537 /* sys.stdout may be None when FILE* stdout isn't connected */
1538 if (file == Py_None)
1539 Py_RETURN_NONE;
1540 }
Guido van Rossum34343512006-11-30 22:13:52 +00001541
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001542 if (sep == Py_None) {
1543 sep = NULL;
1544 }
1545 else if (sep && !PyUnicode_Check(sep)) {
1546 PyErr_Format(PyExc_TypeError,
1547 "sep must be None or a string, not %.200s",
1548 sep->ob_type->tp_name);
1549 return NULL;
1550 }
1551 if (end == Py_None) {
1552 end = NULL;
1553 }
1554 else if (end && !PyUnicode_Check(end)) {
1555 PyErr_Format(PyExc_TypeError,
1556 "end must be None or a string, not %.200s",
1557 end->ob_type->tp_name);
1558 return NULL;
1559 }
Guido van Rossum34343512006-11-30 22:13:52 +00001560
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001561 for (i = 0; i < PyTuple_Size(args); i++) {
1562 if (i > 0) {
1563 if (sep == NULL)
1564 err = PyFile_WriteString(" ", file);
1565 else
1566 err = PyFile_WriteObject(sep, file,
1567 Py_PRINT_RAW);
1568 if (err)
1569 return NULL;
1570 }
1571 err = PyFile_WriteObject(PyTuple_GetItem(args, i), file,
1572 Py_PRINT_RAW);
1573 if (err)
1574 return NULL;
1575 }
Guido van Rossum34343512006-11-30 22:13:52 +00001576
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001577 if (end == NULL)
1578 err = PyFile_WriteString("\n", file);
1579 else
1580 err = PyFile_WriteObject(end, file, Py_PRINT_RAW);
1581 if (err)
1582 return NULL;
Guido van Rossum34343512006-11-30 22:13:52 +00001583
Georg Brandlbc3b6822012-01-13 19:41:25 +01001584 if (flush != NULL) {
1585 PyObject *tmp;
1586 int do_flush = PyObject_IsTrue(flush);
1587 if (do_flush == -1)
1588 return NULL;
1589 else if (do_flush) {
1590 tmp = PyObject_CallMethod(file, "flush", "");
1591 if (tmp == NULL)
1592 return NULL;
1593 else
1594 Py_DECREF(tmp);
1595 }
1596 }
1597
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001598 Py_RETURN_NONE;
Guido van Rossum34343512006-11-30 22:13:52 +00001599}
1600
1601PyDoc_STRVAR(print_doc,
Georg Brandlcd5da7d2008-02-01 15:47:37 +00001602"print(value, ..., sep=' ', end='\\n', file=sys.stdout)\n\
Guido van Rossum34343512006-11-30 22:13:52 +00001603\n\
1604Prints the values to a stream, or to sys.stdout by default.\n\
1605Optional keyword arguments:\n\
1606file: a file-like object (stream); defaults to the current sys.stdout.\n\
1607sep: string inserted between values, default a space.\n\
1608end: string appended after the last value, default a newline.");
1609
1610
Guido van Rossuma88a0332007-02-26 16:59:55 +00001611static PyObject *
1612builtin_input(PyObject *self, PyObject *args)
1613{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001614 PyObject *promptarg = NULL;
1615 PyObject *fin = PySys_GetObject("stdin");
1616 PyObject *fout = PySys_GetObject("stdout");
1617 PyObject *ferr = PySys_GetObject("stderr");
1618 PyObject *tmp;
1619 long fd;
1620 int tty;
Guido van Rossuma88a0332007-02-26 16:59:55 +00001621
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001622 /* Parse arguments */
1623 if (!PyArg_UnpackTuple(args, "input", 0, 1, &promptarg))
1624 return NULL;
Guido van Rossuma88a0332007-02-26 16:59:55 +00001625
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001626 /* Check that stdin/out/err are intact */
1627 if (fin == NULL || fin == Py_None) {
1628 PyErr_SetString(PyExc_RuntimeError,
1629 "input(): lost sys.stdin");
1630 return NULL;
1631 }
1632 if (fout == NULL || fout == Py_None) {
1633 PyErr_SetString(PyExc_RuntimeError,
1634 "input(): lost sys.stdout");
1635 return NULL;
1636 }
1637 if (ferr == NULL || ferr == Py_None) {
1638 PyErr_SetString(PyExc_RuntimeError,
1639 "input(): lost sys.stderr");
1640 return NULL;
1641 }
Guido van Rossumeba76962007-05-27 09:13:28 +00001642
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001643 /* First of all, flush stderr */
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001644 tmp = _PyObject_CallMethodId(ferr, &PyId_flush, "");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001645 if (tmp == NULL)
1646 PyErr_Clear();
1647 else
1648 Py_DECREF(tmp);
Guido van Rossumeba76962007-05-27 09:13:28 +00001649
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001650 /* We should only use (GNU) readline if Python's sys.stdin and
1651 sys.stdout are the same as C's stdin and stdout, because we
1652 need to pass it those. */
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001653 tmp = _PyObject_CallMethodId(fin, &PyId_fileno, "");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001654 if (tmp == NULL) {
1655 PyErr_Clear();
1656 tty = 0;
1657 }
1658 else {
1659 fd = PyLong_AsLong(tmp);
1660 Py_DECREF(tmp);
1661 if (fd < 0 && PyErr_Occurred())
1662 return NULL;
1663 tty = fd == fileno(stdin) && isatty(fd);
1664 }
1665 if (tty) {
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001666 tmp = _PyObject_CallMethodId(fout, &PyId_fileno, "");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001667 if (tmp == NULL)
1668 PyErr_Clear();
1669 else {
1670 fd = PyLong_AsLong(tmp);
1671 Py_DECREF(tmp);
1672 if (fd < 0 && PyErr_Occurred())
1673 return NULL;
1674 tty = fd == fileno(stdout) && isatty(fd);
1675 }
1676 }
Guido van Rossumeba76962007-05-27 09:13:28 +00001677
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001678 /* If we're interactive, use (GNU) readline */
1679 if (tty) {
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001680 PyObject *po = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001681 char *prompt;
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001682 char *s = NULL;
1683 PyObject *stdin_encoding = NULL, *stdin_errors = NULL;
1684 PyObject *stdout_encoding = NULL, *stdout_errors = NULL;
1685 char *stdin_encoding_str, *stdin_errors_str;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001686 PyObject *result;
Victor Stinnerc0f1a1a2011-02-23 12:07:37 +00001687 size_t len;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02001688 _Py_IDENTIFIER(encoding);
Antoine Pitrou5ee9d8a2011-11-06 00:38:45 +01001689 _Py_IDENTIFIER(errors);
Martin v. Löwis4a7b5d52007-09-04 05:24:49 +00001690
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02001691 stdin_encoding = _PyObject_GetAttrId(fin, &PyId_encoding);
Antoine Pitrou5ee9d8a2011-11-06 00:38:45 +01001692 stdin_errors = _PyObject_GetAttrId(fin, &PyId_errors);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001693 if (!stdin_encoding || !stdin_errors)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001694 /* stdin is a text stream, so it must have an
1695 encoding. */
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001696 goto _readline_errors;
Victor Stinner306f0102010-05-19 01:06:22 +00001697 stdin_encoding_str = _PyUnicode_AsString(stdin_encoding);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001698 stdin_errors_str = _PyUnicode_AsString(stdin_errors);
1699 if (!stdin_encoding_str || !stdin_errors_str)
1700 goto _readline_errors;
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001701 tmp = _PyObject_CallMethodId(fout, &PyId_flush, "");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001702 if (tmp == NULL)
1703 PyErr_Clear();
1704 else
1705 Py_DECREF(tmp);
1706 if (promptarg != NULL) {
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001707 /* We have a prompt, encode it as stdout would */
1708 char *stdout_encoding_str, *stdout_errors_str;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001709 PyObject *stringpo;
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02001710 stdout_encoding = _PyObject_GetAttrId(fout, &PyId_encoding);
Antoine Pitrou5ee9d8a2011-11-06 00:38:45 +01001711 stdout_errors = _PyObject_GetAttrId(fout, &PyId_errors);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001712 if (!stdout_encoding || !stdout_errors)
1713 goto _readline_errors;
Victor Stinner306f0102010-05-19 01:06:22 +00001714 stdout_encoding_str = _PyUnicode_AsString(stdout_encoding);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001715 stdout_errors_str = _PyUnicode_AsString(stdout_errors);
1716 if (!stdout_encoding_str || !stdout_errors_str)
1717 goto _readline_errors;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001718 stringpo = PyObject_Str(promptarg);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001719 if (stringpo == NULL)
1720 goto _readline_errors;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001721 po = PyUnicode_AsEncodedString(stringpo,
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001722 stdout_encoding_str, stdout_errors_str);
1723 Py_CLEAR(stdout_encoding);
1724 Py_CLEAR(stdout_errors);
1725 Py_CLEAR(stringpo);
1726 if (po == NULL)
1727 goto _readline_errors;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001728 prompt = PyBytes_AsString(po);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001729 if (prompt == NULL)
1730 goto _readline_errors;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001731 }
1732 else {
1733 po = NULL;
1734 prompt = "";
1735 }
1736 s = PyOS_Readline(stdin, stdout, prompt);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001737 if (s == NULL) {
1738 if (!PyErr_Occurred())
1739 PyErr_SetNone(PyExc_KeyboardInterrupt);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001740 goto _readline_errors;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001741 }
Victor Stinnerc0f1a1a2011-02-23 12:07:37 +00001742
1743 len = strlen(s);
1744 if (len == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001745 PyErr_SetNone(PyExc_EOFError);
1746 result = NULL;
1747 }
Victor Stinnerc0f1a1a2011-02-23 12:07:37 +00001748 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001749 if (len > PY_SSIZE_T_MAX) {
1750 PyErr_SetString(PyExc_OverflowError,
1751 "input: input too long");
1752 result = NULL;
1753 }
1754 else {
Victor Stinnerc0f1a1a2011-02-23 12:07:37 +00001755 len--; /* strip trailing '\n' */
1756 if (len != 0 && s[len-1] == '\r')
1757 len--; /* strip trailing '\r' */
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001758 result = PyUnicode_Decode(s, len, stdin_encoding_str,
1759 stdin_errors_str);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001760 }
1761 }
1762 Py_DECREF(stdin_encoding);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001763 Py_DECREF(stdin_errors);
1764 Py_XDECREF(po);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001765 PyMem_FREE(s);
1766 return result;
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001767 _readline_errors:
1768 Py_XDECREF(stdin_encoding);
1769 Py_XDECREF(stdout_encoding);
1770 Py_XDECREF(stdin_errors);
1771 Py_XDECREF(stdout_errors);
1772 Py_XDECREF(po);
1773 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001774 }
Guido van Rossumeba76962007-05-27 09:13:28 +00001775
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001776 /* Fallback if we're not interactive */
1777 if (promptarg != NULL) {
1778 if (PyFile_WriteObject(promptarg, fout, Py_PRINT_RAW) != 0)
1779 return NULL;
1780 }
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001781 tmp = _PyObject_CallMethodId(fout, &PyId_flush, "");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001782 if (tmp == NULL)
1783 PyErr_Clear();
1784 else
1785 Py_DECREF(tmp);
1786 return PyFile_GetLine(fin, -1);
Guido van Rossuma88a0332007-02-26 16:59:55 +00001787}
1788
1789PyDoc_STRVAR(input_doc,
1790"input([prompt]) -> string\n\
1791\n\
1792Read a string from standard input. The trailing newline is stripped.\n\
1793If the user hits EOF (Unix: Ctl-D, Windows: Ctl-Z+Return), raise EOFError.\n\
1794On Unix, GNU readline is used if enabled. The prompt string, if given,\n\
1795is printed without a trailing newline before reading.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001796
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001797
Guido van Rossum79f25d91997-04-29 20:08:16 +00001798static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001799builtin_repr(PyObject *self, PyObject *v)
Guido van Rossumc89705d1992-11-26 08:54:07 +00001800{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001801 return PyObject_Repr(v);
Guido van Rossumc89705d1992-11-26 08:54:07 +00001802}
1803
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001804PyDoc_STRVAR(repr_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001805"repr(object) -> string\n\
1806\n\
1807Return the canonical string representation of the object.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001808For most object types, eval(repr(object)) == object.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001809
1810
Guido van Rossum79f25d91997-04-29 20:08:16 +00001811static PyObject *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001812builtin_round(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum9e51f9b1993-02-12 16:29:05 +00001813{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001814 static PyObject *round_str = NULL;
1815 PyObject *ndigits = NULL;
1816 static char *kwlist[] = {"number", "ndigits", 0};
1817 PyObject *number, *round;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001818
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001819 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|O:round",
1820 kwlist, &number, &ndigits))
1821 return NULL;
Alex Martelliae211f92007-08-22 23:21:33 +00001822
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001823 if (Py_TYPE(number)->tp_dict == NULL) {
1824 if (PyType_Ready(Py_TYPE(number)) < 0)
1825 return NULL;
1826 }
Guido van Rossum15d3d042007-08-24 02:02:45 +00001827
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001828 if (round_str == NULL) {
1829 round_str = PyUnicode_InternFromString("__round__");
1830 if (round_str == NULL)
1831 return NULL;
1832 }
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001833
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001834 round = _PyType_Lookup(Py_TYPE(number), round_str);
1835 if (round == NULL) {
1836 PyErr_Format(PyExc_TypeError,
1837 "type %.100s doesn't define __round__ method",
1838 Py_TYPE(number)->tp_name);
1839 return NULL;
1840 }
Alex Martelliae211f92007-08-22 23:21:33 +00001841
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001842 if (ndigits == NULL)
1843 return PyObject_CallFunction(round, "O", number);
1844 else
1845 return PyObject_CallFunction(round, "OO", number, ndigits);
Guido van Rossum9e51f9b1993-02-12 16:29:05 +00001846}
1847
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001848PyDoc_STRVAR(round_doc,
Mark Dickinson1124e712009-01-28 21:25:58 +00001849"round(number[, ndigits]) -> number\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001850\n\
1851Round a number to a given precision in decimal digits (default 0 digits).\n\
Mark Dickinson0d748c22008-07-05 11:29:03 +00001852This returns an int when called with one argument, otherwise the\n\
Georg Brandl809ddaa2008-07-01 20:39:59 +00001853same type as the number. ndigits may be negative.");
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001854
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001855
Raymond Hettinger64958a12003-12-17 20:43:33 +00001856static PyObject *
1857builtin_sorted(PyObject *self, PyObject *args, PyObject *kwds)
1858{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001859 PyObject *newlist, *v, *seq, *keyfunc=NULL, *newargs;
1860 PyObject *callable;
1861 static char *kwlist[] = {"iterable", "key", "reverse", 0};
1862 int reverse;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02001863 _Py_IDENTIFIER(sort);
Raymond Hettinger64958a12003-12-17 20:43:33 +00001864
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001865 /* args 1-3 should match listsort in Objects/listobject.c */
1866 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|Oi:sorted",
1867 kwlist, &seq, &keyfunc, &reverse))
1868 return NULL;
Raymond Hettinger64958a12003-12-17 20:43:33 +00001869
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001870 newlist = PySequence_List(seq);
1871 if (newlist == NULL)
1872 return NULL;
Raymond Hettinger64958a12003-12-17 20:43:33 +00001873
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02001874 callable = _PyObject_GetAttrId(newlist, &PyId_sort);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001875 if (callable == NULL) {
1876 Py_DECREF(newlist);
1877 return NULL;
1878 }
Georg Brandl99d7e4e2005-08-31 22:21:15 +00001879
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001880 newargs = PyTuple_GetSlice(args, 1, 4);
1881 if (newargs == NULL) {
1882 Py_DECREF(newlist);
1883 Py_DECREF(callable);
1884 return NULL;
1885 }
Raymond Hettinger64958a12003-12-17 20:43:33 +00001886
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001887 v = PyObject_Call(callable, newargs, kwds);
1888 Py_DECREF(newargs);
1889 Py_DECREF(callable);
1890 if (v == NULL) {
1891 Py_DECREF(newlist);
1892 return NULL;
1893 }
1894 Py_DECREF(v);
1895 return newlist;
Raymond Hettinger64958a12003-12-17 20:43:33 +00001896}
1897
1898PyDoc_STRVAR(sorted_doc,
Raymond Hettinger70b64fc2008-01-30 20:15:17 +00001899"sorted(iterable, key=None, reverse=False) --> new sorted list");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001900
Guido van Rossum79f25d91997-04-29 20:08:16 +00001901static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001902builtin_vars(PyObject *self, PyObject *args)
Guido van Rossum2d951851994-08-29 12:52:16 +00001903{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001904 PyObject *v = NULL;
1905 PyObject *d;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001906
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001907 if (!PyArg_UnpackTuple(args, "vars", 0, 1, &v))
1908 return NULL;
1909 if (v == NULL) {
1910 d = PyEval_GetLocals();
1911 if (d == NULL) {
1912 if (!PyErr_Occurred())
1913 PyErr_SetString(PyExc_SystemError,
1914 "vars(): no locals!?");
1915 }
1916 else
1917 Py_INCREF(d);
1918 }
1919 else {
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02001920 _Py_IDENTIFIER(__dict__);
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02001921 d = _PyObject_GetAttrId(v, &PyId___dict__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001922 if (d == NULL) {
1923 PyErr_SetString(PyExc_TypeError,
1924 "vars() argument must have __dict__ attribute");
1925 return NULL;
1926 }
1927 }
1928 return d;
Guido van Rossum2d951851994-08-29 12:52:16 +00001929}
1930
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001931PyDoc_STRVAR(vars_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001932"vars([object]) -> dictionary\n\
1933\n\
1934Without arguments, equivalent to locals().\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001935With an argument, equivalent to object.__dict__.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001936
Alex Martellia70b1912003-04-22 08:12:33 +00001937static PyObject*
1938builtin_sum(PyObject *self, PyObject *args)
1939{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001940 PyObject *seq;
1941 PyObject *result = NULL;
1942 PyObject *temp, *item, *iter;
Alex Martellia70b1912003-04-22 08:12:33 +00001943
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001944 if (!PyArg_UnpackTuple(args, "sum", 1, 2, &seq, &result))
1945 return NULL;
Alex Martellia70b1912003-04-22 08:12:33 +00001946
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001947 iter = PyObject_GetIter(seq);
1948 if (iter == NULL)
1949 return NULL;
Alex Martellia70b1912003-04-22 08:12:33 +00001950
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001951 if (result == NULL) {
1952 result = PyLong_FromLong(0);
1953 if (result == NULL) {
1954 Py_DECREF(iter);
1955 return NULL;
1956 }
1957 } else {
1958 /* reject string values for 'start' parameter */
1959 if (PyUnicode_Check(result)) {
1960 PyErr_SetString(PyExc_TypeError,
1961 "sum() can't sum strings [use ''.join(seq) instead]");
1962 Py_DECREF(iter);
1963 return NULL;
1964 }
Benjamin Petersonce071ca2011-07-29 14:23:47 -05001965 if (PyBytes_Check(result)) {
1966 PyErr_SetString(PyExc_TypeError,
1967 "sum() can't sum bytes [use b''.join(seq) instead]");
Benjamin Peterson405f32c2011-07-29 22:43:45 -05001968 Py_DECREF(iter);
Benjamin Petersonce071ca2011-07-29 14:23:47 -05001969 return NULL;
1970 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001971 if (PyByteArray_Check(result)) {
1972 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson4f921c22011-07-29 14:24:29 -05001973 "sum() can't sum bytearray [use b''.join(seq) instead]");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001974 Py_DECREF(iter);
1975 return NULL;
1976 }
Guido van Rossum3172c5d2007-10-16 18:12:55 +00001977
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001978 Py_INCREF(result);
1979 }
Alex Martellia70b1912003-04-22 08:12:33 +00001980
Guido van Rossum8ce8a782007-11-01 19:42:39 +00001981#ifndef SLOW_SUM
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001982 /* Fast addition by keeping temporary sums in C instead of new Python objects.
1983 Assumes all inputs are the same type. If the assumption fails, default
1984 to the more general routine.
1985 */
1986 if (PyLong_CheckExact(result)) {
1987 int overflow;
1988 long i_result = PyLong_AsLongAndOverflow(result, &overflow);
1989 /* If this already overflowed, don't even enter the loop. */
1990 if (overflow == 0) {
1991 Py_DECREF(result);
1992 result = NULL;
1993 }
1994 while(result == NULL) {
1995 item = PyIter_Next(iter);
1996 if (item == NULL) {
1997 Py_DECREF(iter);
1998 if (PyErr_Occurred())
1999 return NULL;
2000 return PyLong_FromLong(i_result);
2001 }
2002 if (PyLong_CheckExact(item)) {
2003 long b = PyLong_AsLongAndOverflow(item, &overflow);
2004 long x = i_result + b;
2005 if (overflow == 0 && ((x^i_result) >= 0 || (x^b) >= 0)) {
2006 i_result = x;
2007 Py_DECREF(item);
2008 continue;
2009 }
2010 }
2011 /* Either overflowed or is not an int. Restore real objects and process normally */
2012 result = PyLong_FromLong(i_result);
2013 temp = PyNumber_Add(result, item);
2014 Py_DECREF(result);
2015 Py_DECREF(item);
2016 result = temp;
2017 if (result == NULL) {
2018 Py_DECREF(iter);
2019 return NULL;
2020 }
2021 }
2022 }
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002023
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002024 if (PyFloat_CheckExact(result)) {
2025 double f_result = PyFloat_AS_DOUBLE(result);
2026 Py_DECREF(result);
2027 result = NULL;
2028 while(result == NULL) {
2029 item = PyIter_Next(iter);
2030 if (item == NULL) {
2031 Py_DECREF(iter);
2032 if (PyErr_Occurred())
2033 return NULL;
2034 return PyFloat_FromDouble(f_result);
2035 }
2036 if (PyFloat_CheckExact(item)) {
2037 PyFPE_START_PROTECT("add", Py_DECREF(item); Py_DECREF(iter); return 0)
2038 f_result += PyFloat_AS_DOUBLE(item);
2039 PyFPE_END_PROTECT(f_result)
2040 Py_DECREF(item);
2041 continue;
2042 }
2043 if (PyLong_CheckExact(item)) {
2044 long value;
2045 int overflow;
2046 value = PyLong_AsLongAndOverflow(item, &overflow);
2047 if (!overflow) {
2048 PyFPE_START_PROTECT("add", Py_DECREF(item); Py_DECREF(iter); return 0)
2049 f_result += (double)value;
2050 PyFPE_END_PROTECT(f_result)
2051 Py_DECREF(item);
2052 continue;
2053 }
2054 }
2055 result = PyFloat_FromDouble(f_result);
2056 temp = PyNumber_Add(result, item);
2057 Py_DECREF(result);
2058 Py_DECREF(item);
2059 result = temp;
2060 if (result == NULL) {
2061 Py_DECREF(iter);
2062 return NULL;
2063 }
2064 }
2065 }
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002066#endif
2067
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002068 for(;;) {
2069 item = PyIter_Next(iter);
2070 if (item == NULL) {
2071 /* error, or end-of-sequence */
2072 if (PyErr_Occurred()) {
2073 Py_DECREF(result);
2074 result = NULL;
2075 }
2076 break;
2077 }
2078 /* It's tempting to use PyNumber_InPlaceAdd instead of
2079 PyNumber_Add here, to avoid quadratic running time
2080 when doing 'sum(list_of_lists, [])'. However, this
2081 would produce a change in behaviour: a snippet like
Mark Dickinson9acadc52009-10-26 14:19:42 +00002082
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002083 empty = []
2084 sum([[x] for x in range(10)], empty)
Mark Dickinson9acadc52009-10-26 14:19:42 +00002085
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002086 would change the value of empty. */
2087 temp = PyNumber_Add(result, item);
2088 Py_DECREF(result);
2089 Py_DECREF(item);
2090 result = temp;
2091 if (result == NULL)
2092 break;
2093 }
2094 Py_DECREF(iter);
2095 return result;
Alex Martellia70b1912003-04-22 08:12:33 +00002096}
2097
2098PyDoc_STRVAR(sum_doc,
Georg Brandld11ae5d2008-05-16 13:27:32 +00002099"sum(iterable[, start]) -> value\n\
Alex Martellia70b1912003-04-22 08:12:33 +00002100\n\
Georg Brandld11ae5d2008-05-16 13:27:32 +00002101Returns the sum of an iterable of numbers (NOT strings) plus the value\n\
2102of parameter 'start' (which defaults to 0). When the iterable is\n\
Thomas Wouters89f507f2006-12-13 04:49:30 +00002103empty, returns start.");
Alex Martellia70b1912003-04-22 08:12:33 +00002104
2105
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002106static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002107builtin_isinstance(PyObject *self, PyObject *args)
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002108{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002109 PyObject *inst;
2110 PyObject *cls;
2111 int retval;
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002112
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002113 if (!PyArg_UnpackTuple(args, "isinstance", 2, 2, &inst, &cls))
2114 return NULL;
Guido van Rossumf5dd9141997-12-02 19:11:45 +00002115
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002116 retval = PyObject_IsInstance(inst, cls);
2117 if (retval < 0)
2118 return NULL;
2119 return PyBool_FromLong(retval);
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002120}
2121
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002122PyDoc_STRVAR(isinstance_doc,
Guido van Rossum77f6a652002-04-03 22:41:51 +00002123"isinstance(object, class-or-type-or-tuple) -> bool\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002124\n\
2125Return whether an object is an instance of a class or of a subclass thereof.\n\
Guido van Rossum03290ec2001-10-07 20:54:12 +00002126With a type as second argument, return whether that is the object's type.\n\
2127The form using a tuple, isinstance(x, (A, B, ...)), is a shortcut for\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002128isinstance(x, A) or isinstance(x, B) or ... (etc.).");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002129
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002130
2131static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002132builtin_issubclass(PyObject *self, PyObject *args)
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002133{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002134 PyObject *derived;
2135 PyObject *cls;
2136 int retval;
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002137
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002138 if (!PyArg_UnpackTuple(args, "issubclass", 2, 2, &derived, &cls))
2139 return NULL;
Guido van Rossum668213d1999-06-16 17:28:37 +00002140
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002141 retval = PyObject_IsSubclass(derived, cls);
2142 if (retval < 0)
2143 return NULL;
2144 return PyBool_FromLong(retval);
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002145}
2146
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002147PyDoc_STRVAR(issubclass_doc,
Guido van Rossum77f6a652002-04-03 22:41:51 +00002148"issubclass(C, B) -> bool\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002149\n\
Walter Dörwaldd9a6ad32002-12-12 16:41:44 +00002150Return whether class C is a subclass (i.e., a derived class) of class B.\n\
2151When using a tuple as the second argument issubclass(X, (A, B, ...)),\n\
2152is a shortcut for issubclass(X, A) or issubclass(X, B) or ... (etc.).");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002153
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002154
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002155typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002156 PyObject_HEAD
2157 Py_ssize_t tuplesize;
2158 PyObject *ittuple; /* tuple of iterators */
2159 PyObject *result;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002160} zipobject;
2161
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002162static PyObject *
2163zip_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
Barry Warsawbd599b52000-08-03 15:45:29 +00002164{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002165 zipobject *lz;
2166 Py_ssize_t i;
2167 PyObject *ittuple; /* tuple of iterators */
2168 PyObject *result;
2169 Py_ssize_t tuplesize = PySequence_Length(args);
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002170
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002171 if (type == &PyZip_Type && !_PyArg_NoKeywords("zip()", kwds))
2172 return NULL;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002173
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002174 /* args must be a tuple */
2175 assert(PyTuple_Check(args));
Barry Warsawbd599b52000-08-03 15:45:29 +00002176
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002177 /* obtain iterators */
2178 ittuple = PyTuple_New(tuplesize);
2179 if (ittuple == NULL)
2180 return NULL;
2181 for (i=0; i < tuplesize; ++i) {
2182 PyObject *item = PyTuple_GET_ITEM(args, i);
2183 PyObject *it = PyObject_GetIter(item);
2184 if (it == NULL) {
2185 if (PyErr_ExceptionMatches(PyExc_TypeError))
2186 PyErr_Format(PyExc_TypeError,
2187 "zip argument #%zd must support iteration",
2188 i+1);
2189 Py_DECREF(ittuple);
2190 return NULL;
2191 }
2192 PyTuple_SET_ITEM(ittuple, i, it);
2193 }
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002194
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002195 /* create a result holder */
2196 result = PyTuple_New(tuplesize);
2197 if (result == NULL) {
2198 Py_DECREF(ittuple);
2199 return NULL;
2200 }
2201 for (i=0 ; i < tuplesize ; i++) {
2202 Py_INCREF(Py_None);
2203 PyTuple_SET_ITEM(result, i, Py_None);
2204 }
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002205
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002206 /* create zipobject structure */
2207 lz = (zipobject *)type->tp_alloc(type, 0);
2208 if (lz == NULL) {
2209 Py_DECREF(ittuple);
2210 Py_DECREF(result);
2211 return NULL;
2212 }
2213 lz->ittuple = ittuple;
2214 lz->tuplesize = tuplesize;
2215 lz->result = result;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002216
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002217 return (PyObject *)lz;
Barry Warsawbd599b52000-08-03 15:45:29 +00002218}
2219
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002220static void
2221zip_dealloc(zipobject *lz)
2222{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002223 PyObject_GC_UnTrack(lz);
2224 Py_XDECREF(lz->ittuple);
2225 Py_XDECREF(lz->result);
2226 Py_TYPE(lz)->tp_free(lz);
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002227}
2228
2229static int
2230zip_traverse(zipobject *lz, visitproc visit, void *arg)
2231{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002232 Py_VISIT(lz->ittuple);
2233 Py_VISIT(lz->result);
2234 return 0;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002235}
2236
2237static PyObject *
2238zip_next(zipobject *lz)
2239{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002240 Py_ssize_t i;
2241 Py_ssize_t tuplesize = lz->tuplesize;
2242 PyObject *result = lz->result;
2243 PyObject *it;
2244 PyObject *item;
2245 PyObject *olditem;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002246
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002247 if (tuplesize == 0)
2248 return NULL;
2249 if (Py_REFCNT(result) == 1) {
2250 Py_INCREF(result);
2251 for (i=0 ; i < tuplesize ; i++) {
2252 it = PyTuple_GET_ITEM(lz->ittuple, i);
2253 item = (*Py_TYPE(it)->tp_iternext)(it);
2254 if (item == NULL) {
2255 Py_DECREF(result);
2256 return NULL;
2257 }
2258 olditem = PyTuple_GET_ITEM(result, i);
2259 PyTuple_SET_ITEM(result, i, item);
2260 Py_DECREF(olditem);
2261 }
2262 } else {
2263 result = PyTuple_New(tuplesize);
2264 if (result == NULL)
2265 return NULL;
2266 for (i=0 ; i < tuplesize ; i++) {
2267 it = PyTuple_GET_ITEM(lz->ittuple, i);
2268 item = (*Py_TYPE(it)->tp_iternext)(it);
2269 if (item == NULL) {
2270 Py_DECREF(result);
2271 return NULL;
2272 }
2273 PyTuple_SET_ITEM(result, i, item);
2274 }
2275 }
2276 return result;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002277}
Barry Warsawbd599b52000-08-03 15:45:29 +00002278
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002279static PyObject *
2280zip_reduce(zipobject *lz)
2281{
2282 /* Just recreate the zip with the internal iterator tuple */
2283 return Py_BuildValue("OO", Py_TYPE(lz), lz->ittuple);
2284}
2285
2286static PyMethodDef zip_methods[] = {
2287 {"__reduce__", (PyCFunction)zip_reduce, METH_NOARGS, reduce_doc},
2288 {NULL, NULL} /* sentinel */
2289};
2290
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002291PyDoc_STRVAR(zip_doc,
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002292"zip(iter1 [,iter2 [...]]) --> zip object\n\
Barry Warsawbd599b52000-08-03 15:45:29 +00002293\n\
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002294Return a zip object whose .__next__() method returns a tuple where\n\
2295the i-th element comes from the i-th iterable argument. The .__next__()\n\
2296method continues until the shortest iterable in the argument sequence\n\
Georg Brandlced51db2008-12-04 18:28:38 +00002297is exhausted and then it raises StopIteration.");
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002298
2299PyTypeObject PyZip_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002300 PyVarObject_HEAD_INIT(&PyType_Type, 0)
2301 "zip", /* tp_name */
2302 sizeof(zipobject), /* tp_basicsize */
2303 0, /* tp_itemsize */
2304 /* methods */
2305 (destructor)zip_dealloc, /* tp_dealloc */
2306 0, /* tp_print */
2307 0, /* tp_getattr */
2308 0, /* tp_setattr */
2309 0, /* tp_reserved */
2310 0, /* tp_repr */
2311 0, /* tp_as_number */
2312 0, /* tp_as_sequence */
2313 0, /* tp_as_mapping */
2314 0, /* tp_hash */
2315 0, /* tp_call */
2316 0, /* tp_str */
2317 PyObject_GenericGetAttr, /* tp_getattro */
2318 0, /* tp_setattro */
2319 0, /* tp_as_buffer */
2320 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
2321 Py_TPFLAGS_BASETYPE, /* tp_flags */
2322 zip_doc, /* tp_doc */
2323 (traverseproc)zip_traverse, /* tp_traverse */
2324 0, /* tp_clear */
2325 0, /* tp_richcompare */
2326 0, /* tp_weaklistoffset */
2327 PyObject_SelfIter, /* tp_iter */
2328 (iternextfunc)zip_next, /* tp_iternext */
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002329 zip_methods, /* tp_methods */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002330 0, /* tp_members */
2331 0, /* tp_getset */
2332 0, /* tp_base */
2333 0, /* tp_dict */
2334 0, /* tp_descr_get */
2335 0, /* tp_descr_set */
2336 0, /* tp_dictoffset */
2337 0, /* tp_init */
2338 PyType_GenericAlloc, /* tp_alloc */
2339 zip_new, /* tp_new */
2340 PyObject_GC_Del, /* tp_free */
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002341};
Barry Warsawbd599b52000-08-03 15:45:29 +00002342
2343
Guido van Rossum79f25d91997-04-29 20:08:16 +00002344static PyMethodDef builtin_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002345 {"__build_class__", (PyCFunction)builtin___build_class__,
2346 METH_VARARGS | METH_KEYWORDS, build_class_doc},
2347 {"__import__", (PyCFunction)builtin___import__, METH_VARARGS | METH_KEYWORDS, import_doc},
2348 {"abs", builtin_abs, METH_O, abs_doc},
2349 {"all", builtin_all, METH_O, all_doc},
2350 {"any", builtin_any, METH_O, any_doc},
2351 {"ascii", builtin_ascii, METH_O, ascii_doc},
2352 {"bin", builtin_bin, METH_O, bin_doc},
Antoine Pitroue71362d2010-11-27 22:00:11 +00002353 {"callable", builtin_callable, METH_O, callable_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002354 {"chr", builtin_chr, METH_VARARGS, chr_doc},
2355 {"compile", (PyCFunction)builtin_compile, METH_VARARGS | METH_KEYWORDS, compile_doc},
2356 {"delattr", builtin_delattr, METH_VARARGS, delattr_doc},
2357 {"dir", builtin_dir, METH_VARARGS, dir_doc},
2358 {"divmod", builtin_divmod, METH_VARARGS, divmod_doc},
2359 {"eval", builtin_eval, METH_VARARGS, eval_doc},
2360 {"exec", builtin_exec, METH_VARARGS, exec_doc},
2361 {"format", builtin_format, METH_VARARGS, format_doc},
2362 {"getattr", builtin_getattr, METH_VARARGS, getattr_doc},
2363 {"globals", (PyCFunction)builtin_globals, METH_NOARGS, globals_doc},
2364 {"hasattr", builtin_hasattr, METH_VARARGS, hasattr_doc},
2365 {"hash", builtin_hash, METH_O, hash_doc},
2366 {"hex", builtin_hex, METH_O, hex_doc},
2367 {"id", builtin_id, METH_O, id_doc},
2368 {"input", builtin_input, METH_VARARGS, input_doc},
2369 {"isinstance", builtin_isinstance, METH_VARARGS, isinstance_doc},
2370 {"issubclass", builtin_issubclass, METH_VARARGS, issubclass_doc},
2371 {"iter", builtin_iter, METH_VARARGS, iter_doc},
2372 {"len", builtin_len, METH_O, len_doc},
2373 {"locals", (PyCFunction)builtin_locals, METH_NOARGS, locals_doc},
2374 {"max", (PyCFunction)builtin_max, METH_VARARGS | METH_KEYWORDS, max_doc},
2375 {"min", (PyCFunction)builtin_min, METH_VARARGS | METH_KEYWORDS, min_doc},
2376 {"next", (PyCFunction)builtin_next, METH_VARARGS, next_doc},
2377 {"oct", builtin_oct, METH_O, oct_doc},
2378 {"ord", builtin_ord, METH_O, ord_doc},
2379 {"pow", builtin_pow, METH_VARARGS, pow_doc},
2380 {"print", (PyCFunction)builtin_print, METH_VARARGS | METH_KEYWORDS, print_doc},
2381 {"repr", builtin_repr, METH_O, repr_doc},
2382 {"round", (PyCFunction)builtin_round, METH_VARARGS | METH_KEYWORDS, round_doc},
2383 {"setattr", builtin_setattr, METH_VARARGS, setattr_doc},
2384 {"sorted", (PyCFunction)builtin_sorted, METH_VARARGS | METH_KEYWORDS, sorted_doc},
2385 {"sum", builtin_sum, METH_VARARGS, sum_doc},
2386 {"vars", builtin_vars, METH_VARARGS, vars_doc},
2387 {NULL, NULL},
Guido van Rossum3f5da241990-12-20 15:06:42 +00002388};
2389
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002390PyDoc_STRVAR(builtin_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002391"Built-in functions, exceptions, and other objects.\n\
2392\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002393Noteworthy: None is the `nil' object; Ellipsis represents `...' in slices.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002394
Martin v. Löwis1a214512008-06-11 05:26:20 +00002395static struct PyModuleDef builtinsmodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002396 PyModuleDef_HEAD_INIT,
2397 "builtins",
2398 builtin_doc,
2399 -1, /* multiple "initialization" just copies the module dict. */
2400 builtin_methods,
2401 NULL,
2402 NULL,
2403 NULL,
2404 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00002405};
2406
2407
Guido van Rossum25ce5661997-08-02 03:10:38 +00002408PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002409_PyBuiltin_Init(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +00002410{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002411 PyObject *mod, *dict, *debug;
2412 mod = PyModule_Create(&builtinsmodule);
2413 if (mod == NULL)
2414 return NULL;
2415 dict = PyModule_GetDict(mod);
Tim Peters4b7625e2001-09-13 21:37:17 +00002416
Tim Peters7571a0f2003-03-23 17:52:28 +00002417#ifdef Py_TRACE_REFS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002418 /* "builtins" exposes a number of statically allocated objects
2419 * that, before this code was added in 2.3, never showed up in
2420 * the list of "all objects" maintained by Py_TRACE_REFS. As a
2421 * result, programs leaking references to None and False (etc)
2422 * couldn't be diagnosed by examining sys.getobjects(0).
2423 */
Tim Peters7571a0f2003-03-23 17:52:28 +00002424#define ADD_TO_ALL(OBJECT) _Py_AddToAllObjects((PyObject *)(OBJECT), 0)
2425#else
2426#define ADD_TO_ALL(OBJECT) (void)0
2427#endif
2428
Tim Peters4b7625e2001-09-13 21:37:17 +00002429#define SETBUILTIN(NAME, OBJECT) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002430 if (PyDict_SetItemString(dict, NAME, (PyObject *)OBJECT) < 0) \
2431 return NULL; \
2432 ADD_TO_ALL(OBJECT)
Tim Peters4b7625e2001-09-13 21:37:17 +00002433
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002434 SETBUILTIN("None", Py_None);
2435 SETBUILTIN("Ellipsis", Py_Ellipsis);
2436 SETBUILTIN("NotImplemented", Py_NotImplemented);
2437 SETBUILTIN("False", Py_False);
2438 SETBUILTIN("True", Py_True);
2439 SETBUILTIN("bool", &PyBool_Type);
2440 SETBUILTIN("memoryview", &PyMemoryView_Type);
2441 SETBUILTIN("bytearray", &PyByteArray_Type);
2442 SETBUILTIN("bytes", &PyBytes_Type);
2443 SETBUILTIN("classmethod", &PyClassMethod_Type);
2444 SETBUILTIN("complex", &PyComplex_Type);
2445 SETBUILTIN("dict", &PyDict_Type);
2446 SETBUILTIN("enumerate", &PyEnum_Type);
2447 SETBUILTIN("filter", &PyFilter_Type);
2448 SETBUILTIN("float", &PyFloat_Type);
2449 SETBUILTIN("frozenset", &PyFrozenSet_Type);
2450 SETBUILTIN("property", &PyProperty_Type);
2451 SETBUILTIN("int", &PyLong_Type);
2452 SETBUILTIN("list", &PyList_Type);
2453 SETBUILTIN("map", &PyMap_Type);
2454 SETBUILTIN("object", &PyBaseObject_Type);
2455 SETBUILTIN("range", &PyRange_Type);
2456 SETBUILTIN("reversed", &PyReversed_Type);
2457 SETBUILTIN("set", &PySet_Type);
2458 SETBUILTIN("slice", &PySlice_Type);
2459 SETBUILTIN("staticmethod", &PyStaticMethod_Type);
2460 SETBUILTIN("str", &PyUnicode_Type);
2461 SETBUILTIN("super", &PySuper_Type);
2462 SETBUILTIN("tuple", &PyTuple_Type);
2463 SETBUILTIN("type", &PyType_Type);
2464 SETBUILTIN("zip", &PyZip_Type);
2465 debug = PyBool_FromLong(Py_OptimizeFlag == 0);
2466 if (PyDict_SetItemString(dict, "__debug__", debug) < 0) {
2467 Py_XDECREF(debug);
2468 return NULL;
2469 }
2470 Py_XDECREF(debug);
Barry Warsaw757af0e1997-08-29 22:13:51 +00002471
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002472 return mod;
Tim Peters7571a0f2003-03-23 17:52:28 +00002473#undef ADD_TO_ALL
Tim Peters4b7625e2001-09-13 21:37:17 +00002474#undef SETBUILTIN
Guido van Rossum3f5da241990-12-20 15:06:42 +00002475}