blob: 6069e41b48538aa7734716ed2dbe967eb0d7d703 [file] [log] [blame]
Guido van Rossum3f5da241990-12-20 15:06:42 +00001/* Built-in functions */
2
Guido van Rossum79f25d91997-04-29 20:08:16 +00003#include "Python.h"
Martin v. Löwis618dc5e2008-03-30 20:03:44 +00004#include "Python-ast.h"
Guido van Rossum3f5da241990-12-20 15:06:42 +00005
6#include "node.h"
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00007#include "code.h"
Guido van Rossum3f5da241990-12-20 15:06:42 +00008
Benjamin Petersonea281a52011-08-12 23:10:50 -05009#include "asdl.h"
10#include "ast.h"
11
Guido van Rossum6bf62da1997-04-11 20:37:35 +000012#include <ctype.h>
13
Victor Stinnerb744ba12010-05-15 12:27:16 +000014#ifdef HAVE_LANGINFO_H
15#include <langinfo.h> /* CODESET */
16#endif
17
Mark Hammond26cffde42001-05-14 12:17:34 +000018/* The default encoding used by the platform file system APIs
19 Can remain NULL for all platforms that don't have such a concept
Guido van Rossum00bc0e02007-10-15 02:52:41 +000020
21 Don't forget to modify PyUnicode_DecodeFSDefault() if you touch any of the
22 values for Py_FileSystemDefaultEncoding!
Mark Hammond26cffde42001-05-14 12:17:34 +000023*/
Victor Stinner99b95382011-07-04 14:23:54 +020024#ifdef HAVE_MBCS
Mark Hammond26cffde42001-05-14 12:17:34 +000025const char *Py_FileSystemDefaultEncoding = "mbcs";
Martin v. Löwis04dc25c2008-10-03 16:09:28 +000026int Py_HasFileSystemDefaultEncoding = 1;
Just van Rossumb9b8e9c2003-02-10 09:22:01 +000027#elif defined(__APPLE__)
28const char *Py_FileSystemDefaultEncoding = "utf-8";
Martin v. Löwis04dc25c2008-10-03 16:09:28 +000029int Py_HasFileSystemDefaultEncoding = 1;
Victor Stinnerd64e8a72011-07-04 13:48:30 +020030#else
Victor Stinnerb744ba12010-05-15 12:27:16 +000031const char *Py_FileSystemDefaultEncoding = NULL; /* set by initfsencoding() */
Martin v. Löwis04dc25c2008-10-03 16:09:28 +000032int Py_HasFileSystemDefaultEncoding = 0;
Mark Hammond26cffde42001-05-14 12:17:34 +000033#endif
Mark Hammondef8b6542001-05-13 08:04:26 +000034
Martin v. Löwisbd928fe2011-10-14 10:20:37 +020035_Py_IDENTIFIER(fileno);
36_Py_IDENTIFIER(flush);
Victor Stinnerb44562b2013-11-06 19:03:11 +010037_Py_IDENTIFIER(__builtins__);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +020038
Guido van Rossum79f25d91997-04-29 20:08:16 +000039static PyObject *
Guido van Rossum52cc1d82007-03-18 15:41:51 +000040builtin___build_class__(PyObject *self, PyObject *args, PyObject *kwds)
41{
Nick Coghlande31b192011-10-23 22:04:16 +100042 PyObject *func, *name, *bases, *mkw, *meta, *winner, *prep, *ns, *cell;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000043 PyObject *cls = NULL;
Florent Xicluna4d46c2a2011-10-28 15:00:50 +020044 Py_ssize_t nargs;
Nick Coghlande31b192011-10-23 22:04:16 +100045 int isclass;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +020046 _Py_IDENTIFIER(__prepare__);
Guido van Rossum52cc1d82007-03-18 15:41:51 +000047
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000048 assert(args != NULL);
49 if (!PyTuple_Check(args)) {
50 PyErr_SetString(PyExc_TypeError,
51 "__build_class__: args is not a tuple");
52 return NULL;
53 }
54 nargs = PyTuple_GET_SIZE(args);
55 if (nargs < 2) {
56 PyErr_SetString(PyExc_TypeError,
57 "__build_class__: not enough arguments");
58 return NULL;
59 }
60 func = PyTuple_GET_ITEM(args, 0); /* Better be callable */
Benjamin Petersone8e14592013-05-16 14:37:25 -050061 if (!PyFunction_Check(func)) {
62 PyErr_SetString(PyExc_TypeError,
63 "__build__class__: func must be a function");
64 return NULL;
65 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000066 name = PyTuple_GET_ITEM(args, 1);
67 if (!PyUnicode_Check(name)) {
68 PyErr_SetString(PyExc_TypeError,
69 "__build_class__: name is not a string");
70 return NULL;
71 }
72 bases = PyTuple_GetSlice(args, 2, nargs);
73 if (bases == NULL)
74 return NULL;
Guido van Rossum52cc1d82007-03-18 15:41:51 +000075
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000076 if (kwds == NULL) {
77 meta = NULL;
78 mkw = NULL;
79 }
80 else {
81 mkw = PyDict_Copy(kwds); /* Don't modify kwds passed in! */
82 if (mkw == NULL) {
83 Py_DECREF(bases);
84 return NULL;
Guido van Rossum52cc1d82007-03-18 15:41:51 +000085 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000086 meta = PyDict_GetItemString(mkw, "metaclass");
87 if (meta != NULL) {
88 Py_INCREF(meta);
89 if (PyDict_DelItemString(mkw, "metaclass") < 0) {
90 Py_DECREF(meta);
91 Py_DECREF(mkw);
92 Py_DECREF(bases);
93 return NULL;
94 }
Nick Coghlande31b192011-10-23 22:04:16 +100095 /* metaclass is explicitly given, check if it's indeed a class */
96 isclass = PyType_Check(meta);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000097 }
98 }
99 if (meta == NULL) {
Nick Coghlande31b192011-10-23 22:04:16 +1000100 /* if there are no bases, use type: */
101 if (PyTuple_GET_SIZE(bases) == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000102 meta = (PyObject *) (&PyType_Type);
Nick Coghlande31b192011-10-23 22:04:16 +1000103 }
104 /* else get the type of the first base */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000105 else {
106 PyObject *base0 = PyTuple_GET_ITEM(bases, 0);
107 meta = (PyObject *) (base0->ob_type);
108 }
109 Py_INCREF(meta);
Nick Coghlande31b192011-10-23 22:04:16 +1000110 isclass = 1; /* meta is really a class */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000111 }
Nick Coghlan9715d262011-10-23 22:36:42 +1000112
Nick Coghlande31b192011-10-23 22:04:16 +1000113 if (isclass) {
114 /* meta is really a class, so check for a more derived
115 metaclass, or possible metaclass conflicts: */
116 winner = (PyObject *)_PyType_CalculateMetaclass((PyTypeObject *)meta,
117 bases);
118 if (winner == NULL) {
119 Py_DECREF(meta);
120 Py_XDECREF(mkw);
121 Py_DECREF(bases);
122 return NULL;
123 }
124 if (winner != meta) {
125 Py_DECREF(meta);
126 meta = winner;
127 Py_INCREF(meta);
128 }
129 }
130 /* else: meta is not a class, so we cannot do the metaclass
131 calculation, so we will use the explicitly given object as it is */
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +0200132 prep = _PyObject_GetAttrId(meta, &PyId___prepare__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000133 if (prep == NULL) {
134 if (PyErr_ExceptionMatches(PyExc_AttributeError)) {
135 PyErr_Clear();
136 ns = PyDict_New();
137 }
138 else {
139 Py_DECREF(meta);
140 Py_XDECREF(mkw);
141 Py_DECREF(bases);
142 return NULL;
143 }
144 }
145 else {
146 PyObject *pargs = PyTuple_Pack(2, name, bases);
147 if (pargs == NULL) {
148 Py_DECREF(prep);
149 Py_DECREF(meta);
150 Py_XDECREF(mkw);
151 Py_DECREF(bases);
152 return NULL;
153 }
154 ns = PyEval_CallObjectWithKeywords(prep, pargs, mkw);
155 Py_DECREF(pargs);
156 Py_DECREF(prep);
157 }
158 if (ns == NULL) {
159 Py_DECREF(meta);
160 Py_XDECREF(mkw);
161 Py_DECREF(bases);
162 return NULL;
163 }
Benjamin Petersone8e14592013-05-16 14:37:25 -0500164 cell = PyEval_EvalCodeEx(PyFunction_GET_CODE(func), PyFunction_GET_GLOBALS(func), ns,
165 NULL, 0, NULL, 0, NULL, 0, NULL,
166 PyFunction_GET_CLOSURE(func));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000167 if (cell != NULL) {
168 PyObject *margs;
169 margs = PyTuple_Pack(3, name, bases, ns);
170 if (margs != NULL) {
171 cls = PyEval_CallObjectWithKeywords(meta, margs, mkw);
172 Py_DECREF(margs);
173 }
Benjamin Peterson8e8fbea2012-06-01 23:57:36 -0700174 if (cls != NULL && PyCell_Check(cell))
175 PyCell_Set(cell, cls);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000176 Py_DECREF(cell);
177 }
178 Py_DECREF(ns);
179 Py_DECREF(meta);
180 Py_XDECREF(mkw);
181 Py_DECREF(bases);
182 return cls;
Guido van Rossum52cc1d82007-03-18 15:41:51 +0000183}
184
185PyDoc_STRVAR(build_class_doc,
186"__build_class__(func, name, *bases, metaclass=None, **kwds) -> class\n\
187\n\
188Internal helper function used by the class statement.");
189
190static PyObject *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000191builtin___import__(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000192{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000193 static char *kwlist[] = {"name", "globals", "locals", "fromlist",
194 "level", 0};
Victor Stinnerfe93faf2011-03-14 15:54:52 -0400195 PyObject *name, *globals = NULL, *locals = NULL, *fromlist = NULL;
Brett Cannonfd074152012-04-14 14:10:13 -0400196 int level = 0;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000197
Victor Stinnerfe93faf2011-03-14 15:54:52 -0400198 if (!PyArg_ParseTupleAndKeywords(args, kwds, "U|OOOi:__import__",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000199 kwlist, &name, &globals, &locals, &fromlist, &level))
200 return NULL;
Victor Stinnerfe93faf2011-03-14 15:54:52 -0400201 return PyImport_ImportModuleLevelObject(name, globals, locals,
202 fromlist, level);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000203}
204
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000205PyDoc_STRVAR(import_doc,
Brett Cannoncb4996a2012-08-06 16:34:44 -0400206"__import__(name, globals=None, locals=None, fromlist=(), level=0) -> module\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000207\n\
Brett Cannon5305a992010-09-27 21:08:38 +0000208Import a module. Because this function is meant for use by the Python\n\
209interpreter and not for general use it is better to use\n\
210importlib.import_module() to programmatically import a module.\n\
211\n\
212The globals argument is only used to determine the context;\n\
213they are not modified. The locals argument is unused. The fromlist\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000214should be a list of names to emulate ``from name import ...'', or an\n\
215empty list to emulate ``import name''.\n\
216When importing a module from a package, note that __import__('A.B', ...)\n\
217returns package A when fromlist is empty, but its submodule B when\n\
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000218fromlist is not empty. Level is used to determine whether to perform \n\
Brett Cannon722d3ae2012-07-30 17:45:54 -0400219absolute or relative imports. 0 is absolute while a positive number\n\
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000220is the number of parent directories to search relative to the current module.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000221
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000222
Guido van Rossum79f25d91997-04-29 20:08:16 +0000223static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000224builtin_abs(PyObject *self, PyObject *v)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000225{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000226 return PyNumber_Absolute(v);
Guido van Rossum3f5da241990-12-20 15:06:42 +0000227}
228
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000229PyDoc_STRVAR(abs_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000230"abs(number) -> number\n\
231\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000232Return the absolute value of the argument.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000233
Raymond Hettinger96229b12005-03-11 06:49:40 +0000234static PyObject *
235builtin_all(PyObject *self, PyObject *v)
236{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000237 PyObject *it, *item;
238 PyObject *(*iternext)(PyObject *);
239 int cmp;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000240
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000241 it = PyObject_GetIter(v);
242 if (it == NULL)
243 return NULL;
244 iternext = *Py_TYPE(it)->tp_iternext;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000245
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000246 for (;;) {
247 item = iternext(it);
248 if (item == NULL)
249 break;
250 cmp = PyObject_IsTrue(item);
251 Py_DECREF(item);
252 if (cmp < 0) {
253 Py_DECREF(it);
254 return NULL;
255 }
256 if (cmp == 0) {
257 Py_DECREF(it);
258 Py_RETURN_FALSE;
259 }
260 }
261 Py_DECREF(it);
262 if (PyErr_Occurred()) {
263 if (PyErr_ExceptionMatches(PyExc_StopIteration))
264 PyErr_Clear();
265 else
266 return NULL;
267 }
268 Py_RETURN_TRUE;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000269}
270
271PyDoc_STRVAR(all_doc,
272"all(iterable) -> bool\n\
273\n\
Ezio Melottib19ed572013-02-15 23:35:14 +0200274Return True if bool(x) is True for all values x in the iterable.\n\
275If the iterable is empty, return True.");
Raymond Hettinger96229b12005-03-11 06:49:40 +0000276
277static PyObject *
278builtin_any(PyObject *self, PyObject *v)
279{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000280 PyObject *it, *item;
281 PyObject *(*iternext)(PyObject *);
282 int cmp;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000283
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000284 it = PyObject_GetIter(v);
285 if (it == NULL)
286 return NULL;
287 iternext = *Py_TYPE(it)->tp_iternext;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000288
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000289 for (;;) {
290 item = iternext(it);
291 if (item == NULL)
292 break;
293 cmp = PyObject_IsTrue(item);
294 Py_DECREF(item);
295 if (cmp < 0) {
296 Py_DECREF(it);
297 return NULL;
298 }
299 if (cmp == 1) {
300 Py_DECREF(it);
301 Py_RETURN_TRUE;
302 }
303 }
304 Py_DECREF(it);
305 if (PyErr_Occurred()) {
306 if (PyErr_ExceptionMatches(PyExc_StopIteration))
307 PyErr_Clear();
308 else
309 return NULL;
310 }
311 Py_RETURN_FALSE;
Raymond Hettinger96229b12005-03-11 06:49:40 +0000312}
313
314PyDoc_STRVAR(any_doc,
315"any(iterable) -> bool\n\
316\n\
Ezio Melottib19ed572013-02-15 23:35:14 +0200317Return True if bool(x) is True for any x in the iterable.\n\
318If the iterable is empty, return False.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000319
Georg Brandl559e5d72008-06-11 18:37:52 +0000320static PyObject *
321builtin_ascii(PyObject *self, PyObject *v)
322{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000323 return PyObject_ASCII(v);
Georg Brandl559e5d72008-06-11 18:37:52 +0000324}
325
326PyDoc_STRVAR(ascii_doc,
327"ascii(object) -> string\n\
328\n\
329As repr(), return a string containing a printable representation of an\n\
330object, but escape the non-ASCII characters in the string returned by\n\
331repr() using \\x, \\u or \\U escapes. This generates a string similar\n\
332to that returned by repr() in Python 2.");
333
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000334
Guido van Rossum79f25d91997-04-29 20:08:16 +0000335static PyObject *
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000336builtin_bin(PyObject *self, PyObject *v)
337{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000338 return PyNumber_ToBase(v, 2);
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000339}
340
341PyDoc_STRVAR(bin_doc,
342"bin(number) -> string\n\
343\n\
Alexander Belopolsky12338ab2011-04-07 00:15:33 -0400344Return the binary representation of an integer.");
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000345
346
Antoine Pitroue71362d2010-11-27 22:00:11 +0000347static PyObject *
348builtin_callable(PyObject *self, PyObject *v)
349{
350 return PyBool_FromLong((long)PyCallable_Check(v));
351}
352
353PyDoc_STRVAR(callable_doc,
354"callable(object) -> bool\n\
355\n\
356Return whether the object is callable (i.e., some kind of function).\n\
357Note that classes are callable, as are instances of classes with a\n\
358__call__() method.");
359
360
Raymond Hettinger17301e92008-03-13 00:19:26 +0000361typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000362 PyObject_HEAD
363 PyObject *func;
364 PyObject *it;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000365} filterobject;
366
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000367static PyObject *
Raymond Hettinger17301e92008-03-13 00:19:26 +0000368filter_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
Guido van Rossum12d12c51993-10-26 17:58:25 +0000369{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000370 PyObject *func, *seq;
371 PyObject *it;
372 filterobject *lz;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000373
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000374 if (type == &PyFilter_Type && !_PyArg_NoKeywords("filter()", kwds))
375 return NULL;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000376
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000377 if (!PyArg_UnpackTuple(args, "filter", 2, 2, &func, &seq))
378 return NULL;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000379
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000380 /* Get iterator. */
381 it = PyObject_GetIter(seq);
382 if (it == NULL)
383 return NULL;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000384
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000385 /* create filterobject structure */
386 lz = (filterobject *)type->tp_alloc(type, 0);
387 if (lz == NULL) {
388 Py_DECREF(it);
389 return NULL;
390 }
391 Py_INCREF(func);
392 lz->func = func;
393 lz->it = it;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000394
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000395 return (PyObject *)lz;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000396}
397
398static void
399filter_dealloc(filterobject *lz)
400{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000401 PyObject_GC_UnTrack(lz);
402 Py_XDECREF(lz->func);
403 Py_XDECREF(lz->it);
404 Py_TYPE(lz)->tp_free(lz);
Raymond Hettinger17301e92008-03-13 00:19:26 +0000405}
406
407static int
408filter_traverse(filterobject *lz, visitproc visit, void *arg)
409{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000410 Py_VISIT(lz->it);
411 Py_VISIT(lz->func);
412 return 0;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000413}
414
415static PyObject *
416filter_next(filterobject *lz)
417{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000418 PyObject *item;
419 PyObject *it = lz->it;
420 long ok;
421 PyObject *(*iternext)(PyObject *);
Raymond Hettinger17301e92008-03-13 00:19:26 +0000422
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000423 iternext = *Py_TYPE(it)->tp_iternext;
424 for (;;) {
425 item = iternext(it);
426 if (item == NULL)
427 return NULL;
Raymond Hettinger17301e92008-03-13 00:19:26 +0000428
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000429 if (lz->func == Py_None || lz->func == (PyObject *)&PyBool_Type) {
430 ok = PyObject_IsTrue(item);
431 } else {
432 PyObject *good;
433 good = PyObject_CallFunctionObjArgs(lz->func,
434 item, NULL);
435 if (good == NULL) {
436 Py_DECREF(item);
437 return NULL;
438 }
439 ok = PyObject_IsTrue(good);
440 Py_DECREF(good);
441 }
Antoine Pitrou6f430e42012-08-15 23:18:25 +0200442 if (ok > 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000443 return item;
444 Py_DECREF(item);
Antoine Pitrou6f430e42012-08-15 23:18:25 +0200445 if (ok < 0)
446 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000447 }
Guido van Rossum12d12c51993-10-26 17:58:25 +0000448}
449
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +0000450static PyObject *
451filter_reduce(filterobject *lz)
452{
453 return Py_BuildValue("O(OO)", Py_TYPE(lz), lz->func, lz->it);
454}
455
456PyDoc_STRVAR(reduce_doc, "Return state information for pickling.");
457
458static PyMethodDef filter_methods[] = {
459 {"__reduce__", (PyCFunction)filter_reduce, METH_NOARGS, reduce_doc},
460 {NULL, NULL} /* sentinel */
461};
462
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000463PyDoc_STRVAR(filter_doc,
Georg Brandld11ae5d2008-05-16 13:27:32 +0000464"filter(function or None, iterable) --> filter object\n\
Guido van Rossumc1f779c2007-07-03 08:25:58 +0000465\n\
Georg Brandld11ae5d2008-05-16 13:27:32 +0000466Return an iterator yielding those items of iterable for which function(item)\n\
Raymond Hettinger17301e92008-03-13 00:19:26 +0000467is true. If function is None, return the items that are true.");
468
469PyTypeObject PyFilter_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000470 PyVarObject_HEAD_INIT(&PyType_Type, 0)
471 "filter", /* tp_name */
472 sizeof(filterobject), /* tp_basicsize */
473 0, /* tp_itemsize */
474 /* methods */
475 (destructor)filter_dealloc, /* tp_dealloc */
476 0, /* tp_print */
477 0, /* tp_getattr */
478 0, /* tp_setattr */
479 0, /* tp_reserved */
480 0, /* tp_repr */
481 0, /* tp_as_number */
482 0, /* tp_as_sequence */
483 0, /* tp_as_mapping */
484 0, /* tp_hash */
485 0, /* tp_call */
486 0, /* tp_str */
487 PyObject_GenericGetAttr, /* tp_getattro */
488 0, /* tp_setattro */
489 0, /* tp_as_buffer */
490 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
491 Py_TPFLAGS_BASETYPE, /* tp_flags */
492 filter_doc, /* tp_doc */
493 (traverseproc)filter_traverse, /* tp_traverse */
494 0, /* tp_clear */
495 0, /* tp_richcompare */
496 0, /* tp_weaklistoffset */
497 PyObject_SelfIter, /* tp_iter */
498 (iternextfunc)filter_next, /* tp_iternext */
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +0000499 filter_methods, /* tp_methods */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000500 0, /* tp_members */
501 0, /* tp_getset */
502 0, /* tp_base */
503 0, /* tp_dict */
504 0, /* tp_descr_get */
505 0, /* tp_descr_set */
506 0, /* tp_dictoffset */
507 0, /* tp_init */
508 PyType_GenericAlloc, /* tp_alloc */
509 filter_new, /* tp_new */
510 PyObject_GC_Del, /* tp_free */
Raymond Hettinger17301e92008-03-13 00:19:26 +0000511};
512
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000513
Eric Smith8c663262007-08-25 02:26:07 +0000514static PyObject *
515builtin_format(PyObject *self, PyObject *args)
516{
Christian Heimes94b7d3d2007-12-11 20:20:39 +0000517 PyObject *value;
Eric Smith8fd3eba2008-02-17 19:48:00 +0000518 PyObject *format_spec = NULL;
Eric Smith8c663262007-08-25 02:26:07 +0000519
Eric Smith8fd3eba2008-02-17 19:48:00 +0000520 if (!PyArg_ParseTuple(args, "O|U:format", &value, &format_spec))
Benjamin Petersona12d5c62012-01-03 16:47:22 -0600521 return NULL;
Eric Smith8c663262007-08-25 02:26:07 +0000522
Eric Smith8fd3eba2008-02-17 19:48:00 +0000523 return PyObject_Format(value, format_spec);
Eric Smith8c663262007-08-25 02:26:07 +0000524}
525
Eric Smith8c663262007-08-25 02:26:07 +0000526PyDoc_STRVAR(format_doc,
Eric Smith81936692007-08-31 01:14:01 +0000527"format(value[, format_spec]) -> string\n\
Eric Smith8c663262007-08-25 02:26:07 +0000528\n\
Eric Smith81936692007-08-31 01:14:01 +0000529Returns value.__format__(format_spec)\n\
530format_spec defaults to \"\"");
531
Guido van Rossum7fcf2242007-05-04 17:43:11 +0000532static PyObject *
Walter Dörwalde7efd592007-06-05 20:07:21 +0000533builtin_chr(PyObject *self, PyObject *args)
Guido van Rossum09095f32000-03-10 23:00:52 +0000534{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000535 int x;
Guido van Rossum09095f32000-03-10 23:00:52 +0000536
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000537 if (!PyArg_ParseTuple(args, "i:chr", &x))
538 return NULL;
Fredrik Lundh0dcf67e2001-06-26 20:01:56 +0000539
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000540 return PyUnicode_FromOrdinal(x);
Guido van Rossum09095f32000-03-10 23:00:52 +0000541}
542
Victor Stinner63ab8752011-11-22 03:31:20 +0100543PyDoc_STRVAR(chr_doc,
Guido van Rossum84fc66d2007-05-03 17:18:26 +0000544"chr(i) -> Unicode character\n\
Guido van Rossum09095f32000-03-10 23:00:52 +0000545\n\
Victor Stinner63ab8752011-11-22 03:31:20 +0100546Return a Unicode string of one character with ordinal i; 0 <= i <= 0x10ffff.");
Guido van Rossum09095f32000-03-10 23:00:52 +0000547
548
Guido van Rossumf15a29f2007-05-04 00:41:39 +0000549static char *
Benjamin Petersonf5b52242009-03-02 23:31:26 +0000550source_as_string(PyObject *cmd, char *funcname, char *what, PyCompilerFlags *cf)
Guido van Rossumf15a29f2007-05-04 00:41:39 +0000551{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000552 char *str;
553 Py_ssize_t size;
Guido van Rossumf15a29f2007-05-04 00:41:39 +0000554
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000555 if (PyUnicode_Check(cmd)) {
556 cf->cf_flags |= PyCF_IGNORE_COOKIE;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200557 str = PyUnicode_AsUTF8AndSize(cmd, &size);
558 if (str == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000559 return NULL;
560 }
561 else if (!PyObject_CheckReadBuffer(cmd)) {
562 PyErr_Format(PyExc_TypeError,
563 "%s() arg 1 must be a %s object",
564 funcname, what);
565 return NULL;
566 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200567 else if (PyObject_AsReadBuffer(cmd, (const void **)&str, &size) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000568 return NULL;
569 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200570
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000571 if (strlen(str) != size) {
572 PyErr_SetString(PyExc_TypeError,
573 "source code string cannot contain null bytes");
574 return NULL;
575 }
576 return str;
Guido van Rossumf15a29f2007-05-04 00:41:39 +0000577}
578
Guido van Rossum79f25d91997-04-29 20:08:16 +0000579static PyObject *
Guido van Rossumd8faa362007-04-27 19:54:29 +0000580builtin_compile(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum5b722181993-03-30 17:46:03 +0000581{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000582 char *str;
Victor Stinner14e461d2013-08-26 22:28:21 +0200583 PyObject *filename;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000584 char *startstr;
585 int mode = -1;
586 int dont_inherit = 0;
587 int supplied_flags = 0;
Georg Brandl8334fd92010-12-04 10:26:46 +0000588 int optimize = -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000589 int is_ast;
590 PyCompilerFlags cf;
591 PyObject *cmd;
592 static char *kwlist[] = {"source", "filename", "mode", "flags",
Georg Brandl8334fd92010-12-04 10:26:46 +0000593 "dont_inherit", "optimize", NULL};
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000594 int start[] = {Py_file_input, Py_eval_input, Py_single_input};
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000595 PyObject *result;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000596
Georg Brandl8334fd92010-12-04 10:26:46 +0000597 if (!PyArg_ParseTupleAndKeywords(args, kwds, "OO&s|iii:compile", kwlist,
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000598 &cmd,
Victor Stinner14e461d2013-08-26 22:28:21 +0200599 PyUnicode_FSDecoder, &filename,
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000600 &startstr, &supplied_flags,
Georg Brandl8334fd92010-12-04 10:26:46 +0000601 &dont_inherit, &optimize))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000602 return NULL;
Tim Peters6cd6a822001-08-17 22:11:27 +0000603
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000604 cf.cf_flags = supplied_flags | PyCF_SOURCE_IS_UTF8;
Just van Rossum3aaf42c2003-02-10 08:21:10 +0000605
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000606 if (supplied_flags &
607 ~(PyCF_MASK | PyCF_MASK_OBSOLETE | PyCF_DONT_IMPLY_DEDENT | PyCF_ONLY_AST))
608 {
609 PyErr_SetString(PyExc_ValueError,
610 "compile(): unrecognised flags");
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000611 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000612 }
613 /* XXX Warn if (supplied_flags & PyCF_MASK_OBSOLETE) != 0? */
Tim Peters6cd6a822001-08-17 22:11:27 +0000614
Georg Brandl8334fd92010-12-04 10:26:46 +0000615 if (optimize < -1 || optimize > 2) {
616 PyErr_SetString(PyExc_ValueError,
617 "compile(): invalid optimize value");
618 goto error;
619 }
620
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000621 if (!dont_inherit) {
622 PyEval_MergeCompilerFlags(&cf);
623 }
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000624
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000625 if (strcmp(startstr, "exec") == 0)
626 mode = 0;
627 else if (strcmp(startstr, "eval") == 0)
628 mode = 1;
629 else if (strcmp(startstr, "single") == 0)
630 mode = 2;
631 else {
632 PyErr_SetString(PyExc_ValueError,
633 "compile() arg 3 must be 'exec', 'eval' or 'single'");
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000634 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000635 }
Neal Norwitzdb4115f2008-03-31 04:20:05 +0000636
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000637 is_ast = PyAST_Check(cmd);
638 if (is_ast == -1)
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000639 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000640 if (is_ast) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000641 if (supplied_flags & PyCF_ONLY_AST) {
642 Py_INCREF(cmd);
643 result = cmd;
644 }
645 else {
646 PyArena *arena;
647 mod_ty mod;
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000648
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000649 arena = PyArena_New();
Stefan Krah07795df2012-08-20 17:19:50 +0200650 if (arena == NULL)
651 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000652 mod = PyAST_obj2mod(cmd, arena, mode);
653 if (mod == NULL) {
654 PyArena_Free(arena);
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000655 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000656 }
Benjamin Peterson832bfe22011-08-09 16:15:04 -0500657 if (!PyAST_Validate(mod)) {
658 PyArena_Free(arena);
659 goto error;
660 }
Victor Stinner14e461d2013-08-26 22:28:21 +0200661 result = (PyObject*)PyAST_CompileObject(mod, filename,
662 &cf, optimize, arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000663 PyArena_Free(arena);
664 }
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000665 goto finally;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000666 }
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000667
Philip Jenveyf76f0ee2012-12-13 15:44:18 -0800668 str = source_as_string(cmd, "compile", "string, bytes or AST", &cf);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000669 if (str == NULL)
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000670 goto error;
Martin v. Löwis618dc5e2008-03-30 20:03:44 +0000671
Victor Stinner14e461d2013-08-26 22:28:21 +0200672 result = Py_CompileStringObject(str, filename, start[mode], &cf, optimize);
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000673 goto finally;
674
675error:
676 result = NULL;
677finally:
Victor Stinner14e461d2013-08-26 22:28:21 +0200678 Py_DECREF(filename);
Victor Stinner4c7c8c32010-10-16 13:14:10 +0000679 return result;
Guido van Rossum5b722181993-03-30 17:46:03 +0000680}
681
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000682PyDoc_STRVAR(compile_doc,
Tim Peters6cd6a822001-08-17 22:11:27 +0000683"compile(source, filename, mode[, flags[, dont_inherit]]) -> code object\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000684\n\
685Compile the source string (a Python module, statement or expression)\n\
Georg Brandl7cae87c2006-09-06 06:51:57 +0000686into a code object that can be executed by exec() or eval().\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000687The filename will be used for run-time error messages.\n\
688The mode must be 'exec' to compile a module, 'single' to compile a\n\
Tim Peters6cd6a822001-08-17 22:11:27 +0000689single (interactive) statement, or 'eval' to compile an expression.\n\
690The flags argument, if present, controls which future statements influence\n\
691the compilation of the code.\n\
692The dont_inherit argument, if non-zero, stops the compilation inheriting\n\
693the effects of any future statements in effect in the code calling\n\
694compile; if absent or zero these statements do influence the compilation,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000695in addition to any features explicitly specified.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000696
Guido van Rossum79f25d91997-04-29 20:08:16 +0000697static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000698builtin_dir(PyObject *self, PyObject *args)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000699{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000700 PyObject *arg = NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000701
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000702 if (!PyArg_UnpackTuple(args, "dir", 0, 1, &arg))
703 return NULL;
704 return PyObject_Dir(arg);
Guido van Rossum3f5da241990-12-20 15:06:42 +0000705}
706
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000707PyDoc_STRVAR(dir_doc,
Tim Peters5d2b77c2001-09-03 05:47:38 +0000708"dir([object]) -> list of strings\n"
709"\n"
Georg Brandle32b4222007-03-10 22:13:27 +0000710"If called without an argument, return the names in the current scope.\n"
711"Else, return an alphabetized list of names comprising (some of) the attributes\n"
712"of the given object, and of attributes reachable from it.\n"
713"If the object supplies a method named __dir__, it will be used; otherwise\n"
714"the default dir() logic is used and returns:\n"
715" for a module object: the module's attributes.\n"
716" for a class object: its attributes, and recursively the attributes\n"
717" of its bases.\n"
Guido van Rossumd8faa362007-04-27 19:54:29 +0000718" for any other object: its attributes, its class's attributes, and\n"
Georg Brandle32b4222007-03-10 22:13:27 +0000719" recursively the attributes of its class's base classes.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000720
Guido van Rossum79f25d91997-04-29 20:08:16 +0000721static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000722builtin_divmod(PyObject *self, PyObject *args)
Guido van Rossum6a00cd81995-01-07 12:39:01 +0000723{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000724 PyObject *v, *w;
Guido van Rossum6a00cd81995-01-07 12:39:01 +0000725
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000726 if (!PyArg_UnpackTuple(args, "divmod", 2, 2, &v, &w))
727 return NULL;
728 return PyNumber_Divmod(v, w);
Guido van Rossum3f5da241990-12-20 15:06:42 +0000729}
730
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000731PyDoc_STRVAR(divmod_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000732"divmod(x, y) -> (div, mod)\n\
733\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000734Return the tuple ((x-x%y)/y, x%y). Invariant: div*y + mod == x.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000735
736
Guido van Rossum79f25d91997-04-29 20:08:16 +0000737static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000738builtin_eval(PyObject *self, PyObject *args)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000739{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000740 PyObject *cmd, *result, *tmp = NULL;
741 PyObject *globals = Py_None, *locals = Py_None;
742 char *str;
743 PyCompilerFlags cf;
Guido van Rossum590baa41993-11-30 13:40:46 +0000744
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000745 if (!PyArg_UnpackTuple(args, "eval", 1, 3, &cmd, &globals, &locals))
746 return NULL;
747 if (locals != Py_None && !PyMapping_Check(locals)) {
748 PyErr_SetString(PyExc_TypeError, "locals must be a mapping");
749 return NULL;
750 }
751 if (globals != Py_None && !PyDict_Check(globals)) {
752 PyErr_SetString(PyExc_TypeError, PyMapping_Check(globals) ?
753 "globals must be a real dict; try eval(expr, {}, mapping)"
754 : "globals must be a dict");
755 return NULL;
756 }
757 if (globals == Py_None) {
758 globals = PyEval_GetGlobals();
Victor Stinner41bb43a2013-10-29 01:19:37 +0100759 if (locals == Py_None) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000760 locals = PyEval_GetLocals();
Victor Stinner41bb43a2013-10-29 01:19:37 +0100761 if (locals == NULL)
762 return NULL;
763 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000764 }
765 else if (locals == Py_None)
766 locals = globals;
Tim Peters9fa96be2001-08-17 23:04:59 +0000767
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000768 if (globals == NULL || locals == NULL) {
769 PyErr_SetString(PyExc_TypeError,
770 "eval must be given globals and locals "
771 "when called without a frame");
772 return NULL;
773 }
Georg Brandl77c85e62005-09-15 10:46:13 +0000774
Victor Stinnerb44562b2013-11-06 19:03:11 +0100775 if (_PyDict_GetItemId(globals, &PyId___builtins__) == NULL) {
776 if (_PyDict_SetItemId(globals, &PyId___builtins__,
777 PyEval_GetBuiltins()) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000778 return NULL;
779 }
Tim Peters9fa96be2001-08-17 23:04:59 +0000780
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000781 if (PyCode_Check(cmd)) {
782 if (PyCode_GetNumFree((PyCodeObject *)cmd) > 0) {
783 PyErr_SetString(PyExc_TypeError,
784 "code object passed to eval() may not contain free variables");
785 return NULL;
786 }
Martin v. Löwis4d0d4712010-12-03 20:14:31 +0000787 return PyEval_EvalCode(cmd, globals, locals);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000788 }
Tim Peters9fa96be2001-08-17 23:04:59 +0000789
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000790 cf.cf_flags = PyCF_SOURCE_IS_UTF8;
791 str = source_as_string(cmd, "eval", "string, bytes or code", &cf);
792 if (str == NULL)
793 return NULL;
Just van Rossum3aaf42c2003-02-10 08:21:10 +0000794
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000795 while (*str == ' ' || *str == '\t')
796 str++;
Tim Peters9fa96be2001-08-17 23:04:59 +0000797
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000798 (void)PyEval_MergeCompilerFlags(&cf);
799 result = PyRun_StringFlags(str, Py_eval_input, globals, locals, &cf);
800 Py_XDECREF(tmp);
801 return result;
Guido van Rossum3f5da241990-12-20 15:06:42 +0000802}
803
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000804PyDoc_STRVAR(eval_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000805"eval(source[, globals[, locals]]) -> value\n\
806\n\
807Evaluate the source in the context of globals and locals.\n\
808The source may be a string representing a Python expression\n\
809or a code object as returned by compile().\n\
Thomas Wouters89f507f2006-12-13 04:49:30 +0000810The globals must be a dictionary and locals can be any mapping,\n\
Raymond Hettinger214b1c32004-07-02 06:41:07 +0000811defaulting to the current globals and locals.\n\
812If only globals is given, locals defaults to it.\n");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000813
Georg Brandl7cae87c2006-09-06 06:51:57 +0000814static PyObject *
815builtin_exec(PyObject *self, PyObject *args)
816{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000817 PyObject *v;
818 PyObject *prog, *globals = Py_None, *locals = Py_None;
Georg Brandl7cae87c2006-09-06 06:51:57 +0000819
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000820 if (!PyArg_UnpackTuple(args, "exec", 1, 3, &prog, &globals, &locals))
821 return NULL;
Georg Brandl2cabc562008-08-28 07:57:16 +0000822
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000823 if (globals == Py_None) {
824 globals = PyEval_GetGlobals();
825 if (locals == Py_None) {
826 locals = PyEval_GetLocals();
Victor Stinner41bb43a2013-10-29 01:19:37 +0100827 if (locals == NULL)
828 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000829 }
830 if (!globals || !locals) {
831 PyErr_SetString(PyExc_SystemError,
832 "globals and locals cannot be NULL");
833 return NULL;
834 }
835 }
836 else if (locals == Py_None)
837 locals = globals;
Georg Brandl7cae87c2006-09-06 06:51:57 +0000838
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000839 if (!PyDict_Check(globals)) {
840 PyErr_Format(PyExc_TypeError, "exec() arg 2 must be a dict, not %.100s",
841 globals->ob_type->tp_name);
842 return NULL;
843 }
844 if (!PyMapping_Check(locals)) {
845 PyErr_Format(PyExc_TypeError,
846 "arg 3 must be a mapping or None, not %.100s",
847 locals->ob_type->tp_name);
848 return NULL;
849 }
Victor Stinnerb44562b2013-11-06 19:03:11 +0100850 if (_PyDict_GetItemId(globals, &PyId___builtins__) == NULL) {
851 if (_PyDict_SetItemId(globals, &PyId___builtins__,
852 PyEval_GetBuiltins()) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000853 return NULL;
854 }
855
856 if (PyCode_Check(prog)) {
857 if (PyCode_GetNumFree((PyCodeObject *)prog) > 0) {
858 PyErr_SetString(PyExc_TypeError,
859 "code object passed to exec() may not "
860 "contain free variables");
861 return NULL;
862 }
Martin v. Löwis4d0d4712010-12-03 20:14:31 +0000863 v = PyEval_EvalCode(prog, globals, locals);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000864 }
865 else {
866 char *str;
867 PyCompilerFlags cf;
868 cf.cf_flags = PyCF_SOURCE_IS_UTF8;
869 str = source_as_string(prog, "exec",
870 "string, bytes or code", &cf);
871 if (str == NULL)
872 return NULL;
873 if (PyEval_MergeCompilerFlags(&cf))
874 v = PyRun_StringFlags(str, Py_file_input, globals,
875 locals, &cf);
876 else
877 v = PyRun_String(str, Py_file_input, globals, locals);
878 }
879 if (v == NULL)
880 return NULL;
881 Py_DECREF(v);
882 Py_RETURN_NONE;
Georg Brandl7cae87c2006-09-06 06:51:57 +0000883}
884
885PyDoc_STRVAR(exec_doc,
886"exec(object[, globals[, locals]])\n\
887\n\
Mark Dickinson480e8e32009-12-19 21:19:35 +0000888Read and execute code from an object, which can be a string or a code\n\
Benjamin Peterson38090262009-01-04 15:30:39 +0000889object.\n\
Georg Brandl7cae87c2006-09-06 06:51:57 +0000890The globals and locals are dictionaries, defaulting to the current\n\
891globals and locals. If only globals is given, locals defaults to it.");
892
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000893
Guido van Rossum79f25d91997-04-29 20:08:16 +0000894static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000895builtin_getattr(PyObject *self, PyObject *args)
Guido van Rossum33894be1992-01-27 16:53:09 +0000896{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000897 PyObject *v, *result, *dflt = NULL;
898 PyObject *name;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000899
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000900 if (!PyArg_UnpackTuple(args, "getattr", 2, 3, &v, &name, &dflt))
901 return NULL;
Martin v. Löwis5b222132007-06-10 09:51:05 +0000902
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000903 if (!PyUnicode_Check(name)) {
904 PyErr_SetString(PyExc_TypeError,
905 "getattr(): attribute name must be string");
906 return NULL;
907 }
908 result = PyObject_GetAttr(v, name);
909 if (result == NULL && dflt != NULL &&
910 PyErr_ExceptionMatches(PyExc_AttributeError))
911 {
912 PyErr_Clear();
913 Py_INCREF(dflt);
914 result = dflt;
915 }
916 return result;
Guido van Rossum9bfef441993-03-29 10:43:31 +0000917}
918
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000919PyDoc_STRVAR(getattr_doc,
Guido van Rossum950ff291998-06-29 13:38:57 +0000920"getattr(object, name[, default]) -> value\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000921\n\
Guido van Rossum950ff291998-06-29 13:38:57 +0000922Get a named attribute from an object; getattr(x, 'y') is equivalent to x.y.\n\
923When a default argument is given, it is returned when the attribute doesn't\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000924exist; without it, an exception is raised in that case.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000925
926
Guido van Rossum79f25d91997-04-29 20:08:16 +0000927static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000928builtin_globals(PyObject *self)
Guido van Rossum872537c1995-07-07 22:43:42 +0000929{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000930 PyObject *d;
Guido van Rossum872537c1995-07-07 22:43:42 +0000931
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000932 d = PyEval_GetGlobals();
933 Py_XINCREF(d);
934 return d;
Guido van Rossum872537c1995-07-07 22:43:42 +0000935}
936
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000937PyDoc_STRVAR(globals_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000938"globals() -> dictionary\n\
939\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000940Return the dictionary containing the current scope's global variables.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000941
942
Guido van Rossum79f25d91997-04-29 20:08:16 +0000943static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000944builtin_hasattr(PyObject *self, PyObject *args)
Guido van Rossum9bfef441993-03-29 10:43:31 +0000945{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000946 PyObject *v;
947 PyObject *name;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000948
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000949 if (!PyArg_UnpackTuple(args, "hasattr", 2, 2, &v, &name))
950 return NULL;
951 if (!PyUnicode_Check(name)) {
952 PyErr_SetString(PyExc_TypeError,
953 "hasattr(): attribute name must be string");
954 return NULL;
955 }
956 v = PyObject_GetAttr(v, name);
957 if (v == NULL) {
Benjamin Peterson17689992010-08-24 03:26:23 +0000958 if (PyErr_ExceptionMatches(PyExc_AttributeError)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000959 PyErr_Clear();
Benjamin Peterson17689992010-08-24 03:26:23 +0000960 Py_RETURN_FALSE;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000961 }
Benjamin Peterson17689992010-08-24 03:26:23 +0000962 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000963 }
964 Py_DECREF(v);
Benjamin Peterson17689992010-08-24 03:26:23 +0000965 Py_RETURN_TRUE;
Guido van Rossum33894be1992-01-27 16:53:09 +0000966}
967
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000968PyDoc_STRVAR(hasattr_doc,
Guido van Rossum77f6a652002-04-03 22:41:51 +0000969"hasattr(object, name) -> bool\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000970\n\
971Return whether the object has an attribute with the given name.\n\
Benjamin Peterson17689992010-08-24 03:26:23 +0000972(This is done by calling getattr(object, name) and catching AttributeError.)");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000973
974
Guido van Rossum79f25d91997-04-29 20:08:16 +0000975static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000976builtin_id(PyObject *self, PyObject *v)
Guido van Rossum5b722181993-03-30 17:46:03 +0000977{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000978 return PyLong_FromVoidPtr(v);
Guido van Rossum5b722181993-03-30 17:46:03 +0000979}
980
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000981PyDoc_STRVAR(id_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000982"id(object) -> integer\n\
983\n\
984Return the identity of an object. This is guaranteed to be unique among\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000985simultaneously existing objects. (Hint: it's the object's memory address.)");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000986
987
Raymond Hettingera6c60372008-03-13 01:26:19 +0000988/* map object ************************************************************/
989
990typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000991 PyObject_HEAD
992 PyObject *iters;
993 PyObject *func;
Raymond Hettingera6c60372008-03-13 01:26:19 +0000994} mapobject;
995
Guido van Rossum79f25d91997-04-29 20:08:16 +0000996static PyObject *
Raymond Hettingera6c60372008-03-13 01:26:19 +0000997map_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
Guido van Rossum12d12c51993-10-26 17:58:25 +0000998{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000999 PyObject *it, *iters, *func;
1000 mapobject *lz;
1001 Py_ssize_t numargs, i;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001002
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001003 if (type == &PyMap_Type && !_PyArg_NoKeywords("map()", kwds))
1004 return NULL;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001005
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001006 numargs = PyTuple_Size(args);
1007 if (numargs < 2) {
1008 PyErr_SetString(PyExc_TypeError,
1009 "map() must have at least two arguments.");
1010 return NULL;
1011 }
Raymond Hettingera6c60372008-03-13 01:26:19 +00001012
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001013 iters = PyTuple_New(numargs-1);
1014 if (iters == NULL)
1015 return NULL;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001016
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001017 for (i=1 ; i<numargs ; i++) {
1018 /* Get iterator. */
1019 it = PyObject_GetIter(PyTuple_GET_ITEM(args, i));
1020 if (it == NULL) {
1021 Py_DECREF(iters);
1022 return NULL;
1023 }
1024 PyTuple_SET_ITEM(iters, i-1, it);
1025 }
Raymond Hettingera6c60372008-03-13 01:26:19 +00001026
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001027 /* create mapobject structure */
1028 lz = (mapobject *)type->tp_alloc(type, 0);
1029 if (lz == NULL) {
1030 Py_DECREF(iters);
1031 return NULL;
1032 }
1033 lz->iters = iters;
1034 func = PyTuple_GET_ITEM(args, 0);
1035 Py_INCREF(func);
1036 lz->func = func;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001037
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001038 return (PyObject *)lz;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001039}
1040
1041static void
1042map_dealloc(mapobject *lz)
1043{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001044 PyObject_GC_UnTrack(lz);
1045 Py_XDECREF(lz->iters);
1046 Py_XDECREF(lz->func);
1047 Py_TYPE(lz)->tp_free(lz);
Raymond Hettingera6c60372008-03-13 01:26:19 +00001048}
1049
1050static int
1051map_traverse(mapobject *lz, visitproc visit, void *arg)
1052{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001053 Py_VISIT(lz->iters);
1054 Py_VISIT(lz->func);
1055 return 0;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001056}
1057
1058static PyObject *
1059map_next(mapobject *lz)
1060{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001061 PyObject *val;
1062 PyObject *argtuple;
1063 PyObject *result;
1064 Py_ssize_t numargs, i;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001065
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001066 numargs = PyTuple_Size(lz->iters);
1067 argtuple = PyTuple_New(numargs);
1068 if (argtuple == NULL)
1069 return NULL;
Raymond Hettingera6c60372008-03-13 01:26:19 +00001070
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001071 for (i=0 ; i<numargs ; i++) {
1072 val = PyIter_Next(PyTuple_GET_ITEM(lz->iters, i));
1073 if (val == NULL) {
1074 Py_DECREF(argtuple);
1075 return NULL;
1076 }
1077 PyTuple_SET_ITEM(argtuple, i, val);
1078 }
1079 result = PyObject_Call(lz->func, argtuple, NULL);
1080 Py_DECREF(argtuple);
1081 return result;
Guido van Rossum12d12c51993-10-26 17:58:25 +00001082}
1083
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001084static PyObject *
1085map_reduce(mapobject *lz)
1086{
1087 Py_ssize_t numargs = PyTuple_GET_SIZE(lz->iters);
1088 PyObject *args = PyTuple_New(numargs+1);
1089 Py_ssize_t i;
1090 if (args == NULL)
1091 return NULL;
1092 Py_INCREF(lz->func);
1093 PyTuple_SET_ITEM(args, 0, lz->func);
1094 for (i = 0; i<numargs; i++){
1095 PyObject *it = PyTuple_GET_ITEM(lz->iters, i);
1096 Py_INCREF(it);
1097 PyTuple_SET_ITEM(args, i+1, it);
1098 }
1099
1100 return Py_BuildValue("ON", Py_TYPE(lz), args);
1101}
1102
1103static PyMethodDef map_methods[] = {
1104 {"__reduce__", (PyCFunction)map_reduce, METH_NOARGS, reduce_doc},
1105 {NULL, NULL} /* sentinel */
1106};
1107
1108
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001109PyDoc_STRVAR(map_doc,
Raymond Hettingera6c60372008-03-13 01:26:19 +00001110"map(func, *iterables) --> map object\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001111\n\
Raymond Hettingera6c60372008-03-13 01:26:19 +00001112Make an iterator that computes the function using arguments from\n\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001113each of the iterables. Stops when the shortest iterable is exhausted.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001114
Raymond Hettingera6c60372008-03-13 01:26:19 +00001115PyTypeObject PyMap_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001116 PyVarObject_HEAD_INIT(&PyType_Type, 0)
1117 "map", /* tp_name */
1118 sizeof(mapobject), /* tp_basicsize */
1119 0, /* tp_itemsize */
1120 /* methods */
1121 (destructor)map_dealloc, /* tp_dealloc */
1122 0, /* tp_print */
1123 0, /* tp_getattr */
1124 0, /* tp_setattr */
1125 0, /* tp_reserved */
1126 0, /* tp_repr */
1127 0, /* tp_as_number */
1128 0, /* tp_as_sequence */
1129 0, /* tp_as_mapping */
1130 0, /* tp_hash */
1131 0, /* tp_call */
1132 0, /* tp_str */
1133 PyObject_GenericGetAttr, /* tp_getattro */
1134 0, /* tp_setattro */
1135 0, /* tp_as_buffer */
1136 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
1137 Py_TPFLAGS_BASETYPE, /* tp_flags */
1138 map_doc, /* tp_doc */
1139 (traverseproc)map_traverse, /* tp_traverse */
1140 0, /* tp_clear */
1141 0, /* tp_richcompare */
1142 0, /* tp_weaklistoffset */
1143 PyObject_SelfIter, /* tp_iter */
1144 (iternextfunc)map_next, /* tp_iternext */
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001145 map_methods, /* tp_methods */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001146 0, /* tp_members */
1147 0, /* tp_getset */
1148 0, /* tp_base */
1149 0, /* tp_dict */
1150 0, /* tp_descr_get */
1151 0, /* tp_descr_set */
1152 0, /* tp_dictoffset */
1153 0, /* tp_init */
1154 PyType_GenericAlloc, /* tp_alloc */
1155 map_new, /* tp_new */
1156 PyObject_GC_Del, /* tp_free */
Raymond Hettingera6c60372008-03-13 01:26:19 +00001157};
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001158
Guido van Rossum79f25d91997-04-29 20:08:16 +00001159static PyObject *
Georg Brandla18af4e2007-04-21 15:47:16 +00001160builtin_next(PyObject *self, PyObject *args)
1161{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001162 PyObject *it, *res;
1163 PyObject *def = NULL;
Georg Brandla18af4e2007-04-21 15:47:16 +00001164
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001165 if (!PyArg_UnpackTuple(args, "next", 1, 2, &it, &def))
1166 return NULL;
1167 if (!PyIter_Check(it)) {
1168 PyErr_Format(PyExc_TypeError,
Philip Jenvey50add042011-11-06 16:37:52 -08001169 "'%.200s' object is not an iterator",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001170 it->ob_type->tp_name);
1171 return NULL;
1172 }
1173
1174 res = (*it->ob_type->tp_iternext)(it);
1175 if (res != NULL) {
1176 return res;
1177 } else if (def != NULL) {
1178 if (PyErr_Occurred()) {
1179 if(!PyErr_ExceptionMatches(PyExc_StopIteration))
1180 return NULL;
1181 PyErr_Clear();
1182 }
1183 Py_INCREF(def);
1184 return def;
1185 } else if (PyErr_Occurred()) {
1186 return NULL;
1187 } else {
1188 PyErr_SetNone(PyExc_StopIteration);
1189 return NULL;
1190 }
Georg Brandla18af4e2007-04-21 15:47:16 +00001191}
1192
1193PyDoc_STRVAR(next_doc,
1194"next(iterator[, default])\n\
1195\n\
1196Return the next item from the iterator. If default is given and the iterator\n\
1197is exhausted, it is returned instead of raising StopIteration.");
1198
1199
1200static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001201builtin_setattr(PyObject *self, PyObject *args)
Guido van Rossum33894be1992-01-27 16:53:09 +00001202{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001203 PyObject *v;
1204 PyObject *name;
1205 PyObject *value;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001206
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001207 if (!PyArg_UnpackTuple(args, "setattr", 3, 3, &v, &name, &value))
1208 return NULL;
1209 if (PyObject_SetAttr(v, name, value) != 0)
1210 return NULL;
1211 Py_INCREF(Py_None);
1212 return Py_None;
Guido van Rossum33894be1992-01-27 16:53:09 +00001213}
1214
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001215PyDoc_STRVAR(setattr_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001216"setattr(object, name, value)\n\
1217\n\
1218Set a named attribute on an object; setattr(x, 'y', v) is equivalent to\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001219``x.y = v''.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001220
1221
Guido van Rossum79f25d91997-04-29 20:08:16 +00001222static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001223builtin_delattr(PyObject *self, PyObject *args)
Guido van Rossum14144fc1994-08-29 12:53:40 +00001224{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001225 PyObject *v;
1226 PyObject *name;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001227
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001228 if (!PyArg_UnpackTuple(args, "delattr", 2, 2, &v, &name))
1229 return NULL;
1230 if (PyObject_SetAttr(v, name, (PyObject *)NULL) != 0)
1231 return NULL;
1232 Py_INCREF(Py_None);
1233 return Py_None;
Guido van Rossum14144fc1994-08-29 12:53:40 +00001234}
1235
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001236PyDoc_STRVAR(delattr_doc,
Guido van Rossumdf12a591998-11-23 22:13:04 +00001237"delattr(object, name)\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001238\n\
1239Delete a named attribute on an object; delattr(x, 'y') is equivalent to\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001240``del x.y''.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001241
1242
Guido van Rossum79f25d91997-04-29 20:08:16 +00001243static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001244builtin_hash(PyObject *self, PyObject *v)
Guido van Rossum9bfef441993-03-29 10:43:31 +00001245{
Benjamin Peterson8f67d082010-10-17 20:54:53 +00001246 Py_hash_t x;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001247
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001248 x = PyObject_Hash(v);
1249 if (x == -1)
1250 return NULL;
Benjamin Peterson8f67d082010-10-17 20:54:53 +00001251 return PyLong_FromSsize_t(x);
Guido van Rossum9bfef441993-03-29 10:43:31 +00001252}
1253
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001254PyDoc_STRVAR(hash_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001255"hash(object) -> integer\n\
1256\n\
1257Return a hash value for the object. Two objects with the same value have\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001258the same hash value. The reverse is not necessarily true, but likely.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001259
1260
Guido van Rossum79f25d91997-04-29 20:08:16 +00001261static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001262builtin_hex(PyObject *self, PyObject *v)
Guido van Rossum006bcd41991-10-24 14:54:44 +00001263{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001264 return PyNumber_ToBase(v, 16);
Guido van Rossum006bcd41991-10-24 14:54:44 +00001265}
1266
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001267PyDoc_STRVAR(hex_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001268"hex(number) -> string\n\
1269\n\
Alexander Belopolsky12338ab2011-04-07 00:15:33 -04001270Return the hexadecimal representation of an integer.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001271
1272
Guido van Rossum79f25d91997-04-29 20:08:16 +00001273static PyObject *
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001274builtin_iter(PyObject *self, PyObject *args)
1275{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001276 PyObject *v, *w = NULL;
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001277
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001278 if (!PyArg_UnpackTuple(args, "iter", 1, 2, &v, &w))
1279 return NULL;
1280 if (w == NULL)
1281 return PyObject_GetIter(v);
1282 if (!PyCallable_Check(v)) {
1283 PyErr_SetString(PyExc_TypeError,
1284 "iter(v, w): v must be callable");
1285 return NULL;
1286 }
1287 return PyCallIter_New(v, w);
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001288}
1289
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001290PyDoc_STRVAR(iter_doc,
Georg Brandld11ae5d2008-05-16 13:27:32 +00001291"iter(iterable) -> iterator\n\
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001292iter(callable, sentinel) -> iterator\n\
1293\n\
1294Get an iterator from an object. In the first form, the argument must\n\
1295supply its own iterator, or be a sequence.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001296In the second form, the callable is called until it returns the sentinel.");
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001297
1298
1299static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001300builtin_len(PyObject *self, PyObject *v)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001301{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001302 Py_ssize_t res;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001303
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001304 res = PyObject_Size(v);
1305 if (res < 0 && PyErr_Occurred())
1306 return NULL;
1307 return PyLong_FromSsize_t(res);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001308}
1309
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001310PyDoc_STRVAR(len_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001311"len(object) -> integer\n\
1312\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001313Return the number of items of a sequence or mapping.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001314
1315
Guido van Rossum79f25d91997-04-29 20:08:16 +00001316static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001317builtin_locals(PyObject *self)
Guido van Rossum872537c1995-07-07 22:43:42 +00001318{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001319 PyObject *d;
Guido van Rossum872537c1995-07-07 22:43:42 +00001320
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001321 d = PyEval_GetLocals();
1322 Py_XINCREF(d);
1323 return d;
Guido van Rossum872537c1995-07-07 22:43:42 +00001324}
1325
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001326PyDoc_STRVAR(locals_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001327"locals() -> dictionary\n\
1328\n\
Raymond Hettinger69bf8f32003-01-04 02:16:22 +00001329Update and return a dictionary containing the current scope's local variables.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001330
1331
Guido van Rossum79f25d91997-04-29 20:08:16 +00001332static PyObject *
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001333min_max(PyObject *args, PyObject *kwds, int op)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001334{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001335 PyObject *v, *it, *item, *val, *maxitem, *maxval, *keyfunc=NULL;
Raymond Hettinger4d6018f2013-06-24 22:43:02 -07001336 PyObject *emptytuple, *defaultval = NULL;
1337 static char *kwlist[] = {"key", "default", NULL};
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001338 const char *name = op == Py_LT ? "min" : "max";
Raymond Hettinger4d6018f2013-06-24 22:43:02 -07001339 const int positional = PyTuple_Size(args) > 1;
1340 int ret;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001341
Raymond Hettinger4d6018f2013-06-24 22:43:02 -07001342 if (positional)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001343 v = args;
Serhiy Storchakac6792272013-10-19 21:03:34 +03001344 else if (!PyArg_UnpackTuple(args, name, 1, 1, &v))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001345 return NULL;
Tim Peters67d687a2002-04-29 21:27:32 +00001346
Raymond Hettinger4d6018f2013-06-24 22:43:02 -07001347 emptytuple = PyTuple_New(0);
1348 if (emptytuple == NULL)
1349 return NULL;
1350 ret = PyArg_ParseTupleAndKeywords(emptytuple, kwds, "|$OO", kwlist,
1351 &keyfunc, &defaultval);
1352 Py_DECREF(emptytuple);
1353 if (!ret)
1354 return NULL;
1355
1356 if (positional && defaultval != NULL) {
1357 PyErr_Format(PyExc_TypeError,
1358 "Cannot specify a default for %s() with multiple "
1359 "positional arguments", name);
1360 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001361 }
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001362
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001363 it = PyObject_GetIter(v);
1364 if (it == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001365 return NULL;
1366 }
Tim Petersc3074532001-05-03 07:00:32 +00001367
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001368 maxitem = NULL; /* the result */
1369 maxval = NULL; /* the value associated with the result */
1370 while (( item = PyIter_Next(it) )) {
1371 /* get the value from the key function */
1372 if (keyfunc != NULL) {
1373 val = PyObject_CallFunctionObjArgs(keyfunc, item, NULL);
1374 if (val == NULL)
1375 goto Fail_it_item;
1376 }
1377 /* no key function; the value is the item */
1378 else {
1379 val = item;
1380 Py_INCREF(val);
1381 }
Tim Petersc3074532001-05-03 07:00:32 +00001382
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001383 /* maximum value and item are unset; set them */
1384 if (maxval == NULL) {
1385 maxitem = item;
1386 maxval = val;
1387 }
1388 /* maximum value and item are set; update them as necessary */
1389 else {
1390 int cmp = PyObject_RichCompareBool(val, maxval, op);
1391 if (cmp < 0)
1392 goto Fail_it_item_and_val;
1393 else if (cmp > 0) {
1394 Py_DECREF(maxval);
1395 Py_DECREF(maxitem);
1396 maxval = val;
1397 maxitem = item;
1398 }
1399 else {
1400 Py_DECREF(item);
1401 Py_DECREF(val);
1402 }
1403 }
1404 }
1405 if (PyErr_Occurred())
1406 goto Fail_it;
1407 if (maxval == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001408 assert(maxitem == NULL);
Raymond Hettinger4d6018f2013-06-24 22:43:02 -07001409 if (defaultval != NULL) {
1410 Py_INCREF(defaultval);
1411 maxitem = defaultval;
1412 } else {
1413 PyErr_Format(PyExc_ValueError,
1414 "%s() arg is an empty sequence", name);
1415 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001416 }
1417 else
1418 Py_DECREF(maxval);
1419 Py_DECREF(it);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001420 return maxitem;
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001421
1422Fail_it_item_and_val:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001423 Py_DECREF(val);
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001424Fail_it_item:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001425 Py_DECREF(item);
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001426Fail_it:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001427 Py_XDECREF(maxval);
1428 Py_XDECREF(maxitem);
1429 Py_DECREF(it);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001430 return NULL;
Guido van Rossum3f5da241990-12-20 15:06:42 +00001431}
1432
Guido van Rossum79f25d91997-04-29 20:08:16 +00001433static PyObject *
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001434builtin_min(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001435{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001436 return min_max(args, kwds, Py_LT);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001437}
1438
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001439PyDoc_STRVAR(min_doc,
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001440"min(iterable[, key=func]) -> value\n\
1441min(a, b, c, ...[, key=func]) -> value\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001442\n\
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001443With a single iterable argument, return its smallest item.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001444With two or more arguments, return the smallest argument.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001445
1446
Guido van Rossum79f25d91997-04-29 20:08:16 +00001447static PyObject *
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001448builtin_max(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001449{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001450 return min_max(args, kwds, Py_GT);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001451}
1452
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001453PyDoc_STRVAR(max_doc,
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001454"max(iterable[, key=func]) -> value\n\
1455max(a, b, c, ...[, key=func]) -> value\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001456\n\
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001457With a single iterable argument, return its largest item.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001458With two or more arguments, return the largest argument.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001459
1460
Guido van Rossum79f25d91997-04-29 20:08:16 +00001461static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001462builtin_oct(PyObject *self, PyObject *v)
Guido van Rossum006bcd41991-10-24 14:54:44 +00001463{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001464 return PyNumber_ToBase(v, 8);
Guido van Rossum006bcd41991-10-24 14:54:44 +00001465}
1466
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001467PyDoc_STRVAR(oct_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001468"oct(number) -> string\n\
1469\n\
Alexander Belopolsky12338ab2011-04-07 00:15:33 -04001470Return the octal representation of an integer.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001471
1472
Guido van Rossum79f25d91997-04-29 20:08:16 +00001473static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001474builtin_ord(PyObject *self, PyObject* obj)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001475{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001476 long ord;
1477 Py_ssize_t size;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001478
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001479 if (PyBytes_Check(obj)) {
1480 size = PyBytes_GET_SIZE(obj);
1481 if (size == 1) {
1482 ord = (long)((unsigned char)*PyBytes_AS_STRING(obj));
1483 return PyLong_FromLong(ord);
1484 }
1485 }
1486 else if (PyUnicode_Check(obj)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001487 if (PyUnicode_READY(obj) == -1)
1488 return NULL;
1489 size = PyUnicode_GET_LENGTH(obj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001490 if (size == 1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001491 ord = (long)PyUnicode_READ_CHAR(obj, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001492 return PyLong_FromLong(ord);
1493 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001494 }
1495 else if (PyByteArray_Check(obj)) {
1496 /* XXX Hopefully this is temporary */
1497 size = PyByteArray_GET_SIZE(obj);
1498 if (size == 1) {
1499 ord = (long)((unsigned char)*PyByteArray_AS_STRING(obj));
1500 return PyLong_FromLong(ord);
1501 }
1502 }
1503 else {
1504 PyErr_Format(PyExc_TypeError,
1505 "ord() expected string of length 1, but " \
1506 "%.200s found", obj->ob_type->tp_name);
1507 return NULL;
1508 }
Guido van Rossum09095f32000-03-10 23:00:52 +00001509
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001510 PyErr_Format(PyExc_TypeError,
1511 "ord() expected a character, "
1512 "but string of length %zd found",
1513 size);
1514 return NULL;
Guido van Rossum3f5da241990-12-20 15:06:42 +00001515}
1516
Guido van Rossum307fa8c2007-07-16 20:46:27 +00001517PyDoc_VAR(ord_doc) = PyDoc_STR(
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001518"ord(c) -> integer\n\
1519\n\
Guido van Rossum8ac004e2007-07-15 13:00:05 +00001520Return the integer ordinal of a one-character string."
Antoine Pitrouedc60182012-06-23 14:19:58 +02001521);
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001522
1523
Guido van Rossum79f25d91997-04-29 20:08:16 +00001524static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001525builtin_pow(PyObject *self, PyObject *args)
Guido van Rossum6a00cd81995-01-07 12:39:01 +00001526{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001527 PyObject *v, *w, *z = Py_None;
Guido van Rossum6a00cd81995-01-07 12:39:01 +00001528
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001529 if (!PyArg_UnpackTuple(args, "pow", 2, 3, &v, &w, &z))
1530 return NULL;
1531 return PyNumber_Power(v, w, z);
Guido van Rossumd4905451991-05-05 20:00:36 +00001532}
1533
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001534PyDoc_STRVAR(pow_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001535"pow(x, y[, z]) -> number\n\
1536\n\
1537With two arguments, equivalent to x**y. With three arguments,\n\
Serhiy Storchaka95949422013-08-27 19:40:23 +03001538equivalent to (x**y) % z, but may be more efficient (e.g. for ints).");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001539
1540
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001541
Guido van Rossum34343512006-11-30 22:13:52 +00001542static PyObject *
1543builtin_print(PyObject *self, PyObject *args, PyObject *kwds)
1544{
Georg Brandlbc3b6822012-01-13 19:41:25 +01001545 static char *kwlist[] = {"sep", "end", "file", "flush", 0};
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001546 static PyObject *dummy_args;
Georg Brandlbc3b6822012-01-13 19:41:25 +01001547 PyObject *sep = NULL, *end = NULL, *file = NULL, *flush = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001548 int i, err;
Guido van Rossum34343512006-11-30 22:13:52 +00001549
Benjamin Peterson00102562012-01-11 21:00:16 -05001550 if (dummy_args == NULL && !(dummy_args = PyTuple_New(0)))
Georg Brandlbc3b6822012-01-13 19:41:25 +01001551 return NULL;
1552 if (!PyArg_ParseTupleAndKeywords(dummy_args, kwds, "|OOOO:print",
1553 kwlist, &sep, &end, &file, &flush))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001554 return NULL;
1555 if (file == NULL || file == Py_None) {
1556 file = PySys_GetObject("stdout");
Victor Stinner1e53bba2013-07-16 22:26:05 +02001557 if (file == NULL) {
1558 PyErr_SetString(PyExc_RuntimeError, "lost sys.stdout");
1559 return NULL;
1560 }
1561
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001562 /* sys.stdout may be None when FILE* stdout isn't connected */
1563 if (file == Py_None)
1564 Py_RETURN_NONE;
1565 }
Guido van Rossum34343512006-11-30 22:13:52 +00001566
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001567 if (sep == Py_None) {
1568 sep = NULL;
1569 }
1570 else if (sep && !PyUnicode_Check(sep)) {
1571 PyErr_Format(PyExc_TypeError,
1572 "sep must be None or a string, not %.200s",
1573 sep->ob_type->tp_name);
1574 return NULL;
1575 }
1576 if (end == Py_None) {
1577 end = NULL;
1578 }
1579 else if (end && !PyUnicode_Check(end)) {
1580 PyErr_Format(PyExc_TypeError,
1581 "end must be None or a string, not %.200s",
1582 end->ob_type->tp_name);
1583 return NULL;
1584 }
Guido van Rossum34343512006-11-30 22:13:52 +00001585
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001586 for (i = 0; i < PyTuple_Size(args); i++) {
1587 if (i > 0) {
1588 if (sep == NULL)
1589 err = PyFile_WriteString(" ", file);
1590 else
1591 err = PyFile_WriteObject(sep, file,
1592 Py_PRINT_RAW);
1593 if (err)
1594 return NULL;
1595 }
1596 err = PyFile_WriteObject(PyTuple_GetItem(args, i), file,
1597 Py_PRINT_RAW);
1598 if (err)
1599 return NULL;
1600 }
Guido van Rossum34343512006-11-30 22:13:52 +00001601
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001602 if (end == NULL)
1603 err = PyFile_WriteString("\n", file);
1604 else
1605 err = PyFile_WriteObject(end, file, Py_PRINT_RAW);
1606 if (err)
1607 return NULL;
Guido van Rossum34343512006-11-30 22:13:52 +00001608
Georg Brandlbc3b6822012-01-13 19:41:25 +01001609 if (flush != NULL) {
1610 PyObject *tmp;
1611 int do_flush = PyObject_IsTrue(flush);
1612 if (do_flush == -1)
1613 return NULL;
1614 else if (do_flush) {
1615 tmp = PyObject_CallMethod(file, "flush", "");
1616 if (tmp == NULL)
1617 return NULL;
1618 else
1619 Py_DECREF(tmp);
1620 }
1621 }
1622
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001623 Py_RETURN_NONE;
Guido van Rossum34343512006-11-30 22:13:52 +00001624}
1625
1626PyDoc_STRVAR(print_doc,
Senthil Kumarane9175bd2012-08-10 13:53:45 -07001627"print(value, ..., sep=' ', end='\\n', file=sys.stdout, flush=False)\n\
Guido van Rossum34343512006-11-30 22:13:52 +00001628\n\
1629Prints the values to a stream, or to sys.stdout by default.\n\
1630Optional keyword arguments:\n\
Senthil Kumarane9175bd2012-08-10 13:53:45 -07001631file: a file-like object (stream); defaults to the current sys.stdout.\n\
1632sep: string inserted between values, default a space.\n\
1633end: string appended after the last value, default a newline.\n\
1634flush: whether to forcibly flush the stream.");
Guido van Rossum34343512006-11-30 22:13:52 +00001635
1636
Guido van Rossuma88a0332007-02-26 16:59:55 +00001637static PyObject *
1638builtin_input(PyObject *self, PyObject *args)
1639{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001640 PyObject *promptarg = NULL;
1641 PyObject *fin = PySys_GetObject("stdin");
1642 PyObject *fout = PySys_GetObject("stdout");
1643 PyObject *ferr = PySys_GetObject("stderr");
1644 PyObject *tmp;
1645 long fd;
1646 int tty;
Guido van Rossuma88a0332007-02-26 16:59:55 +00001647
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001648 /* Parse arguments */
1649 if (!PyArg_UnpackTuple(args, "input", 0, 1, &promptarg))
1650 return NULL;
Guido van Rossuma88a0332007-02-26 16:59:55 +00001651
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001652 /* Check that stdin/out/err are intact */
1653 if (fin == NULL || fin == Py_None) {
1654 PyErr_SetString(PyExc_RuntimeError,
1655 "input(): lost sys.stdin");
1656 return NULL;
1657 }
1658 if (fout == NULL || fout == Py_None) {
1659 PyErr_SetString(PyExc_RuntimeError,
1660 "input(): lost sys.stdout");
1661 return NULL;
1662 }
1663 if (ferr == NULL || ferr == Py_None) {
1664 PyErr_SetString(PyExc_RuntimeError,
1665 "input(): lost sys.stderr");
1666 return NULL;
1667 }
Guido van Rossumeba76962007-05-27 09:13:28 +00001668
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001669 /* First of all, flush stderr */
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001670 tmp = _PyObject_CallMethodId(ferr, &PyId_flush, "");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001671 if (tmp == NULL)
1672 PyErr_Clear();
1673 else
1674 Py_DECREF(tmp);
Guido van Rossumeba76962007-05-27 09:13:28 +00001675
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001676 /* We should only use (GNU) readline if Python's sys.stdin and
1677 sys.stdout are the same as C's stdin and stdout, because we
1678 need to pass it those. */
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001679 tmp = _PyObject_CallMethodId(fin, &PyId_fileno, "");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001680 if (tmp == NULL) {
1681 PyErr_Clear();
1682 tty = 0;
1683 }
1684 else {
1685 fd = PyLong_AsLong(tmp);
1686 Py_DECREF(tmp);
1687 if (fd < 0 && PyErr_Occurred())
1688 return NULL;
1689 tty = fd == fileno(stdin) && isatty(fd);
1690 }
1691 if (tty) {
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001692 tmp = _PyObject_CallMethodId(fout, &PyId_fileno, "");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001693 if (tmp == NULL)
1694 PyErr_Clear();
1695 else {
1696 fd = PyLong_AsLong(tmp);
1697 Py_DECREF(tmp);
1698 if (fd < 0 && PyErr_Occurred())
1699 return NULL;
1700 tty = fd == fileno(stdout) && isatty(fd);
1701 }
1702 }
Guido van Rossumeba76962007-05-27 09:13:28 +00001703
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001704 /* If we're interactive, use (GNU) readline */
1705 if (tty) {
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001706 PyObject *po = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001707 char *prompt;
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001708 char *s = NULL;
1709 PyObject *stdin_encoding = NULL, *stdin_errors = NULL;
1710 PyObject *stdout_encoding = NULL, *stdout_errors = NULL;
1711 char *stdin_encoding_str, *stdin_errors_str;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001712 PyObject *result;
Victor Stinnerc0f1a1a2011-02-23 12:07:37 +00001713 size_t len;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02001714 _Py_IDENTIFIER(encoding);
Antoine Pitrou5ee9d8a2011-11-06 00:38:45 +01001715 _Py_IDENTIFIER(errors);
Martin v. Löwis4a7b5d52007-09-04 05:24:49 +00001716
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02001717 stdin_encoding = _PyObject_GetAttrId(fin, &PyId_encoding);
Antoine Pitrou5ee9d8a2011-11-06 00:38:45 +01001718 stdin_errors = _PyObject_GetAttrId(fin, &PyId_errors);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001719 if (!stdin_encoding || !stdin_errors)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001720 /* stdin is a text stream, so it must have an
1721 encoding. */
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001722 goto _readline_errors;
Victor Stinner306f0102010-05-19 01:06:22 +00001723 stdin_encoding_str = _PyUnicode_AsString(stdin_encoding);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001724 stdin_errors_str = _PyUnicode_AsString(stdin_errors);
1725 if (!stdin_encoding_str || !stdin_errors_str)
1726 goto _readline_errors;
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001727 tmp = _PyObject_CallMethodId(fout, &PyId_flush, "");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001728 if (tmp == NULL)
1729 PyErr_Clear();
1730 else
1731 Py_DECREF(tmp);
1732 if (promptarg != NULL) {
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001733 /* We have a prompt, encode it as stdout would */
1734 char *stdout_encoding_str, *stdout_errors_str;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001735 PyObject *stringpo;
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02001736 stdout_encoding = _PyObject_GetAttrId(fout, &PyId_encoding);
Antoine Pitrou5ee9d8a2011-11-06 00:38:45 +01001737 stdout_errors = _PyObject_GetAttrId(fout, &PyId_errors);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001738 if (!stdout_encoding || !stdout_errors)
1739 goto _readline_errors;
Victor Stinner306f0102010-05-19 01:06:22 +00001740 stdout_encoding_str = _PyUnicode_AsString(stdout_encoding);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001741 stdout_errors_str = _PyUnicode_AsString(stdout_errors);
1742 if (!stdout_encoding_str || !stdout_errors_str)
1743 goto _readline_errors;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001744 stringpo = PyObject_Str(promptarg);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001745 if (stringpo == NULL)
1746 goto _readline_errors;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001747 po = PyUnicode_AsEncodedString(stringpo,
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001748 stdout_encoding_str, stdout_errors_str);
1749 Py_CLEAR(stdout_encoding);
1750 Py_CLEAR(stdout_errors);
1751 Py_CLEAR(stringpo);
1752 if (po == NULL)
1753 goto _readline_errors;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001754 prompt = PyBytes_AsString(po);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001755 if (prompt == NULL)
1756 goto _readline_errors;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001757 }
1758 else {
1759 po = NULL;
1760 prompt = "";
1761 }
1762 s = PyOS_Readline(stdin, stdout, prompt);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001763 if (s == NULL) {
Richard Oudkerk614c5782013-04-03 13:44:50 +01001764 PyErr_CheckSignals();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001765 if (!PyErr_Occurred())
1766 PyErr_SetNone(PyExc_KeyboardInterrupt);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001767 goto _readline_errors;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001768 }
Victor Stinnerc0f1a1a2011-02-23 12:07:37 +00001769
1770 len = strlen(s);
1771 if (len == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001772 PyErr_SetNone(PyExc_EOFError);
1773 result = NULL;
1774 }
Victor Stinnerc0f1a1a2011-02-23 12:07:37 +00001775 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001776 if (len > PY_SSIZE_T_MAX) {
1777 PyErr_SetString(PyExc_OverflowError,
1778 "input: input too long");
1779 result = NULL;
1780 }
1781 else {
Victor Stinnerc0f1a1a2011-02-23 12:07:37 +00001782 len--; /* strip trailing '\n' */
1783 if (len != 0 && s[len-1] == '\r')
1784 len--; /* strip trailing '\r' */
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001785 result = PyUnicode_Decode(s, len, stdin_encoding_str,
1786 stdin_errors_str);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001787 }
1788 }
1789 Py_DECREF(stdin_encoding);
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001790 Py_DECREF(stdin_errors);
1791 Py_XDECREF(po);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001792 PyMem_FREE(s);
1793 return result;
Antoine Pitrou0d776b12011-11-06 00:34:26 +01001794 _readline_errors:
1795 Py_XDECREF(stdin_encoding);
1796 Py_XDECREF(stdout_encoding);
1797 Py_XDECREF(stdin_errors);
1798 Py_XDECREF(stdout_errors);
1799 Py_XDECREF(po);
1800 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001801 }
Guido van Rossumeba76962007-05-27 09:13:28 +00001802
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001803 /* Fallback if we're not interactive */
1804 if (promptarg != NULL) {
1805 if (PyFile_WriteObject(promptarg, fout, Py_PRINT_RAW) != 0)
1806 return NULL;
1807 }
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001808 tmp = _PyObject_CallMethodId(fout, &PyId_flush, "");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001809 if (tmp == NULL)
1810 PyErr_Clear();
1811 else
1812 Py_DECREF(tmp);
1813 return PyFile_GetLine(fin, -1);
Guido van Rossuma88a0332007-02-26 16:59:55 +00001814}
1815
1816PyDoc_STRVAR(input_doc,
1817"input([prompt]) -> string\n\
1818\n\
1819Read a string from standard input. The trailing newline is stripped.\n\
1820If the user hits EOF (Unix: Ctl-D, Windows: Ctl-Z+Return), raise EOFError.\n\
1821On Unix, GNU readline is used if enabled. The prompt string, if given,\n\
1822is printed without a trailing newline before reading.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001823
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001824
Guido van Rossum79f25d91997-04-29 20:08:16 +00001825static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001826builtin_repr(PyObject *self, PyObject *v)
Guido van Rossumc89705d1992-11-26 08:54:07 +00001827{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001828 return PyObject_Repr(v);
Guido van Rossumc89705d1992-11-26 08:54:07 +00001829}
1830
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001831PyDoc_STRVAR(repr_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001832"repr(object) -> string\n\
1833\n\
1834Return the canonical string representation of the object.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001835For most object types, eval(repr(object)) == object.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001836
1837
Guido van Rossum79f25d91997-04-29 20:08:16 +00001838static PyObject *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001839builtin_round(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum9e51f9b1993-02-12 16:29:05 +00001840{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001841 PyObject *ndigits = NULL;
1842 static char *kwlist[] = {"number", "ndigits", 0};
Benjamin Peterson214a7d22013-04-13 17:19:01 -04001843 PyObject *number, *round, *result;
1844 _Py_IDENTIFIER(__round__);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001845
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001846 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|O:round",
1847 kwlist, &number, &ndigits))
1848 return NULL;
Alex Martelliae211f92007-08-22 23:21:33 +00001849
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001850 if (Py_TYPE(number)->tp_dict == NULL) {
1851 if (PyType_Ready(Py_TYPE(number)) < 0)
1852 return NULL;
1853 }
Guido van Rossum15d3d042007-08-24 02:02:45 +00001854
Benjamin Peterson214a7d22013-04-13 17:19:01 -04001855 round = _PyObject_LookupSpecial(number, &PyId___round__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001856 if (round == NULL) {
Benjamin Peterson214a7d22013-04-13 17:19:01 -04001857 if (!PyErr_Occurred())
1858 PyErr_Format(PyExc_TypeError,
1859 "type %.100s doesn't define __round__ method",
1860 Py_TYPE(number)->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001861 return NULL;
1862 }
Alex Martelliae211f92007-08-22 23:21:33 +00001863
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001864 if (ndigits == NULL)
Benjamin Peterson214a7d22013-04-13 17:19:01 -04001865 result = PyObject_CallFunctionObjArgs(round, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001866 else
Benjamin Peterson214a7d22013-04-13 17:19:01 -04001867 result = PyObject_CallFunctionObjArgs(round, ndigits, NULL);
1868 Py_DECREF(round);
1869 return result;
Guido van Rossum9e51f9b1993-02-12 16:29:05 +00001870}
1871
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001872PyDoc_STRVAR(round_doc,
Mark Dickinson1124e712009-01-28 21:25:58 +00001873"round(number[, ndigits]) -> number\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001874\n\
1875Round a number to a given precision in decimal digits (default 0 digits).\n\
Mark Dickinson0d748c22008-07-05 11:29:03 +00001876This returns an int when called with one argument, otherwise the\n\
Georg Brandl809ddaa2008-07-01 20:39:59 +00001877same type as the number. ndigits may be negative.");
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001878
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001879
Raymond Hettinger64958a12003-12-17 20:43:33 +00001880static PyObject *
1881builtin_sorted(PyObject *self, PyObject *args, PyObject *kwds)
1882{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001883 PyObject *newlist, *v, *seq, *keyfunc=NULL, *newargs;
1884 PyObject *callable;
1885 static char *kwlist[] = {"iterable", "key", "reverse", 0};
1886 int reverse;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02001887 _Py_IDENTIFIER(sort);
Raymond Hettinger64958a12003-12-17 20:43:33 +00001888
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001889 /* args 1-3 should match listsort in Objects/listobject.c */
1890 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|Oi:sorted",
1891 kwlist, &seq, &keyfunc, &reverse))
1892 return NULL;
Raymond Hettinger64958a12003-12-17 20:43:33 +00001893
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001894 newlist = PySequence_List(seq);
1895 if (newlist == NULL)
1896 return NULL;
Raymond Hettinger64958a12003-12-17 20:43:33 +00001897
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02001898 callable = _PyObject_GetAttrId(newlist, &PyId_sort);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001899 if (callable == NULL) {
1900 Py_DECREF(newlist);
1901 return NULL;
1902 }
Georg Brandl99d7e4e2005-08-31 22:21:15 +00001903
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001904 newargs = PyTuple_GetSlice(args, 1, 4);
1905 if (newargs == NULL) {
1906 Py_DECREF(newlist);
1907 Py_DECREF(callable);
1908 return NULL;
1909 }
Raymond Hettinger64958a12003-12-17 20:43:33 +00001910
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001911 v = PyObject_Call(callable, newargs, kwds);
1912 Py_DECREF(newargs);
1913 Py_DECREF(callable);
1914 if (v == NULL) {
1915 Py_DECREF(newlist);
1916 return NULL;
1917 }
1918 Py_DECREF(v);
1919 return newlist;
Raymond Hettinger64958a12003-12-17 20:43:33 +00001920}
1921
1922PyDoc_STRVAR(sorted_doc,
Raymond Hettinger70b64fc2008-01-30 20:15:17 +00001923"sorted(iterable, key=None, reverse=False) --> new sorted list");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001924
Guido van Rossum79f25d91997-04-29 20:08:16 +00001925static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001926builtin_vars(PyObject *self, PyObject *args)
Guido van Rossum2d951851994-08-29 12:52:16 +00001927{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001928 PyObject *v = NULL;
1929 PyObject *d;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001930
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001931 if (!PyArg_UnpackTuple(args, "vars", 0, 1, &v))
1932 return NULL;
1933 if (v == NULL) {
1934 d = PyEval_GetLocals();
Victor Stinner41bb43a2013-10-29 01:19:37 +01001935 if (d == NULL)
1936 return NULL;
1937 Py_INCREF(d);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001938 }
1939 else {
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02001940 _Py_IDENTIFIER(__dict__);
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02001941 d = _PyObject_GetAttrId(v, &PyId___dict__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001942 if (d == NULL) {
1943 PyErr_SetString(PyExc_TypeError,
1944 "vars() argument must have __dict__ attribute");
1945 return NULL;
1946 }
1947 }
1948 return d;
Guido van Rossum2d951851994-08-29 12:52:16 +00001949}
1950
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001951PyDoc_STRVAR(vars_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001952"vars([object]) -> dictionary\n\
1953\n\
1954Without arguments, equivalent to locals().\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001955With an argument, equivalent to object.__dict__.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001956
Alex Martellia70b1912003-04-22 08:12:33 +00001957static PyObject*
1958builtin_sum(PyObject *self, PyObject *args)
1959{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001960 PyObject *seq;
1961 PyObject *result = NULL;
1962 PyObject *temp, *item, *iter;
Alex Martellia70b1912003-04-22 08:12:33 +00001963
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001964 if (!PyArg_UnpackTuple(args, "sum", 1, 2, &seq, &result))
1965 return NULL;
Alex Martellia70b1912003-04-22 08:12:33 +00001966
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001967 iter = PyObject_GetIter(seq);
1968 if (iter == NULL)
1969 return NULL;
Alex Martellia70b1912003-04-22 08:12:33 +00001970
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001971 if (result == NULL) {
1972 result = PyLong_FromLong(0);
1973 if (result == NULL) {
1974 Py_DECREF(iter);
1975 return NULL;
1976 }
1977 } else {
1978 /* reject string values for 'start' parameter */
1979 if (PyUnicode_Check(result)) {
1980 PyErr_SetString(PyExc_TypeError,
1981 "sum() can't sum strings [use ''.join(seq) instead]");
1982 Py_DECREF(iter);
1983 return NULL;
1984 }
Benjamin Petersonce071ca2011-07-29 14:23:47 -05001985 if (PyBytes_Check(result)) {
1986 PyErr_SetString(PyExc_TypeError,
1987 "sum() can't sum bytes [use b''.join(seq) instead]");
Benjamin Peterson405f32c2011-07-29 22:43:45 -05001988 Py_DECREF(iter);
Benjamin Petersonce071ca2011-07-29 14:23:47 -05001989 return NULL;
1990 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001991 if (PyByteArray_Check(result)) {
1992 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson4f921c22011-07-29 14:24:29 -05001993 "sum() can't sum bytearray [use b''.join(seq) instead]");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001994 Py_DECREF(iter);
1995 return NULL;
1996 }
Guido van Rossum3172c5d2007-10-16 18:12:55 +00001997
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001998 Py_INCREF(result);
1999 }
Alex Martellia70b1912003-04-22 08:12:33 +00002000
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002001#ifndef SLOW_SUM
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002002 /* Fast addition by keeping temporary sums in C instead of new Python objects.
2003 Assumes all inputs are the same type. If the assumption fails, default
2004 to the more general routine.
2005 */
2006 if (PyLong_CheckExact(result)) {
2007 int overflow;
2008 long i_result = PyLong_AsLongAndOverflow(result, &overflow);
2009 /* If this already overflowed, don't even enter the loop. */
2010 if (overflow == 0) {
2011 Py_DECREF(result);
2012 result = NULL;
2013 }
2014 while(result == NULL) {
2015 item = PyIter_Next(iter);
2016 if (item == NULL) {
2017 Py_DECREF(iter);
2018 if (PyErr_Occurred())
2019 return NULL;
2020 return PyLong_FromLong(i_result);
2021 }
2022 if (PyLong_CheckExact(item)) {
2023 long b = PyLong_AsLongAndOverflow(item, &overflow);
2024 long x = i_result + b;
2025 if (overflow == 0 && ((x^i_result) >= 0 || (x^b) >= 0)) {
2026 i_result = x;
2027 Py_DECREF(item);
2028 continue;
2029 }
2030 }
2031 /* Either overflowed or is not an int. Restore real objects and process normally */
2032 result = PyLong_FromLong(i_result);
Christian Heimes704e2d32013-07-26 22:49:26 +02002033 if (result == NULL) {
2034 Py_DECREF(item);
2035 Py_DECREF(iter);
2036 return NULL;
2037 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002038 temp = PyNumber_Add(result, item);
2039 Py_DECREF(result);
2040 Py_DECREF(item);
2041 result = temp;
2042 if (result == NULL) {
2043 Py_DECREF(iter);
2044 return NULL;
2045 }
2046 }
2047 }
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002048
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002049 if (PyFloat_CheckExact(result)) {
2050 double f_result = PyFloat_AS_DOUBLE(result);
2051 Py_DECREF(result);
2052 result = NULL;
2053 while(result == NULL) {
2054 item = PyIter_Next(iter);
2055 if (item == NULL) {
2056 Py_DECREF(iter);
2057 if (PyErr_Occurred())
2058 return NULL;
2059 return PyFloat_FromDouble(f_result);
2060 }
2061 if (PyFloat_CheckExact(item)) {
2062 PyFPE_START_PROTECT("add", Py_DECREF(item); Py_DECREF(iter); return 0)
2063 f_result += PyFloat_AS_DOUBLE(item);
2064 PyFPE_END_PROTECT(f_result)
2065 Py_DECREF(item);
2066 continue;
2067 }
2068 if (PyLong_CheckExact(item)) {
2069 long value;
2070 int overflow;
2071 value = PyLong_AsLongAndOverflow(item, &overflow);
2072 if (!overflow) {
2073 PyFPE_START_PROTECT("add", Py_DECREF(item); Py_DECREF(iter); return 0)
2074 f_result += (double)value;
2075 PyFPE_END_PROTECT(f_result)
2076 Py_DECREF(item);
2077 continue;
2078 }
2079 }
2080 result = PyFloat_FromDouble(f_result);
2081 temp = PyNumber_Add(result, item);
2082 Py_DECREF(result);
2083 Py_DECREF(item);
2084 result = temp;
2085 if (result == NULL) {
2086 Py_DECREF(iter);
2087 return NULL;
2088 }
2089 }
2090 }
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002091#endif
2092
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002093 for(;;) {
2094 item = PyIter_Next(iter);
2095 if (item == NULL) {
2096 /* error, or end-of-sequence */
2097 if (PyErr_Occurred()) {
2098 Py_DECREF(result);
2099 result = NULL;
2100 }
2101 break;
2102 }
2103 /* It's tempting to use PyNumber_InPlaceAdd instead of
2104 PyNumber_Add here, to avoid quadratic running time
2105 when doing 'sum(list_of_lists, [])'. However, this
2106 would produce a change in behaviour: a snippet like
Mark Dickinson9acadc52009-10-26 14:19:42 +00002107
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002108 empty = []
2109 sum([[x] for x in range(10)], empty)
Mark Dickinson9acadc52009-10-26 14:19:42 +00002110
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002111 would change the value of empty. */
2112 temp = PyNumber_Add(result, item);
2113 Py_DECREF(result);
2114 Py_DECREF(item);
2115 result = temp;
2116 if (result == NULL)
2117 break;
2118 }
2119 Py_DECREF(iter);
2120 return result;
Alex Martellia70b1912003-04-22 08:12:33 +00002121}
2122
2123PyDoc_STRVAR(sum_doc,
Georg Brandld11ae5d2008-05-16 13:27:32 +00002124"sum(iterable[, start]) -> value\n\
Alex Martellia70b1912003-04-22 08:12:33 +00002125\n\
R David Murray87ead112013-07-10 16:22:14 -04002126Return the sum of an iterable of numbers (NOT strings) plus the value\n\
Georg Brandld11ae5d2008-05-16 13:27:32 +00002127of parameter 'start' (which defaults to 0). When the iterable is\n\
R David Murray87ead112013-07-10 16:22:14 -04002128empty, return start.");
Alex Martellia70b1912003-04-22 08:12:33 +00002129
2130
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002131static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002132builtin_isinstance(PyObject *self, PyObject *args)
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002133{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002134 PyObject *inst;
2135 PyObject *cls;
2136 int retval;
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002137
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002138 if (!PyArg_UnpackTuple(args, "isinstance", 2, 2, &inst, &cls))
2139 return NULL;
Guido van Rossumf5dd9141997-12-02 19:11:45 +00002140
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002141 retval = PyObject_IsInstance(inst, cls);
2142 if (retval < 0)
2143 return NULL;
2144 return PyBool_FromLong(retval);
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002145}
2146
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002147PyDoc_STRVAR(isinstance_doc,
Guido van Rossum77f6a652002-04-03 22:41:51 +00002148"isinstance(object, class-or-type-or-tuple) -> bool\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002149\n\
2150Return whether an object is an instance of a class or of a subclass thereof.\n\
Guido van Rossum03290ec2001-10-07 20:54:12 +00002151With a type as second argument, return whether that is the object's type.\n\
2152The form using a tuple, isinstance(x, (A, B, ...)), is a shortcut for\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002153isinstance(x, A) or isinstance(x, B) or ... (etc.).");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002154
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002155
2156static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002157builtin_issubclass(PyObject *self, PyObject *args)
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002158{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002159 PyObject *derived;
2160 PyObject *cls;
2161 int retval;
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002162
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002163 if (!PyArg_UnpackTuple(args, "issubclass", 2, 2, &derived, &cls))
2164 return NULL;
Guido van Rossum668213d1999-06-16 17:28:37 +00002165
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002166 retval = PyObject_IsSubclass(derived, cls);
2167 if (retval < 0)
2168 return NULL;
2169 return PyBool_FromLong(retval);
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002170}
2171
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002172PyDoc_STRVAR(issubclass_doc,
Guido van Rossum77f6a652002-04-03 22:41:51 +00002173"issubclass(C, B) -> bool\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002174\n\
Walter Dörwaldd9a6ad32002-12-12 16:41:44 +00002175Return whether class C is a subclass (i.e., a derived class) of class B.\n\
2176When using a tuple as the second argument issubclass(X, (A, B, ...)),\n\
2177is a shortcut for issubclass(X, A) or issubclass(X, B) or ... (etc.).");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002178
Barry Warsawcde8b1b1997-08-22 21:14:38 +00002179
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002180typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002181 PyObject_HEAD
2182 Py_ssize_t tuplesize;
2183 PyObject *ittuple; /* tuple of iterators */
2184 PyObject *result;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002185} zipobject;
2186
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002187static PyObject *
2188zip_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
Barry Warsawbd599b52000-08-03 15:45:29 +00002189{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002190 zipobject *lz;
2191 Py_ssize_t i;
2192 PyObject *ittuple; /* tuple of iterators */
2193 PyObject *result;
2194 Py_ssize_t tuplesize = PySequence_Length(args);
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002195
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002196 if (type == &PyZip_Type && !_PyArg_NoKeywords("zip()", kwds))
2197 return NULL;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002198
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002199 /* args must be a tuple */
2200 assert(PyTuple_Check(args));
Barry Warsawbd599b52000-08-03 15:45:29 +00002201
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002202 /* obtain iterators */
2203 ittuple = PyTuple_New(tuplesize);
2204 if (ittuple == NULL)
2205 return NULL;
2206 for (i=0; i < tuplesize; ++i) {
2207 PyObject *item = PyTuple_GET_ITEM(args, i);
2208 PyObject *it = PyObject_GetIter(item);
2209 if (it == NULL) {
2210 if (PyErr_ExceptionMatches(PyExc_TypeError))
2211 PyErr_Format(PyExc_TypeError,
2212 "zip argument #%zd must support iteration",
2213 i+1);
2214 Py_DECREF(ittuple);
2215 return NULL;
2216 }
2217 PyTuple_SET_ITEM(ittuple, i, it);
2218 }
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002219
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002220 /* create a result holder */
2221 result = PyTuple_New(tuplesize);
2222 if (result == NULL) {
2223 Py_DECREF(ittuple);
2224 return NULL;
2225 }
2226 for (i=0 ; i < tuplesize ; i++) {
2227 Py_INCREF(Py_None);
2228 PyTuple_SET_ITEM(result, i, Py_None);
2229 }
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002230
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002231 /* create zipobject structure */
2232 lz = (zipobject *)type->tp_alloc(type, 0);
2233 if (lz == NULL) {
2234 Py_DECREF(ittuple);
2235 Py_DECREF(result);
2236 return NULL;
2237 }
2238 lz->ittuple = ittuple;
2239 lz->tuplesize = tuplesize;
2240 lz->result = result;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002241
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002242 return (PyObject *)lz;
Barry Warsawbd599b52000-08-03 15:45:29 +00002243}
2244
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002245static void
2246zip_dealloc(zipobject *lz)
2247{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002248 PyObject_GC_UnTrack(lz);
2249 Py_XDECREF(lz->ittuple);
2250 Py_XDECREF(lz->result);
2251 Py_TYPE(lz)->tp_free(lz);
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002252}
2253
2254static int
2255zip_traverse(zipobject *lz, visitproc visit, void *arg)
2256{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002257 Py_VISIT(lz->ittuple);
2258 Py_VISIT(lz->result);
2259 return 0;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002260}
2261
2262static PyObject *
2263zip_next(zipobject *lz)
2264{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002265 Py_ssize_t i;
2266 Py_ssize_t tuplesize = lz->tuplesize;
2267 PyObject *result = lz->result;
2268 PyObject *it;
2269 PyObject *item;
2270 PyObject *olditem;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002271
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002272 if (tuplesize == 0)
2273 return NULL;
2274 if (Py_REFCNT(result) == 1) {
2275 Py_INCREF(result);
2276 for (i=0 ; i < tuplesize ; i++) {
2277 it = PyTuple_GET_ITEM(lz->ittuple, i);
2278 item = (*Py_TYPE(it)->tp_iternext)(it);
Serhiy Storchaka278d03b2013-04-06 22:52:34 +03002279 if (item == NULL) {
2280 Py_DECREF(result);
2281 return NULL;
2282 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002283 olditem = PyTuple_GET_ITEM(result, i);
2284 PyTuple_SET_ITEM(result, i, item);
2285 Py_DECREF(olditem);
2286 }
2287 } else {
2288 result = PyTuple_New(tuplesize);
2289 if (result == NULL)
Serhiy Storchaka278d03b2013-04-06 22:52:34 +03002290 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002291 for (i=0 ; i < tuplesize ; i++) {
2292 it = PyTuple_GET_ITEM(lz->ittuple, i);
2293 item = (*Py_TYPE(it)->tp_iternext)(it);
Serhiy Storchaka278d03b2013-04-06 22:52:34 +03002294 if (item == NULL) {
2295 Py_DECREF(result);
2296 return NULL;
2297 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002298 PyTuple_SET_ITEM(result, i, item);
2299 }
2300 }
2301 return result;
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002302}
Barry Warsawbd599b52000-08-03 15:45:29 +00002303
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002304static PyObject *
2305zip_reduce(zipobject *lz)
2306{
2307 /* Just recreate the zip with the internal iterator tuple */
2308 return Py_BuildValue("OO", Py_TYPE(lz), lz->ittuple);
2309}
2310
2311static PyMethodDef zip_methods[] = {
2312 {"__reduce__", (PyCFunction)zip_reduce, METH_NOARGS, reduce_doc},
2313 {NULL, NULL} /* sentinel */
2314};
2315
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002316PyDoc_STRVAR(zip_doc,
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002317"zip(iter1 [,iter2 [...]]) --> zip object\n\
Barry Warsawbd599b52000-08-03 15:45:29 +00002318\n\
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002319Return a zip object whose .__next__() method returns a tuple where\n\
2320the i-th element comes from the i-th iterable argument. The .__next__()\n\
2321method continues until the shortest iterable in the argument sequence\n\
Georg Brandlced51db2008-12-04 18:28:38 +00002322is exhausted and then it raises StopIteration.");
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002323
2324PyTypeObject PyZip_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002325 PyVarObject_HEAD_INIT(&PyType_Type, 0)
2326 "zip", /* tp_name */
2327 sizeof(zipobject), /* tp_basicsize */
2328 0, /* tp_itemsize */
2329 /* methods */
2330 (destructor)zip_dealloc, /* tp_dealloc */
2331 0, /* tp_print */
2332 0, /* tp_getattr */
2333 0, /* tp_setattr */
2334 0, /* tp_reserved */
2335 0, /* tp_repr */
2336 0, /* tp_as_number */
2337 0, /* tp_as_sequence */
2338 0, /* tp_as_mapping */
2339 0, /* tp_hash */
2340 0, /* tp_call */
2341 0, /* tp_str */
2342 PyObject_GenericGetAttr, /* tp_getattro */
2343 0, /* tp_setattro */
2344 0, /* tp_as_buffer */
2345 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
2346 Py_TPFLAGS_BASETYPE, /* tp_flags */
2347 zip_doc, /* tp_doc */
2348 (traverseproc)zip_traverse, /* tp_traverse */
2349 0, /* tp_clear */
2350 0, /* tp_richcompare */
2351 0, /* tp_weaklistoffset */
2352 PyObject_SelfIter, /* tp_iter */
2353 (iternextfunc)zip_next, /* tp_iternext */
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002354 zip_methods, /* tp_methods */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002355 0, /* tp_members */
2356 0, /* tp_getset */
2357 0, /* tp_base */
2358 0, /* tp_dict */
2359 0, /* tp_descr_get */
2360 0, /* tp_descr_set */
2361 0, /* tp_dictoffset */
2362 0, /* tp_init */
2363 PyType_GenericAlloc, /* tp_alloc */
2364 zip_new, /* tp_new */
2365 PyObject_GC_Del, /* tp_free */
Raymond Hettinger736c0ab2008-03-13 02:09:15 +00002366};
Barry Warsawbd599b52000-08-03 15:45:29 +00002367
2368
Guido van Rossum79f25d91997-04-29 20:08:16 +00002369static PyMethodDef builtin_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002370 {"__build_class__", (PyCFunction)builtin___build_class__,
2371 METH_VARARGS | METH_KEYWORDS, build_class_doc},
2372 {"__import__", (PyCFunction)builtin___import__, METH_VARARGS | METH_KEYWORDS, import_doc},
2373 {"abs", builtin_abs, METH_O, abs_doc},
2374 {"all", builtin_all, METH_O, all_doc},
2375 {"any", builtin_any, METH_O, any_doc},
2376 {"ascii", builtin_ascii, METH_O, ascii_doc},
2377 {"bin", builtin_bin, METH_O, bin_doc},
Antoine Pitroue71362d2010-11-27 22:00:11 +00002378 {"callable", builtin_callable, METH_O, callable_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002379 {"chr", builtin_chr, METH_VARARGS, chr_doc},
2380 {"compile", (PyCFunction)builtin_compile, METH_VARARGS | METH_KEYWORDS, compile_doc},
2381 {"delattr", builtin_delattr, METH_VARARGS, delattr_doc},
2382 {"dir", builtin_dir, METH_VARARGS, dir_doc},
2383 {"divmod", builtin_divmod, METH_VARARGS, divmod_doc},
2384 {"eval", builtin_eval, METH_VARARGS, eval_doc},
2385 {"exec", builtin_exec, METH_VARARGS, exec_doc},
2386 {"format", builtin_format, METH_VARARGS, format_doc},
2387 {"getattr", builtin_getattr, METH_VARARGS, getattr_doc},
2388 {"globals", (PyCFunction)builtin_globals, METH_NOARGS, globals_doc},
2389 {"hasattr", builtin_hasattr, METH_VARARGS, hasattr_doc},
2390 {"hash", builtin_hash, METH_O, hash_doc},
2391 {"hex", builtin_hex, METH_O, hex_doc},
2392 {"id", builtin_id, METH_O, id_doc},
2393 {"input", builtin_input, METH_VARARGS, input_doc},
2394 {"isinstance", builtin_isinstance, METH_VARARGS, isinstance_doc},
2395 {"issubclass", builtin_issubclass, METH_VARARGS, issubclass_doc},
2396 {"iter", builtin_iter, METH_VARARGS, iter_doc},
2397 {"len", builtin_len, METH_O, len_doc},
2398 {"locals", (PyCFunction)builtin_locals, METH_NOARGS, locals_doc},
2399 {"max", (PyCFunction)builtin_max, METH_VARARGS | METH_KEYWORDS, max_doc},
2400 {"min", (PyCFunction)builtin_min, METH_VARARGS | METH_KEYWORDS, min_doc},
2401 {"next", (PyCFunction)builtin_next, METH_VARARGS, next_doc},
2402 {"oct", builtin_oct, METH_O, oct_doc},
2403 {"ord", builtin_ord, METH_O, ord_doc},
2404 {"pow", builtin_pow, METH_VARARGS, pow_doc},
2405 {"print", (PyCFunction)builtin_print, METH_VARARGS | METH_KEYWORDS, print_doc},
2406 {"repr", builtin_repr, METH_O, repr_doc},
2407 {"round", (PyCFunction)builtin_round, METH_VARARGS | METH_KEYWORDS, round_doc},
2408 {"setattr", builtin_setattr, METH_VARARGS, setattr_doc},
2409 {"sorted", (PyCFunction)builtin_sorted, METH_VARARGS | METH_KEYWORDS, sorted_doc},
2410 {"sum", builtin_sum, METH_VARARGS, sum_doc},
2411 {"vars", builtin_vars, METH_VARARGS, vars_doc},
2412 {NULL, NULL},
Guido van Rossum3f5da241990-12-20 15:06:42 +00002413};
2414
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002415PyDoc_STRVAR(builtin_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002416"Built-in functions, exceptions, and other objects.\n\
2417\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002418Noteworthy: None is the `nil' object; Ellipsis represents `...' in slices.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002419
Martin v. Löwis1a214512008-06-11 05:26:20 +00002420static struct PyModuleDef builtinsmodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002421 PyModuleDef_HEAD_INIT,
2422 "builtins",
2423 builtin_doc,
2424 -1, /* multiple "initialization" just copies the module dict. */
2425 builtin_methods,
2426 NULL,
2427 NULL,
2428 NULL,
2429 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00002430};
2431
2432
Guido van Rossum25ce5661997-08-02 03:10:38 +00002433PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002434_PyBuiltin_Init(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +00002435{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002436 PyObject *mod, *dict, *debug;
Benjamin Peterson42124a72012-10-30 23:41:54 -04002437
2438 if (PyType_Ready(&PyFilter_Type) < 0 ||
2439 PyType_Ready(&PyMap_Type) < 0 ||
2440 PyType_Ready(&PyZip_Type) < 0)
2441 return NULL;
2442
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002443 mod = PyModule_Create(&builtinsmodule);
2444 if (mod == NULL)
2445 return NULL;
2446 dict = PyModule_GetDict(mod);
Tim Peters4b7625e2001-09-13 21:37:17 +00002447
Tim Peters7571a0f2003-03-23 17:52:28 +00002448#ifdef Py_TRACE_REFS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002449 /* "builtins" exposes a number of statically allocated objects
2450 * that, before this code was added in 2.3, never showed up in
2451 * the list of "all objects" maintained by Py_TRACE_REFS. As a
2452 * result, programs leaking references to None and False (etc)
2453 * couldn't be diagnosed by examining sys.getobjects(0).
2454 */
Tim Peters7571a0f2003-03-23 17:52:28 +00002455#define ADD_TO_ALL(OBJECT) _Py_AddToAllObjects((PyObject *)(OBJECT), 0)
2456#else
2457#define ADD_TO_ALL(OBJECT) (void)0
2458#endif
2459
Tim Peters4b7625e2001-09-13 21:37:17 +00002460#define SETBUILTIN(NAME, OBJECT) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002461 if (PyDict_SetItemString(dict, NAME, (PyObject *)OBJECT) < 0) \
2462 return NULL; \
2463 ADD_TO_ALL(OBJECT)
Tim Peters4b7625e2001-09-13 21:37:17 +00002464
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002465 SETBUILTIN("None", Py_None);
2466 SETBUILTIN("Ellipsis", Py_Ellipsis);
2467 SETBUILTIN("NotImplemented", Py_NotImplemented);
2468 SETBUILTIN("False", Py_False);
2469 SETBUILTIN("True", Py_True);
2470 SETBUILTIN("bool", &PyBool_Type);
2471 SETBUILTIN("memoryview", &PyMemoryView_Type);
2472 SETBUILTIN("bytearray", &PyByteArray_Type);
2473 SETBUILTIN("bytes", &PyBytes_Type);
2474 SETBUILTIN("classmethod", &PyClassMethod_Type);
2475 SETBUILTIN("complex", &PyComplex_Type);
2476 SETBUILTIN("dict", &PyDict_Type);
2477 SETBUILTIN("enumerate", &PyEnum_Type);
2478 SETBUILTIN("filter", &PyFilter_Type);
2479 SETBUILTIN("float", &PyFloat_Type);
2480 SETBUILTIN("frozenset", &PyFrozenSet_Type);
2481 SETBUILTIN("property", &PyProperty_Type);
2482 SETBUILTIN("int", &PyLong_Type);
2483 SETBUILTIN("list", &PyList_Type);
2484 SETBUILTIN("map", &PyMap_Type);
2485 SETBUILTIN("object", &PyBaseObject_Type);
2486 SETBUILTIN("range", &PyRange_Type);
2487 SETBUILTIN("reversed", &PyReversed_Type);
2488 SETBUILTIN("set", &PySet_Type);
2489 SETBUILTIN("slice", &PySlice_Type);
2490 SETBUILTIN("staticmethod", &PyStaticMethod_Type);
2491 SETBUILTIN("str", &PyUnicode_Type);
2492 SETBUILTIN("super", &PySuper_Type);
2493 SETBUILTIN("tuple", &PyTuple_Type);
2494 SETBUILTIN("type", &PyType_Type);
2495 SETBUILTIN("zip", &PyZip_Type);
2496 debug = PyBool_FromLong(Py_OptimizeFlag == 0);
2497 if (PyDict_SetItemString(dict, "__debug__", debug) < 0) {
2498 Py_XDECREF(debug);
2499 return NULL;
2500 }
2501 Py_XDECREF(debug);
Barry Warsaw757af0e1997-08-29 22:13:51 +00002502
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002503 return mod;
Tim Peters7571a0f2003-03-23 17:52:28 +00002504#undef ADD_TO_ALL
Tim Peters4b7625e2001-09-13 21:37:17 +00002505#undef SETBUILTIN
Guido van Rossum3f5da241990-12-20 15:06:42 +00002506}