blob: 53009e3fbdc77dc6b9cc67902b548a4fe8ca0363 [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
Victor Stinnerbd303c12013-11-07 23:07:29 +010035_Py_IDENTIFIER(__builtins__);
36_Py_IDENTIFIER(__dict__);
37_Py_IDENTIFIER(__prepare__);
38_Py_IDENTIFIER(__round__);
39_Py_IDENTIFIER(encoding);
40_Py_IDENTIFIER(errors);
Martin v. Löwisbd928fe2011-10-14 10:20:37 +020041_Py_IDENTIFIER(fileno);
42_Py_IDENTIFIER(flush);
Victor Stinnerbd303c12013-11-07 23:07:29 +010043_Py_IDENTIFIER(metaclass);
44_Py_IDENTIFIER(sort);
45_Py_IDENTIFIER(stdin);
46_Py_IDENTIFIER(stdout);
47_Py_IDENTIFIER(stderr);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +020048
Guido van Rossum79f25d91997-04-29 20:08:16 +000049static PyObject *
Guido van Rossum52cc1d82007-03-18 15:41:51 +000050builtin___build_class__(PyObject *self, PyObject *args, PyObject *kwds)
51{
Nick Coghlande31b192011-10-23 22:04:16 +100052 PyObject *func, *name, *bases, *mkw, *meta, *winner, *prep, *ns, *cell;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000053 PyObject *cls = NULL;
Florent Xicluna4d46c2a2011-10-28 15:00:50 +020054 Py_ssize_t nargs;
Nick Coghlande31b192011-10-23 22:04:16 +100055 int isclass;
Guido van Rossum52cc1d82007-03-18 15:41:51 +000056
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000057 assert(args != NULL);
58 if (!PyTuple_Check(args)) {
59 PyErr_SetString(PyExc_TypeError,
60 "__build_class__: args is not a tuple");
61 return NULL;
62 }
63 nargs = PyTuple_GET_SIZE(args);
64 if (nargs < 2) {
65 PyErr_SetString(PyExc_TypeError,
66 "__build_class__: not enough arguments");
67 return NULL;
68 }
69 func = PyTuple_GET_ITEM(args, 0); /* Better be callable */
Benjamin Petersone8e14592013-05-16 14:37:25 -050070 if (!PyFunction_Check(func)) {
71 PyErr_SetString(PyExc_TypeError,
Zachary Ware9b338722014-08-05 14:01:10 -050072 "__build_class__: func must be a function");
Benjamin Petersone8e14592013-05-16 14:37:25 -050073 return NULL;
74 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000075 name = PyTuple_GET_ITEM(args, 1);
76 if (!PyUnicode_Check(name)) {
77 PyErr_SetString(PyExc_TypeError,
78 "__build_class__: name is not a string");
79 return NULL;
80 }
81 bases = PyTuple_GetSlice(args, 2, nargs);
82 if (bases == NULL)
83 return NULL;
Guido van Rossum52cc1d82007-03-18 15:41:51 +000084
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000085 if (kwds == NULL) {
86 meta = NULL;
87 mkw = NULL;
88 }
89 else {
90 mkw = PyDict_Copy(kwds); /* Don't modify kwds passed in! */
91 if (mkw == NULL) {
92 Py_DECREF(bases);
93 return NULL;
Guido van Rossum52cc1d82007-03-18 15:41:51 +000094 }
Victor Stinnerae9f1612013-11-06 22:46:51 +010095 meta = _PyDict_GetItemId(mkw, &PyId_metaclass);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000096 if (meta != NULL) {
97 Py_INCREF(meta);
Victor Stinnerae9f1612013-11-06 22:46:51 +010098 if (_PyDict_DelItemId(mkw, &PyId_metaclass) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000099 Py_DECREF(meta);
100 Py_DECREF(mkw);
101 Py_DECREF(bases);
102 return NULL;
103 }
Nick Coghlande31b192011-10-23 22:04:16 +1000104 /* metaclass is explicitly given, check if it's indeed a class */
105 isclass = PyType_Check(meta);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000106 }
107 }
108 if (meta == NULL) {
Nick Coghlande31b192011-10-23 22:04:16 +1000109 /* if there are no bases, use type: */
110 if (PyTuple_GET_SIZE(bases) == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000111 meta = (PyObject *) (&PyType_Type);
Nick Coghlande31b192011-10-23 22:04:16 +1000112 }
113 /* else get the type of the first base */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000114 else {
115 PyObject *base0 = PyTuple_GET_ITEM(bases, 0);
116 meta = (PyObject *) (base0->ob_type);
117 }
118 Py_INCREF(meta);
Nick Coghlande31b192011-10-23 22:04:16 +1000119 isclass = 1; /* meta is really a class */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000120 }
Nick Coghlan9715d262011-10-23 22:36:42 +1000121
Nick Coghlande31b192011-10-23 22:04:16 +1000122 if (isclass) {
123 /* meta is really a class, so check for a more derived
124 metaclass, or possible metaclass conflicts: */
125 winner = (PyObject *)_PyType_CalculateMetaclass((PyTypeObject *)meta,
126 bases);
127 if (winner == NULL) {
128 Py_DECREF(meta);
129 Py_XDECREF(mkw);
130 Py_DECREF(bases);
131 return NULL;
132 }
133 if (winner != meta) {
134 Py_DECREF(meta);
135 meta = winner;
136 Py_INCREF(meta);
137 }
138 }
139 /* else: meta is not a class, so we cannot do the metaclass
140 calculation, so we will use the explicitly given object as it is */
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +0200141 prep = _PyObject_GetAttrId(meta, &PyId___prepare__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000142 if (prep == NULL) {
143 if (PyErr_ExceptionMatches(PyExc_AttributeError)) {
144 PyErr_Clear();
145 ns = PyDict_New();
146 }
147 else {
148 Py_DECREF(meta);
149 Py_XDECREF(mkw);
150 Py_DECREF(bases);
151 return NULL;
152 }
153 }
154 else {
155 PyObject *pargs = PyTuple_Pack(2, name, bases);
156 if (pargs == NULL) {
157 Py_DECREF(prep);
158 Py_DECREF(meta);
159 Py_XDECREF(mkw);
160 Py_DECREF(bases);
161 return NULL;
162 }
163 ns = PyEval_CallObjectWithKeywords(prep, pargs, mkw);
164 Py_DECREF(pargs);
165 Py_DECREF(prep);
166 }
167 if (ns == NULL) {
168 Py_DECREF(meta);
169 Py_XDECREF(mkw);
170 Py_DECREF(bases);
171 return NULL;
172 }
Benjamin Petersone8e14592013-05-16 14:37:25 -0500173 cell = PyEval_EvalCodeEx(PyFunction_GET_CODE(func), PyFunction_GET_GLOBALS(func), ns,
174 NULL, 0, NULL, 0, NULL, 0, NULL,
175 PyFunction_GET_CLOSURE(func));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000176 if (cell != NULL) {
177 PyObject *margs;
178 margs = PyTuple_Pack(3, name, bases, ns);
179 if (margs != NULL) {
180 cls = PyEval_CallObjectWithKeywords(meta, margs, mkw);
181 Py_DECREF(margs);
182 }
Benjamin Peterson8e8fbea2012-06-01 23:57:36 -0700183 if (cls != NULL && PyCell_Check(cell))
184 PyCell_Set(cell, cls);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000185 Py_DECREF(cell);
186 }
187 Py_DECREF(ns);
188 Py_DECREF(meta);
189 Py_XDECREF(mkw);
190 Py_DECREF(bases);
191 return cls;
Guido van Rossum52cc1d82007-03-18 15:41:51 +0000192}
193
194PyDoc_STRVAR(build_class_doc,
195"__build_class__(func, name, *bases, metaclass=None, **kwds) -> class\n\
196\n\
197Internal helper function used by the class statement.");
198
199static PyObject *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000200builtin___import__(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000201{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000202 static char *kwlist[] = {"name", "globals", "locals", "fromlist",
203 "level", 0};
Victor Stinnerfe93faf2011-03-14 15:54:52 -0400204 PyObject *name, *globals = NULL, *locals = NULL, *fromlist = NULL;
Brett Cannonfd074152012-04-14 14:10:13 -0400205 int level = 0;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000206
Victor Stinnerfe93faf2011-03-14 15:54:52 -0400207 if (!PyArg_ParseTupleAndKeywords(args, kwds, "U|OOOi:__import__",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000208 kwlist, &name, &globals, &locals, &fromlist, &level))
209 return NULL;
Victor Stinnerfe93faf2011-03-14 15:54:52 -0400210 return PyImport_ImportModuleLevelObject(name, globals, locals,
211 fromlist, level);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000212}
213
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000214PyDoc_STRVAR(import_doc,
Brett Cannoncb4996a2012-08-06 16:34:44 -0400215"__import__(name, globals=None, locals=None, fromlist=(), level=0) -> module\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000216\n\
Brett Cannon5305a992010-09-27 21:08:38 +0000217Import a module. Because this function is meant for use by the Python\n\
218interpreter and not for general use it is better to use\n\
219importlib.import_module() to programmatically import a module.\n\
220\n\
221The globals argument is only used to determine the context;\n\
222they are not modified. The locals argument is unused. The fromlist\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000223should be a list of names to emulate ``from name import ...'', or an\n\
224empty list to emulate ``import name''.\n\
225When importing a module from a package, note that __import__('A.B', ...)\n\
226returns package A when fromlist is empty, but its submodule B when\n\
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000227fromlist is not empty. Level is used to determine whether to perform \n\
Brett Cannon722d3ae2012-07-30 17:45:54 -0400228absolute or relative imports. 0 is absolute while a positive number\n\
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000229is the number of parent directories to search relative to the current module.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000230
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000231
Guido van Rossum79f25d91997-04-29 20:08:16 +0000232static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000233builtin_abs(PyObject *self, PyObject *v)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000234{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000235 return PyNumber_Absolute(v);
Guido van Rossum3f5da241990-12-20 15:06:42 +0000236}
237
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000238PyDoc_STRVAR(abs_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000239"abs(number) -> number\n\
240\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000241Return the absolute value of the argument.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000242
Raymond Hettinger96229b12005-03-11 06:49:40 +0000243static PyObject *
244builtin_all(PyObject *self, PyObject *v)
245{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000246 PyObject *it, *item;
247 PyObject *(*iternext)(PyObject *);
248 int cmp;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000249
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000250 it = PyObject_GetIter(v);
251 if (it == NULL)
252 return NULL;
253 iternext = *Py_TYPE(it)->tp_iternext;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000254
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000255 for (;;) {
256 item = iternext(it);
257 if (item == NULL)
258 break;
259 cmp = PyObject_IsTrue(item);
260 Py_DECREF(item);
261 if (cmp < 0) {
262 Py_DECREF(it);
263 return NULL;
264 }
265 if (cmp == 0) {
266 Py_DECREF(it);
267 Py_RETURN_FALSE;
268 }
269 }
270 Py_DECREF(it);
271 if (PyErr_Occurred()) {
272 if (PyErr_ExceptionMatches(PyExc_StopIteration))
273 PyErr_Clear();
274 else
275 return NULL;
276 }
277 Py_RETURN_TRUE;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000278}
279
280PyDoc_STRVAR(all_doc,
281"all(iterable) -> bool\n\
282\n\
Ezio Melottib19ed572013-02-15 23:35:14 +0200283Return True if bool(x) is True for all values x in the iterable.\n\
284If the iterable is empty, return True.");
Raymond Hettinger96229b12005-03-11 06:49:40 +0000285
286static PyObject *
287builtin_any(PyObject *self, PyObject *v)
288{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000289 PyObject *it, *item;
290 PyObject *(*iternext)(PyObject *);
291 int cmp;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000292
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000293 it = PyObject_GetIter(v);
294 if (it == NULL)
295 return NULL;
296 iternext = *Py_TYPE(it)->tp_iternext;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000297
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000298 for (;;) {
299 item = iternext(it);
300 if (item == NULL)
301 break;
302 cmp = PyObject_IsTrue(item);
303 Py_DECREF(item);
304 if (cmp < 0) {
305 Py_DECREF(it);
306 return NULL;
307 }
308 if (cmp == 1) {
309 Py_DECREF(it);
310 Py_RETURN_TRUE;
311 }
312 }
313 Py_DECREF(it);
314 if (PyErr_Occurred()) {
315 if (PyErr_ExceptionMatches(PyExc_StopIteration))
316 PyErr_Clear();
317 else
318 return NULL;
319 }
320 Py_RETURN_FALSE;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000321}
322
323PyDoc_STRVAR(any_doc,
324"any(iterable) -> bool\n\
325\n\
Ezio Melottib19ed572013-02-15 23:35:14 +0200326Return True if bool(x) is True for any x in the iterable.\n\
327If the iterable is empty, return False.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000328
Georg Brandl559e5d72008-06-11 18:37:52 +0000329static PyObject *
330builtin_ascii(PyObject *self, PyObject *v)
331{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000332 return PyObject_ASCII(v);
Georg Brandl559e5d72008-06-11 18:37:52 +0000333}
334
335PyDoc_STRVAR(ascii_doc,
336"ascii(object) -> string\n\
337\n\
338As repr(), return a string containing a printable representation of an\n\
339object, but escape the non-ASCII characters in the string returned by\n\
340repr() using \\x, \\u or \\U escapes. This generates a string similar\n\
341to that returned by repr() in Python 2.");
342
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000343
Guido van Rossum79f25d91997-04-29 20:08:16 +0000344static PyObject *
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000345builtin_bin(PyObject *self, PyObject *v)
346{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000347 return PyNumber_ToBase(v, 2);
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000348}
349
350PyDoc_STRVAR(bin_doc,
351"bin(number) -> string\n\
352\n\
Zachary Warea4b7a752013-11-24 01:19:09 -0600353Return the binary representation of an integer.\n\
354\n\
355 >>> bin(2796202)\n\
356 '0b1010101010101010101010'\n\
357");
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000358
359
Antoine Pitroue71362d2010-11-27 22:00:11 +0000360static PyObject *
361builtin_callable(PyObject *self, PyObject *v)
362{
363 return PyBool_FromLong((long)PyCallable_Check(v));
364}
365
366PyDoc_STRVAR(callable_doc,
367"callable(object) -> bool\n\
368\n\
369Return whether the object is callable (i.e., some kind of function).\n\
370Note that classes are callable, as are instances of classes with a\n\
371__call__() method.");
372
373
Raymond Hettinger17301e92008-03-13 00:19:26 +0000374typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000375 PyObject_HEAD
376 PyObject *func;
377 PyObject *it;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000378} filterobject;
379
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000380static PyObject *
Raymond Hettinger17301e92008-03-13 00:19:26 +0000381filter_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
Guido van Rossum12d12c51993-10-26 17:58:25 +0000382{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000383 PyObject *func, *seq;
384 PyObject *it;
385 filterobject *lz;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000386
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000387 if (type == &PyFilter_Type && !_PyArg_NoKeywords("filter()", kwds))
388 return NULL;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000389
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000390 if (!PyArg_UnpackTuple(args, "filter", 2, 2, &func, &seq))
391 return NULL;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000392
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000393 /* Get iterator. */
394 it = PyObject_GetIter(seq);
395 if (it == NULL)
396 return NULL;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000397
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000398 /* create filterobject structure */
399 lz = (filterobject *)type->tp_alloc(type, 0);
400 if (lz == NULL) {
401 Py_DECREF(it);
402 return NULL;
403 }
404 Py_INCREF(func);
405 lz->func = func;
406 lz->it = it;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000407
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000408 return (PyObject *)lz;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000409}
410
411static void
412filter_dealloc(filterobject *lz)
413{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000414 PyObject_GC_UnTrack(lz);
415 Py_XDECREF(lz->func);
416 Py_XDECREF(lz->it);
417 Py_TYPE(lz)->tp_free(lz);
Raymond Hettinger17301e92008-03-13 00:19:26 +0000418}
419
420static int
421filter_traverse(filterobject *lz, visitproc visit, void *arg)
422{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000423 Py_VISIT(lz->it);
424 Py_VISIT(lz->func);
425 return 0;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000426}
427
428static PyObject *
429filter_next(filterobject *lz)
430{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000431 PyObject *item;
432 PyObject *it = lz->it;
433 long ok;
434 PyObject *(*iternext)(PyObject *);
Raymond Hettinger17301e92008-03-13 00:19:26 +0000435
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000436 iternext = *Py_TYPE(it)->tp_iternext;
437 for (;;) {
438 item = iternext(it);
439 if (item == NULL)
440 return NULL;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000441
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000442 if (lz->func == Py_None || lz->func == (PyObject *)&PyBool_Type) {
443 ok = PyObject_IsTrue(item);
444 } else {
445 PyObject *good;
446 good = PyObject_CallFunctionObjArgs(lz->func,
447 item, NULL);
448 if (good == NULL) {
449 Py_DECREF(item);
450 return NULL;
451 }
452 ok = PyObject_IsTrue(good);
453 Py_DECREF(good);
454 }
Antoine Pitrou6f430e42012-08-15 23:18:25 +0200455 if (ok > 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000456 return item;
457 Py_DECREF(item);
Antoine Pitrou6f430e42012-08-15 23:18:25 +0200458 if (ok < 0)
459 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000460 }
Guido van Rossum12d12c51993-10-26 17:58:25 +0000461}
462
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +0000463static PyObject *
464filter_reduce(filterobject *lz)
465{
466 return Py_BuildValue("O(OO)", Py_TYPE(lz), lz->func, lz->it);
467}
468
469PyDoc_STRVAR(reduce_doc, "Return state information for pickling.");
470
471static PyMethodDef filter_methods[] = {
472 {"__reduce__", (PyCFunction)filter_reduce, METH_NOARGS, reduce_doc},
473 {NULL, NULL} /* sentinel */
474};
475
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000476PyDoc_STRVAR(filter_doc,
Georg Brandld11ae5d2008-05-16 13:27:32 +0000477"filter(function or None, iterable) --> filter object\n\
Guido van Rossumc1f779c2007-07-03 08:25:58 +0000478\n\
Georg Brandld11ae5d2008-05-16 13:27:32 +0000479Return an iterator yielding those items of iterable for which function(item)\n\
Raymond Hettinger17301e92008-03-13 00:19:26 +0000480is true. If function is None, return the items that are true.");
481
482PyTypeObject PyFilter_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000483 PyVarObject_HEAD_INIT(&PyType_Type, 0)
484 "filter", /* tp_name */
485 sizeof(filterobject), /* tp_basicsize */
486 0, /* tp_itemsize */
487 /* methods */
488 (destructor)filter_dealloc, /* tp_dealloc */
489 0, /* tp_print */
490 0, /* tp_getattr */
491 0, /* tp_setattr */
492 0, /* tp_reserved */
493 0, /* tp_repr */
494 0, /* tp_as_number */
495 0, /* tp_as_sequence */
496 0, /* tp_as_mapping */
497 0, /* tp_hash */
498 0, /* tp_call */
499 0, /* tp_str */
500 PyObject_GenericGetAttr, /* tp_getattro */
501 0, /* tp_setattro */
502 0, /* tp_as_buffer */
503 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
504 Py_TPFLAGS_BASETYPE, /* tp_flags */
505 filter_doc, /* tp_doc */
506 (traverseproc)filter_traverse, /* tp_traverse */
507 0, /* tp_clear */
508 0, /* tp_richcompare */
509 0, /* tp_weaklistoffset */
510 PyObject_SelfIter, /* tp_iter */
511 (iternextfunc)filter_next, /* tp_iternext */
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +0000512 filter_methods, /* tp_methods */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000513 0, /* tp_members */
514 0, /* tp_getset */
515 0, /* tp_base */
516 0, /* tp_dict */
517 0, /* tp_descr_get */
518 0, /* tp_descr_set */
519 0, /* tp_dictoffset */
520 0, /* tp_init */
521 PyType_GenericAlloc, /* tp_alloc */
522 filter_new, /* tp_new */
523 PyObject_GC_Del, /* tp_free */
Raymond Hettinger17301e92008-03-13 00:19:26 +0000524};
525
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000526
Eric Smith8c663262007-08-25 02:26:07 +0000527static PyObject *
528builtin_format(PyObject *self, PyObject *args)
529{
Christian Heimes94b7d3d2007-12-11 20:20:39 +0000530 PyObject *value;
Eric Smith8fd3eba2008-02-17 19:48:00 +0000531 PyObject *format_spec = NULL;
Eric Smith8c663262007-08-25 02:26:07 +0000532
Eric Smith8fd3eba2008-02-17 19:48:00 +0000533 if (!PyArg_ParseTuple(args, "O|U:format", &value, &format_spec))
Benjamin Petersona12d5c62012-01-03 16:47:22 -0600534 return NULL;
Eric Smith8c663262007-08-25 02:26:07 +0000535
Eric Smith8fd3eba2008-02-17 19:48:00 +0000536 return PyObject_Format(value, format_spec);
Eric Smith8c663262007-08-25 02:26:07 +0000537}
538
Eric Smith8c663262007-08-25 02:26:07 +0000539PyDoc_STRVAR(format_doc,
Eric Smith81936692007-08-31 01:14:01 +0000540"format(value[, format_spec]) -> string\n\
Eric Smith8c663262007-08-25 02:26:07 +0000541\n\
Eric Smith81936692007-08-31 01:14:01 +0000542Returns value.__format__(format_spec)\n\
543format_spec defaults to \"\"");
544
Guido van Rossum7fcf2242007-05-04 17:43:11 +0000545static PyObject *
Walter Dörwalde7efd592007-06-05 20:07:21 +0000546builtin_chr(PyObject *self, PyObject *args)
Guido van Rossum09095f32000-03-10 23:00:52 +0000547{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000548 int x;
Guido van Rossum09095f32000-03-10 23:00:52 +0000549
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000550 if (!PyArg_ParseTuple(args, "i:chr", &x))
551 return NULL;
Fredrik Lundh0dcf67e2001-06-26 20:01:56 +0000552
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000553 return PyUnicode_FromOrdinal(x);
Guido van Rossum09095f32000-03-10 23:00:52 +0000554}
555
Victor Stinner63ab8752011-11-22 03:31:20 +0100556PyDoc_STRVAR(chr_doc,
Guido van Rossum84fc66d2007-05-03 17:18:26 +0000557"chr(i) -> Unicode character\n\
Guido van Rossum09095f32000-03-10 23:00:52 +0000558\n\
Victor Stinner63ab8752011-11-22 03:31:20 +0100559Return a Unicode string of one character with ordinal i; 0 <= i <= 0x10ffff.");
Guido van Rossum09095f32000-03-10 23:00:52 +0000560
561
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +0200562static const char *
Martin Pantereeb896c2015-11-07 02:32:21 +0000563source_as_string(PyObject *cmd, const char *funcname, const char *what, PyCompilerFlags *cf, PyObject **cmd_copy)
Guido van Rossumf15a29f2007-05-04 00:41:39 +0000564{
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +0200565 const char *str;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000566 Py_ssize_t size;
Martin Pantereeb896c2015-11-07 02:32:21 +0000567 Py_buffer view;
Guido van Rossumf15a29f2007-05-04 00:41:39 +0000568
Martin Pantereeb896c2015-11-07 02:32:21 +0000569 *cmd_copy = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000570 if (PyUnicode_Check(cmd)) {
571 cf->cf_flags |= PyCF_IGNORE_COOKIE;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200572 str = PyUnicode_AsUTF8AndSize(cmd, &size);
573 if (str == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000574 return NULL;
575 }
Martin Pantereeb896c2015-11-07 02:32:21 +0000576 else if (PyBytes_Check(cmd)) {
577 str = PyBytes_AS_STRING(cmd);
578 size = PyBytes_GET_SIZE(cmd);
579 }
580 else if (PyByteArray_Check(cmd)) {
581 str = PyByteArray_AS_STRING(cmd);
582 size = PyByteArray_GET_SIZE(cmd);
583 }
584 else if (PyObject_GetBuffer(cmd, &view, PyBUF_SIMPLE) == 0) {
585 /* Copy to NUL-terminated buffer. */
586 *cmd_copy = PyBytes_FromStringAndSize(
587 (const char *)view.buf, view.len);
588 PyBuffer_Release(&view);
589 if (*cmd_copy == NULL) {
590 return NULL;
591 }
592 str = PyBytes_AS_STRING(*cmd_copy);
593 size = PyBytes_GET_SIZE(*cmd_copy);
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +0200594 }
595 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000596 PyErr_Format(PyExc_TypeError,
597 "%s() arg 1 must be a %s object",
598 funcname, what);
599 return NULL;
600 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200601
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000602 if (strlen(str) != size) {
603 PyErr_SetString(PyExc_TypeError,
604 "source code string cannot contain null bytes");
Martin Pantereeb896c2015-11-07 02:32:21 +0000605 Py_CLEAR(*cmd_copy);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000606 return NULL;
607 }
608 return str;
Guido van Rossumf15a29f2007-05-04 00:41:39 +0000609}
610
Guido van Rossum79f25d91997-04-29 20:08:16 +0000611static PyObject *
Guido van Rossumd8faa362007-04-27 19:54:29 +0000612builtin_compile(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum5b722181993-03-30 17:46:03 +0000613{
Martin Pantereeb896c2015-11-07 02:32:21 +0000614 PyObject *cmd_copy;
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +0200615 const char *str;
Victor Stinner14e461d2013-08-26 22:28:21 +0200616 PyObject *filename;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000617 char *startstr;
618 int mode = -1;
619 int dont_inherit = 0;
620 int supplied_flags = 0;
Georg Brandl8334fd92010-12-04 10:26:46 +0000621 int optimize = -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000622 int is_ast;
623 PyCompilerFlags cf;
624 PyObject *cmd;
625 static char *kwlist[] = {"source", "filename", "mode", "flags",
Georg Brandl8334fd92010-12-04 10:26:46 +0000626 "dont_inherit", "optimize", NULL};
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000627 int start[] = {Py_file_input, Py_eval_input, Py_single_input};
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000628 PyObject *result;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000629
Georg Brandl8334fd92010-12-04 10:26:46 +0000630 if (!PyArg_ParseTupleAndKeywords(args, kwds, "OO&s|iii:compile", kwlist,
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000631 &cmd,
Victor Stinner14e461d2013-08-26 22:28:21 +0200632 PyUnicode_FSDecoder, &filename,
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000633 &startstr, &supplied_flags,
Georg Brandl8334fd92010-12-04 10:26:46 +0000634 &dont_inherit, &optimize))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000635 return NULL;
Tim Peters6cd6a822001-08-17 22:11:27 +0000636
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000637 cf.cf_flags = supplied_flags | PyCF_SOURCE_IS_UTF8;
Just van Rossum3aaf42c2003-02-10 08:21:10 +0000638
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000639 if (supplied_flags &
640 ~(PyCF_MASK | PyCF_MASK_OBSOLETE | PyCF_DONT_IMPLY_DEDENT | PyCF_ONLY_AST))
641 {
642 PyErr_SetString(PyExc_ValueError,
643 "compile(): unrecognised flags");
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000644 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000645 }
646 /* XXX Warn if (supplied_flags & PyCF_MASK_OBSOLETE) != 0? */
Tim Peters6cd6a822001-08-17 22:11:27 +0000647
Georg Brandl8334fd92010-12-04 10:26:46 +0000648 if (optimize < -1 || optimize > 2) {
649 PyErr_SetString(PyExc_ValueError,
650 "compile(): invalid optimize value");
651 goto error;
652 }
653
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000654 if (!dont_inherit) {
655 PyEval_MergeCompilerFlags(&cf);
656 }
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000657
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000658 if (strcmp(startstr, "exec") == 0)
659 mode = 0;
660 else if (strcmp(startstr, "eval") == 0)
661 mode = 1;
662 else if (strcmp(startstr, "single") == 0)
663 mode = 2;
664 else {
665 PyErr_SetString(PyExc_ValueError,
666 "compile() arg 3 must be 'exec', 'eval' or 'single'");
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000667 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000668 }
Neal Norwitzdb4115f2008-03-31 04:20:05 +0000669
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000670 is_ast = PyAST_Check(cmd);
671 if (is_ast == -1)
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000672 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000673 if (is_ast) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000674 if (supplied_flags & PyCF_ONLY_AST) {
675 Py_INCREF(cmd);
676 result = cmd;
677 }
678 else {
679 PyArena *arena;
680 mod_ty mod;
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000681
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000682 arena = PyArena_New();
Stefan Krah07795df2012-08-20 17:19:50 +0200683 if (arena == NULL)
684 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000685 mod = PyAST_obj2mod(cmd, arena, mode);
686 if (mod == NULL) {
687 PyArena_Free(arena);
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000688 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000689 }
Benjamin Peterson832bfe22011-08-09 16:15:04 -0500690 if (!PyAST_Validate(mod)) {
691 PyArena_Free(arena);
692 goto error;
693 }
Victor Stinner14e461d2013-08-26 22:28:21 +0200694 result = (PyObject*)PyAST_CompileObject(mod, filename,
695 &cf, optimize, arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000696 PyArena_Free(arena);
697 }
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000698 goto finally;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000699 }
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000700
Martin Pantereeb896c2015-11-07 02:32:21 +0000701 str = source_as_string(cmd, "compile", "string, bytes or AST", &cf, &cmd_copy);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000702 if (str == NULL)
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000703 goto error;
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000704
Victor Stinner14e461d2013-08-26 22:28:21 +0200705 result = Py_CompileStringObject(str, filename, start[mode], &cf, optimize);
Martin Pantereeb896c2015-11-07 02:32:21 +0000706 Py_XDECREF(cmd_copy);
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000707 goto finally;
708
709error:
710 result = NULL;
711finally:
Victor Stinner14e461d2013-08-26 22:28:21 +0200712 Py_DECREF(filename);
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000713 return result;
Guido van Rossum5b722181993-03-30 17:46:03 +0000714}
715
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000716PyDoc_STRVAR(compile_doc,
Tim Peters6cd6a822001-08-17 22:11:27 +0000717"compile(source, filename, mode[, flags[, dont_inherit]]) -> code object\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000718\n\
Benjamin Peterson933142a2013-12-06 20:12:39 -0500719Compile the source (a Python module, statement or expression)\n\
Georg Brandl7cae87c2006-09-06 06:51:57 +0000720into a code object that can be executed by exec() or eval().\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000721The filename will be used for run-time error messages.\n\
722The mode must be 'exec' to compile a module, 'single' to compile a\n\
Tim Peters6cd6a822001-08-17 22:11:27 +0000723single (interactive) statement, or 'eval' to compile an expression.\n\
724The flags argument, if present, controls which future statements influence\n\
725the compilation of the code.\n\
726The dont_inherit argument, if non-zero, stops the compilation inheriting\n\
727the effects of any future statements in effect in the code calling\n\
728compile; if absent or zero these statements do influence the compilation,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000729in addition to any features explicitly specified.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000730
Guido van Rossum79f25d91997-04-29 20:08:16 +0000731static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000732builtin_dir(PyObject *self, PyObject *args)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000733{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000734 PyObject *arg = NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000735
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000736 if (!PyArg_UnpackTuple(args, "dir", 0, 1, &arg))
737 return NULL;
738 return PyObject_Dir(arg);
Guido van Rossum3f5da241990-12-20 15:06:42 +0000739}
740
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000741PyDoc_STRVAR(dir_doc,
Tim Peters5d2b77c2001-09-03 05:47:38 +0000742"dir([object]) -> list of strings\n"
743"\n"
Georg Brandle32b4222007-03-10 22:13:27 +0000744"If called without an argument, return the names in the current scope.\n"
745"Else, return an alphabetized list of names comprising (some of) the attributes\n"
746"of the given object, and of attributes reachable from it.\n"
747"If the object supplies a method named __dir__, it will be used; otherwise\n"
748"the default dir() logic is used and returns:\n"
749" for a module object: the module's attributes.\n"
750" for a class object: its attributes, and recursively the attributes\n"
751" of its bases.\n"
Guido van Rossumd8faa362007-04-27 19:54:29 +0000752" for any other object: its attributes, its class's attributes, and\n"
Georg Brandle32b4222007-03-10 22:13:27 +0000753" recursively the attributes of its class's base classes.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000754
Guido van Rossum79f25d91997-04-29 20:08:16 +0000755static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000756builtin_divmod(PyObject *self, PyObject *args)
Guido van Rossum6a00cd81995-01-07 12:39:01 +0000757{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000758 PyObject *v, *w;
Guido van Rossum6a00cd81995-01-07 12:39:01 +0000759
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000760 if (!PyArg_UnpackTuple(args, "divmod", 2, 2, &v, &w))
761 return NULL;
762 return PyNumber_Divmod(v, w);
Guido van Rossum3f5da241990-12-20 15:06:42 +0000763}
764
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000765PyDoc_STRVAR(divmod_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000766"divmod(x, y) -> (div, mod)\n\
767\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000768Return the tuple ((x-x%y)/y, x%y). Invariant: div*y + mod == x.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000769
770
Guido van Rossum79f25d91997-04-29 20:08:16 +0000771static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000772builtin_eval(PyObject *self, PyObject *args)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000773{
Martin Pantereeb896c2015-11-07 02:32:21 +0000774 PyObject *cmd, *result, *cmd_copy;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000775 PyObject *globals = Py_None, *locals = Py_None;
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +0200776 const char *str;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000777 PyCompilerFlags cf;
Guido van Rossum590baa41993-11-30 13:40:46 +0000778
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000779 if (!PyArg_UnpackTuple(args, "eval", 1, 3, &cmd, &globals, &locals))
780 return NULL;
781 if (locals != Py_None && !PyMapping_Check(locals)) {
782 PyErr_SetString(PyExc_TypeError, "locals must be a mapping");
783 return NULL;
784 }
785 if (globals != Py_None && !PyDict_Check(globals)) {
786 PyErr_SetString(PyExc_TypeError, PyMapping_Check(globals) ?
787 "globals must be a real dict; try eval(expr, {}, mapping)"
788 : "globals must be a dict");
789 return NULL;
790 }
791 if (globals == Py_None) {
792 globals = PyEval_GetGlobals();
Victor Stinner41bb43a2013-10-29 01:19:37 +0100793 if (locals == Py_None) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000794 locals = PyEval_GetLocals();
Victor Stinner41bb43a2013-10-29 01:19:37 +0100795 if (locals == NULL)
796 return NULL;
797 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000798 }
799 else if (locals == Py_None)
800 locals = globals;
Tim Peters9fa96be2001-08-17 23:04:59 +0000801
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000802 if (globals == NULL || locals == NULL) {
803 PyErr_SetString(PyExc_TypeError,
804 "eval must be given globals and locals "
805 "when called without a frame");
806 return NULL;
807 }
Georg Brandl77c85e62005-09-15 10:46:13 +0000808
Victor Stinnerb44562b2013-11-06 19:03:11 +0100809 if (_PyDict_GetItemId(globals, &PyId___builtins__) == NULL) {
810 if (_PyDict_SetItemId(globals, &PyId___builtins__,
811 PyEval_GetBuiltins()) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000812 return NULL;
813 }
Tim Peters9fa96be2001-08-17 23:04:59 +0000814
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000815 if (PyCode_Check(cmd)) {
816 if (PyCode_GetNumFree((PyCodeObject *)cmd) > 0) {
817 PyErr_SetString(PyExc_TypeError,
818 "code object passed to eval() may not contain free variables");
819 return NULL;
820 }
Martin v. Löwis4d0d4712010-12-03 20:14:31 +0000821 return PyEval_EvalCode(cmd, globals, locals);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000822 }
Tim Peters9fa96be2001-08-17 23:04:59 +0000823
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000824 cf.cf_flags = PyCF_SOURCE_IS_UTF8;
Martin Pantereeb896c2015-11-07 02:32:21 +0000825 str = source_as_string(cmd, "eval", "string, bytes or code", &cf, &cmd_copy);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000826 if (str == NULL)
827 return NULL;
Just van Rossum3aaf42c2003-02-10 08:21:10 +0000828
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000829 while (*str == ' ' || *str == '\t')
830 str++;
Tim Peters9fa96be2001-08-17 23:04:59 +0000831
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000832 (void)PyEval_MergeCompilerFlags(&cf);
833 result = PyRun_StringFlags(str, Py_eval_input, globals, locals, &cf);
Martin Pantereeb896c2015-11-07 02:32:21 +0000834 Py_XDECREF(cmd_copy);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000835 return result;
Guido van Rossum3f5da241990-12-20 15:06:42 +0000836}
837
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000838PyDoc_STRVAR(eval_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000839"eval(source[, globals[, locals]]) -> value\n\
840\n\
841Evaluate the source in the context of globals and locals.\n\
842The source may be a string representing a Python expression\n\
843or a code object as returned by compile().\n\
Thomas Wouters89f507f2006-12-13 04:49:30 +0000844The globals must be a dictionary and locals can be any mapping,\n\
Raymond Hettinger214b1c32004-07-02 06:41:07 +0000845defaulting to the current globals and locals.\n\
846If only globals is given, locals defaults to it.\n");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000847
Georg Brandl7cae87c2006-09-06 06:51:57 +0000848static PyObject *
849builtin_exec(PyObject *self, PyObject *args)
850{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000851 PyObject *v;
852 PyObject *prog, *globals = Py_None, *locals = Py_None;
Georg Brandl7cae87c2006-09-06 06:51:57 +0000853
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000854 if (!PyArg_UnpackTuple(args, "exec", 1, 3, &prog, &globals, &locals))
855 return NULL;
Georg Brandl2cabc562008-08-28 07:57:16 +0000856
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000857 if (globals == Py_None) {
858 globals = PyEval_GetGlobals();
859 if (locals == Py_None) {
860 locals = PyEval_GetLocals();
Victor Stinner41bb43a2013-10-29 01:19:37 +0100861 if (locals == NULL)
862 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000863 }
864 if (!globals || !locals) {
865 PyErr_SetString(PyExc_SystemError,
866 "globals and locals cannot be NULL");
867 return NULL;
868 }
869 }
870 else if (locals == Py_None)
871 locals = globals;
Georg Brandl7cae87c2006-09-06 06:51:57 +0000872
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000873 if (!PyDict_Check(globals)) {
874 PyErr_Format(PyExc_TypeError, "exec() arg 2 must be a dict, not %.100s",
875 globals->ob_type->tp_name);
876 return NULL;
877 }
878 if (!PyMapping_Check(locals)) {
879 PyErr_Format(PyExc_TypeError,
880 "arg 3 must be a mapping or None, not %.100s",
881 locals->ob_type->tp_name);
882 return NULL;
883 }
Victor Stinnerb44562b2013-11-06 19:03:11 +0100884 if (_PyDict_GetItemId(globals, &PyId___builtins__) == NULL) {
885 if (_PyDict_SetItemId(globals, &PyId___builtins__,
886 PyEval_GetBuiltins()) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000887 return NULL;
888 }
889
890 if (PyCode_Check(prog)) {
891 if (PyCode_GetNumFree((PyCodeObject *)prog) > 0) {
892 PyErr_SetString(PyExc_TypeError,
893 "code object passed to exec() may not "
894 "contain free variables");
895 return NULL;
896 }
Martin v. Löwis4d0d4712010-12-03 20:14:31 +0000897 v = PyEval_EvalCode(prog, globals, locals);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000898 }
899 else {
Martin Pantereeb896c2015-11-07 02:32:21 +0000900 PyObject *prog_copy;
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +0200901 const char *str;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000902 PyCompilerFlags cf;
903 cf.cf_flags = PyCF_SOURCE_IS_UTF8;
904 str = source_as_string(prog, "exec",
Martin Pantereeb896c2015-11-07 02:32:21 +0000905 "string, bytes or code", &cf,
906 &prog_copy);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000907 if (str == NULL)
908 return NULL;
909 if (PyEval_MergeCompilerFlags(&cf))
910 v = PyRun_StringFlags(str, Py_file_input, globals,
911 locals, &cf);
912 else
913 v = PyRun_String(str, Py_file_input, globals, locals);
Martin Pantereeb896c2015-11-07 02:32:21 +0000914 Py_XDECREF(prog_copy);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000915 }
916 if (v == NULL)
917 return NULL;
918 Py_DECREF(v);
919 Py_RETURN_NONE;
Georg Brandl7cae87c2006-09-06 06:51:57 +0000920}
921
922PyDoc_STRVAR(exec_doc,
923"exec(object[, globals[, locals]])\n\
924\n\
Mark Dickinson480e8e32009-12-19 21:19:35 +0000925Read and execute code from an object, which can be a string or a code\n\
Benjamin Peterson38090262009-01-04 15:30:39 +0000926object.\n\
Georg Brandl7cae87c2006-09-06 06:51:57 +0000927The globals and locals are dictionaries, defaulting to the current\n\
928globals and locals. If only globals is given, locals defaults to it.");
929
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000930
Guido van Rossum79f25d91997-04-29 20:08:16 +0000931static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000932builtin_getattr(PyObject *self, PyObject *args)
Guido van Rossum33894be1992-01-27 16:53:09 +0000933{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000934 PyObject *v, *result, *dflt = NULL;
935 PyObject *name;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000936
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000937 if (!PyArg_UnpackTuple(args, "getattr", 2, 3, &v, &name, &dflt))
938 return NULL;
Martin v. Löwis5b222132007-06-10 09:51:05 +0000939
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000940 if (!PyUnicode_Check(name)) {
941 PyErr_SetString(PyExc_TypeError,
942 "getattr(): attribute name must be string");
943 return NULL;
944 }
945 result = PyObject_GetAttr(v, name);
946 if (result == NULL && dflt != NULL &&
947 PyErr_ExceptionMatches(PyExc_AttributeError))
948 {
949 PyErr_Clear();
950 Py_INCREF(dflt);
951 result = dflt;
952 }
953 return result;
Guido van Rossum9bfef441993-03-29 10:43:31 +0000954}
955
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000956PyDoc_STRVAR(getattr_doc,
Guido van Rossum950ff291998-06-29 13:38:57 +0000957"getattr(object, name[, default]) -> value\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000958\n\
Guido van Rossum950ff291998-06-29 13:38:57 +0000959Get a named attribute from an object; getattr(x, 'y') is equivalent to x.y.\n\
960When a default argument is given, it is returned when the attribute doesn't\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000961exist; without it, an exception is raised in that case.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000962
963
Guido van Rossum79f25d91997-04-29 20:08:16 +0000964static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000965builtin_globals(PyObject *self)
Guido van Rossum872537c1995-07-07 22:43:42 +0000966{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000967 PyObject *d;
Guido van Rossum872537c1995-07-07 22:43:42 +0000968
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000969 d = PyEval_GetGlobals();
970 Py_XINCREF(d);
971 return d;
Guido van Rossum872537c1995-07-07 22:43:42 +0000972}
973
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000974PyDoc_STRVAR(globals_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000975"globals() -> dictionary\n\
976\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000977Return the dictionary containing the current scope's global variables.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000978
979
Guido van Rossum79f25d91997-04-29 20:08:16 +0000980static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000981builtin_hasattr(PyObject *self, PyObject *args)
Guido van Rossum9bfef441993-03-29 10:43:31 +0000982{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000983 PyObject *v;
984 PyObject *name;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000985
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000986 if (!PyArg_UnpackTuple(args, "hasattr", 2, 2, &v, &name))
987 return NULL;
988 if (!PyUnicode_Check(name)) {
989 PyErr_SetString(PyExc_TypeError,
990 "hasattr(): attribute name must be string");
991 return NULL;
992 }
993 v = PyObject_GetAttr(v, name);
994 if (v == NULL) {
Benjamin Peterson17689992010-08-24 03:26:23 +0000995 if (PyErr_ExceptionMatches(PyExc_AttributeError)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000996 PyErr_Clear();
Benjamin Peterson17689992010-08-24 03:26:23 +0000997 Py_RETURN_FALSE;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000998 }
Benjamin Peterson17689992010-08-24 03:26:23 +0000999 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001000 }
1001 Py_DECREF(v);
Benjamin Peterson17689992010-08-24 03:26:23 +00001002 Py_RETURN_TRUE;
Guido van Rossum33894be1992-01-27 16:53:09 +00001003}
1004
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001005PyDoc_STRVAR(hasattr_doc,
Guido van Rossum77f6a652002-04-03 22:41:51 +00001006"hasattr(object, name) -> bool\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001007\n\
1008Return whether the object has an attribute with the given name.\n\
Benjamin Peterson17689992010-08-24 03:26:23 +00001009(This is done by calling getattr(object, name) and catching AttributeError.)");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001010
1011
Guido van Rossum79f25d91997-04-29 20:08:16 +00001012static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001013builtin_id(PyObject *self, PyObject *v)
Guido van Rossum5b722181993-03-30 17:46:03 +00001014{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001015 return PyLong_FromVoidPtr(v);
Guido van Rossum5b722181993-03-30 17:46:03 +00001016}
1017
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001018PyDoc_STRVAR(id_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001019"id(object) -> integer\n\
1020\n\
1021Return the identity of an object. This is guaranteed to be unique among\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001022simultaneously existing objects. (Hint: it's the object's memory address.)");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001023
1024
Raymond Hettingera6c60372008-03-13 01:26:19 +00001025/* map object ************************************************************/
1026
1027typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001028 PyObject_HEAD
1029 PyObject *iters;
1030 PyObject *func;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001031} mapobject;
1032
Guido van Rossum79f25d91997-04-29 20:08:16 +00001033static PyObject *
Raymond Hettingera6c60372008-03-13 01:26:19 +00001034map_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
Guido van Rossum12d12c51993-10-26 17:58:25 +00001035{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001036 PyObject *it, *iters, *func;
1037 mapobject *lz;
1038 Py_ssize_t numargs, i;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001039
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001040 if (type == &PyMap_Type && !_PyArg_NoKeywords("map()", kwds))
1041 return NULL;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001042
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001043 numargs = PyTuple_Size(args);
1044 if (numargs < 2) {
1045 PyErr_SetString(PyExc_TypeError,
1046 "map() must have at least two arguments.");
1047 return NULL;
1048 }
Raymond Hettingera6c60372008-03-13 01:26:19 +00001049
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001050 iters = PyTuple_New(numargs-1);
1051 if (iters == NULL)
1052 return NULL;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001053
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001054 for (i=1 ; i<numargs ; i++) {
1055 /* Get iterator. */
1056 it = PyObject_GetIter(PyTuple_GET_ITEM(args, i));
1057 if (it == NULL) {
1058 Py_DECREF(iters);
1059 return NULL;
1060 }
1061 PyTuple_SET_ITEM(iters, i-1, it);
1062 }
Raymond Hettingera6c60372008-03-13 01:26:19 +00001063
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001064 /* create mapobject structure */
1065 lz = (mapobject *)type->tp_alloc(type, 0);
1066 if (lz == NULL) {
1067 Py_DECREF(iters);
1068 return NULL;
1069 }
1070 lz->iters = iters;
1071 func = PyTuple_GET_ITEM(args, 0);
1072 Py_INCREF(func);
1073 lz->func = func;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001074
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001075 return (PyObject *)lz;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001076}
1077
1078static void
1079map_dealloc(mapobject *lz)
1080{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001081 PyObject_GC_UnTrack(lz);
1082 Py_XDECREF(lz->iters);
1083 Py_XDECREF(lz->func);
1084 Py_TYPE(lz)->tp_free(lz);
Raymond Hettingera6c60372008-03-13 01:26:19 +00001085}
1086
1087static int
1088map_traverse(mapobject *lz, visitproc visit, void *arg)
1089{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001090 Py_VISIT(lz->iters);
1091 Py_VISIT(lz->func);
1092 return 0;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001093}
1094
1095static PyObject *
1096map_next(mapobject *lz)
1097{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001098 PyObject *val;
1099 PyObject *argtuple;
1100 PyObject *result;
1101 Py_ssize_t numargs, i;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001102
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001103 numargs = PyTuple_Size(lz->iters);
1104 argtuple = PyTuple_New(numargs);
1105 if (argtuple == NULL)
1106 return NULL;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001107
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001108 for (i=0 ; i<numargs ; i++) {
1109 val = PyIter_Next(PyTuple_GET_ITEM(lz->iters, i));
1110 if (val == NULL) {
1111 Py_DECREF(argtuple);
1112 return NULL;
1113 }
1114 PyTuple_SET_ITEM(argtuple, i, val);
1115 }
1116 result = PyObject_Call(lz->func, argtuple, NULL);
1117 Py_DECREF(argtuple);
1118 return result;
Guido van Rossum12d12c51993-10-26 17:58:25 +00001119}
1120
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001121static PyObject *
1122map_reduce(mapobject *lz)
1123{
1124 Py_ssize_t numargs = PyTuple_GET_SIZE(lz->iters);
1125 PyObject *args = PyTuple_New(numargs+1);
1126 Py_ssize_t i;
1127 if (args == NULL)
1128 return NULL;
1129 Py_INCREF(lz->func);
1130 PyTuple_SET_ITEM(args, 0, lz->func);
1131 for (i = 0; i<numargs; i++){
1132 PyObject *it = PyTuple_GET_ITEM(lz->iters, i);
1133 Py_INCREF(it);
1134 PyTuple_SET_ITEM(args, i+1, it);
1135 }
1136
1137 return Py_BuildValue("ON", Py_TYPE(lz), args);
1138}
1139
1140static PyMethodDef map_methods[] = {
1141 {"__reduce__", (PyCFunction)map_reduce, METH_NOARGS, reduce_doc},
1142 {NULL, NULL} /* sentinel */
1143};
1144
1145
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001146PyDoc_STRVAR(map_doc,
Raymond Hettingera6c60372008-03-13 01:26:19 +00001147"map(func, *iterables) --> map object\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001148\n\
Raymond Hettingera6c60372008-03-13 01:26:19 +00001149Make an iterator that computes the function using arguments from\n\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001150each of the iterables. Stops when the shortest iterable is exhausted.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001151
Raymond Hettingera6c60372008-03-13 01:26:19 +00001152PyTypeObject PyMap_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001153 PyVarObject_HEAD_INIT(&PyType_Type, 0)
1154 "map", /* tp_name */
1155 sizeof(mapobject), /* tp_basicsize */
1156 0, /* tp_itemsize */
1157 /* methods */
1158 (destructor)map_dealloc, /* tp_dealloc */
1159 0, /* tp_print */
1160 0, /* tp_getattr */
1161 0, /* tp_setattr */
1162 0, /* tp_reserved */
1163 0, /* tp_repr */
1164 0, /* tp_as_number */
1165 0, /* tp_as_sequence */
1166 0, /* tp_as_mapping */
1167 0, /* tp_hash */
1168 0, /* tp_call */
1169 0, /* tp_str */
1170 PyObject_GenericGetAttr, /* tp_getattro */
1171 0, /* tp_setattro */
1172 0, /* tp_as_buffer */
1173 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
1174 Py_TPFLAGS_BASETYPE, /* tp_flags */
1175 map_doc, /* tp_doc */
1176 (traverseproc)map_traverse, /* tp_traverse */
1177 0, /* tp_clear */
1178 0, /* tp_richcompare */
1179 0, /* tp_weaklistoffset */
1180 PyObject_SelfIter, /* tp_iter */
1181 (iternextfunc)map_next, /* tp_iternext */
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001182 map_methods, /* tp_methods */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001183 0, /* tp_members */
1184 0, /* tp_getset */
1185 0, /* tp_base */
1186 0, /* tp_dict */
1187 0, /* tp_descr_get */
1188 0, /* tp_descr_set */
1189 0, /* tp_dictoffset */
1190 0, /* tp_init */
1191 PyType_GenericAlloc, /* tp_alloc */
1192 map_new, /* tp_new */
1193 PyObject_GC_Del, /* tp_free */
Raymond Hettingera6c60372008-03-13 01:26:19 +00001194};
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001195
Guido van Rossum79f25d91997-04-29 20:08:16 +00001196static PyObject *
Georg Brandla18af4e2007-04-21 15:47:16 +00001197builtin_next(PyObject *self, PyObject *args)
1198{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001199 PyObject *it, *res;
1200 PyObject *def = NULL;
Georg Brandla18af4e2007-04-21 15:47:16 +00001201
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001202 if (!PyArg_UnpackTuple(args, "next", 1, 2, &it, &def))
1203 return NULL;
1204 if (!PyIter_Check(it)) {
1205 PyErr_Format(PyExc_TypeError,
Philip Jenvey50add042011-11-06 16:37:52 -08001206 "'%.200s' object is not an iterator",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001207 it->ob_type->tp_name);
1208 return NULL;
1209 }
1210
1211 res = (*it->ob_type->tp_iternext)(it);
1212 if (res != NULL) {
1213 return res;
1214 } else if (def != NULL) {
1215 if (PyErr_Occurred()) {
1216 if(!PyErr_ExceptionMatches(PyExc_StopIteration))
1217 return NULL;
1218 PyErr_Clear();
1219 }
1220 Py_INCREF(def);
1221 return def;
1222 } else if (PyErr_Occurred()) {
1223 return NULL;
1224 } else {
1225 PyErr_SetNone(PyExc_StopIteration);
1226 return NULL;
1227 }
Georg Brandla18af4e2007-04-21 15:47:16 +00001228}
1229
1230PyDoc_STRVAR(next_doc,
1231"next(iterator[, default])\n\
1232\n\
1233Return the next item from the iterator. If default is given and the iterator\n\
1234is exhausted, it is returned instead of raising StopIteration.");
1235
1236
1237static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001238builtin_setattr(PyObject *self, PyObject *args)
Guido van Rossum33894be1992-01-27 16:53:09 +00001239{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001240 PyObject *v;
1241 PyObject *name;
1242 PyObject *value;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001243
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001244 if (!PyArg_UnpackTuple(args, "setattr", 3, 3, &v, &name, &value))
1245 return NULL;
1246 if (PyObject_SetAttr(v, name, value) != 0)
1247 return NULL;
1248 Py_INCREF(Py_None);
1249 return Py_None;
Guido van Rossum33894be1992-01-27 16:53:09 +00001250}
1251
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001252PyDoc_STRVAR(setattr_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001253"setattr(object, name, value)\n\
1254\n\
1255Set a named attribute on an object; setattr(x, 'y', v) is equivalent to\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001256``x.y = v''.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001257
1258
Guido van Rossum79f25d91997-04-29 20:08:16 +00001259static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001260builtin_delattr(PyObject *self, PyObject *args)
Guido van Rossum14144fc1994-08-29 12:53:40 +00001261{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001262 PyObject *v;
1263 PyObject *name;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001264
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001265 if (!PyArg_UnpackTuple(args, "delattr", 2, 2, &v, &name))
1266 return NULL;
1267 if (PyObject_SetAttr(v, name, (PyObject *)NULL) != 0)
1268 return NULL;
1269 Py_INCREF(Py_None);
1270 return Py_None;
Guido van Rossum14144fc1994-08-29 12:53:40 +00001271}
1272
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001273PyDoc_STRVAR(delattr_doc,
Guido van Rossumdf12a591998-11-23 22:13:04 +00001274"delattr(object, name)\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001275\n\
1276Delete a named attribute on an object; delattr(x, 'y') is equivalent to\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001277``del x.y''.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001278
1279
Guido van Rossum79f25d91997-04-29 20:08:16 +00001280static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001281builtin_hash(PyObject *self, PyObject *v)
Guido van Rossum9bfef441993-03-29 10:43:31 +00001282{
Benjamin Peterson8f67d082010-10-17 20:54:53 +00001283 Py_hash_t x;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001284
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001285 x = PyObject_Hash(v);
1286 if (x == -1)
1287 return NULL;
Benjamin Peterson8f67d082010-10-17 20:54:53 +00001288 return PyLong_FromSsize_t(x);
Guido van Rossum9bfef441993-03-29 10:43:31 +00001289}
1290
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001291PyDoc_STRVAR(hash_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001292"hash(object) -> integer\n\
1293\n\
1294Return a hash value for the object. Two objects with the same value have\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001295the same hash value. The reverse is not necessarily true, but likely.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001296
1297
Guido van Rossum79f25d91997-04-29 20:08:16 +00001298static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001299builtin_hex(PyObject *self, PyObject *v)
Guido van Rossum006bcd41991-10-24 14:54:44 +00001300{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001301 return PyNumber_ToBase(v, 16);
Guido van Rossum006bcd41991-10-24 14:54:44 +00001302}
1303
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001304PyDoc_STRVAR(hex_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001305"hex(number) -> string\n\
1306\n\
Zachary Warea4b7a752013-11-24 01:19:09 -06001307Return the hexadecimal representation of an integer.\n\
1308\n\
1309 >>> hex(3735928559)\n\
1310 '0xdeadbeef'\n\
1311");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001312
1313
Guido van Rossum79f25d91997-04-29 20:08:16 +00001314static PyObject *
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001315builtin_iter(PyObject *self, PyObject *args)
1316{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001317 PyObject *v, *w = NULL;
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001318
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001319 if (!PyArg_UnpackTuple(args, "iter", 1, 2, &v, &w))
1320 return NULL;
1321 if (w == NULL)
1322 return PyObject_GetIter(v);
1323 if (!PyCallable_Check(v)) {
1324 PyErr_SetString(PyExc_TypeError,
1325 "iter(v, w): v must be callable");
1326 return NULL;
1327 }
1328 return PyCallIter_New(v, w);
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001329}
1330
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001331PyDoc_STRVAR(iter_doc,
Georg Brandld11ae5d2008-05-16 13:27:32 +00001332"iter(iterable) -> iterator\n\
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001333iter(callable, sentinel) -> iterator\n\
1334\n\
1335Get an iterator from an object. In the first form, the argument must\n\
1336supply its own iterator, or be a sequence.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001337In the second form, the callable is called until it returns the sentinel.");
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001338
1339
1340static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001341builtin_len(PyObject *self, PyObject *v)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001342{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001343 Py_ssize_t res;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001344
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001345 res = PyObject_Size(v);
1346 if (res < 0 && PyErr_Occurred())
1347 return NULL;
1348 return PyLong_FromSsize_t(res);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001349}
1350
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001351PyDoc_STRVAR(len_doc,
Benjamin Peterson5edbb7b2014-04-18 01:03:59 -04001352"len(object)\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001353\n\
Terry Jan Reedyf2fb73f2014-06-16 03:05:37 -04001354Return the number of items of a sequence or collection.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001355
1356
Guido van Rossum79f25d91997-04-29 20:08:16 +00001357static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001358builtin_locals(PyObject *self)
Guido van Rossum872537c1995-07-07 22:43:42 +00001359{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001360 PyObject *d;
Guido van Rossum872537c1995-07-07 22:43:42 +00001361
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001362 d = PyEval_GetLocals();
1363 Py_XINCREF(d);
1364 return d;
Guido van Rossum872537c1995-07-07 22:43:42 +00001365}
1366
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001367PyDoc_STRVAR(locals_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001368"locals() -> dictionary\n\
1369\n\
Raymond Hettinger69bf8f32003-01-04 02:16:22 +00001370Update and return a dictionary containing the current scope's local variables.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001371
1372
Guido van Rossum79f25d91997-04-29 20:08:16 +00001373static PyObject *
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001374min_max(PyObject *args, PyObject *kwds, int op)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001375{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001376 PyObject *v, *it, *item, *val, *maxitem, *maxval, *keyfunc=NULL;
Raymond Hettinger4d6018f2013-06-24 22:43:02 -07001377 PyObject *emptytuple, *defaultval = NULL;
1378 static char *kwlist[] = {"key", "default", NULL};
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001379 const char *name = op == Py_LT ? "min" : "max";
Raymond Hettinger4d6018f2013-06-24 22:43:02 -07001380 const int positional = PyTuple_Size(args) > 1;
1381 int ret;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001382
Raymond Hettinger4d6018f2013-06-24 22:43:02 -07001383 if (positional)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001384 v = args;
Serhiy Storchakac6792272013-10-19 21:03:34 +03001385 else if (!PyArg_UnpackTuple(args, name, 1, 1, &v))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001386 return NULL;
Tim Peters67d687a2002-04-29 21:27:32 +00001387
Raymond Hettinger4d6018f2013-06-24 22:43:02 -07001388 emptytuple = PyTuple_New(0);
1389 if (emptytuple == NULL)
1390 return NULL;
1391 ret = PyArg_ParseTupleAndKeywords(emptytuple, kwds, "|$OO", kwlist,
1392 &keyfunc, &defaultval);
1393 Py_DECREF(emptytuple);
1394 if (!ret)
1395 return NULL;
1396
1397 if (positional && defaultval != NULL) {
1398 PyErr_Format(PyExc_TypeError,
1399 "Cannot specify a default for %s() with multiple "
1400 "positional arguments", name);
1401 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001402 }
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001403
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001404 it = PyObject_GetIter(v);
1405 if (it == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001406 return NULL;
1407 }
Tim Petersc3074532001-05-03 07:00:32 +00001408
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001409 maxitem = NULL; /* the result */
1410 maxval = NULL; /* the value associated with the result */
1411 while (( item = PyIter_Next(it) )) {
1412 /* get the value from the key function */
1413 if (keyfunc != NULL) {
1414 val = PyObject_CallFunctionObjArgs(keyfunc, item, NULL);
1415 if (val == NULL)
1416 goto Fail_it_item;
1417 }
1418 /* no key function; the value is the item */
1419 else {
1420 val = item;
1421 Py_INCREF(val);
1422 }
Tim Petersc3074532001-05-03 07:00:32 +00001423
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001424 /* maximum value and item are unset; set them */
1425 if (maxval == NULL) {
1426 maxitem = item;
1427 maxval = val;
1428 }
1429 /* maximum value and item are set; update them as necessary */
1430 else {
1431 int cmp = PyObject_RichCompareBool(val, maxval, op);
1432 if (cmp < 0)
1433 goto Fail_it_item_and_val;
1434 else if (cmp > 0) {
1435 Py_DECREF(maxval);
1436 Py_DECREF(maxitem);
1437 maxval = val;
1438 maxitem = item;
1439 }
1440 else {
1441 Py_DECREF(item);
1442 Py_DECREF(val);
1443 }
1444 }
1445 }
1446 if (PyErr_Occurred())
1447 goto Fail_it;
1448 if (maxval == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001449 assert(maxitem == NULL);
Raymond Hettinger4d6018f2013-06-24 22:43:02 -07001450 if (defaultval != NULL) {
1451 Py_INCREF(defaultval);
1452 maxitem = defaultval;
1453 } else {
1454 PyErr_Format(PyExc_ValueError,
1455 "%s() arg is an empty sequence", name);
1456 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001457 }
1458 else
1459 Py_DECREF(maxval);
1460 Py_DECREF(it);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001461 return maxitem;
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001462
1463Fail_it_item_and_val:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001464 Py_DECREF(val);
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001465Fail_it_item:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001466 Py_DECREF(item);
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001467Fail_it:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001468 Py_XDECREF(maxval);
1469 Py_XDECREF(maxitem);
1470 Py_DECREF(it);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001471 return NULL;
Guido van Rossum3f5da241990-12-20 15:06:42 +00001472}
1473
Guido van Rossum79f25d91997-04-29 20:08:16 +00001474static PyObject *
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001475builtin_min(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001476{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001477 return min_max(args, kwds, Py_LT);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001478}
1479
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001480PyDoc_STRVAR(min_doc,
Raymond Hettinger2a545822014-05-19 22:20:52 +01001481"min(iterable, *[, default=obj, key=func]) -> value\n\
1482min(arg1, arg2, *args, *[, key=func]) -> value\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001483\n\
Raymond Hettinger2a545822014-05-19 22:20:52 +01001484With a single iterable argument, return its smallest item. The\n\
1485default keyword-only argument specifies an object to return if\n\
1486the provided iterable is empty.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001487With two or more arguments, return the smallest argument.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001488
1489
Guido van Rossum79f25d91997-04-29 20:08:16 +00001490static PyObject *
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001491builtin_max(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001492{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001493 return min_max(args, kwds, Py_GT);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001494}
1495
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001496PyDoc_STRVAR(max_doc,
Raymond Hettinger2a545822014-05-19 22:20:52 +01001497"max(iterable, *[, default=obj, key=func]) -> value\n\
1498max(arg1, arg2, *args, *[, key=func]) -> value\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001499\n\
Raymond Hettinger2a545822014-05-19 22:20:52 +01001500With a single iterable argument, return its biggest item. The\n\
1501default keyword-only argument specifies an object to return if\n\
1502the provided iterable is empty.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001503With two or more arguments, return the largest argument.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001504
1505
Guido van Rossum79f25d91997-04-29 20:08:16 +00001506static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001507builtin_oct(PyObject *self, PyObject *v)
Guido van Rossum006bcd41991-10-24 14:54:44 +00001508{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001509 return PyNumber_ToBase(v, 8);
Guido van Rossum006bcd41991-10-24 14:54:44 +00001510}
1511
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001512PyDoc_STRVAR(oct_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001513"oct(number) -> string\n\
1514\n\
Zachary Warea4b7a752013-11-24 01:19:09 -06001515Return the octal representation of an integer.\n\
1516\n\
1517 >>> oct(342391)\n\
1518 '0o1234567'\n\
1519");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001520
1521
Guido van Rossum79f25d91997-04-29 20:08:16 +00001522static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001523builtin_ord(PyObject *self, PyObject* obj)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001524{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001525 long ord;
1526 Py_ssize_t size;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001527
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001528 if (PyBytes_Check(obj)) {
1529 size = PyBytes_GET_SIZE(obj);
1530 if (size == 1) {
1531 ord = (long)((unsigned char)*PyBytes_AS_STRING(obj));
1532 return PyLong_FromLong(ord);
1533 }
1534 }
1535 else if (PyUnicode_Check(obj)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001536 if (PyUnicode_READY(obj) == -1)
1537 return NULL;
1538 size = PyUnicode_GET_LENGTH(obj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001539 if (size == 1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001540 ord = (long)PyUnicode_READ_CHAR(obj, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001541 return PyLong_FromLong(ord);
1542 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001543 }
1544 else if (PyByteArray_Check(obj)) {
1545 /* XXX Hopefully this is temporary */
1546 size = PyByteArray_GET_SIZE(obj);
1547 if (size == 1) {
1548 ord = (long)((unsigned char)*PyByteArray_AS_STRING(obj));
1549 return PyLong_FromLong(ord);
1550 }
1551 }
1552 else {
1553 PyErr_Format(PyExc_TypeError,
1554 "ord() expected string of length 1, but " \
1555 "%.200s found", obj->ob_type->tp_name);
1556 return NULL;
1557 }
Guido van Rossum09095f32000-03-10 23:00:52 +00001558
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001559 PyErr_Format(PyExc_TypeError,
1560 "ord() expected a character, "
1561 "but string of length %zd found",
1562 size);
1563 return NULL;
Guido van Rossum3f5da241990-12-20 15:06:42 +00001564}
1565
Guido van Rossum307fa8c2007-07-16 20:46:27 +00001566PyDoc_VAR(ord_doc) = PyDoc_STR(
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001567"ord(c) -> integer\n\
1568\n\
Guido van Rossum8ac004e2007-07-15 13:00:05 +00001569Return the integer ordinal of a one-character string."
Antoine Pitrouedc60182012-06-23 14:19:58 +02001570);
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001571
1572
Guido van Rossum79f25d91997-04-29 20:08:16 +00001573static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001574builtin_pow(PyObject *self, PyObject *args)
Guido van Rossum6a00cd81995-01-07 12:39:01 +00001575{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001576 PyObject *v, *w, *z = Py_None;
Guido van Rossum6a00cd81995-01-07 12:39:01 +00001577
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001578 if (!PyArg_UnpackTuple(args, "pow", 2, 3, &v, &w, &z))
1579 return NULL;
1580 return PyNumber_Power(v, w, z);
Guido van Rossumd4905451991-05-05 20:00:36 +00001581}
1582
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001583PyDoc_STRVAR(pow_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001584"pow(x, y[, z]) -> number\n\
1585\n\
1586With two arguments, equivalent to x**y. With three arguments,\n\
Serhiy Storchaka95949422013-08-27 19:40:23 +03001587equivalent to (x**y) % z, but may be more efficient (e.g. for ints).");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001588
1589
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001590
Guido van Rossum34343512006-11-30 22:13:52 +00001591static PyObject *
1592builtin_print(PyObject *self, PyObject *args, PyObject *kwds)
1593{
Georg Brandlbc3b6822012-01-13 19:41:25 +01001594 static char *kwlist[] = {"sep", "end", "file", "flush", 0};
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001595 static PyObject *dummy_args;
Georg Brandlbc3b6822012-01-13 19:41:25 +01001596 PyObject *sep = NULL, *end = NULL, *file = NULL, *flush = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001597 int i, err;
Guido van Rossum34343512006-11-30 22:13:52 +00001598
Benjamin Peterson00102562012-01-11 21:00:16 -05001599 if (dummy_args == NULL && !(dummy_args = PyTuple_New(0)))
Georg Brandlbc3b6822012-01-13 19:41:25 +01001600 return NULL;
1601 if (!PyArg_ParseTupleAndKeywords(dummy_args, kwds, "|OOOO:print",
1602 kwlist, &sep, &end, &file, &flush))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001603 return NULL;
1604 if (file == NULL || file == Py_None) {
Victor Stinnerbd303c12013-11-07 23:07:29 +01001605 file = _PySys_GetObjectId(&PyId_stdout);
Victor Stinner1e53bba2013-07-16 22:26:05 +02001606 if (file == NULL) {
1607 PyErr_SetString(PyExc_RuntimeError, "lost sys.stdout");
1608 return NULL;
1609 }
1610
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001611 /* sys.stdout may be None when FILE* stdout isn't connected */
1612 if (file == Py_None)
1613 Py_RETURN_NONE;
1614 }
Guido van Rossum34343512006-11-30 22:13:52 +00001615
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001616 if (sep == Py_None) {
1617 sep = NULL;
1618 }
1619 else if (sep && !PyUnicode_Check(sep)) {
1620 PyErr_Format(PyExc_TypeError,
1621 "sep must be None or a string, not %.200s",
1622 sep->ob_type->tp_name);
1623 return NULL;
1624 }
1625 if (end == Py_None) {
1626 end = NULL;
1627 }
1628 else if (end && !PyUnicode_Check(end)) {
1629 PyErr_Format(PyExc_TypeError,
1630 "end must be None or a string, not %.200s",
1631 end->ob_type->tp_name);
1632 return NULL;
1633 }
Guido van Rossum34343512006-11-30 22:13:52 +00001634
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001635 for (i = 0; i < PyTuple_Size(args); i++) {
1636 if (i > 0) {
1637 if (sep == NULL)
1638 err = PyFile_WriteString(" ", file);
1639 else
1640 err = PyFile_WriteObject(sep, file,
1641 Py_PRINT_RAW);
1642 if (err)
1643 return NULL;
1644 }
1645 err = PyFile_WriteObject(PyTuple_GetItem(args, i), file,
1646 Py_PRINT_RAW);
1647 if (err)
1648 return NULL;
1649 }
Guido van Rossum34343512006-11-30 22:13:52 +00001650
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001651 if (end == NULL)
1652 err = PyFile_WriteString("\n", file);
1653 else
1654 err = PyFile_WriteObject(end, file, Py_PRINT_RAW);
1655 if (err)
1656 return NULL;
Guido van Rossum34343512006-11-30 22:13:52 +00001657
Georg Brandlbc3b6822012-01-13 19:41:25 +01001658 if (flush != NULL) {
1659 PyObject *tmp;
1660 int do_flush = PyObject_IsTrue(flush);
1661 if (do_flush == -1)
1662 return NULL;
1663 else if (do_flush) {
Victor Stinnereaa28832013-11-07 00:01:51 +01001664 tmp = _PyObject_CallMethodId(file, &PyId_flush, "");
Georg Brandlbc3b6822012-01-13 19:41:25 +01001665 if (tmp == NULL)
1666 return NULL;
1667 else
1668 Py_DECREF(tmp);
1669 }
1670 }
1671
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001672 Py_RETURN_NONE;
Guido van Rossum34343512006-11-30 22:13:52 +00001673}
1674
1675PyDoc_STRVAR(print_doc,
Senthil Kumarane9175bd2012-08-10 13:53:45 -07001676"print(value, ..., sep=' ', end='\\n', file=sys.stdout, flush=False)\n\
Guido van Rossum34343512006-11-30 22:13:52 +00001677\n\
1678Prints the values to a stream, or to sys.stdout by default.\n\
1679Optional keyword arguments:\n\
Senthil Kumarane9175bd2012-08-10 13:53:45 -07001680file: a file-like object (stream); defaults to the current sys.stdout.\n\
1681sep: string inserted between values, default a space.\n\
1682end: string appended after the last value, default a newline.\n\
1683flush: whether to forcibly flush the stream.");
Guido van Rossum34343512006-11-30 22:13:52 +00001684
1685
Guido van Rossuma88a0332007-02-26 16:59:55 +00001686static PyObject *
1687builtin_input(PyObject *self, PyObject *args)
1688{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001689 PyObject *promptarg = NULL;
Victor Stinnerbd303c12013-11-07 23:07:29 +01001690 PyObject *fin = _PySys_GetObjectId(&PyId_stdin);
1691 PyObject *fout = _PySys_GetObjectId(&PyId_stdout);
1692 PyObject *ferr = _PySys_GetObjectId(&PyId_stderr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001693 PyObject *tmp;
1694 long fd;
1695 int tty;
Guido van Rossuma88a0332007-02-26 16:59:55 +00001696
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001697 /* Parse arguments */
1698 if (!PyArg_UnpackTuple(args, "input", 0, 1, &promptarg))
1699 return NULL;
Guido van Rossuma88a0332007-02-26 16:59:55 +00001700
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001701 /* Check that stdin/out/err are intact */
1702 if (fin == NULL || fin == Py_None) {
1703 PyErr_SetString(PyExc_RuntimeError,
1704 "input(): lost sys.stdin");
1705 return NULL;
1706 }
1707 if (fout == NULL || fout == Py_None) {
1708 PyErr_SetString(PyExc_RuntimeError,
1709 "input(): lost sys.stdout");
1710 return NULL;
1711 }
1712 if (ferr == NULL || ferr == Py_None) {
1713 PyErr_SetString(PyExc_RuntimeError,
1714 "input(): lost sys.stderr");
1715 return NULL;
1716 }
Guido van Rossumeba76962007-05-27 09:13:28 +00001717
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001718 /* First of all, flush stderr */
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001719 tmp = _PyObject_CallMethodId(ferr, &PyId_flush, "");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001720 if (tmp == NULL)
1721 PyErr_Clear();
1722 else
1723 Py_DECREF(tmp);
Guido van Rossumeba76962007-05-27 09:13:28 +00001724
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001725 /* We should only use (GNU) readline if Python's sys.stdin and
1726 sys.stdout are the same as C's stdin and stdout, because we
1727 need to pass it those. */
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001728 tmp = _PyObject_CallMethodId(fin, &PyId_fileno, "");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001729 if (tmp == NULL) {
1730 PyErr_Clear();
1731 tty = 0;
1732 }
1733 else {
1734 fd = PyLong_AsLong(tmp);
1735 Py_DECREF(tmp);
1736 if (fd < 0 && PyErr_Occurred())
1737 return NULL;
1738 tty = fd == fileno(stdin) && isatty(fd);
1739 }
1740 if (tty) {
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001741 tmp = _PyObject_CallMethodId(fout, &PyId_fileno, "");
Martin Panterc9a6ab52015-10-10 01:25:38 +00001742 if (tmp == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001743 PyErr_Clear();
Martin Panterc9a6ab52015-10-10 01:25:38 +00001744 tty = 0;
1745 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001746 else {
1747 fd = PyLong_AsLong(tmp);
1748 Py_DECREF(tmp);
1749 if (fd < 0 && PyErr_Occurred())
1750 return NULL;
1751 tty = fd == fileno(stdout) && isatty(fd);
1752 }
1753 }
Guido van Rossumeba76962007-05-27 09:13:28 +00001754
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001755 /* If we're interactive, use (GNU) readline */
1756 if (tty) {
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001757 PyObject *po = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001758 char *prompt;
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001759 char *s = NULL;
1760 PyObject *stdin_encoding = NULL, *stdin_errors = NULL;
1761 PyObject *stdout_encoding = NULL, *stdout_errors = NULL;
1762 char *stdin_encoding_str, *stdin_errors_str;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001763 PyObject *result;
Victor Stinnerc0f1a1a2011-02-23 12:07:37 +00001764 size_t len;
Martin v. Löwis4a7b5d52007-09-04 05:24:49 +00001765
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02001766 stdin_encoding = _PyObject_GetAttrId(fin, &PyId_encoding);
Antoine Pitrou5ee9d8a2011-11-06 00:38:45 +01001767 stdin_errors = _PyObject_GetAttrId(fin, &PyId_errors);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001768 if (!stdin_encoding || !stdin_errors)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001769 /* stdin is a text stream, so it must have an
1770 encoding. */
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001771 goto _readline_errors;
Victor Stinner306f0102010-05-19 01:06:22 +00001772 stdin_encoding_str = _PyUnicode_AsString(stdin_encoding);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001773 stdin_errors_str = _PyUnicode_AsString(stdin_errors);
1774 if (!stdin_encoding_str || !stdin_errors_str)
1775 goto _readline_errors;
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001776 tmp = _PyObject_CallMethodId(fout, &PyId_flush, "");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001777 if (tmp == NULL)
1778 PyErr_Clear();
1779 else
1780 Py_DECREF(tmp);
1781 if (promptarg != NULL) {
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001782 /* We have a prompt, encode it as stdout would */
1783 char *stdout_encoding_str, *stdout_errors_str;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001784 PyObject *stringpo;
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02001785 stdout_encoding = _PyObject_GetAttrId(fout, &PyId_encoding);
Antoine Pitrou5ee9d8a2011-11-06 00:38:45 +01001786 stdout_errors = _PyObject_GetAttrId(fout, &PyId_errors);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001787 if (!stdout_encoding || !stdout_errors)
1788 goto _readline_errors;
Victor Stinner306f0102010-05-19 01:06:22 +00001789 stdout_encoding_str = _PyUnicode_AsString(stdout_encoding);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001790 stdout_errors_str = _PyUnicode_AsString(stdout_errors);
1791 if (!stdout_encoding_str || !stdout_errors_str)
1792 goto _readline_errors;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001793 stringpo = PyObject_Str(promptarg);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001794 if (stringpo == NULL)
1795 goto _readline_errors;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001796 po = PyUnicode_AsEncodedString(stringpo,
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001797 stdout_encoding_str, stdout_errors_str);
1798 Py_CLEAR(stdout_encoding);
1799 Py_CLEAR(stdout_errors);
1800 Py_CLEAR(stringpo);
1801 if (po == NULL)
1802 goto _readline_errors;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001803 prompt = PyBytes_AsString(po);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001804 if (prompt == NULL)
1805 goto _readline_errors;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001806 }
1807 else {
1808 po = NULL;
1809 prompt = "";
1810 }
1811 s = PyOS_Readline(stdin, stdout, prompt);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001812 if (s == NULL) {
Richard Oudkerk614c5782013-04-03 13:44:50 +01001813 PyErr_CheckSignals();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001814 if (!PyErr_Occurred())
1815 PyErr_SetNone(PyExc_KeyboardInterrupt);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001816 goto _readline_errors;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001817 }
Victor Stinnerc0f1a1a2011-02-23 12:07:37 +00001818
1819 len = strlen(s);
1820 if (len == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001821 PyErr_SetNone(PyExc_EOFError);
1822 result = NULL;
1823 }
Victor Stinnerc0f1a1a2011-02-23 12:07:37 +00001824 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001825 if (len > PY_SSIZE_T_MAX) {
1826 PyErr_SetString(PyExc_OverflowError,
1827 "input: input too long");
1828 result = NULL;
1829 }
1830 else {
Victor Stinnerc0f1a1a2011-02-23 12:07:37 +00001831 len--; /* strip trailing '\n' */
1832 if (len != 0 && s[len-1] == '\r')
1833 len--; /* strip trailing '\r' */
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001834 result = PyUnicode_Decode(s, len, stdin_encoding_str,
1835 stdin_errors_str);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001836 }
1837 }
1838 Py_DECREF(stdin_encoding);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001839 Py_DECREF(stdin_errors);
1840 Py_XDECREF(po);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001841 PyMem_FREE(s);
1842 return result;
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001843 _readline_errors:
1844 Py_XDECREF(stdin_encoding);
1845 Py_XDECREF(stdout_encoding);
1846 Py_XDECREF(stdin_errors);
1847 Py_XDECREF(stdout_errors);
1848 Py_XDECREF(po);
1849 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001850 }
Guido van Rossumeba76962007-05-27 09:13:28 +00001851
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001852 /* Fallback if we're not interactive */
1853 if (promptarg != NULL) {
1854 if (PyFile_WriteObject(promptarg, fout, Py_PRINT_RAW) != 0)
1855 return NULL;
1856 }
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001857 tmp = _PyObject_CallMethodId(fout, &PyId_flush, "");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001858 if (tmp == NULL)
1859 PyErr_Clear();
1860 else
1861 Py_DECREF(tmp);
1862 return PyFile_GetLine(fin, -1);
Guido van Rossuma88a0332007-02-26 16:59:55 +00001863}
1864
1865PyDoc_STRVAR(input_doc,
1866"input([prompt]) -> string\n\
1867\n\
1868Read a string from standard input. The trailing newline is stripped.\n\
1869If the user hits EOF (Unix: Ctl-D, Windows: Ctl-Z+Return), raise EOFError.\n\
1870On Unix, GNU readline is used if enabled. The prompt string, if given,\n\
1871is printed without a trailing newline before reading.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001872
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001873
Guido van Rossum79f25d91997-04-29 20:08:16 +00001874static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001875builtin_repr(PyObject *self, PyObject *v)
Guido van Rossumc89705d1992-11-26 08:54:07 +00001876{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001877 return PyObject_Repr(v);
Guido van Rossumc89705d1992-11-26 08:54:07 +00001878}
1879
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001880PyDoc_STRVAR(repr_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001881"repr(object) -> string\n\
1882\n\
1883Return the canonical string representation of the object.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001884For most object types, eval(repr(object)) == object.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001885
1886
Guido van Rossum79f25d91997-04-29 20:08:16 +00001887static PyObject *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001888builtin_round(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum9e51f9b1993-02-12 16:29:05 +00001889{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001890 PyObject *ndigits = NULL;
1891 static char *kwlist[] = {"number", "ndigits", 0};
Benjamin Peterson214a7d22013-04-13 17:19:01 -04001892 PyObject *number, *round, *result;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001893
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001894 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|O:round",
1895 kwlist, &number, &ndigits))
1896 return NULL;
Alex Martelliae211f92007-08-22 23:21:33 +00001897
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001898 if (Py_TYPE(number)->tp_dict == NULL) {
1899 if (PyType_Ready(Py_TYPE(number)) < 0)
1900 return NULL;
1901 }
Guido van Rossum15d3d042007-08-24 02:02:45 +00001902
Benjamin Peterson214a7d22013-04-13 17:19:01 -04001903 round = _PyObject_LookupSpecial(number, &PyId___round__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001904 if (round == NULL) {
Benjamin Peterson214a7d22013-04-13 17:19:01 -04001905 if (!PyErr_Occurred())
1906 PyErr_Format(PyExc_TypeError,
1907 "type %.100s doesn't define __round__ method",
1908 Py_TYPE(number)->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001909 return NULL;
1910 }
Alex Martelliae211f92007-08-22 23:21:33 +00001911
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001912 if (ndigits == NULL)
Benjamin Peterson214a7d22013-04-13 17:19:01 -04001913 result = PyObject_CallFunctionObjArgs(round, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001914 else
Benjamin Peterson214a7d22013-04-13 17:19:01 -04001915 result = PyObject_CallFunctionObjArgs(round, ndigits, NULL);
1916 Py_DECREF(round);
1917 return result;
Guido van Rossum9e51f9b1993-02-12 16:29:05 +00001918}
1919
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001920PyDoc_STRVAR(round_doc,
Mark Dickinson1124e712009-01-28 21:25:58 +00001921"round(number[, ndigits]) -> number\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001922\n\
1923Round a number to a given precision in decimal digits (default 0 digits).\n\
Mark Dickinson0d748c22008-07-05 11:29:03 +00001924This returns an int when called with one argument, otherwise the\n\
Georg Brandl809ddaa2008-07-01 20:39:59 +00001925same type as the number. ndigits may be negative.");
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001926
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001927
Raymond Hettinger64958a12003-12-17 20:43:33 +00001928static PyObject *
1929builtin_sorted(PyObject *self, PyObject *args, PyObject *kwds)
1930{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001931 PyObject *newlist, *v, *seq, *keyfunc=NULL, *newargs;
1932 PyObject *callable;
1933 static char *kwlist[] = {"iterable", "key", "reverse", 0};
1934 int reverse;
Raymond Hettinger64958a12003-12-17 20:43:33 +00001935
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001936 /* args 1-3 should match listsort in Objects/listobject.c */
1937 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|Oi:sorted",
1938 kwlist, &seq, &keyfunc, &reverse))
1939 return NULL;
Raymond Hettinger64958a12003-12-17 20:43:33 +00001940
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001941 newlist = PySequence_List(seq);
1942 if (newlist == NULL)
1943 return NULL;
Raymond Hettinger64958a12003-12-17 20:43:33 +00001944
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02001945 callable = _PyObject_GetAttrId(newlist, &PyId_sort);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001946 if (callable == NULL) {
1947 Py_DECREF(newlist);
1948 return NULL;
1949 }
Georg Brandl99d7e4e2005-08-31 22:21:15 +00001950
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001951 newargs = PyTuple_GetSlice(args, 1, 4);
1952 if (newargs == NULL) {
1953 Py_DECREF(newlist);
1954 Py_DECREF(callable);
1955 return NULL;
1956 }
Raymond Hettinger64958a12003-12-17 20:43:33 +00001957
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001958 v = PyObject_Call(callable, newargs, kwds);
1959 Py_DECREF(newargs);
1960 Py_DECREF(callable);
1961 if (v == NULL) {
1962 Py_DECREF(newlist);
1963 return NULL;
1964 }
1965 Py_DECREF(v);
1966 return newlist;
Raymond Hettinger64958a12003-12-17 20:43:33 +00001967}
1968
1969PyDoc_STRVAR(sorted_doc,
Raymond Hettinger70b64fc2008-01-30 20:15:17 +00001970"sorted(iterable, key=None, reverse=False) --> new sorted list");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001971
Guido van Rossum79f25d91997-04-29 20:08:16 +00001972static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001973builtin_vars(PyObject *self, PyObject *args)
Guido van Rossum2d951851994-08-29 12:52:16 +00001974{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001975 PyObject *v = NULL;
1976 PyObject *d;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001977
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001978 if (!PyArg_UnpackTuple(args, "vars", 0, 1, &v))
1979 return NULL;
1980 if (v == NULL) {
1981 d = PyEval_GetLocals();
Victor Stinner41bb43a2013-10-29 01:19:37 +01001982 if (d == NULL)
1983 return NULL;
1984 Py_INCREF(d);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001985 }
1986 else {
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02001987 d = _PyObject_GetAttrId(v, &PyId___dict__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001988 if (d == NULL) {
1989 PyErr_SetString(PyExc_TypeError,
1990 "vars() argument must have __dict__ attribute");
1991 return NULL;
1992 }
1993 }
1994 return d;
Guido van Rossum2d951851994-08-29 12:52:16 +00001995}
1996
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001997PyDoc_STRVAR(vars_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001998"vars([object]) -> dictionary\n\
1999\n\
2000Without arguments, equivalent to locals().\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002001With an argument, equivalent to object.__dict__.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002002
Alex Martellia70b1912003-04-22 08:12:33 +00002003static PyObject*
2004builtin_sum(PyObject *self, PyObject *args)
2005{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002006 PyObject *seq;
2007 PyObject *result = NULL;
2008 PyObject *temp, *item, *iter;
Alex Martellia70b1912003-04-22 08:12:33 +00002009
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002010 if (!PyArg_UnpackTuple(args, "sum", 1, 2, &seq, &result))
2011 return NULL;
Alex Martellia70b1912003-04-22 08:12:33 +00002012
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002013 iter = PyObject_GetIter(seq);
2014 if (iter == NULL)
2015 return NULL;
Alex Martellia70b1912003-04-22 08:12:33 +00002016
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002017 if (result == NULL) {
2018 result = PyLong_FromLong(0);
2019 if (result == NULL) {
2020 Py_DECREF(iter);
2021 return NULL;
2022 }
2023 } else {
2024 /* reject string values for 'start' parameter */
2025 if (PyUnicode_Check(result)) {
2026 PyErr_SetString(PyExc_TypeError,
2027 "sum() can't sum strings [use ''.join(seq) instead]");
2028 Py_DECREF(iter);
2029 return NULL;
2030 }
Benjamin Petersonce071ca2011-07-29 14:23:47 -05002031 if (PyBytes_Check(result)) {
2032 PyErr_SetString(PyExc_TypeError,
2033 "sum() can't sum bytes [use b''.join(seq) instead]");
Benjamin Peterson405f32c2011-07-29 22:43:45 -05002034 Py_DECREF(iter);
Benjamin Petersonce071ca2011-07-29 14:23:47 -05002035 return NULL;
2036 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002037 if (PyByteArray_Check(result)) {
2038 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson4f921c22011-07-29 14:24:29 -05002039 "sum() can't sum bytearray [use b''.join(seq) instead]");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002040 Py_DECREF(iter);
2041 return NULL;
2042 }
Guido van Rossum3172c5d2007-10-16 18:12:55 +00002043
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002044 Py_INCREF(result);
2045 }
Alex Martellia70b1912003-04-22 08:12:33 +00002046
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002047#ifndef SLOW_SUM
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002048 /* Fast addition by keeping temporary sums in C instead of new Python objects.
2049 Assumes all inputs are the same type. If the assumption fails, default
2050 to the more general routine.
2051 */
2052 if (PyLong_CheckExact(result)) {
2053 int overflow;
2054 long i_result = PyLong_AsLongAndOverflow(result, &overflow);
2055 /* If this already overflowed, don't even enter the loop. */
2056 if (overflow == 0) {
2057 Py_DECREF(result);
2058 result = NULL;
2059 }
2060 while(result == NULL) {
2061 item = PyIter_Next(iter);
2062 if (item == NULL) {
2063 Py_DECREF(iter);
2064 if (PyErr_Occurred())
2065 return NULL;
2066 return PyLong_FromLong(i_result);
2067 }
2068 if (PyLong_CheckExact(item)) {
2069 long b = PyLong_AsLongAndOverflow(item, &overflow);
2070 long x = i_result + b;
2071 if (overflow == 0 && ((x^i_result) >= 0 || (x^b) >= 0)) {
2072 i_result = x;
2073 Py_DECREF(item);
2074 continue;
2075 }
2076 }
2077 /* Either overflowed or is not an int. Restore real objects and process normally */
2078 result = PyLong_FromLong(i_result);
Christian Heimes704e2d32013-07-26 22:49:26 +02002079 if (result == NULL) {
2080 Py_DECREF(item);
2081 Py_DECREF(iter);
2082 return NULL;
2083 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002084 temp = PyNumber_Add(result, item);
2085 Py_DECREF(result);
2086 Py_DECREF(item);
2087 result = temp;
2088 if (result == NULL) {
2089 Py_DECREF(iter);
2090 return NULL;
2091 }
2092 }
2093 }
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002094
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002095 if (PyFloat_CheckExact(result)) {
2096 double f_result = PyFloat_AS_DOUBLE(result);
2097 Py_DECREF(result);
2098 result = NULL;
2099 while(result == NULL) {
2100 item = PyIter_Next(iter);
2101 if (item == NULL) {
2102 Py_DECREF(iter);
2103 if (PyErr_Occurred())
2104 return NULL;
2105 return PyFloat_FromDouble(f_result);
2106 }
2107 if (PyFloat_CheckExact(item)) {
2108 PyFPE_START_PROTECT("add", Py_DECREF(item); Py_DECREF(iter); return 0)
2109 f_result += PyFloat_AS_DOUBLE(item);
2110 PyFPE_END_PROTECT(f_result)
2111 Py_DECREF(item);
2112 continue;
2113 }
2114 if (PyLong_CheckExact(item)) {
2115 long value;
2116 int overflow;
2117 value = PyLong_AsLongAndOverflow(item, &overflow);
2118 if (!overflow) {
2119 PyFPE_START_PROTECT("add", Py_DECREF(item); Py_DECREF(iter); return 0)
2120 f_result += (double)value;
2121 PyFPE_END_PROTECT(f_result)
2122 Py_DECREF(item);
2123 continue;
2124 }
2125 }
2126 result = PyFloat_FromDouble(f_result);
2127 temp = PyNumber_Add(result, item);
2128 Py_DECREF(result);
2129 Py_DECREF(item);
2130 result = temp;
2131 if (result == NULL) {
2132 Py_DECREF(iter);
2133 return NULL;
2134 }
2135 }
2136 }
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002137#endif
2138
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002139 for(;;) {
2140 item = PyIter_Next(iter);
2141 if (item == NULL) {
2142 /* error, or end-of-sequence */
2143 if (PyErr_Occurred()) {
2144 Py_DECREF(result);
2145 result = NULL;
2146 }
2147 break;
2148 }
2149 /* It's tempting to use PyNumber_InPlaceAdd instead of
2150 PyNumber_Add here, to avoid quadratic running time
2151 when doing 'sum(list_of_lists, [])'. However, this
2152 would produce a change in behaviour: a snippet like
Mark Dickinson9acadc52009-10-26 14:19:42 +00002153
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002154 empty = []
2155 sum([[x] for x in range(10)], empty)
Mark Dickinson9acadc52009-10-26 14:19:42 +00002156
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002157 would change the value of empty. */
2158 temp = PyNumber_Add(result, item);
2159 Py_DECREF(result);
2160 Py_DECREF(item);
2161 result = temp;
2162 if (result == NULL)
2163 break;
2164 }
2165 Py_DECREF(iter);
2166 return result;
Alex Martellia70b1912003-04-22 08:12:33 +00002167}
2168
2169PyDoc_STRVAR(sum_doc,
Georg Brandld11ae5d2008-05-16 13:27:32 +00002170"sum(iterable[, start]) -> value\n\
Alex Martellia70b1912003-04-22 08:12:33 +00002171\n\
R David Murray87ead112013-07-10 16:22:14 -04002172Return the sum of an iterable of numbers (NOT strings) plus the value\n\
Georg Brandld11ae5d2008-05-16 13:27:32 +00002173of parameter 'start' (which defaults to 0). When the iterable is\n\
R David Murray87ead112013-07-10 16:22:14 -04002174empty, return start.");
Alex Martellia70b1912003-04-22 08:12:33 +00002175
2176
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002177static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002178builtin_isinstance(PyObject *self, PyObject *args)
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002179{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002180 PyObject *inst;
2181 PyObject *cls;
2182 int retval;
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002183
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002184 if (!PyArg_UnpackTuple(args, "isinstance", 2, 2, &inst, &cls))
2185 return NULL;
Guido van Rossumf5dd9141997-12-02 19:11:45 +00002186
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002187 retval = PyObject_IsInstance(inst, cls);
2188 if (retval < 0)
2189 return NULL;
2190 return PyBool_FromLong(retval);
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002191}
2192
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002193PyDoc_STRVAR(isinstance_doc,
Guido van Rossum77f6a652002-04-03 22:41:51 +00002194"isinstance(object, class-or-type-or-tuple) -> bool\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002195\n\
2196Return whether an object is an instance of a class or of a subclass thereof.\n\
Guido van Rossum03290ec2001-10-07 20:54:12 +00002197With a type as second argument, return whether that is the object's type.\n\
2198The form using a tuple, isinstance(x, (A, B, ...)), is a shortcut for\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002199isinstance(x, A) or isinstance(x, B) or ... (etc.).");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002200
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002201
2202static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002203builtin_issubclass(PyObject *self, PyObject *args)
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002204{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002205 PyObject *derived;
2206 PyObject *cls;
2207 int retval;
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002208
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002209 if (!PyArg_UnpackTuple(args, "issubclass", 2, 2, &derived, &cls))
2210 return NULL;
Guido van Rossum668213d1999-06-16 17:28:37 +00002211
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002212 retval = PyObject_IsSubclass(derived, cls);
2213 if (retval < 0)
2214 return NULL;
2215 return PyBool_FromLong(retval);
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002216}
2217
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002218PyDoc_STRVAR(issubclass_doc,
Guido van Rossum77f6a652002-04-03 22:41:51 +00002219"issubclass(C, B) -> bool\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002220\n\
Walter Dörwaldd9a6ad32002-12-12 16:41:44 +00002221Return whether class C is a subclass (i.e., a derived class) of class B.\n\
2222When using a tuple as the second argument issubclass(X, (A, B, ...)),\n\
2223is a shortcut for issubclass(X, A) or issubclass(X, B) or ... (etc.).");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002224
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002225
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002226typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002227 PyObject_HEAD
2228 Py_ssize_t tuplesize;
2229 PyObject *ittuple; /* tuple of iterators */
2230 PyObject *result;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002231} zipobject;
2232
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002233static PyObject *
2234zip_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
Barry Warsawbd599b52000-08-03 15:45:29 +00002235{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002236 zipobject *lz;
2237 Py_ssize_t i;
2238 PyObject *ittuple; /* tuple of iterators */
2239 PyObject *result;
2240 Py_ssize_t tuplesize = PySequence_Length(args);
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002241
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002242 if (type == &PyZip_Type && !_PyArg_NoKeywords("zip()", kwds))
2243 return NULL;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002244
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002245 /* args must be a tuple */
2246 assert(PyTuple_Check(args));
Barry Warsawbd599b52000-08-03 15:45:29 +00002247
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002248 /* obtain iterators */
2249 ittuple = PyTuple_New(tuplesize);
2250 if (ittuple == NULL)
2251 return NULL;
2252 for (i=0; i < tuplesize; ++i) {
2253 PyObject *item = PyTuple_GET_ITEM(args, i);
2254 PyObject *it = PyObject_GetIter(item);
2255 if (it == NULL) {
2256 if (PyErr_ExceptionMatches(PyExc_TypeError))
2257 PyErr_Format(PyExc_TypeError,
2258 "zip argument #%zd must support iteration",
2259 i+1);
2260 Py_DECREF(ittuple);
2261 return NULL;
2262 }
2263 PyTuple_SET_ITEM(ittuple, i, it);
2264 }
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002265
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002266 /* create a result holder */
2267 result = PyTuple_New(tuplesize);
2268 if (result == NULL) {
2269 Py_DECREF(ittuple);
2270 return NULL;
2271 }
2272 for (i=0 ; i < tuplesize ; i++) {
2273 Py_INCREF(Py_None);
2274 PyTuple_SET_ITEM(result, i, Py_None);
2275 }
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002276
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002277 /* create zipobject structure */
2278 lz = (zipobject *)type->tp_alloc(type, 0);
2279 if (lz == NULL) {
2280 Py_DECREF(ittuple);
2281 Py_DECREF(result);
2282 return NULL;
2283 }
2284 lz->ittuple = ittuple;
2285 lz->tuplesize = tuplesize;
2286 lz->result = result;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002287
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002288 return (PyObject *)lz;
Barry Warsawbd599b52000-08-03 15:45:29 +00002289}
2290
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002291static void
2292zip_dealloc(zipobject *lz)
2293{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002294 PyObject_GC_UnTrack(lz);
2295 Py_XDECREF(lz->ittuple);
2296 Py_XDECREF(lz->result);
2297 Py_TYPE(lz)->tp_free(lz);
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002298}
2299
2300static int
2301zip_traverse(zipobject *lz, visitproc visit, void *arg)
2302{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002303 Py_VISIT(lz->ittuple);
2304 Py_VISIT(lz->result);
2305 return 0;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002306}
2307
2308static PyObject *
2309zip_next(zipobject *lz)
2310{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002311 Py_ssize_t i;
2312 Py_ssize_t tuplesize = lz->tuplesize;
2313 PyObject *result = lz->result;
2314 PyObject *it;
2315 PyObject *item;
2316 PyObject *olditem;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002317
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002318 if (tuplesize == 0)
2319 return NULL;
2320 if (Py_REFCNT(result) == 1) {
2321 Py_INCREF(result);
2322 for (i=0 ; i < tuplesize ; i++) {
2323 it = PyTuple_GET_ITEM(lz->ittuple, i);
2324 item = (*Py_TYPE(it)->tp_iternext)(it);
Serhiy Storchaka278d03b2013-04-06 22:52:34 +03002325 if (item == NULL) {
2326 Py_DECREF(result);
2327 return NULL;
2328 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002329 olditem = PyTuple_GET_ITEM(result, i);
2330 PyTuple_SET_ITEM(result, i, item);
2331 Py_DECREF(olditem);
2332 }
2333 } else {
2334 result = PyTuple_New(tuplesize);
2335 if (result == NULL)
Serhiy Storchaka278d03b2013-04-06 22:52:34 +03002336 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002337 for (i=0 ; i < tuplesize ; i++) {
2338 it = PyTuple_GET_ITEM(lz->ittuple, i);
2339 item = (*Py_TYPE(it)->tp_iternext)(it);
Serhiy Storchaka278d03b2013-04-06 22:52:34 +03002340 if (item == NULL) {
2341 Py_DECREF(result);
2342 return NULL;
2343 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002344 PyTuple_SET_ITEM(result, i, item);
2345 }
2346 }
2347 return result;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002348}
Barry Warsawbd599b52000-08-03 15:45:29 +00002349
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002350static PyObject *
2351zip_reduce(zipobject *lz)
2352{
2353 /* Just recreate the zip with the internal iterator tuple */
2354 return Py_BuildValue("OO", Py_TYPE(lz), lz->ittuple);
2355}
2356
2357static PyMethodDef zip_methods[] = {
2358 {"__reduce__", (PyCFunction)zip_reduce, METH_NOARGS, reduce_doc},
2359 {NULL, NULL} /* sentinel */
2360};
2361
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002362PyDoc_STRVAR(zip_doc,
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002363"zip(iter1 [,iter2 [...]]) --> zip object\n\
Barry Warsawbd599b52000-08-03 15:45:29 +00002364\n\
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002365Return a zip object whose .__next__() method returns a tuple where\n\
2366the i-th element comes from the i-th iterable argument. The .__next__()\n\
2367method continues until the shortest iterable in the argument sequence\n\
Georg Brandlced51db2008-12-04 18:28:38 +00002368is exhausted and then it raises StopIteration.");
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002369
2370PyTypeObject PyZip_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002371 PyVarObject_HEAD_INIT(&PyType_Type, 0)
2372 "zip", /* tp_name */
2373 sizeof(zipobject), /* tp_basicsize */
2374 0, /* tp_itemsize */
2375 /* methods */
2376 (destructor)zip_dealloc, /* tp_dealloc */
2377 0, /* tp_print */
2378 0, /* tp_getattr */
2379 0, /* tp_setattr */
2380 0, /* tp_reserved */
2381 0, /* tp_repr */
2382 0, /* tp_as_number */
2383 0, /* tp_as_sequence */
2384 0, /* tp_as_mapping */
2385 0, /* tp_hash */
2386 0, /* tp_call */
2387 0, /* tp_str */
2388 PyObject_GenericGetAttr, /* tp_getattro */
2389 0, /* tp_setattro */
2390 0, /* tp_as_buffer */
2391 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
2392 Py_TPFLAGS_BASETYPE, /* tp_flags */
2393 zip_doc, /* tp_doc */
2394 (traverseproc)zip_traverse, /* tp_traverse */
2395 0, /* tp_clear */
2396 0, /* tp_richcompare */
2397 0, /* tp_weaklistoffset */
2398 PyObject_SelfIter, /* tp_iter */
2399 (iternextfunc)zip_next, /* tp_iternext */
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002400 zip_methods, /* tp_methods */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002401 0, /* tp_members */
2402 0, /* tp_getset */
2403 0, /* tp_base */
2404 0, /* tp_dict */
2405 0, /* tp_descr_get */
2406 0, /* tp_descr_set */
2407 0, /* tp_dictoffset */
2408 0, /* tp_init */
2409 PyType_GenericAlloc, /* tp_alloc */
2410 zip_new, /* tp_new */
2411 PyObject_GC_Del, /* tp_free */
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002412};
Barry Warsawbd599b52000-08-03 15:45:29 +00002413
2414
Guido van Rossum79f25d91997-04-29 20:08:16 +00002415static PyMethodDef builtin_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002416 {"__build_class__", (PyCFunction)builtin___build_class__,
2417 METH_VARARGS | METH_KEYWORDS, build_class_doc},
2418 {"__import__", (PyCFunction)builtin___import__, METH_VARARGS | METH_KEYWORDS, import_doc},
2419 {"abs", builtin_abs, METH_O, abs_doc},
2420 {"all", builtin_all, METH_O, all_doc},
2421 {"any", builtin_any, METH_O, any_doc},
2422 {"ascii", builtin_ascii, METH_O, ascii_doc},
2423 {"bin", builtin_bin, METH_O, bin_doc},
Antoine Pitroue71362d2010-11-27 22:00:11 +00002424 {"callable", builtin_callable, METH_O, callable_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002425 {"chr", builtin_chr, METH_VARARGS, chr_doc},
2426 {"compile", (PyCFunction)builtin_compile, METH_VARARGS | METH_KEYWORDS, compile_doc},
2427 {"delattr", builtin_delattr, METH_VARARGS, delattr_doc},
2428 {"dir", builtin_dir, METH_VARARGS, dir_doc},
2429 {"divmod", builtin_divmod, METH_VARARGS, divmod_doc},
2430 {"eval", builtin_eval, METH_VARARGS, eval_doc},
2431 {"exec", builtin_exec, METH_VARARGS, exec_doc},
2432 {"format", builtin_format, METH_VARARGS, format_doc},
2433 {"getattr", builtin_getattr, METH_VARARGS, getattr_doc},
2434 {"globals", (PyCFunction)builtin_globals, METH_NOARGS, globals_doc},
2435 {"hasattr", builtin_hasattr, METH_VARARGS, hasattr_doc},
2436 {"hash", builtin_hash, METH_O, hash_doc},
2437 {"hex", builtin_hex, METH_O, hex_doc},
2438 {"id", builtin_id, METH_O, id_doc},
2439 {"input", builtin_input, METH_VARARGS, input_doc},
2440 {"isinstance", builtin_isinstance, METH_VARARGS, isinstance_doc},
2441 {"issubclass", builtin_issubclass, METH_VARARGS, issubclass_doc},
2442 {"iter", builtin_iter, METH_VARARGS, iter_doc},
2443 {"len", builtin_len, METH_O, len_doc},
2444 {"locals", (PyCFunction)builtin_locals, METH_NOARGS, locals_doc},
2445 {"max", (PyCFunction)builtin_max, METH_VARARGS | METH_KEYWORDS, max_doc},
2446 {"min", (PyCFunction)builtin_min, METH_VARARGS | METH_KEYWORDS, min_doc},
2447 {"next", (PyCFunction)builtin_next, METH_VARARGS, next_doc},
2448 {"oct", builtin_oct, METH_O, oct_doc},
2449 {"ord", builtin_ord, METH_O, ord_doc},
2450 {"pow", builtin_pow, METH_VARARGS, pow_doc},
2451 {"print", (PyCFunction)builtin_print, METH_VARARGS | METH_KEYWORDS, print_doc},
2452 {"repr", builtin_repr, METH_O, repr_doc},
2453 {"round", (PyCFunction)builtin_round, METH_VARARGS | METH_KEYWORDS, round_doc},
2454 {"setattr", builtin_setattr, METH_VARARGS, setattr_doc},
2455 {"sorted", (PyCFunction)builtin_sorted, METH_VARARGS | METH_KEYWORDS, sorted_doc},
2456 {"sum", builtin_sum, METH_VARARGS, sum_doc},
2457 {"vars", builtin_vars, METH_VARARGS, vars_doc},
2458 {NULL, NULL},
Guido van Rossum3f5da241990-12-20 15:06:42 +00002459};
2460
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002461PyDoc_STRVAR(builtin_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002462"Built-in functions, exceptions, and other objects.\n\
2463\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002464Noteworthy: None is the `nil' object; Ellipsis represents `...' in slices.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002465
Martin v. Löwis1a214512008-06-11 05:26:20 +00002466static struct PyModuleDef builtinsmodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002467 PyModuleDef_HEAD_INIT,
2468 "builtins",
2469 builtin_doc,
2470 -1, /* multiple "initialization" just copies the module dict. */
2471 builtin_methods,
2472 NULL,
2473 NULL,
2474 NULL,
2475 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00002476};
2477
2478
Guido van Rossum25ce5661997-08-02 03:10:38 +00002479PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002480_PyBuiltin_Init(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +00002481{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002482 PyObject *mod, *dict, *debug;
Benjamin Peterson42124a72012-10-30 23:41:54 -04002483
2484 if (PyType_Ready(&PyFilter_Type) < 0 ||
2485 PyType_Ready(&PyMap_Type) < 0 ||
2486 PyType_Ready(&PyZip_Type) < 0)
2487 return NULL;
2488
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002489 mod = PyModule_Create(&builtinsmodule);
2490 if (mod == NULL)
2491 return NULL;
2492 dict = PyModule_GetDict(mod);
Tim Peters4b7625e2001-09-13 21:37:17 +00002493
Tim Peters7571a0f2003-03-23 17:52:28 +00002494#ifdef Py_TRACE_REFS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002495 /* "builtins" exposes a number of statically allocated objects
2496 * that, before this code was added in 2.3, never showed up in
2497 * the list of "all objects" maintained by Py_TRACE_REFS. As a
2498 * result, programs leaking references to None and False (etc)
2499 * couldn't be diagnosed by examining sys.getobjects(0).
2500 */
Tim Peters7571a0f2003-03-23 17:52:28 +00002501#define ADD_TO_ALL(OBJECT) _Py_AddToAllObjects((PyObject *)(OBJECT), 0)
2502#else
2503#define ADD_TO_ALL(OBJECT) (void)0
2504#endif
2505
Tim Peters4b7625e2001-09-13 21:37:17 +00002506#define SETBUILTIN(NAME, OBJECT) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002507 if (PyDict_SetItemString(dict, NAME, (PyObject *)OBJECT) < 0) \
2508 return NULL; \
2509 ADD_TO_ALL(OBJECT)
Tim Peters4b7625e2001-09-13 21:37:17 +00002510
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002511 SETBUILTIN("None", Py_None);
2512 SETBUILTIN("Ellipsis", Py_Ellipsis);
2513 SETBUILTIN("NotImplemented", Py_NotImplemented);
2514 SETBUILTIN("False", Py_False);
2515 SETBUILTIN("True", Py_True);
2516 SETBUILTIN("bool", &PyBool_Type);
2517 SETBUILTIN("memoryview", &PyMemoryView_Type);
2518 SETBUILTIN("bytearray", &PyByteArray_Type);
2519 SETBUILTIN("bytes", &PyBytes_Type);
2520 SETBUILTIN("classmethod", &PyClassMethod_Type);
2521 SETBUILTIN("complex", &PyComplex_Type);
2522 SETBUILTIN("dict", &PyDict_Type);
2523 SETBUILTIN("enumerate", &PyEnum_Type);
2524 SETBUILTIN("filter", &PyFilter_Type);
2525 SETBUILTIN("float", &PyFloat_Type);
2526 SETBUILTIN("frozenset", &PyFrozenSet_Type);
2527 SETBUILTIN("property", &PyProperty_Type);
2528 SETBUILTIN("int", &PyLong_Type);
2529 SETBUILTIN("list", &PyList_Type);
2530 SETBUILTIN("map", &PyMap_Type);
2531 SETBUILTIN("object", &PyBaseObject_Type);
2532 SETBUILTIN("range", &PyRange_Type);
2533 SETBUILTIN("reversed", &PyReversed_Type);
2534 SETBUILTIN("set", &PySet_Type);
2535 SETBUILTIN("slice", &PySlice_Type);
2536 SETBUILTIN("staticmethod", &PyStaticMethod_Type);
2537 SETBUILTIN("str", &PyUnicode_Type);
2538 SETBUILTIN("super", &PySuper_Type);
2539 SETBUILTIN("tuple", &PyTuple_Type);
2540 SETBUILTIN("type", &PyType_Type);
2541 SETBUILTIN("zip", &PyZip_Type);
2542 debug = PyBool_FromLong(Py_OptimizeFlag == 0);
2543 if (PyDict_SetItemString(dict, "__debug__", debug) < 0) {
2544 Py_XDECREF(debug);
2545 return NULL;
2546 }
2547 Py_XDECREF(debug);
Barry Warsaw757af0e1997-08-29 22:13:51 +00002548
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002549 return mod;
Tim Peters7571a0f2003-03-23 17:52:28 +00002550#undef ADD_TO_ALL
Tim Peters4b7625e2001-09-13 21:37:17 +00002551#undef SETBUILTIN
Guido van Rossum3f5da241990-12-20 15:06:42 +00002552}