blob: c4fc57df697657b34174f258abc310aa34e93b40 [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"
Guido van Rossum3f5da241990-12-20 15:06:42 +00004
5#include "node.h"
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00006#include "code.h"
Guido van Rossum5b722181993-03-30 17:46:03 +00007#include "eval.h"
Guido van Rossum3f5da241990-12-20 15:06:42 +00008
Guido van Rossum6bf62da1997-04-11 20:37:35 +00009#include <ctype.h>
10
Mark Hammond26cffde42001-05-14 12:17:34 +000011/* The default encoding used by the platform file system APIs
12 Can remain NULL for all platforms that don't have such a concept
13*/
Martin v. Löwis6238d2b2002-06-30 15:26:10 +000014#if defined(MS_WINDOWS) && defined(HAVE_USABLE_WCHAR_T)
Mark Hammond26cffde42001-05-14 12:17:34 +000015const char *Py_FileSystemDefaultEncoding = "mbcs";
Just van Rossumb9b8e9c2003-02-10 09:22:01 +000016#elif defined(__APPLE__)
17const char *Py_FileSystemDefaultEncoding = "utf-8";
Mark Hammond26cffde42001-05-14 12:17:34 +000018#else
19const char *Py_FileSystemDefaultEncoding = NULL; /* use default */
20#endif
Mark Hammondef8b6542001-05-13 08:04:26 +000021
Guido van Rossum79f25d91997-04-29 20:08:16 +000022static PyObject *
Guido van Rossum52cc1d82007-03-18 15:41:51 +000023builtin___build_class__(PyObject *self, PyObject *args, PyObject *kwds)
24{
Guido van Rossumcd16bf62007-06-13 18:07:49 +000025 PyObject *func, *name, *bases, *mkw, *meta, *prep, *ns, *cell;
26 PyObject *cls = NULL;
Guido van Rossum52cc1d82007-03-18 15:41:51 +000027 Py_ssize_t nargs, nbases;
28
29 assert(args != NULL);
30 if (!PyTuple_Check(args)) {
31 PyErr_SetString(PyExc_TypeError,
32 "__build_class__: args is not a tuple");
33 return NULL;
34 }
35 nargs = PyTuple_GET_SIZE(args);
36 if (nargs < 2) {
37 PyErr_SetString(PyExc_TypeError,
38 "__build_class__: not enough arguments");
39 return NULL;
40 }
41 func = PyTuple_GET_ITEM(args, 0); /* Better be callable */
42 name = PyTuple_GET_ITEM(args, 1);
Neal Norwitz6ea45d32007-08-26 04:19:43 +000043 if (!PyUnicode_Check(name)) {
Guido van Rossum52cc1d82007-03-18 15:41:51 +000044 PyErr_SetString(PyExc_TypeError,
45 "__build_class__: name is not a string");
46 return NULL;
47 }
48 bases = PyTuple_GetSlice(args, 2, nargs);
49 if (bases == NULL)
50 return NULL;
51 nbases = nargs - 2;
52
53 if (kwds == NULL) {
54 meta = NULL;
55 mkw = NULL;
56 }
57 else {
58 mkw = PyDict_Copy(kwds); /* Don't modify kwds passed in! */
59 if (mkw == NULL) {
60 Py_DECREF(bases);
61 return NULL;
62 }
63 meta = PyDict_GetItemString(mkw, "metaclass");
64 if (meta != NULL) {
65 Py_INCREF(meta);
66 if (PyDict_DelItemString(mkw, "metaclass") < 0) {
67 Py_DECREF(meta);
68 Py_DECREF(mkw);
69 Py_DECREF(bases);
70 return NULL;
71 }
72 }
73 }
74 if (meta == NULL) {
75 if (PyTuple_GET_SIZE(bases) == 0)
76 meta = (PyObject *) (&PyType_Type);
77 else {
78 PyObject *base0 = PyTuple_GET_ITEM(bases, 0);
79 meta = (PyObject *) (base0->ob_type);
80 }
81 Py_INCREF(meta);
82 }
83 prep = PyObject_GetAttrString(meta, "__prepare__");
84 if (prep == NULL) {
85 PyErr_Clear();
86 ns = PyDict_New();
87 }
88 else {
89 PyObject *pargs = Py_BuildValue("OO", name, bases);
90 if (pargs == NULL) {
91 Py_DECREF(prep);
92 Py_DECREF(meta);
93 Py_XDECREF(mkw);
94 Py_DECREF(bases);
95 return NULL;
96 }
97 ns = PyEval_CallObjectWithKeywords(prep, pargs, mkw);
98 Py_DECREF(pargs);
99 Py_DECREF(prep);
100 if (ns == NULL) {
101 Py_DECREF(meta);
102 Py_XDECREF(mkw);
103 Py_DECREF(bases);
104 return NULL;
105 }
106 }
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000107 cell = PyObject_CallFunctionObjArgs(func, ns, NULL);
108 if (cell != NULL) {
Guido van Rossum52cc1d82007-03-18 15:41:51 +0000109 PyObject *margs;
Guido van Rossum52cc1d82007-03-18 15:41:51 +0000110 margs = Py_BuildValue("OOO", name, bases, ns);
111 if (margs != NULL) {
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000112 cls = PyEval_CallObjectWithKeywords(meta, margs, mkw);
Guido van Rossum52cc1d82007-03-18 15:41:51 +0000113 Py_DECREF(margs);
114 }
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000115 if (cls != NULL && PyCell_Check(cell)) {
116 Py_INCREF(cls);
117 PyCell_SET(cell, cls);
118 }
119 Py_DECREF(cell);
Guido van Rossum52cc1d82007-03-18 15:41:51 +0000120 }
121 Py_DECREF(ns);
122 Py_DECREF(meta);
123 Py_XDECREF(mkw);
124 Py_DECREF(bases);
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000125 return cls;
Guido van Rossum52cc1d82007-03-18 15:41:51 +0000126}
127
128PyDoc_STRVAR(build_class_doc,
129"__build_class__(func, name, *bases, metaclass=None, **kwds) -> class\n\
130\n\
131Internal helper function used by the class statement.");
132
133static PyObject *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000134builtin___import__(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000135{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000136 static char *kwlist[] = {"name", "globals", "locals", "fromlist",
137 "level", 0};
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000138 char *name;
Guido van Rossum79f25d91997-04-29 20:08:16 +0000139 PyObject *globals = NULL;
140 PyObject *locals = NULL;
141 PyObject *fromlist = NULL;
Thomas Woutersf7f438b2006-02-28 16:09:29 +0000142 int level = -1;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000143
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000144 if (!PyArg_ParseTupleAndKeywords(args, kwds, "s|OOOi:__import__",
145 kwlist, &name, &globals, &locals, &fromlist, &level))
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000146 return NULL;
Thomas Woutersf7f438b2006-02-28 16:09:29 +0000147 return PyImport_ImportModuleLevel(name, globals, locals,
148 fromlist, level);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000149}
150
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000151PyDoc_STRVAR(import_doc,
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000152"__import__(name, globals={}, locals={}, fromlist=[], level=-1) -> module\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000153\n\
154Import a module. The globals are only used to determine the context;\n\
155they are not modified. The locals are currently unused. The fromlist\n\
156should be a list of names to emulate ``from name import ...'', or an\n\
157empty list to emulate ``import name''.\n\
158When importing a module from a package, note that __import__('A.B', ...)\n\
159returns package A when fromlist is empty, but its submodule B when\n\
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000160fromlist is not empty. Level is used to determine whether to perform \n\
161absolute or relative imports. -1 is the original strategy of attempting\n\
162both absolute and relative imports, 0 is absolute, a positive number\n\
163is the number of parent directories to search relative to the current module.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000164
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000165
Guido van Rossum79f25d91997-04-29 20:08:16 +0000166static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000167builtin_abs(PyObject *self, PyObject *v)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000168{
Guido van Rossum09df08a1998-05-22 00:51:39 +0000169 return PyNumber_Absolute(v);
Guido van Rossum3f5da241990-12-20 15:06:42 +0000170}
171
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000172PyDoc_STRVAR(abs_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000173"abs(number) -> number\n\
174\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000175Return the absolute value of the argument.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000176
Raymond Hettinger96229b12005-03-11 06:49:40 +0000177static PyObject *
178builtin_all(PyObject *self, PyObject *v)
179{
180 PyObject *it, *item;
181
182 it = PyObject_GetIter(v);
183 if (it == NULL)
184 return NULL;
185
186 while ((item = PyIter_Next(it)) != NULL) {
187 int cmp = PyObject_IsTrue(item);
188 Py_DECREF(item);
189 if (cmp < 0) {
190 Py_DECREF(it);
191 return NULL;
192 }
193 if (cmp == 0) {
194 Py_DECREF(it);
195 Py_RETURN_FALSE;
196 }
197 }
198 Py_DECREF(it);
199 if (PyErr_Occurred())
200 return NULL;
201 Py_RETURN_TRUE;
202}
203
204PyDoc_STRVAR(all_doc,
205"all(iterable) -> bool\n\
206\n\
207Return True if bool(x) is True for all values x in the iterable.");
208
209static PyObject *
210builtin_any(PyObject *self, PyObject *v)
211{
212 PyObject *it, *item;
213
214 it = PyObject_GetIter(v);
215 if (it == NULL)
216 return NULL;
217
218 while ((item = PyIter_Next(it)) != NULL) {
219 int cmp = PyObject_IsTrue(item);
220 Py_DECREF(item);
221 if (cmp < 0) {
222 Py_DECREF(it);
223 return NULL;
224 }
225 if (cmp == 1) {
226 Py_DECREF(it);
227 Py_RETURN_TRUE;
228 }
229 }
230 Py_DECREF(it);
231 if (PyErr_Occurred())
232 return NULL;
233 Py_RETURN_FALSE;
234}
235
236PyDoc_STRVAR(any_doc,
237"any(iterable) -> bool\n\
238\n\
239Return True if bool(x) is True for any x in the iterable.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000240
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000241
Guido van Rossum79f25d91997-04-29 20:08:16 +0000242static PyObject *
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000243builtin_bin(PyObject *self, PyObject *v)
244{
245 return PyNumber_ToBase(v, 2);
246}
247
248PyDoc_STRVAR(bin_doc,
249"bin(number) -> string\n\
250\n\
251Return the binary representation of an integer or long integer.");
252
253
254static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000255builtin_filter(PyObject *self, PyObject *args)
Guido van Rossum12d12c51993-10-26 17:58:25 +0000256{
Guido van Rossumc1f779c2007-07-03 08:25:58 +0000257 PyObject *itertools, *ifilter, *result;
258 itertools = PyImport_ImportModule("itertools");
259 if (itertools == NULL)
Guido van Rossum12d12c51993-10-26 17:58:25 +0000260 return NULL;
Guido van Rossumc1f779c2007-07-03 08:25:58 +0000261 ifilter = PyObject_GetAttrString(itertools, "ifilter");
262 Py_DECREF(itertools);
263 if (ifilter == NULL)
Georg Brandle35b6572005-07-19 22:20:20 +0000264 return NULL;
Guido van Rossumc1f779c2007-07-03 08:25:58 +0000265 result = PyObject_Call(ifilter, args, NULL);
266 Py_DECREF(ifilter);
Guido van Rossum12d12c51993-10-26 17:58:25 +0000267 return result;
Guido van Rossum12d12c51993-10-26 17:58:25 +0000268}
269
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000270PyDoc_STRVAR(filter_doc,
Guido van Rossumc1f779c2007-07-03 08:25:58 +0000271"filter(predicate, iterable) -> iterator\n\
272\n\
273Return an iterator yielding only those elements of the input iterable\n\
274for which the predicate (a Boolean function) returns true.\n\
275If the predicate is None, 'lambda x: bool(x)' is assumed.\n\
276(This is identical to itertools.ifilter().)");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000277
Eric Smith8c663262007-08-25 02:26:07 +0000278static PyObject *
279builtin_format(PyObject *self, PyObject *args)
280{
281 static PyObject * format_str = NULL;
282 PyObject *value;
Eric Smith81936692007-08-31 01:14:01 +0000283 PyObject *spec = NULL;
Eric Smith8c663262007-08-25 02:26:07 +0000284 PyObject *meth;
Eric Smith81936692007-08-31 01:14:01 +0000285 PyObject *empty = NULL;
286 PyObject *result = NULL;
Eric Smith8c663262007-08-25 02:26:07 +0000287
288 /* Initialize cached value */
289 if (format_str == NULL) {
290 /* Initialize static variable needed by _PyType_Lookup */
291 format_str = PyUnicode_FromString("__format__");
292 if (format_str == NULL)
Eric Smith81936692007-08-31 01:14:01 +0000293 goto done;
Eric Smith8c663262007-08-25 02:26:07 +0000294 }
295
Eric Smith81936692007-08-31 01:14:01 +0000296 if (!PyArg_ParseTuple(args, "O|O:format", &value, &spec))
297 goto done;
298
299 /* initialize the default value */
300 if (spec == NULL) {
301 empty = PyUnicode_FromUnicode(NULL, 0);
302 spec = empty;
303 }
Eric Smith8c663262007-08-25 02:26:07 +0000304
305 /* Make sure the type is initialized. float gets initialized late */
306 if (Py_Type(value)->tp_dict == NULL)
307 if (PyType_Ready(Py_Type(value)) < 0)
Eric Smith81936692007-08-31 01:14:01 +0000308 goto done;
Eric Smith8c663262007-08-25 02:26:07 +0000309
310 /* Find the (unbound!) __format__ method (a borrowed reference) */
311 meth = _PyType_Lookup(Py_Type(value), format_str);
312 if (meth == NULL) {
313 PyErr_Format(PyExc_TypeError,
314 "Type %.100s doesn't define __format__",
315 Py_Type(value)->tp_name);
Eric Smith81936692007-08-31 01:14:01 +0000316 goto done;
Eric Smith8c663262007-08-25 02:26:07 +0000317 }
318
319 /* And call it, binding it to the value */
320 result = PyObject_CallFunctionObjArgs(meth, value, spec, NULL);
321
Eric Smith81936692007-08-31 01:14:01 +0000322 if (result && !PyUnicode_Check(result)) {
Eric Smith8c663262007-08-25 02:26:07 +0000323 PyErr_SetString(PyExc_TypeError,
324 "__format__ method did not return string");
325 Py_DECREF(result);
Eric Smith81936692007-08-31 01:14:01 +0000326 result = NULL;
327 goto done;
Eric Smith8c663262007-08-25 02:26:07 +0000328 }
Eric Smith8c663262007-08-25 02:26:07 +0000329
Eric Smith81936692007-08-31 01:14:01 +0000330done:
331 Py_XDECREF(empty);
Eric Smith8c663262007-08-25 02:26:07 +0000332 return result;
333}
334
Eric Smith8c663262007-08-25 02:26:07 +0000335PyDoc_STRVAR(format_doc,
Eric Smith81936692007-08-31 01:14:01 +0000336"format(value[, format_spec]) -> string\n\
Eric Smith8c663262007-08-25 02:26:07 +0000337\n\
Eric Smith81936692007-08-31 01:14:01 +0000338Returns value.__format__(format_spec)\n\
339format_spec defaults to \"\"");
340
Guido van Rossum7fcf2242007-05-04 17:43:11 +0000341static PyObject *
Walter Dörwalde7efd592007-06-05 20:07:21 +0000342builtin_chr(PyObject *self, PyObject *args)
Guido van Rossum09095f32000-03-10 23:00:52 +0000343{
344 long x;
Guido van Rossum09095f32000-03-10 23:00:52 +0000345
Walter Dörwalde7efd592007-06-05 20:07:21 +0000346 if (!PyArg_ParseTuple(args, "l:chr", &x))
Guido van Rossum09095f32000-03-10 23:00:52 +0000347 return NULL;
Fredrik Lundh0dcf67e2001-06-26 20:01:56 +0000348
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +0000349 return PyUnicode_FromOrdinal(x);
Guido van Rossum09095f32000-03-10 23:00:52 +0000350}
351
Guido van Rossum307fa8c2007-07-16 20:46:27 +0000352PyDoc_VAR(chr_doc) = PyDoc_STR(
Guido van Rossum84fc66d2007-05-03 17:18:26 +0000353"chr(i) -> Unicode character\n\
Guido van Rossum09095f32000-03-10 23:00:52 +0000354\n\
Guido van Rossum8ac004e2007-07-15 13:00:05 +0000355Return a Unicode string of one character with ordinal i; 0 <= i <= 0x10ffff."
Guido van Rossum307fa8c2007-07-16 20:46:27 +0000356)
Guido van Rossum8ac004e2007-07-15 13:00:05 +0000357#ifndef Py_UNICODE_WIDE
Guido van Rossum307fa8c2007-07-16 20:46:27 +0000358PyDoc_STR(
Guido van Rossum8ac004e2007-07-15 13:00:05 +0000359"\nIf 0x10000 <= i, a surrogate pair is returned."
Guido van Rossum307fa8c2007-07-16 20:46:27 +0000360)
Guido van Rossum8ac004e2007-07-15 13:00:05 +0000361#endif
Guido van Rossum307fa8c2007-07-16 20:46:27 +0000362;
Guido van Rossum09095f32000-03-10 23:00:52 +0000363
364
365static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000366builtin_cmp(PyObject *self, PyObject *args)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +0000367{
Guido van Rossum79f25d91997-04-29 20:08:16 +0000368 PyObject *a, *b;
Guido van Rossum09df08a1998-05-22 00:51:39 +0000369 int c;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000370
Raymond Hettingerea3fdf42002-12-29 16:33:45 +0000371 if (!PyArg_UnpackTuple(args, "cmp", 2, 2, &a, &b))
Guido van Rossuma9e7dc11992-10-18 18:53:57 +0000372 return NULL;
Guido van Rossum09df08a1998-05-22 00:51:39 +0000373 if (PyObject_Cmp(a, b, &c) < 0)
Guido van Rossumc8b6df91997-05-23 00:06:51 +0000374 return NULL;
Guido van Rossum09df08a1998-05-22 00:51:39 +0000375 return PyInt_FromLong((long)c);
Guido van Rossuma9e7dc11992-10-18 18:53:57 +0000376}
377
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000378PyDoc_STRVAR(cmp_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000379"cmp(x, y) -> integer\n\
380\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000381Return negative if x<y, zero if x==y, positive if x>y.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000382
Guido van Rossumf15a29f2007-05-04 00:41:39 +0000383
384static char *
385source_as_string(PyObject *cmd)
386{
387 char *str;
388 Py_ssize_t size;
389
Guido van Rossumf15a29f2007-05-04 00:41:39 +0000390 if (PyUnicode_Check(cmd)) {
391 cmd = _PyUnicode_AsDefaultEncodedString(cmd, NULL);
392 if (cmd == NULL)
393 return NULL;
394 }
Guido van Rossuma4b8d1d2007-08-27 15:02:28 +0000395 else if (!PyObject_CheckReadBuffer(cmd)) {
396 PyErr_SetString(PyExc_TypeError,
397 "eval()/exec() arg 1 must be a string, bytes or code object");
398 return NULL;
399 }
Guido van Rossumf15a29f2007-05-04 00:41:39 +0000400 if (PyObject_AsReadBuffer(cmd, (const void **)&str, &size) < 0) {
401 return NULL;
402 }
403 if (strlen(str) != size) {
404 PyErr_SetString(PyExc_TypeError,
405 "source code string cannot contain null bytes");
406 return NULL;
407 }
408 return str;
409}
410
Guido van Rossum79f25d91997-04-29 20:08:16 +0000411static PyObject *
Guido van Rossumd8faa362007-04-27 19:54:29 +0000412builtin_compile(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum5b722181993-03-30 17:46:03 +0000413{
414 char *str;
415 char *filename;
416 char *startstr;
417 int start;
Tim Peters6cd6a822001-08-17 22:11:27 +0000418 int dont_inherit = 0;
419 int supplied_flags = 0;
Tim Peters5ba58662001-07-16 02:29:45 +0000420 PyCompilerFlags cf;
Guido van Rossumf15a29f2007-05-04 00:41:39 +0000421 PyObject *cmd;
Guido van Rossumd8faa362007-04-27 19:54:29 +0000422 static char *kwlist[] = {"source", "filename", "mode", "flags",
423 "dont_inherit", NULL};
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000424
Guido van Rossumd8faa362007-04-27 19:54:29 +0000425 if (!PyArg_ParseTupleAndKeywords(args, kwds, "Oss|ii:compile",
426 kwlist, &cmd, &filename, &startstr,
427 &supplied_flags, &dont_inherit))
Guido van Rossum5b722181993-03-30 17:46:03 +0000428 return NULL;
Tim Peters6cd6a822001-08-17 22:11:27 +0000429
Guido van Rossumf15a29f2007-05-04 00:41:39 +0000430 cf.cf_flags = supplied_flags | PyCF_SOURCE_IS_UTF8;
Just van Rossum3aaf42c2003-02-10 08:21:10 +0000431
Guido van Rossumf15a29f2007-05-04 00:41:39 +0000432 str = source_as_string(cmd);
433 if (str == NULL)
Just van Rossumb9b8e9c2003-02-10 09:22:01 +0000434 return NULL;
Just van Rossum3aaf42c2003-02-10 08:21:10 +0000435
Guido van Rossum5b722181993-03-30 17:46:03 +0000436 if (strcmp(startstr, "exec") == 0)
Guido van Rossumb05a5c71997-05-07 17:46:13 +0000437 start = Py_file_input;
Guido van Rossum5b722181993-03-30 17:46:03 +0000438 else if (strcmp(startstr, "eval") == 0)
Guido van Rossumb05a5c71997-05-07 17:46:13 +0000439 start = Py_eval_input;
Guido van Rossum872537c1995-07-07 22:43:42 +0000440 else if (strcmp(startstr, "single") == 0)
Guido van Rossumb05a5c71997-05-07 17:46:13 +0000441 start = Py_single_input;
Guido van Rossum5b722181993-03-30 17:46:03 +0000442 else {
Guido van Rossum79f25d91997-04-29 20:08:16 +0000443 PyErr_SetString(PyExc_ValueError,
Fred Drake661ea262000-10-24 19:57:45 +0000444 "compile() arg 3 must be 'exec' or 'eval' or 'single'");
Guido van Rossumf15a29f2007-05-04 00:41:39 +0000445 return NULL;
Guido van Rossum5b722181993-03-30 17:46:03 +0000446 }
Tim Peters6cd6a822001-08-17 22:11:27 +0000447
Guido van Rossum4b499dd32003-02-13 22:07:59 +0000448 if (supplied_flags &
Martin v. Löwisbd260da2006-02-26 19:42:26 +0000449 ~(PyCF_MASK | PyCF_MASK_OBSOLETE | PyCF_DONT_IMPLY_DEDENT | PyCF_ONLY_AST))
Guido van Rossum4b499dd32003-02-13 22:07:59 +0000450 {
Tim Peters6cd6a822001-08-17 22:11:27 +0000451 PyErr_SetString(PyExc_ValueError,
452 "compile(): unrecognised flags");
Guido van Rossumf15a29f2007-05-04 00:41:39 +0000453 return NULL;
Tim Peters6cd6a822001-08-17 22:11:27 +0000454 }
455 /* XXX Warn if (supplied_flags & PyCF_MASK_OBSOLETE) != 0? */
456
Tim Peters6cd6a822001-08-17 22:11:27 +0000457 if (!dont_inherit) {
458 PyEval_MergeCompilerFlags(&cf);
459 }
Guido van Rossumf15a29f2007-05-04 00:41:39 +0000460 return Py_CompileStringFlags(str, filename, start, &cf);
Guido van Rossum5b722181993-03-30 17:46:03 +0000461}
462
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000463PyDoc_STRVAR(compile_doc,
Tim Peters6cd6a822001-08-17 22:11:27 +0000464"compile(source, filename, mode[, flags[, dont_inherit]]) -> code object\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000465\n\
466Compile the source string (a Python module, statement or expression)\n\
Georg Brandl7cae87c2006-09-06 06:51:57 +0000467into a code object that can be executed by exec() or eval().\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000468The filename will be used for run-time error messages.\n\
469The mode must be 'exec' to compile a module, 'single' to compile a\n\
Tim Peters6cd6a822001-08-17 22:11:27 +0000470single (interactive) statement, or 'eval' to compile an expression.\n\
471The flags argument, if present, controls which future statements influence\n\
472the compilation of the code.\n\
473The dont_inherit argument, if non-zero, stops the compilation inheriting\n\
474the effects of any future statements in effect in the code calling\n\
475compile; if absent or zero these statements do influence the compilation,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000476in addition to any features explicitly specified.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000477
Guido van Rossum79f25d91997-04-29 20:08:16 +0000478static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000479builtin_dir(PyObject *self, PyObject *args)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000480{
Tim Peters5d2b77c2001-09-03 05:47:38 +0000481 PyObject *arg = NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000482
Raymond Hettingerea3fdf42002-12-29 16:33:45 +0000483 if (!PyArg_UnpackTuple(args, "dir", 0, 1, &arg))
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000484 return NULL;
Tim Peters7eea37e2001-09-04 22:08:56 +0000485 return PyObject_Dir(arg);
Guido van Rossum3f5da241990-12-20 15:06:42 +0000486}
487
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000488PyDoc_STRVAR(dir_doc,
Tim Peters5d2b77c2001-09-03 05:47:38 +0000489"dir([object]) -> list of strings\n"
490"\n"
Georg Brandle32b4222007-03-10 22:13:27 +0000491"If called without an argument, return the names in the current scope.\n"
492"Else, return an alphabetized list of names comprising (some of) the attributes\n"
493"of the given object, and of attributes reachable from it.\n"
494"If the object supplies a method named __dir__, it will be used; otherwise\n"
495"the default dir() logic is used and returns:\n"
496" for a module object: the module's attributes.\n"
497" for a class object: its attributes, and recursively the attributes\n"
498" of its bases.\n"
Guido van Rossumd8faa362007-04-27 19:54:29 +0000499" for any other object: its attributes, its class's attributes, and\n"
Georg Brandle32b4222007-03-10 22:13:27 +0000500" recursively the attributes of its class's base classes.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000501
Guido van Rossum79f25d91997-04-29 20:08:16 +0000502static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000503builtin_divmod(PyObject *self, PyObject *args)
Guido van Rossum6a00cd81995-01-07 12:39:01 +0000504{
Guido van Rossum79f25d91997-04-29 20:08:16 +0000505 PyObject *v, *w;
Guido van Rossum6a00cd81995-01-07 12:39:01 +0000506
Raymond Hettingerea3fdf42002-12-29 16:33:45 +0000507 if (!PyArg_UnpackTuple(args, "divmod", 2, 2, &v, &w))
Guido van Rossum6a00cd81995-01-07 12:39:01 +0000508 return NULL;
Guido van Rossum09df08a1998-05-22 00:51:39 +0000509 return PyNumber_Divmod(v, w);
Guido van Rossum3f5da241990-12-20 15:06:42 +0000510}
511
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000512PyDoc_STRVAR(divmod_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000513"divmod(x, y) -> (div, mod)\n\
514\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000515Return the tuple ((x-x%y)/y, x%y). Invariant: div*y + mod == x.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000516
517
Guido van Rossum79f25d91997-04-29 20:08:16 +0000518static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000519builtin_eval(PyObject *self, PyObject *args)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000520{
Just van Rossum3aaf42c2003-02-10 08:21:10 +0000521 PyObject *cmd, *result, *tmp = NULL;
Guido van Rossum79f25d91997-04-29 20:08:16 +0000522 PyObject *globals = Py_None, *locals = Py_None;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000523 char *str;
Tim Peters9fa96be2001-08-17 23:04:59 +0000524 PyCompilerFlags cf;
Guido van Rossum590baa41993-11-30 13:40:46 +0000525
Raymond Hettinger214b1c32004-07-02 06:41:07 +0000526 if (!PyArg_UnpackTuple(args, "eval", 1, 3, &cmd, &globals, &locals))
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000527 return NULL;
Raymond Hettinger214b1c32004-07-02 06:41:07 +0000528 if (locals != Py_None && !PyMapping_Check(locals)) {
529 PyErr_SetString(PyExc_TypeError, "locals must be a mapping");
Raymond Hettinger513ffe82004-07-06 13:44:41 +0000530 return NULL;
Raymond Hettinger214b1c32004-07-02 06:41:07 +0000531 }
532 if (globals != Py_None && !PyDict_Check(globals)) {
Georg Brandl99d7e4e2005-08-31 22:21:15 +0000533 PyErr_SetString(PyExc_TypeError, PyMapping_Check(globals) ?
Raymond Hettinger214b1c32004-07-02 06:41:07 +0000534 "globals must be a real dict; try eval(expr, {}, mapping)"
535 : "globals must be a dict");
Raymond Hettinger513ffe82004-07-06 13:44:41 +0000536 return NULL;
Raymond Hettinger214b1c32004-07-02 06:41:07 +0000537 }
Guido van Rossum79f25d91997-04-29 20:08:16 +0000538 if (globals == Py_None) {
539 globals = PyEval_GetGlobals();
540 if (locals == Py_None)
541 locals = PyEval_GetLocals();
Guido van Rossum6135a871995-01-09 17:53:26 +0000542 }
Guido van Rossum79f25d91997-04-29 20:08:16 +0000543 else if (locals == Py_None)
Guido van Rossum6135a871995-01-09 17:53:26 +0000544 locals = globals;
Tim Peters9fa96be2001-08-17 23:04:59 +0000545
Georg Brandl77c85e62005-09-15 10:46:13 +0000546 if (globals == NULL || locals == NULL) {
547 PyErr_SetString(PyExc_TypeError,
548 "eval must be given globals and locals "
549 "when called without a frame");
550 return NULL;
551 }
552
Guido van Rossum79f25d91997-04-29 20:08:16 +0000553 if (PyDict_GetItemString(globals, "__builtins__") == NULL) {
554 if (PyDict_SetItemString(globals, "__builtins__",
555 PyEval_GetBuiltins()) != 0)
Guido van Rossum6135a871995-01-09 17:53:26 +0000556 return NULL;
557 }
Tim Peters9fa96be2001-08-17 23:04:59 +0000558
Jeremy Hylton15c1c4f2001-07-30 21:50:55 +0000559 if (PyCode_Check(cmd)) {
Jeremy Hylton733c8932001-12-13 19:51:56 +0000560 if (PyCode_GetNumFree((PyCodeObject *)cmd) > 0) {
Jeremy Hylton15c1c4f2001-07-30 21:50:55 +0000561 PyErr_SetString(PyExc_TypeError,
562 "code object passed to eval() may not contain free variables");
563 return NULL;
564 }
Guido van Rossum79f25d91997-04-29 20:08:16 +0000565 return PyEval_EvalCode((PyCodeObject *) cmd, globals, locals);
Jeremy Hylton15c1c4f2001-07-30 21:50:55 +0000566 }
Tim Peters9fa96be2001-08-17 23:04:59 +0000567
Guido van Rossumf15a29f2007-05-04 00:41:39 +0000568 str = source_as_string(cmd);
569 if (str == NULL)
Guido van Rossum94390a41992-08-14 15:14:30 +0000570 return NULL;
Just van Rossum3aaf42c2003-02-10 08:21:10 +0000571
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000572 while (*str == ' ' || *str == '\t')
573 str++;
Tim Peters9fa96be2001-08-17 23:04:59 +0000574
Guido van Rossumf15a29f2007-05-04 00:41:39 +0000575 cf.cf_flags = PyCF_SOURCE_IS_UTF8;
Tim Peters9fa96be2001-08-17 23:04:59 +0000576 (void)PyEval_MergeCompilerFlags(&cf);
Just van Rossum3aaf42c2003-02-10 08:21:10 +0000577 result = PyRun_StringFlags(str, Py_eval_input, globals, locals, &cf);
578 Py_XDECREF(tmp);
579 return result;
Guido van Rossum3f5da241990-12-20 15:06:42 +0000580}
581
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000582PyDoc_STRVAR(eval_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000583"eval(source[, globals[, locals]]) -> value\n\
584\n\
585Evaluate the source in the context of globals and locals.\n\
586The source may be a string representing a Python expression\n\
587or a code object as returned by compile().\n\
Thomas Wouters89f507f2006-12-13 04:49:30 +0000588The globals must be a dictionary and locals can be any mapping,\n\
Raymond Hettinger214b1c32004-07-02 06:41:07 +0000589defaulting to the current globals and locals.\n\
590If only globals is given, locals defaults to it.\n");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000591
Georg Brandl7cae87c2006-09-06 06:51:57 +0000592static PyObject *
593builtin_exec(PyObject *self, PyObject *args)
594{
595 PyObject *v;
596 PyObject *prog, *globals = Py_None, *locals = Py_None;
597 int plain = 0;
598
599 if (!PyArg_ParseTuple(args, "O|OO:exec", &prog, &globals, &locals))
600 return NULL;
601
602 if (globals == Py_None) {
603 globals = PyEval_GetGlobals();
604 if (locals == Py_None) {
605 locals = PyEval_GetLocals();
606 plain = 1;
607 }
608 if (!globals || !locals) {
609 PyErr_SetString(PyExc_SystemError,
610 "globals and locals cannot be NULL");
611 return NULL;
612 }
613 }
614 else if (locals == Py_None)
615 locals = globals;
Neal Norwitz6ea45d32007-08-26 04:19:43 +0000616 if (!PyUnicode_Check(prog) &&
Guido van Rossumda5b8f22007-06-12 23:30:11 +0000617 !PyCode_Check(prog)) {
Georg Brandl7cae87c2006-09-06 06:51:57 +0000618 PyErr_Format(PyExc_TypeError,
619 "exec() arg 1 must be a string, file, or code "
620 "object, not %.100s", prog->ob_type->tp_name);
621 return NULL;
622 }
623 if (!PyDict_Check(globals)) {
624 PyErr_Format(PyExc_TypeError, "exec() arg 2 must be a dict, not %.100s",
625 globals->ob_type->tp_name);
626 return NULL;
627 }
628 if (!PyMapping_Check(locals)) {
629 PyErr_Format(PyExc_TypeError,
630 "arg 3 must be a mapping or None, not %.100s",
631 locals->ob_type->tp_name);
632 return NULL;
633 }
634 if (PyDict_GetItemString(globals, "__builtins__") == NULL) {
635 if (PyDict_SetItemString(globals, "__builtins__",
636 PyEval_GetBuiltins()) != 0)
637 return NULL;
638 }
639
640 if (PyCode_Check(prog)) {
641 if (PyCode_GetNumFree((PyCodeObject *)prog) > 0) {
642 PyErr_SetString(PyExc_TypeError,
643 "code object passed to exec() may not "
644 "contain free variables");
645 return NULL;
646 }
647 v = PyEval_EvalCode((PyCodeObject *) prog, globals, locals);
648 }
Georg Brandl7cae87c2006-09-06 06:51:57 +0000649 else {
Guido van Rossumf15a29f2007-05-04 00:41:39 +0000650 char *str = source_as_string(prog);
Georg Brandl7cae87c2006-09-06 06:51:57 +0000651 PyCompilerFlags cf;
Guido van Rossumf15a29f2007-05-04 00:41:39 +0000652 if (str == NULL)
Georg Brandl7cae87c2006-09-06 06:51:57 +0000653 return NULL;
Guido van Rossumf15a29f2007-05-04 00:41:39 +0000654 cf.cf_flags = PyCF_SOURCE_IS_UTF8;
Georg Brandl7cae87c2006-09-06 06:51:57 +0000655 if (PyEval_MergeCompilerFlags(&cf))
656 v = PyRun_StringFlags(str, Py_file_input, globals,
657 locals, &cf);
658 else
659 v = PyRun_String(str, Py_file_input, globals, locals);
Georg Brandl7cae87c2006-09-06 06:51:57 +0000660 }
661 if (v == NULL)
662 return NULL;
663 Py_DECREF(v);
664 Py_RETURN_NONE;
665}
666
667PyDoc_STRVAR(exec_doc,
668"exec(object[, globals[, locals]])\n\
669\n\
670Read and execute code from a object, which can be a string, a code\n\
671object or a file object.\n\
672The globals and locals are dictionaries, defaulting to the current\n\
673globals and locals. If only globals is given, locals defaults to it.");
674
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000675
Guido van Rossum79f25d91997-04-29 20:08:16 +0000676static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000677builtin_getattr(PyObject *self, PyObject *args)
Guido van Rossum33894be1992-01-27 16:53:09 +0000678{
Neal Norwitz6ea45d32007-08-26 04:19:43 +0000679 PyObject *v, *result, *dflt = NULL;
Guido van Rossum79f25d91997-04-29 20:08:16 +0000680 PyObject *name;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000681
Raymond Hettingerea3fdf42002-12-29 16:33:45 +0000682 if (!PyArg_UnpackTuple(args, "getattr", 2, 3, &v, &name, &dflt))
Guido van Rossum33894be1992-01-27 16:53:09 +0000683 return NULL;
Martin v. Löwis5b222132007-06-10 09:51:05 +0000684
Martin v. Löwis5b222132007-06-10 09:51:05 +0000685 if (!PyUnicode_Check(name)) {
Jeremy Hylton0eb11152001-07-30 22:39:31 +0000686 PyErr_SetString(PyExc_TypeError,
Alex Martellia9b9c9f2003-04-23 13:34:35 +0000687 "getattr(): attribute name must be string");
Jeremy Hylton0eb11152001-07-30 22:39:31 +0000688 return NULL;
689 }
Guido van Rossum950ff291998-06-29 13:38:57 +0000690 result = PyObject_GetAttr(v, name);
Guido van Rossumd8923572001-10-16 21:31:32 +0000691 if (result == NULL && dflt != NULL &&
692 PyErr_ExceptionMatches(PyExc_AttributeError))
693 {
Guido van Rossum950ff291998-06-29 13:38:57 +0000694 PyErr_Clear();
695 Py_INCREF(dflt);
696 result = dflt;
697 }
698 return result;
Guido van Rossum9bfef441993-03-29 10:43:31 +0000699}
700
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000701PyDoc_STRVAR(getattr_doc,
Guido van Rossum950ff291998-06-29 13:38:57 +0000702"getattr(object, name[, default]) -> value\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000703\n\
Guido van Rossum950ff291998-06-29 13:38:57 +0000704Get a named attribute from an object; getattr(x, 'y') is equivalent to x.y.\n\
705When a default argument is given, it is returned when the attribute doesn't\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000706exist; without it, an exception is raised in that case.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000707
708
Guido van Rossum79f25d91997-04-29 20:08:16 +0000709static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000710builtin_globals(PyObject *self)
Guido van Rossum872537c1995-07-07 22:43:42 +0000711{
Guido van Rossum79f25d91997-04-29 20:08:16 +0000712 PyObject *d;
Guido van Rossum872537c1995-07-07 22:43:42 +0000713
Guido van Rossum79f25d91997-04-29 20:08:16 +0000714 d = PyEval_GetGlobals();
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000715 Py_XINCREF(d);
Guido van Rossum872537c1995-07-07 22:43:42 +0000716 return d;
717}
718
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000719PyDoc_STRVAR(globals_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000720"globals() -> dictionary\n\
721\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000722Return the dictionary containing the current scope's global variables.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000723
724
Guido van Rossum79f25d91997-04-29 20:08:16 +0000725static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000726builtin_hasattr(PyObject *self, PyObject *args)
Guido van Rossum9bfef441993-03-29 10:43:31 +0000727{
Guido van Rossum79f25d91997-04-29 20:08:16 +0000728 PyObject *v;
729 PyObject *name;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000730
Raymond Hettingerea3fdf42002-12-29 16:33:45 +0000731 if (!PyArg_UnpackTuple(args, "hasattr", 2, 2, &v, &name))
Guido van Rossum9bfef441993-03-29 10:43:31 +0000732 return NULL;
Martin v. Löwis5b222132007-06-10 09:51:05 +0000733 if (!PyUnicode_Check(name)) {
Jeremy Hylton302b54a2001-07-30 22:45:19 +0000734 PyErr_SetString(PyExc_TypeError,
Alex Martellia9b9c9f2003-04-23 13:34:35 +0000735 "hasattr(): attribute name must be string");
Jeremy Hylton302b54a2001-07-30 22:45:19 +0000736 return NULL;
737 }
Guido van Rossum79f25d91997-04-29 20:08:16 +0000738 v = PyObject_GetAttr(v, name);
Guido van Rossum9bfef441993-03-29 10:43:31 +0000739 if (v == NULL) {
Guido van Rossum79f25d91997-04-29 20:08:16 +0000740 PyErr_Clear();
Guido van Rossum09df08a1998-05-22 00:51:39 +0000741 Py_INCREF(Py_False);
742 return Py_False;
Guido van Rossum9bfef441993-03-29 10:43:31 +0000743 }
Guido van Rossum79f25d91997-04-29 20:08:16 +0000744 Py_DECREF(v);
Guido van Rossum09df08a1998-05-22 00:51:39 +0000745 Py_INCREF(Py_True);
746 return Py_True;
Guido van Rossum33894be1992-01-27 16:53:09 +0000747}
748
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000749PyDoc_STRVAR(hasattr_doc,
Guido van Rossum77f6a652002-04-03 22:41:51 +0000750"hasattr(object, name) -> bool\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000751\n\
752Return whether the object has an attribute with the given name.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000753(This is done by calling getattr(object, name) and catching exceptions.)");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000754
755
Guido van Rossum79f25d91997-04-29 20:08:16 +0000756static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000757builtin_id(PyObject *self, PyObject *v)
Guido van Rossum5b722181993-03-30 17:46:03 +0000758{
Guido van Rossum106f2da2000-06-28 21:12:25 +0000759 return PyLong_FromVoidPtr(v);
Guido van Rossum5b722181993-03-30 17:46:03 +0000760}
761
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000762PyDoc_STRVAR(id_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000763"id(object) -> integer\n\
764\n\
765Return the identity of an object. This is guaranteed to be unique among\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000766simultaneously existing objects. (Hint: it's the object's memory address.)");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000767
768
Guido van Rossum79f25d91997-04-29 20:08:16 +0000769static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000770builtin_map(PyObject *self, PyObject *args)
Guido van Rossum12d12c51993-10-26 17:58:25 +0000771{
Guido van Rossumc1f779c2007-07-03 08:25:58 +0000772 PyObject *itertools, *imap, *result;
773 itertools = PyImport_ImportModule("itertools");
774 if (itertools == NULL)
Guido van Rossum12d12c51993-10-26 17:58:25 +0000775 return NULL;
Guido van Rossumc1f779c2007-07-03 08:25:58 +0000776 imap = PyObject_GetAttrString(itertools, "imap");
777 Py_DECREF(itertools);
778 if (imap == NULL)
Tim Peters4e9afdc2001-05-03 23:54:49 +0000779 return NULL;
Guido van Rossumc1f779c2007-07-03 08:25:58 +0000780 result = PyObject_Call(imap, args, NULL);
781 Py_DECREF(imap);
Tim Peters4e9afdc2001-05-03 23:54:49 +0000782 return result;
Guido van Rossum12d12c51993-10-26 17:58:25 +0000783}
784
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000785PyDoc_STRVAR(map_doc,
Guido van Rossumc1f779c2007-07-03 08:25:58 +0000786"map(function, iterable[, iterable, ...]) -> iterator\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000787\n\
Guido van Rossumc1f779c2007-07-03 08:25:58 +0000788Return an iterator yielding the results of applying the function to the\n\
789items of the argument iterables(s). If more than one iterable is given,\n\
790the function is called with an argument list consisting of the\n\
791corresponding item of each iterable, until an iterable is exhausted.\n\
792If the function is None, 'lambda *a: a' is assumed.\n\
793(This is identical to itertools.imap().)");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000794
795
Guido van Rossum79f25d91997-04-29 20:08:16 +0000796static PyObject *
Georg Brandla18af4e2007-04-21 15:47:16 +0000797builtin_next(PyObject *self, PyObject *args)
798{
799 PyObject *it, *res;
800 PyObject *def = NULL;
801
802 if (!PyArg_UnpackTuple(args, "next", 1, 2, &it, &def))
803 return NULL;
804 if (!PyIter_Check(it)) {
805 PyErr_Format(PyExc_TypeError,
806 "%.200s object is not an iterator", it->ob_type->tp_name);
807 return NULL;
808 }
809
810 res = (*it->ob_type->tp_iternext)(it);
811 if (res == NULL) {
812 if (def) {
813 if (PyErr_Occurred() &&
814 !PyErr_ExceptionMatches(PyExc_StopIteration))
815 return NULL;
816 PyErr_Clear();
817 Py_INCREF(def);
818 return def;
819 } else if (PyErr_Occurred()) {
820 return NULL;
821 } else {
822 PyErr_SetNone(PyExc_StopIteration);
823 return NULL;
824 }
825 }
826 return res;
827}
828
829PyDoc_STRVAR(next_doc,
830"next(iterator[, default])\n\
831\n\
832Return the next item from the iterator. If default is given and the iterator\n\
833is exhausted, it is returned instead of raising StopIteration.");
834
835
836static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000837builtin_setattr(PyObject *self, PyObject *args)
Guido van Rossum33894be1992-01-27 16:53:09 +0000838{
Guido van Rossum79f25d91997-04-29 20:08:16 +0000839 PyObject *v;
840 PyObject *name;
841 PyObject *value;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000842
Raymond Hettingerea3fdf42002-12-29 16:33:45 +0000843 if (!PyArg_UnpackTuple(args, "setattr", 3, 3, &v, &name, &value))
Guido van Rossum33894be1992-01-27 16:53:09 +0000844 return NULL;
Guido van Rossum79f25d91997-04-29 20:08:16 +0000845 if (PyObject_SetAttr(v, name, value) != 0)
Guido van Rossum33894be1992-01-27 16:53:09 +0000846 return NULL;
Guido van Rossum79f25d91997-04-29 20:08:16 +0000847 Py_INCREF(Py_None);
848 return Py_None;
Guido van Rossum33894be1992-01-27 16:53:09 +0000849}
850
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000851PyDoc_STRVAR(setattr_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000852"setattr(object, name, value)\n\
853\n\
854Set a named attribute on an object; setattr(x, 'y', v) is equivalent to\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000855``x.y = v''.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000856
857
Guido van Rossum79f25d91997-04-29 20:08:16 +0000858static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000859builtin_delattr(PyObject *self, PyObject *args)
Guido van Rossum14144fc1994-08-29 12:53:40 +0000860{
Guido van Rossum79f25d91997-04-29 20:08:16 +0000861 PyObject *v;
862 PyObject *name;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000863
Raymond Hettingerea3fdf42002-12-29 16:33:45 +0000864 if (!PyArg_UnpackTuple(args, "delattr", 2, 2, &v, &name))
Guido van Rossum14144fc1994-08-29 12:53:40 +0000865 return NULL;
Guido van Rossum79f25d91997-04-29 20:08:16 +0000866 if (PyObject_SetAttr(v, name, (PyObject *)NULL) != 0)
Guido van Rossum14144fc1994-08-29 12:53:40 +0000867 return NULL;
Guido van Rossum79f25d91997-04-29 20:08:16 +0000868 Py_INCREF(Py_None);
869 return Py_None;
Guido van Rossum14144fc1994-08-29 12:53:40 +0000870}
871
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000872PyDoc_STRVAR(delattr_doc,
Guido van Rossumdf12a591998-11-23 22:13:04 +0000873"delattr(object, name)\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000874\n\
875Delete a named attribute on an object; delattr(x, 'y') is equivalent to\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000876``del x.y''.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000877
878
Guido van Rossum79f25d91997-04-29 20:08:16 +0000879static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000880builtin_hash(PyObject *self, PyObject *v)
Guido van Rossum9bfef441993-03-29 10:43:31 +0000881{
Guido van Rossum9bfef441993-03-29 10:43:31 +0000882 long x;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000883
Guido van Rossum79f25d91997-04-29 20:08:16 +0000884 x = PyObject_Hash(v);
Guido van Rossum9bfef441993-03-29 10:43:31 +0000885 if (x == -1)
886 return NULL;
Guido van Rossum79f25d91997-04-29 20:08:16 +0000887 return PyInt_FromLong(x);
Guido van Rossum9bfef441993-03-29 10:43:31 +0000888}
889
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000890PyDoc_STRVAR(hash_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000891"hash(object) -> integer\n\
892\n\
893Return a hash value for the object. Two objects with the same value have\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000894the same hash value. The reverse is not necessarily true, but likely.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000895
896
Guido van Rossum79f25d91997-04-29 20:08:16 +0000897static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000898builtin_hex(PyObject *self, PyObject *v)
Guido van Rossum006bcd41991-10-24 14:54:44 +0000899{
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000900 return PyNumber_ToBase(v, 16);
Guido van Rossum006bcd41991-10-24 14:54:44 +0000901}
902
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000903PyDoc_STRVAR(hex_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000904"hex(number) -> string\n\
905\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000906Return the hexadecimal representation of an integer or long integer.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000907
908
Guido van Rossum79f25d91997-04-29 20:08:16 +0000909static PyObject *
Guido van Rossum59d1d2b2001-04-20 19:13:02 +0000910builtin_iter(PyObject *self, PyObject *args)
911{
912 PyObject *v, *w = NULL;
913
Raymond Hettingerea3fdf42002-12-29 16:33:45 +0000914 if (!PyArg_UnpackTuple(args, "iter", 1, 2, &v, &w))
Guido van Rossum59d1d2b2001-04-20 19:13:02 +0000915 return NULL;
916 if (w == NULL)
917 return PyObject_GetIter(v);
918 if (!PyCallable_Check(v)) {
919 PyErr_SetString(PyExc_TypeError,
920 "iter(v, w): v must be callable");
921 return NULL;
922 }
923 return PyCallIter_New(v, w);
924}
925
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000926PyDoc_STRVAR(iter_doc,
Guido van Rossum59d1d2b2001-04-20 19:13:02 +0000927"iter(collection) -> iterator\n\
928iter(callable, sentinel) -> iterator\n\
929\n\
930Get an iterator from an object. In the first form, the argument must\n\
931supply its own iterator, or be a sequence.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000932In the second form, the callable is called until it returns the sentinel.");
Guido van Rossum59d1d2b2001-04-20 19:13:02 +0000933
934
935static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000936builtin_len(PyObject *self, PyObject *v)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000937{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000938 Py_ssize_t res;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000939
Jeremy Hylton03657cf2000-07-12 13:05:33 +0000940 res = PyObject_Size(v);
Guido van Rossum8ea9f4d1998-06-29 22:26:50 +0000941 if (res < 0 && PyErr_Occurred())
942 return NULL;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000943 return PyInt_FromSsize_t(res);
Guido van Rossum3f5da241990-12-20 15:06:42 +0000944}
945
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000946PyDoc_STRVAR(len_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000947"len(object) -> integer\n\
948\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000949Return the number of items of a sequence or mapping.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000950
951
Guido van Rossum79f25d91997-04-29 20:08:16 +0000952static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000953builtin_locals(PyObject *self)
Guido van Rossum872537c1995-07-07 22:43:42 +0000954{
Guido van Rossum79f25d91997-04-29 20:08:16 +0000955 PyObject *d;
Guido van Rossum872537c1995-07-07 22:43:42 +0000956
Guido van Rossum79f25d91997-04-29 20:08:16 +0000957 d = PyEval_GetLocals();
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000958 Py_XINCREF(d);
Guido van Rossum872537c1995-07-07 22:43:42 +0000959 return d;
960}
961
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000962PyDoc_STRVAR(locals_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000963"locals() -> dictionary\n\
964\n\
Raymond Hettinger69bf8f32003-01-04 02:16:22 +0000965Update and return a dictionary containing the current scope's local variables.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000966
967
Guido van Rossum79f25d91997-04-29 20:08:16 +0000968static PyObject *
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +0000969min_max(PyObject *args, PyObject *kwds, int op)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000970{
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +0000971 PyObject *v, *it, *item, *val, *maxitem, *maxval, *keyfunc=NULL;
Martin v. Löwisfd39ad42004-08-12 14:42:37 +0000972 const char *name = op == Py_LT ? "min" : "max";
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000973
Guido van Rossum79f25d91997-04-29 20:08:16 +0000974 if (PyTuple_Size(args) > 1)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000975 v = args;
Martin v. Löwisfd39ad42004-08-12 14:42:37 +0000976 else if (!PyArg_UnpackTuple(args, (char *)name, 1, 1, &v))
Guido van Rossum3f5da241990-12-20 15:06:42 +0000977 return NULL;
Tim Peters67d687a2002-04-29 21:27:32 +0000978
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +0000979 if (kwds != NULL && PyDict_Check(kwds) && PyDict_Size(kwds)) {
980 keyfunc = PyDict_GetItemString(kwds, "key");
981 if (PyDict_Size(kwds)!=1 || keyfunc == NULL) {
Georg Brandl99d7e4e2005-08-31 22:21:15 +0000982 PyErr_Format(PyExc_TypeError,
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +0000983 "%s() got an unexpected keyword argument", name);
984 return NULL;
985 }
Georg Brandl99d7e4e2005-08-31 22:21:15 +0000986 }
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +0000987
Tim Petersc3074532001-05-03 07:00:32 +0000988 it = PyObject_GetIter(v);
989 if (it == NULL)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000990 return NULL;
Tim Petersc3074532001-05-03 07:00:32 +0000991
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +0000992 maxitem = NULL; /* the result */
993 maxval = NULL; /* the value associated with the result */
Brett Cannon9e635cf2004-12-07 00:25:35 +0000994 while (( item = PyIter_Next(it) )) {
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +0000995 /* get the value from the key function */
996 if (keyfunc != NULL) {
997 val = PyObject_CallFunctionObjArgs(keyfunc, item, NULL);
998 if (val == NULL)
999 goto Fail_it_item;
1000 }
1001 /* no key function; the value is the item */
1002 else {
1003 val = item;
1004 Py_INCREF(val);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001005 }
Tim Petersc3074532001-05-03 07:00:32 +00001006
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001007 /* maximum value and item are unset; set them */
1008 if (maxval == NULL) {
1009 maxitem = item;
1010 maxval = val;
1011 }
1012 /* maximum value and item are set; update them as necessary */
Guido van Rossum2d951851994-08-29 12:52:16 +00001013 else {
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001014 int cmp = PyObject_RichCompareBool(val, maxval, op);
1015 if (cmp < 0)
1016 goto Fail_it_item_and_val;
1017 else if (cmp > 0) {
1018 Py_DECREF(maxval);
1019 Py_DECREF(maxitem);
1020 maxval = val;
1021 maxitem = item;
Guido van Rossum53451b32001-01-17 15:47:24 +00001022 }
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001023 else {
1024 Py_DECREF(item);
1025 Py_DECREF(val);
Guido van Rossumc8b6df91997-05-23 00:06:51 +00001026 }
Guido van Rossum2d951851994-08-29 12:52:16 +00001027 }
Guido van Rossum3f5da241990-12-20 15:06:42 +00001028 }
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001029 if (PyErr_Occurred())
1030 goto Fail_it;
1031 if (maxval == NULL) {
Martin v. Löwisfd39ad42004-08-12 14:42:37 +00001032 PyErr_Format(PyExc_ValueError,
1033 "%s() arg is an empty sequence", name);
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001034 assert(maxitem == NULL);
1035 }
1036 else
1037 Py_DECREF(maxval);
Tim Petersc3074532001-05-03 07:00:32 +00001038 Py_DECREF(it);
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001039 return maxitem;
1040
1041Fail_it_item_and_val:
1042 Py_DECREF(val);
1043Fail_it_item:
1044 Py_DECREF(item);
1045Fail_it:
1046 Py_XDECREF(maxval);
1047 Py_XDECREF(maxitem);
1048 Py_DECREF(it);
1049 return NULL;
Guido van Rossum3f5da241990-12-20 15:06:42 +00001050}
1051
Guido van Rossum79f25d91997-04-29 20:08:16 +00001052static PyObject *
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001053builtin_min(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001054{
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001055 return min_max(args, kwds, Py_LT);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001056}
1057
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001058PyDoc_STRVAR(min_doc,
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001059"min(iterable[, key=func]) -> value\n\
1060min(a, b, c, ...[, key=func]) -> value\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001061\n\
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001062With a single iterable argument, return its smallest item.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001063With two or more arguments, return the smallest argument.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001064
1065
Guido van Rossum79f25d91997-04-29 20:08:16 +00001066static PyObject *
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001067builtin_max(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001068{
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001069 return min_max(args, kwds, Py_GT);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001070}
1071
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001072PyDoc_STRVAR(max_doc,
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001073"max(iterable[, key=func]) -> value\n\
1074max(a, b, c, ...[, key=func]) -> value\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001075\n\
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001076With a single iterable argument, return its largest item.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001077With two or more arguments, return the largest argument.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001078
1079
Guido van Rossum79f25d91997-04-29 20:08:16 +00001080static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001081builtin_oct(PyObject *self, PyObject *v)
Guido van Rossum006bcd41991-10-24 14:54:44 +00001082{
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001083 return PyNumber_ToBase(v, 8);
Guido van Rossum006bcd41991-10-24 14:54:44 +00001084}
1085
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001086PyDoc_STRVAR(oct_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001087"oct(number) -> string\n\
1088\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001089Return the octal representation of an integer or long integer.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001090
1091
Guido van Rossum79f25d91997-04-29 20:08:16 +00001092static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001093builtin_ord(PyObject *self, PyObject* obj)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001094{
Guido van Rossum09095f32000-03-10 23:00:52 +00001095 long ord;
Martin v. Löwisd96ee902006-02-16 14:37:16 +00001096 Py_ssize_t size;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001097
Jeremy Hylton394b54d2000-04-12 21:19:47 +00001098 if (PyString_Check(obj)) {
1099 size = PyString_GET_SIZE(obj);
Andrew M. Kuchling34c20cf2000-12-20 14:36:56 +00001100 if (size == 1) {
Jeremy Hylton394b54d2000-04-12 21:19:47 +00001101 ord = (long)((unsigned char)*PyString_AS_STRING(obj));
Andrew M. Kuchling34c20cf2000-12-20 14:36:56 +00001102 return PyInt_FromLong(ord);
1103 }
Guido van Rossum98f97462007-04-13 03:31:13 +00001104 }
1105 else if (PyUnicode_Check(obj)) {
Jeremy Hylton394b54d2000-04-12 21:19:47 +00001106 size = PyUnicode_GET_SIZE(obj);
Andrew M. Kuchling34c20cf2000-12-20 14:36:56 +00001107 if (size == 1) {
Jeremy Hylton394b54d2000-04-12 21:19:47 +00001108 ord = (long)*PyUnicode_AS_UNICODE(obj);
Andrew M. Kuchling34c20cf2000-12-20 14:36:56 +00001109 return PyInt_FromLong(ord);
1110 }
Guido van Rossum8ac004e2007-07-15 13:00:05 +00001111#ifndef Py_UNICODE_WIDE
1112 if (size == 2) {
1113 /* Decode a valid surrogate pair */
1114 int c0 = PyUnicode_AS_UNICODE(obj)[0];
1115 int c1 = PyUnicode_AS_UNICODE(obj)[1];
1116 if (0xD800 <= c0 && c0 <= 0xDBFF &&
1117 0xDC00 <= c1 && c1 <= 0xDFFF) {
1118 ord = ((((c0 & 0x03FF) << 10) | (c1 & 0x03FF)) +
1119 0x00010000);
1120 return PyInt_FromLong(ord);
1121 }
1122 }
1123#endif
Guido van Rossum6f376c42007-05-24 14:31:33 +00001124 }
Guido van Rossum98f97462007-04-13 03:31:13 +00001125 else if (PyBytes_Check(obj)) {
1126 /* XXX Hopefully this is temporary */
1127 size = PyBytes_GET_SIZE(obj);
1128 if (size == 1) {
Guido van Rossumf9e91c92007-05-08 21:05:48 +00001129 ord = (long)((unsigned char)*PyBytes_AS_STRING(obj));
Guido van Rossum98f97462007-04-13 03:31:13 +00001130 return PyInt_FromLong(ord);
1131 }
1132 }
1133 else {
Jeremy Hylton394b54d2000-04-12 21:19:47 +00001134 PyErr_Format(PyExc_TypeError,
Andrew M. Kuchlingf07aad12000-12-23 14:11:28 +00001135 "ord() expected string of length 1, but " \
Jeremy Hylton394b54d2000-04-12 21:19:47 +00001136 "%.200s found", obj->ob_type->tp_name);
Guido van Rossum09095f32000-03-10 23:00:52 +00001137 return NULL;
1138 }
1139
Guido van Rossumad991772001-01-12 16:03:05 +00001140 PyErr_Format(PyExc_TypeError,
Andrew M. Kuchlingf07aad12000-12-23 14:11:28 +00001141 "ord() expected a character, "
Martin v. Löwisd96ee902006-02-16 14:37:16 +00001142 "but string of length %zd found",
Jeremy Hylton394b54d2000-04-12 21:19:47 +00001143 size);
1144 return NULL;
Guido van Rossum3f5da241990-12-20 15:06:42 +00001145}
1146
Guido van Rossum307fa8c2007-07-16 20:46:27 +00001147PyDoc_VAR(ord_doc) = PyDoc_STR(
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001148"ord(c) -> integer\n\
1149\n\
Guido van Rossum8ac004e2007-07-15 13:00:05 +00001150Return the integer ordinal of a one-character string."
Guido van Rossum307fa8c2007-07-16 20:46:27 +00001151)
Guido van Rossum8ac004e2007-07-15 13:00:05 +00001152#ifndef Py_UNICODE_WIDE
Guido van Rossum307fa8c2007-07-16 20:46:27 +00001153PyDoc_STR(
Guido van Rossum8ac004e2007-07-15 13:00:05 +00001154"\nA valid surrogate pair is also accepted."
Guido van Rossum307fa8c2007-07-16 20:46:27 +00001155)
Guido van Rossum8ac004e2007-07-15 13:00:05 +00001156#endif
Guido van Rossum307fa8c2007-07-16 20:46:27 +00001157;
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001158
1159
Guido van Rossum79f25d91997-04-29 20:08:16 +00001160static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001161builtin_pow(PyObject *self, PyObject *args)
Guido van Rossum6a00cd81995-01-07 12:39:01 +00001162{
Guido van Rossum09df08a1998-05-22 00:51:39 +00001163 PyObject *v, *w, *z = Py_None;
Guido van Rossum6a00cd81995-01-07 12:39:01 +00001164
Raymond Hettingerea3fdf42002-12-29 16:33:45 +00001165 if (!PyArg_UnpackTuple(args, "pow", 2, 3, &v, &w, &z))
Guido van Rossum6a00cd81995-01-07 12:39:01 +00001166 return NULL;
Guido van Rossum09df08a1998-05-22 00:51:39 +00001167 return PyNumber_Power(v, w, z);
Guido van Rossumd4905451991-05-05 20:00:36 +00001168}
1169
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001170PyDoc_STRVAR(pow_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001171"pow(x, y[, z]) -> number\n\
1172\n\
1173With two arguments, equivalent to x**y. With three arguments,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001174equivalent to (x**y) % z, but may be more efficient (e.g. for longs).");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001175
1176
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001177
Guido van Rossum34343512006-11-30 22:13:52 +00001178static PyObject *
1179builtin_print(PyObject *self, PyObject *args, PyObject *kwds)
1180{
1181 static char *kwlist[] = {"sep", "end", "file", 0};
Georg Brandl257d3d92007-02-26 10:35:10 +00001182 static PyObject *dummy_args;
Guido van Rossum34343512006-11-30 22:13:52 +00001183 PyObject *sep = NULL, *end = NULL, *file = NULL;
1184 int i, err;
1185
Georg Brandl257d3d92007-02-26 10:35:10 +00001186 if (dummy_args == NULL) {
1187 if (!(dummy_args = PyTuple_New(0)))
1188 return NULL;
1189 }
Georg Brandl88fc6642007-02-09 21:28:07 +00001190 if (!PyArg_ParseTupleAndKeywords(dummy_args, kwds, "|OOO:print",
Guido van Rossum34343512006-11-30 22:13:52 +00001191 kwlist, &sep, &end, &file))
1192 return NULL;
1193 if (file == NULL || file == Py_None)
1194 file = PySys_GetObject("stdout");
1195
Neal Norwitz6ea45d32007-08-26 04:19:43 +00001196 if (sep && sep != Py_None && !PyUnicode_Check(sep)) {
Georg Brandl16f3e032006-11-30 22:46:03 +00001197 PyErr_Format(PyExc_TypeError,
Neal Norwitz6ea45d32007-08-26 04:19:43 +00001198 "sep must be None or a string, not %.200s",
Georg Brandl16f3e032006-11-30 22:46:03 +00001199 sep->ob_type->tp_name);
1200 return NULL;
1201 }
Neal Norwitz6ea45d32007-08-26 04:19:43 +00001202 if (end && end != Py_None && !PyUnicode_Check(end)) {
Georg Brandl16f3e032006-11-30 22:46:03 +00001203 PyErr_Format(PyExc_TypeError,
Neal Norwitz6ea45d32007-08-26 04:19:43 +00001204 "end must be None or a string, not %.200s",
Georg Brandl16f3e032006-11-30 22:46:03 +00001205 end->ob_type->tp_name);
1206 return NULL;
1207 }
Guido van Rossum34343512006-11-30 22:13:52 +00001208
1209 for (i = 0; i < PyTuple_Size(args); i++) {
1210 if (i > 0) {
1211 if (sep == NULL || sep == Py_None)
1212 err = PyFile_WriteString(" ", file);
1213 else
1214 err = PyFile_WriteObject(sep, file,
1215 Py_PRINT_RAW);
1216 if (err)
1217 return NULL;
1218 }
1219 err = PyFile_WriteObject(PyTuple_GetItem(args, i), file,
1220 Py_PRINT_RAW);
1221 if (err)
1222 return NULL;
1223 }
1224
1225 if (end == NULL || end == Py_None)
1226 err = PyFile_WriteString("\n", file);
1227 else
1228 err = PyFile_WriteObject(end, file, Py_PRINT_RAW);
1229 if (err)
1230 return NULL;
1231
1232 Py_RETURN_NONE;
1233}
1234
1235PyDoc_STRVAR(print_doc,
Guido van Rossum452bf512007-02-09 05:32:43 +00001236"print(value, ..., file=None, sep=' ', end='\\n')\n\
Guido van Rossum34343512006-11-30 22:13:52 +00001237\n\
1238Prints the values to a stream, or to sys.stdout by default.\n\
1239Optional keyword arguments:\n\
1240file: a file-like object (stream); defaults to the current sys.stdout.\n\
1241sep: string inserted between values, default a space.\n\
1242end: string appended after the last value, default a newline.");
1243
1244
Guido van Rossuma88a0332007-02-26 16:59:55 +00001245static PyObject *
1246builtin_input(PyObject *self, PyObject *args)
1247{
Guido van Rossumeba76962007-05-27 09:13:28 +00001248 PyObject *promptarg = NULL;
Guido van Rossuma88a0332007-02-26 16:59:55 +00001249 PyObject *fin = PySys_GetObject("stdin");
1250 PyObject *fout = PySys_GetObject("stdout");
Guido van Rossumeba76962007-05-27 09:13:28 +00001251 PyObject *ferr = PySys_GetObject("stderr");
1252 PyObject *tmp;
1253 long fd;
1254 int tty;
Guido van Rossuma88a0332007-02-26 16:59:55 +00001255
Guido van Rossumeba76962007-05-27 09:13:28 +00001256 /* Parse arguments */
1257 if (!PyArg_UnpackTuple(args, "input", 0, 1, &promptarg))
Guido van Rossuma88a0332007-02-26 16:59:55 +00001258 return NULL;
1259
Guido van Rossumeba76962007-05-27 09:13:28 +00001260 /* Check that stdin/out/err are intact */
Guido van Rossuma88a0332007-02-26 16:59:55 +00001261 if (fin == NULL) {
Guido van Rossumeba76962007-05-27 09:13:28 +00001262 PyErr_SetString(PyExc_RuntimeError,
1263 "input(): lost sys.stdin");
Guido van Rossuma88a0332007-02-26 16:59:55 +00001264 return NULL;
1265 }
1266 if (fout == NULL) {
Guido van Rossumeba76962007-05-27 09:13:28 +00001267 PyErr_SetString(PyExc_RuntimeError,
1268 "input(): lost sys.stdout");
Guido van Rossuma88a0332007-02-26 16:59:55 +00001269 return NULL;
1270 }
Guido van Rossumeba76962007-05-27 09:13:28 +00001271 if (ferr == NULL) {
1272 PyErr_SetString(PyExc_RuntimeError,
1273 "input(): lost sys.stderr");
1274 return NULL;
1275 }
1276
1277 /* First of all, flush stderr */
1278 tmp = PyObject_CallMethod(ferr, "flush", "");
1279 if (tmp == NULL)
Guido van Rossumc1f779c2007-07-03 08:25:58 +00001280 PyErr_Clear();
1281 else
1282 Py_DECREF(tmp);
Guido van Rossumeba76962007-05-27 09:13:28 +00001283
1284 /* We should only use (GNU) readline if Python's sys.stdin and
1285 sys.stdout are the same as C's stdin and stdout, because we
1286 need to pass it those. */
1287 tmp = PyObject_CallMethod(fin, "fileno", "");
Guido van Rossumc1f779c2007-07-03 08:25:58 +00001288 if (tmp == NULL) {
1289 PyErr_Clear();
1290 tty = 0;
1291 }
1292 else {
Guido van Rossumeba76962007-05-27 09:13:28 +00001293 fd = PyInt_AsLong(tmp);
1294 Py_DECREF(tmp);
1295 if (fd < 0 && PyErr_Occurred())
1296 return NULL;
Guido van Rossumc1f779c2007-07-03 08:25:58 +00001297 tty = fd == fileno(stdin) && isatty(fd);
1298 }
1299 if (tty) {
1300 tmp = PyObject_CallMethod(fout, "fileno", "");
1301 if (tmp == NULL)
1302 PyErr_Clear();
1303 else {
1304 fd = PyInt_AsLong(tmp);
1305 Py_DECREF(tmp);
1306 if (fd < 0 && PyErr_Occurred())
1307 return NULL;
1308 tty = fd == fileno(stdout) && isatty(fd);
1309 }
Guido van Rossumeba76962007-05-27 09:13:28 +00001310 }
1311
1312 /* If we're interactive, use (GNU) readline */
1313 if (tty) {
Guido van Rossuma88a0332007-02-26 16:59:55 +00001314 PyObject *po;
1315 char *prompt;
1316 char *s;
1317 PyObject *result;
Guido van Rossumeba76962007-05-27 09:13:28 +00001318 tmp = PyObject_CallMethod(fout, "flush", "");
1319 if (tmp == NULL)
Guido van Rossumc1f779c2007-07-03 08:25:58 +00001320 PyErr_Clear();
1321 else
1322 Py_DECREF(tmp);
Guido van Rossumeba76962007-05-27 09:13:28 +00001323 if (promptarg != NULL) {
1324 po = PyObject_Str(promptarg);
Guido van Rossuma88a0332007-02-26 16:59:55 +00001325 if (po == NULL)
1326 return NULL;
1327 prompt = PyString_AsString(po);
Guido van Rossumeba76962007-05-27 09:13:28 +00001328 if (prompt == NULL) {
1329 Py_DECREF(po);
Guido van Rossuma88a0332007-02-26 16:59:55 +00001330 return NULL;
Guido van Rossumeba76962007-05-27 09:13:28 +00001331 }
Guido van Rossuma88a0332007-02-26 16:59:55 +00001332 }
1333 else {
1334 po = NULL;
1335 prompt = "";
1336 }
Guido van Rossumeba76962007-05-27 09:13:28 +00001337 s = PyOS_Readline(stdin, stdout, prompt);
Guido van Rossuma88a0332007-02-26 16:59:55 +00001338 Py_XDECREF(po);
1339 if (s == NULL) {
1340 if (!PyErr_Occurred())
1341 PyErr_SetNone(PyExc_KeyboardInterrupt);
1342 return NULL;
1343 }
1344 if (*s == '\0') {
1345 PyErr_SetNone(PyExc_EOFError);
1346 result = NULL;
1347 }
1348 else { /* strip trailing '\n' */
1349 size_t len = strlen(s);
1350 if (len > PY_SSIZE_T_MAX) {
1351 PyErr_SetString(PyExc_OverflowError,
1352 "input: input too long");
1353 result = NULL;
1354 }
1355 else {
Neal Norwitz6ea45d32007-08-26 04:19:43 +00001356 result = PyUnicode_FromStringAndSize(s, len-1);
Guido van Rossuma88a0332007-02-26 16:59:55 +00001357 }
1358 }
1359 PyMem_FREE(s);
1360 return result;
1361 }
Guido van Rossumeba76962007-05-27 09:13:28 +00001362
1363 /* Fallback if we're not interactive */
1364 if (promptarg != NULL) {
1365 if (PyFile_WriteObject(promptarg, fout, Py_PRINT_RAW) != 0)
Guido van Rossuma88a0332007-02-26 16:59:55 +00001366 return NULL;
1367 }
Guido van Rossumeba76962007-05-27 09:13:28 +00001368 tmp = PyObject_CallMethod(fout, "flush", "");
1369 if (tmp == NULL)
Guido van Rossumc1f779c2007-07-03 08:25:58 +00001370 PyErr_Clear();
1371 else
1372 Py_DECREF(tmp);
Guido van Rossuma88a0332007-02-26 16:59:55 +00001373 return PyFile_GetLine(fin, -1);
1374}
1375
1376PyDoc_STRVAR(input_doc,
1377"input([prompt]) -> string\n\
1378\n\
1379Read a string from standard input. The trailing newline is stripped.\n\
1380If the user hits EOF (Unix: Ctl-D, Windows: Ctl-Z+Return), raise EOFError.\n\
1381On Unix, GNU readline is used if enabled. The prompt string, if given,\n\
1382is printed without a trailing newline before reading.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001383
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001384
Guido van Rossum79f25d91997-04-29 20:08:16 +00001385static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001386builtin_repr(PyObject *self, PyObject *v)
Guido van Rossumc89705d1992-11-26 08:54:07 +00001387{
Guido van Rossum79f25d91997-04-29 20:08:16 +00001388 return PyObject_Repr(v);
Guido van Rossumc89705d1992-11-26 08:54:07 +00001389}
1390
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001391PyDoc_STRVAR(repr_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001392"repr(object) -> string\n\
1393\n\
1394Return the canonical string representation of the object.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001395For most object types, eval(repr(object)) == object.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001396
1397
Guido van Rossum79f25d91997-04-29 20:08:16 +00001398static PyObject *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001399builtin_round(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum9e51f9b1993-02-12 16:29:05 +00001400{
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001401#define UNDEF_NDIGITS (-0x7fffffff) /* Unlikely ndigits value */
1402 static PyObject *round_str = NULL;
1403 int ndigits = UNDEF_NDIGITS;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001404 static char *kwlist[] = {"number", "ndigits", 0};
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001405 PyObject *number, *round;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001406
Alex Martelliae211f92007-08-22 23:21:33 +00001407 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|i:round",
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001408 kwlist, &number, &ndigits))
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001409 return NULL;
Alex Martelliae211f92007-08-22 23:21:33 +00001410
Guido van Rossum15d3d042007-08-24 02:02:45 +00001411 if (Py_Type(number)->tp_dict == NULL) {
1412 if (PyType_Ready(Py_Type(number)) < 0)
1413 return NULL;
1414 }
1415
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001416 if (round_str == NULL) {
1417 round_str = PyUnicode_FromString("__round__");
1418 if (round_str == NULL)
Alex Martelliae211f92007-08-22 23:21:33 +00001419 return NULL;
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001420 }
1421
1422 round = _PyType_Lookup(Py_Type(number), round_str);
1423 if (round == NULL) {
1424 PyErr_Format(PyExc_TypeError,
1425 "type %.100s doesn't define __round__ method",
1426 Py_Type(number)->tp_name);
Alex Martelliae211f92007-08-22 23:21:33 +00001427 return NULL;
1428 }
1429
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001430 if (ndigits == UNDEF_NDIGITS)
1431 return PyObject_CallFunction(round, "O", number);
Guido van Rossum9e51f9b1993-02-12 16:29:05 +00001432 else
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001433 return PyObject_CallFunction(round, "Oi", number, ndigits);
1434#undef UNDEF_NDIGITS
Guido van Rossum9e51f9b1993-02-12 16:29:05 +00001435}
1436
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001437PyDoc_STRVAR(round_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001438"round(number[, ndigits]) -> floating point number\n\
1439\n\
1440Round a number to a given precision in decimal digits (default 0 digits).\n\
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001441This returns an int when called with one argument, otherwise a float.\n\
1442Precision may be negative.");
1443
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001444
Raymond Hettinger64958a12003-12-17 20:43:33 +00001445static PyObject *
1446builtin_sorted(PyObject *self, PyObject *args, PyObject *kwds)
1447{
1448 PyObject *newlist, *v, *seq, *compare=NULL, *keyfunc=NULL, *newargs;
1449 PyObject *callable;
Martin v. Löwis15e62742006-02-27 16:46:16 +00001450 static char *kwlist[] = {"iterable", "cmp", "key", "reverse", 0};
Neal Norwitz6f0d4792005-12-15 06:40:36 +00001451 int reverse;
Raymond Hettinger64958a12003-12-17 20:43:33 +00001452
Neal Norwitz6f0d4792005-12-15 06:40:36 +00001453 /* args 1-4 should match listsort in Objects/listobject.c */
Armin Rigo71d7e702005-09-20 18:13:03 +00001454 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|OOi:sorted",
1455 kwlist, &seq, &compare, &keyfunc, &reverse))
1456 return NULL;
Raymond Hettinger64958a12003-12-17 20:43:33 +00001457
1458 newlist = PySequence_List(seq);
1459 if (newlist == NULL)
1460 return NULL;
1461
1462 callable = PyObject_GetAttrString(newlist, "sort");
1463 if (callable == NULL) {
1464 Py_DECREF(newlist);
1465 return NULL;
1466 }
Georg Brandl99d7e4e2005-08-31 22:21:15 +00001467
Raymond Hettinger64958a12003-12-17 20:43:33 +00001468 newargs = PyTuple_GetSlice(args, 1, 4);
1469 if (newargs == NULL) {
1470 Py_DECREF(newlist);
1471 Py_DECREF(callable);
1472 return NULL;
1473 }
1474
1475 v = PyObject_Call(callable, newargs, kwds);
1476 Py_DECREF(newargs);
1477 Py_DECREF(callable);
1478 if (v == NULL) {
1479 Py_DECREF(newlist);
1480 return NULL;
1481 }
1482 Py_DECREF(v);
1483 return newlist;
1484}
1485
1486PyDoc_STRVAR(sorted_doc,
1487"sorted(iterable, cmp=None, key=None, reverse=False) --> new sorted list");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001488
Guido van Rossum79f25d91997-04-29 20:08:16 +00001489static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001490builtin_vars(PyObject *self, PyObject *args)
Guido van Rossum2d951851994-08-29 12:52:16 +00001491{
Guido van Rossum79f25d91997-04-29 20:08:16 +00001492 PyObject *v = NULL;
1493 PyObject *d;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001494
Raymond Hettingerea3fdf42002-12-29 16:33:45 +00001495 if (!PyArg_UnpackTuple(args, "vars", 0, 1, &v))
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001496 return NULL;
Guido van Rossum2d951851994-08-29 12:52:16 +00001497 if (v == NULL) {
Guido van Rossum79f25d91997-04-29 20:08:16 +00001498 d = PyEval_GetLocals();
Guido van Rossum53bb7ff1995-07-26 16:26:31 +00001499 if (d == NULL) {
Guido van Rossum79f25d91997-04-29 20:08:16 +00001500 if (!PyErr_Occurred())
1501 PyErr_SetString(PyExc_SystemError,
Alex Martellia9b9c9f2003-04-23 13:34:35 +00001502 "vars(): no locals!?");
Guido van Rossum53bb7ff1995-07-26 16:26:31 +00001503 }
1504 else
Guido van Rossum79f25d91997-04-29 20:08:16 +00001505 Py_INCREF(d);
Guido van Rossum2d951851994-08-29 12:52:16 +00001506 }
1507 else {
Guido van Rossum79f25d91997-04-29 20:08:16 +00001508 d = PyObject_GetAttrString(v, "__dict__");
Guido van Rossum2d951851994-08-29 12:52:16 +00001509 if (d == NULL) {
Guido van Rossum79f25d91997-04-29 20:08:16 +00001510 PyErr_SetString(PyExc_TypeError,
Guido van Rossum2d951851994-08-29 12:52:16 +00001511 "vars() argument must have __dict__ attribute");
1512 return NULL;
1513 }
1514 }
1515 return d;
1516}
1517
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001518PyDoc_STRVAR(vars_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001519"vars([object]) -> dictionary\n\
1520\n\
1521Without arguments, equivalent to locals().\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001522With an argument, equivalent to object.__dict__.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001523
Alex Martelli86d8b342007-08-22 22:39:42 +00001524static PyObject *
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001525builtin_trunc(PyObject *self, PyObject *number)
Alex Martelli86d8b342007-08-22 22:39:42 +00001526{
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001527 static PyObject *trunc_str = NULL;
1528 PyObject *trunc;
1529
Guido van Rossum15d3d042007-08-24 02:02:45 +00001530 if (Py_Type(number)->tp_dict == NULL) {
1531 if (PyType_Ready(Py_Type(number)) < 0)
1532 return NULL;
1533 }
1534
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001535 if (trunc_str == NULL) {
1536 trunc_str = PyUnicode_FromString("__trunc__");
1537 if (trunc_str == NULL)
1538 return NULL;
1539 }
1540
1541 trunc = _PyType_Lookup(Py_Type(number), trunc_str);
1542 if (trunc == NULL) {
1543 PyErr_Format(PyExc_TypeError,
1544 "type %.100s doesn't define __trunc__ method",
1545 Py_Type(number)->tp_name);
Alex Martelli86d8b342007-08-22 22:39:42 +00001546 return NULL;
1547 }
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001548 return PyObject_CallFunction(trunc, "O", number);
Alex Martelli86d8b342007-08-22 22:39:42 +00001549}
1550
1551PyDoc_STRVAR(trunc_doc,
1552"trunc(Real) -> Integral\n\
1553\n\
1554returns the integral closest to x between 0 and x.");
1555
1556
Alex Martellia70b1912003-04-22 08:12:33 +00001557
1558static PyObject*
1559builtin_sum(PyObject *self, PyObject *args)
1560{
1561 PyObject *seq;
1562 PyObject *result = NULL;
1563 PyObject *temp, *item, *iter;
1564
Raymond Hettinger5cf63942003-10-25 06:41:37 +00001565 if (!PyArg_UnpackTuple(args, "sum", 1, 2, &seq, &result))
Alex Martellia70b1912003-04-22 08:12:33 +00001566 return NULL;
1567
1568 iter = PyObject_GetIter(seq);
1569 if (iter == NULL)
1570 return NULL;
1571
1572 if (result == NULL) {
1573 result = PyInt_FromLong(0);
1574 if (result == NULL) {
1575 Py_DECREF(iter);
1576 return NULL;
1577 }
1578 } else {
1579 /* reject string values for 'start' parameter */
1580 if (PyObject_TypeCheck(result, &PyBaseString_Type)) {
1581 PyErr_SetString(PyExc_TypeError,
Alex Martellia9b9c9f2003-04-23 13:34:35 +00001582 "sum() can't sum strings [use ''.join(seq) instead]");
Alex Martellia70b1912003-04-22 08:12:33 +00001583 Py_DECREF(iter);
1584 return NULL;
1585 }
Alex Martelli41c9f882003-04-22 09:24:48 +00001586 Py_INCREF(result);
Alex Martellia70b1912003-04-22 08:12:33 +00001587 }
1588
1589 for(;;) {
1590 item = PyIter_Next(iter);
1591 if (item == NULL) {
1592 /* error, or end-of-sequence */
1593 if (PyErr_Occurred()) {
1594 Py_DECREF(result);
1595 result = NULL;
1596 }
1597 break;
1598 }
Alex Martellia253e182003-10-25 23:24:14 +00001599 temp = PyNumber_Add(result, item);
Alex Martellia70b1912003-04-22 08:12:33 +00001600 Py_DECREF(result);
1601 Py_DECREF(item);
1602 result = temp;
1603 if (result == NULL)
1604 break;
1605 }
1606 Py_DECREF(iter);
1607 return result;
1608}
1609
1610PyDoc_STRVAR(sum_doc,
Thomas Wouters89f507f2006-12-13 04:49:30 +00001611"sum(sequence[, start]) -> value\n\
Alex Martellia70b1912003-04-22 08:12:33 +00001612\n\
1613Returns the sum of a sequence of numbers (NOT strings) plus the value\n\
Thomas Wouters89f507f2006-12-13 04:49:30 +00001614of parameter 'start' (which defaults to 0). When the sequence is\n\
1615empty, returns start.");
Alex Martellia70b1912003-04-22 08:12:33 +00001616
1617
Barry Warsawcde8b1b1997-08-22 21:14:38 +00001618static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001619builtin_isinstance(PyObject *self, PyObject *args)
Barry Warsawcde8b1b1997-08-22 21:14:38 +00001620{
1621 PyObject *inst;
1622 PyObject *cls;
Guido van Rossum823649d2001-03-21 18:40:58 +00001623 int retval;
Barry Warsawcde8b1b1997-08-22 21:14:38 +00001624
Raymond Hettingerea3fdf42002-12-29 16:33:45 +00001625 if (!PyArg_UnpackTuple(args, "isinstance", 2, 2, &inst, &cls))
Barry Warsawcde8b1b1997-08-22 21:14:38 +00001626 return NULL;
Guido van Rossumf5dd9141997-12-02 19:11:45 +00001627
Guido van Rossum823649d2001-03-21 18:40:58 +00001628 retval = PyObject_IsInstance(inst, cls);
1629 if (retval < 0)
Guido van Rossumad991772001-01-12 16:03:05 +00001630 return NULL;
Guido van Rossum77f6a652002-04-03 22:41:51 +00001631 return PyBool_FromLong(retval);
Barry Warsawcde8b1b1997-08-22 21:14:38 +00001632}
1633
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001634PyDoc_STRVAR(isinstance_doc,
Guido van Rossum77f6a652002-04-03 22:41:51 +00001635"isinstance(object, class-or-type-or-tuple) -> bool\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001636\n\
1637Return whether an object is an instance of a class or of a subclass thereof.\n\
Guido van Rossum03290ec2001-10-07 20:54:12 +00001638With a type as second argument, return whether that is the object's type.\n\
1639The form using a tuple, isinstance(x, (A, B, ...)), is a shortcut for\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001640isinstance(x, A) or isinstance(x, B) or ... (etc.).");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001641
Barry Warsawcde8b1b1997-08-22 21:14:38 +00001642
1643static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001644builtin_issubclass(PyObject *self, PyObject *args)
Barry Warsawcde8b1b1997-08-22 21:14:38 +00001645{
1646 PyObject *derived;
1647 PyObject *cls;
1648 int retval;
1649
Raymond Hettingerea3fdf42002-12-29 16:33:45 +00001650 if (!PyArg_UnpackTuple(args, "issubclass", 2, 2, &derived, &cls))
Barry Warsawcde8b1b1997-08-22 21:14:38 +00001651 return NULL;
Guido van Rossum668213d1999-06-16 17:28:37 +00001652
Guido van Rossum823649d2001-03-21 18:40:58 +00001653 retval = PyObject_IsSubclass(derived, cls);
1654 if (retval < 0)
1655 return NULL;
Guido van Rossum77f6a652002-04-03 22:41:51 +00001656 return PyBool_FromLong(retval);
Barry Warsawcde8b1b1997-08-22 21:14:38 +00001657}
1658
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001659PyDoc_STRVAR(issubclass_doc,
Guido van Rossum77f6a652002-04-03 22:41:51 +00001660"issubclass(C, B) -> bool\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001661\n\
Walter Dörwaldd9a6ad32002-12-12 16:41:44 +00001662Return whether class C is a subclass (i.e., a derived class) of class B.\n\
1663When using a tuple as the second argument issubclass(X, (A, B, ...)),\n\
1664is a shortcut for issubclass(X, A) or issubclass(X, B) or ... (etc.).");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001665
Barry Warsawcde8b1b1997-08-22 21:14:38 +00001666
Barry Warsawbd599b52000-08-03 15:45:29 +00001667static PyObject*
1668builtin_zip(PyObject *self, PyObject *args)
1669{
Guido van Rossumb65fb332006-08-25 23:26:40 +00001670 /* args must be a tuple */
1671 assert(PyTuple_Check(args));
Barry Warsawbd599b52000-08-03 15:45:29 +00001672
Guido van Rossumb65fb332006-08-25 23:26:40 +00001673 return _PyZip_CreateIter(args);
Barry Warsawbd599b52000-08-03 15:45:29 +00001674}
1675
1676
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001677PyDoc_STRVAR(zip_doc,
Guido van Rossum801f0d72006-08-24 19:48:10 +00001678"zip(it1 [, it2 [...]]) -> iter([(it1[0], it2[0] ...), ...])\n\
Barry Warsawbd599b52000-08-03 15:45:29 +00001679\n\
Guido van Rossum801f0d72006-08-24 19:48:10 +00001680Return an iterator yielding tuples, where each tuple contains the\n\
1681corresponding element from each of the argument iterables.\n\
1682The returned iterator ends when the shortest argument iterable is exhausted.\n\
Guido van Rossumc1f779c2007-07-03 08:25:58 +00001683(This is identical to itertools.izip().)");
Barry Warsawbd599b52000-08-03 15:45:29 +00001684
1685
Guido van Rossum79f25d91997-04-29 20:08:16 +00001686static PyMethodDef builtin_methods[] = {
Guido van Rossum52cc1d82007-03-18 15:41:51 +00001687 {"__build_class__", (PyCFunction)builtin___build_class__,
1688 METH_VARARGS | METH_KEYWORDS, build_class_doc},
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001689 {"__import__", (PyCFunction)builtin___import__, METH_VARARGS | METH_KEYWORDS, import_doc},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001690 {"abs", builtin_abs, METH_O, abs_doc},
Raymond Hettinger96229b12005-03-11 06:49:40 +00001691 {"all", builtin_all, METH_O, all_doc},
1692 {"any", builtin_any, METH_O, any_doc},
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001693 {"bin", builtin_bin, METH_O, bin_doc},
Neal Norwitzc2550c72007-08-31 04:17:51 +00001694 {"chr", builtin_chr, METH_VARARGS, chr_doc},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001695 {"cmp", builtin_cmp, METH_VARARGS, cmp_doc},
Guido van Rossumd8faa362007-04-27 19:54:29 +00001696 {"compile", (PyCFunction)builtin_compile, METH_VARARGS | METH_KEYWORDS, compile_doc},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001697 {"delattr", builtin_delattr, METH_VARARGS, delattr_doc},
1698 {"dir", builtin_dir, METH_VARARGS, dir_doc},
1699 {"divmod", builtin_divmod, METH_VARARGS, divmod_doc},
1700 {"eval", builtin_eval, METH_VARARGS, eval_doc},
Georg Brandl7cae87c2006-09-06 06:51:57 +00001701 {"exec", builtin_exec, METH_VARARGS, exec_doc},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001702 {"filter", builtin_filter, METH_VARARGS, filter_doc},
Eric Smith8c663262007-08-25 02:26:07 +00001703 {"format", builtin_format, METH_VARARGS, format_doc},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001704 {"getattr", builtin_getattr, METH_VARARGS, getattr_doc},
1705 {"globals", (PyCFunction)builtin_globals, METH_NOARGS, globals_doc},
1706 {"hasattr", builtin_hasattr, METH_VARARGS, hasattr_doc},
1707 {"hash", builtin_hash, METH_O, hash_doc},
1708 {"hex", builtin_hex, METH_O, hex_doc},
1709 {"id", builtin_id, METH_O, id_doc},
Guido van Rossuma88a0332007-02-26 16:59:55 +00001710 {"input", builtin_input, METH_VARARGS, input_doc},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001711 {"isinstance", builtin_isinstance, METH_VARARGS, isinstance_doc},
1712 {"issubclass", builtin_issubclass, METH_VARARGS, issubclass_doc},
1713 {"iter", builtin_iter, METH_VARARGS, iter_doc},
1714 {"len", builtin_len, METH_O, len_doc},
1715 {"locals", (PyCFunction)builtin_locals, METH_NOARGS, locals_doc},
1716 {"map", builtin_map, METH_VARARGS, map_doc},
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001717 {"max", (PyCFunction)builtin_max, METH_VARARGS | METH_KEYWORDS, max_doc},
1718 {"min", (PyCFunction)builtin_min, METH_VARARGS | METH_KEYWORDS, min_doc},
Georg Brandla18af4e2007-04-21 15:47:16 +00001719 {"next", (PyCFunction)builtin_next, METH_VARARGS, next_doc},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001720 {"oct", builtin_oct, METH_O, oct_doc},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001721 {"ord", builtin_ord, METH_O, ord_doc},
1722 {"pow", builtin_pow, METH_VARARGS, pow_doc},
Guido van Rossum452bf512007-02-09 05:32:43 +00001723 {"print", (PyCFunction)builtin_print, METH_VARARGS | METH_KEYWORDS, print_doc},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001724 {"repr", builtin_repr, METH_O, repr_doc},
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001725 {"round", (PyCFunction)builtin_round, METH_VARARGS | METH_KEYWORDS, round_doc},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001726 {"setattr", builtin_setattr, METH_VARARGS, setattr_doc},
Raymond Hettinger64958a12003-12-17 20:43:33 +00001727 {"sorted", (PyCFunction)builtin_sorted, METH_VARARGS | METH_KEYWORDS, sorted_doc},
Alex Martellia70b1912003-04-22 08:12:33 +00001728 {"sum", builtin_sum, METH_VARARGS, sum_doc},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001729 {"vars", builtin_vars, METH_VARARGS, vars_doc},
Alex Martelli86d8b342007-08-22 22:39:42 +00001730 {"trunc", builtin_trunc, METH_O, trunc_doc},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001731 {"zip", builtin_zip, METH_VARARGS, zip_doc},
Guido van Rossumc02e15c1991-12-16 13:03:00 +00001732 {NULL, NULL},
Guido van Rossum3f5da241990-12-20 15:06:42 +00001733};
1734
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001735PyDoc_STRVAR(builtin_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001736"Built-in functions, exceptions, and other objects.\n\
1737\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001738Noteworthy: None is the `nil' object; Ellipsis represents `...' in slices.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001739
Guido van Rossum25ce5661997-08-02 03:10:38 +00001740PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001741_PyBuiltin_Init(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +00001742{
Fred Drake5550de32000-06-20 04:54:19 +00001743 PyObject *mod, *dict, *debug;
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001744 mod = Py_InitModule4("__builtin__", builtin_methods,
1745 builtin_doc, (PyObject *)NULL,
1746 PYTHON_API_VERSION);
Guido van Rossum25ce5661997-08-02 03:10:38 +00001747 if (mod == NULL)
1748 return NULL;
1749 dict = PyModule_GetDict(mod);
Tim Peters4b7625e2001-09-13 21:37:17 +00001750
Tim Peters7571a0f2003-03-23 17:52:28 +00001751#ifdef Py_TRACE_REFS
1752 /* __builtin__ exposes a number of statically allocated objects
1753 * that, before this code was added in 2.3, never showed up in
1754 * the list of "all objects" maintained by Py_TRACE_REFS. As a
1755 * result, programs leaking references to None and False (etc)
1756 * couldn't be diagnosed by examining sys.getobjects(0).
1757 */
1758#define ADD_TO_ALL(OBJECT) _Py_AddToAllObjects((PyObject *)(OBJECT), 0)
1759#else
1760#define ADD_TO_ALL(OBJECT) (void)0
1761#endif
1762
Tim Peters4b7625e2001-09-13 21:37:17 +00001763#define SETBUILTIN(NAME, OBJECT) \
Tim Peters7571a0f2003-03-23 17:52:28 +00001764 if (PyDict_SetItemString(dict, NAME, (PyObject *)OBJECT) < 0) \
1765 return NULL; \
1766 ADD_TO_ALL(OBJECT)
Tim Peters4b7625e2001-09-13 21:37:17 +00001767
1768 SETBUILTIN("None", Py_None);
1769 SETBUILTIN("Ellipsis", Py_Ellipsis);
1770 SETBUILTIN("NotImplemented", Py_NotImplemented);
Guido van Rossum77f6a652002-04-03 22:41:51 +00001771 SETBUILTIN("False", Py_False);
1772 SETBUILTIN("True", Py_True);
Neal Norwitz32a7e7f2002-05-31 19:58:02 +00001773 SETBUILTIN("basestring", &PyBaseString_Type);
Guido van Rossum77f6a652002-04-03 22:41:51 +00001774 SETBUILTIN("bool", &PyBool_Type);
Guido van Rossumbea18cc2002-06-14 20:41:17 +00001775 SETBUILTIN("buffer", &PyBuffer_Type);
Travis E. Oliphantb99f7622007-08-18 11:21:56 +00001776 SETBUILTIN("memoryview", &PyMemoryView_Type);
Guido van Rossum4dfe8a12006-04-22 23:28:04 +00001777 SETBUILTIN("bytes", &PyBytes_Type);
Tim Peters4b7625e2001-09-13 21:37:17 +00001778 SETBUILTIN("classmethod", &PyClassMethod_Type);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001779#ifndef WITHOUT_COMPLEX
Tim Peters4b7625e2001-09-13 21:37:17 +00001780 SETBUILTIN("complex", &PyComplex_Type);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001781#endif
Tim Petersa427a2b2001-10-29 22:25:45 +00001782 SETBUILTIN("dict", &PyDict_Type);
Tim Peters67d687a2002-04-29 21:27:32 +00001783 SETBUILTIN("enumerate", &PyEnum_Type);
Tim Peters4b7625e2001-09-13 21:37:17 +00001784 SETBUILTIN("float", &PyFloat_Type);
Raymond Hettingera690a992003-11-16 16:17:49 +00001785 SETBUILTIN("frozenset", &PyFrozenSet_Type);
Tim Peters4b7625e2001-09-13 21:37:17 +00001786 SETBUILTIN("property", &PyProperty_Type);
Guido van Rossumddefaf32007-01-14 03:31:43 +00001787 SETBUILTIN("int", &PyLong_Type);
Tim Peters4b7625e2001-09-13 21:37:17 +00001788 SETBUILTIN("list", &PyList_Type);
Tim Peters4b7625e2001-09-13 21:37:17 +00001789 SETBUILTIN("object", &PyBaseObject_Type);
Guido van Rossum805365e2007-05-07 22:24:25 +00001790 SETBUILTIN("range", &PyRange_Type);
Raymond Hettinger85c20a42003-11-06 14:06:48 +00001791 SETBUILTIN("reversed", &PyReversed_Type);
Raymond Hettingera690a992003-11-16 16:17:49 +00001792 SETBUILTIN("set", &PySet_Type);
Guido van Rossumbea18cc2002-06-14 20:41:17 +00001793 SETBUILTIN("slice", &PySlice_Type);
Tim Peters4b7625e2001-09-13 21:37:17 +00001794 SETBUILTIN("staticmethod", &PyStaticMethod_Type);
Guido van Rossum572dbf82007-04-27 23:53:51 +00001795 SETBUILTIN("str", &PyUnicode_Type);
Guido van Rossum84fc66d2007-05-03 17:18:26 +00001796 SETBUILTIN("str8", &PyString_Type);
Tim Peters4b7625e2001-09-13 21:37:17 +00001797 SETBUILTIN("super", &PySuper_Type);
1798 SETBUILTIN("tuple", &PyTuple_Type);
1799 SETBUILTIN("type", &PyType_Type);
Guido van Rossum77f6a652002-04-03 22:41:51 +00001800 debug = PyBool_FromLong(Py_OptimizeFlag == 0);
Fred Drake5550de32000-06-20 04:54:19 +00001801 if (PyDict_SetItemString(dict, "__debug__", debug) < 0) {
1802 Py_XDECREF(debug);
Guido van Rossum25ce5661997-08-02 03:10:38 +00001803 return NULL;
Fred Drake5550de32000-06-20 04:54:19 +00001804 }
1805 Py_XDECREF(debug);
Barry Warsaw757af0e1997-08-29 22:13:51 +00001806
Guido van Rossum25ce5661997-08-02 03:10:38 +00001807 return mod;
Tim Peters7571a0f2003-03-23 17:52:28 +00001808#undef ADD_TO_ALL
Tim Peters4b7625e2001-09-13 21:37:17 +00001809#undef SETBUILTIN
Guido van Rossum3f5da241990-12-20 15:06:42 +00001810}