blob: d087e9c786df60b1b7d26edc7b0a048001fecd45 [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);
Martin v. Löwis5b222132007-06-10 09:51:05 +000043 if ((!PyString_Check(name) && !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
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000278
Guido van Rossum79f25d91997-04-29 20:08:16 +0000279static PyObject *
Walter Dörwalde7efd592007-06-05 20:07:21 +0000280builtin_chr8(PyObject *self, PyObject *args)
Guido van Rossum7fcf2242007-05-04 17:43:11 +0000281{
282 long x;
283 char s[1];
284
285 if (!PyArg_ParseTuple(args, "l:chr8", &x))
286 return NULL;
287 if (x < 0 || x >= 256) {
288 PyErr_SetString(PyExc_ValueError,
289 "chr8() arg not in range(256)");
290 return NULL;
291 }
292 s[0] = (char)x;
293 return PyString_FromStringAndSize(s, 1);
294}
295
Walter Dörwalde7efd592007-06-05 20:07:21 +0000296PyDoc_STRVAR(chr8_doc,
Guido van Rossum7fcf2242007-05-04 17:43:11 +0000297"chr8(i) -> 8-bit character\n\
298\n\
299Return a string of one character with ordinal i; 0 <= i < 256.");
300
301
302static PyObject *
Walter Dörwalde7efd592007-06-05 20:07:21 +0000303builtin_chr(PyObject *self, PyObject *args)
Guido van Rossum09095f32000-03-10 23:00:52 +0000304{
305 long x;
Guido van Rossum09095f32000-03-10 23:00:52 +0000306
Walter Dörwalde7efd592007-06-05 20:07:21 +0000307 if (!PyArg_ParseTuple(args, "l:chr", &x))
Guido van Rossum09095f32000-03-10 23:00:52 +0000308 return NULL;
Fredrik Lundh0dcf67e2001-06-26 20:01:56 +0000309
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +0000310 return PyUnicode_FromOrdinal(x);
Guido van Rossum09095f32000-03-10 23:00:52 +0000311}
312
Guido van Rossum307fa8c2007-07-16 20:46:27 +0000313PyDoc_VAR(chr_doc) = PyDoc_STR(
Guido van Rossum84fc66d2007-05-03 17:18:26 +0000314"chr(i) -> Unicode character\n\
Guido van Rossum09095f32000-03-10 23:00:52 +0000315\n\
Guido van Rossum8ac004e2007-07-15 13:00:05 +0000316Return a Unicode string of one character with ordinal i; 0 <= i <= 0x10ffff."
Guido van Rossum307fa8c2007-07-16 20:46:27 +0000317)
Guido van Rossum8ac004e2007-07-15 13:00:05 +0000318#ifndef Py_UNICODE_WIDE
Guido van Rossum307fa8c2007-07-16 20:46:27 +0000319PyDoc_STR(
Guido van Rossum8ac004e2007-07-15 13:00:05 +0000320"\nIf 0x10000 <= i, a surrogate pair is returned."
Guido van Rossum307fa8c2007-07-16 20:46:27 +0000321)
Guido van Rossum8ac004e2007-07-15 13:00:05 +0000322#endif
Guido van Rossum307fa8c2007-07-16 20:46:27 +0000323;
Guido van Rossum09095f32000-03-10 23:00:52 +0000324
325
326static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000327builtin_cmp(PyObject *self, PyObject *args)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +0000328{
Guido van Rossum79f25d91997-04-29 20:08:16 +0000329 PyObject *a, *b;
Guido van Rossum09df08a1998-05-22 00:51:39 +0000330 int c;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000331
Raymond Hettingerea3fdf42002-12-29 16:33:45 +0000332 if (!PyArg_UnpackTuple(args, "cmp", 2, 2, &a, &b))
Guido van Rossuma9e7dc11992-10-18 18:53:57 +0000333 return NULL;
Guido van Rossum09df08a1998-05-22 00:51:39 +0000334 if (PyObject_Cmp(a, b, &c) < 0)
Guido van Rossumc8b6df91997-05-23 00:06:51 +0000335 return NULL;
Guido van Rossum09df08a1998-05-22 00:51:39 +0000336 return PyInt_FromLong((long)c);
Guido van Rossuma9e7dc11992-10-18 18:53:57 +0000337}
338
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000339PyDoc_STRVAR(cmp_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000340"cmp(x, y) -> integer\n\
341\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000342Return negative if x<y, zero if x==y, positive if x>y.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000343
Guido van Rossumf15a29f2007-05-04 00:41:39 +0000344
345static char *
346source_as_string(PyObject *cmd)
347{
348 char *str;
349 Py_ssize_t size;
350
351 if (!PyObject_CheckReadBuffer(cmd) &&
352 !PyUnicode_Check(cmd)) {
353 PyErr_SetString(PyExc_TypeError,
354 "eval()/exec() arg 1 must be a string, bytes or code object");
355 return NULL;
356 }
357
358 if (PyUnicode_Check(cmd)) {
359 cmd = _PyUnicode_AsDefaultEncodedString(cmd, NULL);
360 if (cmd == NULL)
361 return NULL;
362 }
363 if (PyObject_AsReadBuffer(cmd, (const void **)&str, &size) < 0) {
364 return NULL;
365 }
366 if (strlen(str) != size) {
367 PyErr_SetString(PyExc_TypeError,
368 "source code string cannot contain null bytes");
369 return NULL;
370 }
371 return str;
372}
373
Guido van Rossum79f25d91997-04-29 20:08:16 +0000374static PyObject *
Guido van Rossumd8faa362007-04-27 19:54:29 +0000375builtin_compile(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum5b722181993-03-30 17:46:03 +0000376{
377 char *str;
378 char *filename;
379 char *startstr;
380 int start;
Tim Peters6cd6a822001-08-17 22:11:27 +0000381 int dont_inherit = 0;
382 int supplied_flags = 0;
Tim Peters5ba58662001-07-16 02:29:45 +0000383 PyCompilerFlags cf;
Guido van Rossumf15a29f2007-05-04 00:41:39 +0000384 PyObject *cmd;
Guido van Rossumd8faa362007-04-27 19:54:29 +0000385 static char *kwlist[] = {"source", "filename", "mode", "flags",
386 "dont_inherit", NULL};
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000387
Guido van Rossumd8faa362007-04-27 19:54:29 +0000388 if (!PyArg_ParseTupleAndKeywords(args, kwds, "Oss|ii:compile",
389 kwlist, &cmd, &filename, &startstr,
390 &supplied_flags, &dont_inherit))
Guido van Rossum5b722181993-03-30 17:46:03 +0000391 return NULL;
Tim Peters6cd6a822001-08-17 22:11:27 +0000392
Guido van Rossumf15a29f2007-05-04 00:41:39 +0000393 cf.cf_flags = supplied_flags | PyCF_SOURCE_IS_UTF8;
Just van Rossum3aaf42c2003-02-10 08:21:10 +0000394
Guido van Rossumf15a29f2007-05-04 00:41:39 +0000395 str = source_as_string(cmd);
396 if (str == NULL)
Just van Rossumb9b8e9c2003-02-10 09:22:01 +0000397 return NULL;
Just van Rossum3aaf42c2003-02-10 08:21:10 +0000398
Guido van Rossum5b722181993-03-30 17:46:03 +0000399 if (strcmp(startstr, "exec") == 0)
Guido van Rossumb05a5c71997-05-07 17:46:13 +0000400 start = Py_file_input;
Guido van Rossum5b722181993-03-30 17:46:03 +0000401 else if (strcmp(startstr, "eval") == 0)
Guido van Rossumb05a5c71997-05-07 17:46:13 +0000402 start = Py_eval_input;
Guido van Rossum872537c1995-07-07 22:43:42 +0000403 else if (strcmp(startstr, "single") == 0)
Guido van Rossumb05a5c71997-05-07 17:46:13 +0000404 start = Py_single_input;
Guido van Rossum5b722181993-03-30 17:46:03 +0000405 else {
Guido van Rossum79f25d91997-04-29 20:08:16 +0000406 PyErr_SetString(PyExc_ValueError,
Fred Drake661ea262000-10-24 19:57:45 +0000407 "compile() arg 3 must be 'exec' or 'eval' or 'single'");
Guido van Rossumf15a29f2007-05-04 00:41:39 +0000408 return NULL;
Guido van Rossum5b722181993-03-30 17:46:03 +0000409 }
Tim Peters6cd6a822001-08-17 22:11:27 +0000410
Guido van Rossum4b499dd32003-02-13 22:07:59 +0000411 if (supplied_flags &
Martin v. Löwisbd260da2006-02-26 19:42:26 +0000412 ~(PyCF_MASK | PyCF_MASK_OBSOLETE | PyCF_DONT_IMPLY_DEDENT | PyCF_ONLY_AST))
Guido van Rossum4b499dd32003-02-13 22:07:59 +0000413 {
Tim Peters6cd6a822001-08-17 22:11:27 +0000414 PyErr_SetString(PyExc_ValueError,
415 "compile(): unrecognised flags");
Guido van Rossumf15a29f2007-05-04 00:41:39 +0000416 return NULL;
Tim Peters6cd6a822001-08-17 22:11:27 +0000417 }
418 /* XXX Warn if (supplied_flags & PyCF_MASK_OBSOLETE) != 0? */
419
Tim Peters6cd6a822001-08-17 22:11:27 +0000420 if (!dont_inherit) {
421 PyEval_MergeCompilerFlags(&cf);
422 }
Guido van Rossumf15a29f2007-05-04 00:41:39 +0000423 return Py_CompileStringFlags(str, filename, start, &cf);
Guido van Rossum5b722181993-03-30 17:46:03 +0000424}
425
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000426PyDoc_STRVAR(compile_doc,
Tim Peters6cd6a822001-08-17 22:11:27 +0000427"compile(source, filename, mode[, flags[, dont_inherit]]) -> code object\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000428\n\
429Compile the source string (a Python module, statement or expression)\n\
Georg Brandl7cae87c2006-09-06 06:51:57 +0000430into a code object that can be executed by exec() or eval().\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000431The filename will be used for run-time error messages.\n\
432The mode must be 'exec' to compile a module, 'single' to compile a\n\
Tim Peters6cd6a822001-08-17 22:11:27 +0000433single (interactive) statement, or 'eval' to compile an expression.\n\
434The flags argument, if present, controls which future statements influence\n\
435the compilation of the code.\n\
436The dont_inherit argument, if non-zero, stops the compilation inheriting\n\
437the effects of any future statements in effect in the code calling\n\
438compile; if absent or zero these statements do influence the compilation,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000439in addition to any features explicitly specified.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000440
Guido van Rossum79f25d91997-04-29 20:08:16 +0000441static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000442builtin_dir(PyObject *self, PyObject *args)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000443{
Tim Peters5d2b77c2001-09-03 05:47:38 +0000444 PyObject *arg = NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000445
Raymond Hettingerea3fdf42002-12-29 16:33:45 +0000446 if (!PyArg_UnpackTuple(args, "dir", 0, 1, &arg))
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000447 return NULL;
Tim Peters7eea37e2001-09-04 22:08:56 +0000448 return PyObject_Dir(arg);
Guido van Rossum3f5da241990-12-20 15:06:42 +0000449}
450
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000451PyDoc_STRVAR(dir_doc,
Tim Peters5d2b77c2001-09-03 05:47:38 +0000452"dir([object]) -> list of strings\n"
453"\n"
Georg Brandle32b4222007-03-10 22:13:27 +0000454"If called without an argument, return the names in the current scope.\n"
455"Else, return an alphabetized list of names comprising (some of) the attributes\n"
456"of the given object, and of attributes reachable from it.\n"
457"If the object supplies a method named __dir__, it will be used; otherwise\n"
458"the default dir() logic is used and returns:\n"
459" for a module object: the module's attributes.\n"
460" for a class object: its attributes, and recursively the attributes\n"
461" of its bases.\n"
Guido van Rossumd8faa362007-04-27 19:54:29 +0000462" for any other object: its attributes, its class's attributes, and\n"
Georg Brandle32b4222007-03-10 22:13:27 +0000463" recursively the attributes of its class's base classes.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000464
Guido van Rossum79f25d91997-04-29 20:08:16 +0000465static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000466builtin_divmod(PyObject *self, PyObject *args)
Guido van Rossum6a00cd81995-01-07 12:39:01 +0000467{
Guido van Rossum79f25d91997-04-29 20:08:16 +0000468 PyObject *v, *w;
Guido van Rossum6a00cd81995-01-07 12:39:01 +0000469
Raymond Hettingerea3fdf42002-12-29 16:33:45 +0000470 if (!PyArg_UnpackTuple(args, "divmod", 2, 2, &v, &w))
Guido van Rossum6a00cd81995-01-07 12:39:01 +0000471 return NULL;
Guido van Rossum09df08a1998-05-22 00:51:39 +0000472 return PyNumber_Divmod(v, w);
Guido van Rossum3f5da241990-12-20 15:06:42 +0000473}
474
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000475PyDoc_STRVAR(divmod_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000476"divmod(x, y) -> (div, mod)\n\
477\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000478Return the tuple ((x-x%y)/y, x%y). Invariant: div*y + mod == x.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000479
480
Guido van Rossum79f25d91997-04-29 20:08:16 +0000481static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000482builtin_eval(PyObject *self, PyObject *args)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000483{
Just van Rossum3aaf42c2003-02-10 08:21:10 +0000484 PyObject *cmd, *result, *tmp = NULL;
Guido van Rossum79f25d91997-04-29 20:08:16 +0000485 PyObject *globals = Py_None, *locals = Py_None;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000486 char *str;
Tim Peters9fa96be2001-08-17 23:04:59 +0000487 PyCompilerFlags cf;
Guido van Rossum590baa41993-11-30 13:40:46 +0000488
Raymond Hettinger214b1c32004-07-02 06:41:07 +0000489 if (!PyArg_UnpackTuple(args, "eval", 1, 3, &cmd, &globals, &locals))
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000490 return NULL;
Raymond Hettinger214b1c32004-07-02 06:41:07 +0000491 if (locals != Py_None && !PyMapping_Check(locals)) {
492 PyErr_SetString(PyExc_TypeError, "locals must be a mapping");
Raymond Hettinger513ffe82004-07-06 13:44:41 +0000493 return NULL;
Raymond Hettinger214b1c32004-07-02 06:41:07 +0000494 }
495 if (globals != Py_None && !PyDict_Check(globals)) {
Georg Brandl99d7e4e2005-08-31 22:21:15 +0000496 PyErr_SetString(PyExc_TypeError, PyMapping_Check(globals) ?
Raymond Hettinger214b1c32004-07-02 06:41:07 +0000497 "globals must be a real dict; try eval(expr, {}, mapping)"
498 : "globals must be a dict");
Raymond Hettinger513ffe82004-07-06 13:44:41 +0000499 return NULL;
Raymond Hettinger214b1c32004-07-02 06:41:07 +0000500 }
Guido van Rossum79f25d91997-04-29 20:08:16 +0000501 if (globals == Py_None) {
502 globals = PyEval_GetGlobals();
503 if (locals == Py_None)
504 locals = PyEval_GetLocals();
Guido van Rossum6135a871995-01-09 17:53:26 +0000505 }
Guido van Rossum79f25d91997-04-29 20:08:16 +0000506 else if (locals == Py_None)
Guido van Rossum6135a871995-01-09 17:53:26 +0000507 locals = globals;
Tim Peters9fa96be2001-08-17 23:04:59 +0000508
Georg Brandl77c85e62005-09-15 10:46:13 +0000509 if (globals == NULL || locals == NULL) {
510 PyErr_SetString(PyExc_TypeError,
511 "eval must be given globals and locals "
512 "when called without a frame");
513 return NULL;
514 }
515
Guido van Rossum79f25d91997-04-29 20:08:16 +0000516 if (PyDict_GetItemString(globals, "__builtins__") == NULL) {
517 if (PyDict_SetItemString(globals, "__builtins__",
518 PyEval_GetBuiltins()) != 0)
Guido van Rossum6135a871995-01-09 17:53:26 +0000519 return NULL;
520 }
Tim Peters9fa96be2001-08-17 23:04:59 +0000521
Jeremy Hylton15c1c4f2001-07-30 21:50:55 +0000522 if (PyCode_Check(cmd)) {
Jeremy Hylton733c8932001-12-13 19:51:56 +0000523 if (PyCode_GetNumFree((PyCodeObject *)cmd) > 0) {
Jeremy Hylton15c1c4f2001-07-30 21:50:55 +0000524 PyErr_SetString(PyExc_TypeError,
525 "code object passed to eval() may not contain free variables");
526 return NULL;
527 }
Guido van Rossum79f25d91997-04-29 20:08:16 +0000528 return PyEval_EvalCode((PyCodeObject *) cmd, globals, locals);
Jeremy Hylton15c1c4f2001-07-30 21:50:55 +0000529 }
Tim Peters9fa96be2001-08-17 23:04:59 +0000530
Guido van Rossumf15a29f2007-05-04 00:41:39 +0000531 str = source_as_string(cmd);
532 if (str == NULL)
Guido van Rossum94390a41992-08-14 15:14:30 +0000533 return NULL;
Just van Rossum3aaf42c2003-02-10 08:21:10 +0000534
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000535 while (*str == ' ' || *str == '\t')
536 str++;
Tim Peters9fa96be2001-08-17 23:04:59 +0000537
Guido van Rossumf15a29f2007-05-04 00:41:39 +0000538 cf.cf_flags = PyCF_SOURCE_IS_UTF8;
Tim Peters9fa96be2001-08-17 23:04:59 +0000539 (void)PyEval_MergeCompilerFlags(&cf);
Just van Rossum3aaf42c2003-02-10 08:21:10 +0000540 result = PyRun_StringFlags(str, Py_eval_input, globals, locals, &cf);
541 Py_XDECREF(tmp);
542 return result;
Guido van Rossum3f5da241990-12-20 15:06:42 +0000543}
544
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000545PyDoc_STRVAR(eval_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000546"eval(source[, globals[, locals]]) -> value\n\
547\n\
548Evaluate the source in the context of globals and locals.\n\
549The source may be a string representing a Python expression\n\
550or a code object as returned by compile().\n\
Thomas Wouters89f507f2006-12-13 04:49:30 +0000551The globals must be a dictionary and locals can be any mapping,\n\
Raymond Hettinger214b1c32004-07-02 06:41:07 +0000552defaulting to the current globals and locals.\n\
553If only globals is given, locals defaults to it.\n");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000554
Georg Brandl7cae87c2006-09-06 06:51:57 +0000555static PyObject *
556builtin_exec(PyObject *self, PyObject *args)
557{
558 PyObject *v;
559 PyObject *prog, *globals = Py_None, *locals = Py_None;
560 int plain = 0;
561
562 if (!PyArg_ParseTuple(args, "O|OO:exec", &prog, &globals, &locals))
563 return NULL;
564
565 if (globals == Py_None) {
566 globals = PyEval_GetGlobals();
567 if (locals == Py_None) {
568 locals = PyEval_GetLocals();
569 plain = 1;
570 }
571 if (!globals || !locals) {
572 PyErr_SetString(PyExc_SystemError,
573 "globals and locals cannot be NULL");
574 return NULL;
575 }
576 }
577 else if (locals == Py_None)
578 locals = globals;
579 if (!PyString_Check(prog) &&
580 !PyUnicode_Check(prog) &&
Guido van Rossumda5b8f22007-06-12 23:30:11 +0000581 !PyCode_Check(prog)) {
Georg Brandl7cae87c2006-09-06 06:51:57 +0000582 PyErr_Format(PyExc_TypeError,
583 "exec() arg 1 must be a string, file, or code "
584 "object, not %.100s", prog->ob_type->tp_name);
585 return NULL;
586 }
587 if (!PyDict_Check(globals)) {
588 PyErr_Format(PyExc_TypeError, "exec() arg 2 must be a dict, not %.100s",
589 globals->ob_type->tp_name);
590 return NULL;
591 }
592 if (!PyMapping_Check(locals)) {
593 PyErr_Format(PyExc_TypeError,
594 "arg 3 must be a mapping or None, not %.100s",
595 locals->ob_type->tp_name);
596 return NULL;
597 }
598 if (PyDict_GetItemString(globals, "__builtins__") == NULL) {
599 if (PyDict_SetItemString(globals, "__builtins__",
600 PyEval_GetBuiltins()) != 0)
601 return NULL;
602 }
603
604 if (PyCode_Check(prog)) {
605 if (PyCode_GetNumFree((PyCodeObject *)prog) > 0) {
606 PyErr_SetString(PyExc_TypeError,
607 "code object passed to exec() may not "
608 "contain free variables");
609 return NULL;
610 }
611 v = PyEval_EvalCode((PyCodeObject *) prog, globals, locals);
612 }
Georg Brandl7cae87c2006-09-06 06:51:57 +0000613 else {
Guido van Rossumf15a29f2007-05-04 00:41:39 +0000614 char *str = source_as_string(prog);
Georg Brandl7cae87c2006-09-06 06:51:57 +0000615 PyCompilerFlags cf;
Guido van Rossumf15a29f2007-05-04 00:41:39 +0000616 if (str == NULL)
Georg Brandl7cae87c2006-09-06 06:51:57 +0000617 return NULL;
Guido van Rossumf15a29f2007-05-04 00:41:39 +0000618 cf.cf_flags = PyCF_SOURCE_IS_UTF8;
Georg Brandl7cae87c2006-09-06 06:51:57 +0000619 if (PyEval_MergeCompilerFlags(&cf))
620 v = PyRun_StringFlags(str, Py_file_input, globals,
621 locals, &cf);
622 else
623 v = PyRun_String(str, Py_file_input, globals, locals);
Georg Brandl7cae87c2006-09-06 06:51:57 +0000624 }
625 if (v == NULL)
626 return NULL;
627 Py_DECREF(v);
628 Py_RETURN_NONE;
629}
630
631PyDoc_STRVAR(exec_doc,
632"exec(object[, globals[, locals]])\n\
633\n\
634Read and execute code from a object, which can be a string, a code\n\
635object or a file object.\n\
636The globals and locals are dictionaries, defaulting to the current\n\
637globals and locals. If only globals is given, locals defaults to it.");
638
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000639
Guido van Rossum79f25d91997-04-29 20:08:16 +0000640static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000641builtin_getattr(PyObject *self, PyObject *args)
Guido van Rossum33894be1992-01-27 16:53:09 +0000642{
Martin v. Löwis5b222132007-06-10 09:51:05 +0000643 PyObject *v, *result, *dflt = NULL, *release = NULL;
Guido van Rossum79f25d91997-04-29 20:08:16 +0000644 PyObject *name;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000645
Raymond Hettingerea3fdf42002-12-29 16:33:45 +0000646 if (!PyArg_UnpackTuple(args, "getattr", 2, 3, &v, &name, &dflt))
Guido van Rossum33894be1992-01-27 16:53:09 +0000647 return NULL;
Martin v. Löwis5b222132007-06-10 09:51:05 +0000648
649 if (PyString_Check(name)) {
650 release = PyString_AsDecodedObject(name, NULL, NULL);
651 if (!release)
Jeremy Hylton0eb11152001-07-30 22:39:31 +0000652 return NULL;
Martin v. Löwis5b222132007-06-10 09:51:05 +0000653 name = release;
Jeremy Hylton0eb11152001-07-30 22:39:31 +0000654 }
655
Martin v. Löwis5b222132007-06-10 09:51:05 +0000656 if (!PyUnicode_Check(name)) {
Jeremy Hylton0eb11152001-07-30 22:39:31 +0000657 PyErr_SetString(PyExc_TypeError,
Alex Martellia9b9c9f2003-04-23 13:34:35 +0000658 "getattr(): attribute name must be string");
Martin v. Löwis5b222132007-06-10 09:51:05 +0000659 Py_XDECREF(release);
Jeremy Hylton0eb11152001-07-30 22:39:31 +0000660 return NULL;
661 }
Guido van Rossum950ff291998-06-29 13:38:57 +0000662 result = PyObject_GetAttr(v, name);
Guido van Rossumd8923572001-10-16 21:31:32 +0000663 if (result == NULL && dflt != NULL &&
664 PyErr_ExceptionMatches(PyExc_AttributeError))
665 {
Guido van Rossum950ff291998-06-29 13:38:57 +0000666 PyErr_Clear();
667 Py_INCREF(dflt);
668 result = dflt;
669 }
Martin v. Löwis5b222132007-06-10 09:51:05 +0000670 Py_XDECREF(release);
Guido van Rossum950ff291998-06-29 13:38:57 +0000671 return result;
Guido van Rossum9bfef441993-03-29 10:43:31 +0000672}
673
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000674PyDoc_STRVAR(getattr_doc,
Guido van Rossum950ff291998-06-29 13:38:57 +0000675"getattr(object, name[, default]) -> value\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000676\n\
Guido van Rossum950ff291998-06-29 13:38:57 +0000677Get a named attribute from an object; getattr(x, 'y') is equivalent to x.y.\n\
678When a default argument is given, it is returned when the attribute doesn't\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000679exist; without it, an exception is raised in that case.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000680
681
Guido van Rossum79f25d91997-04-29 20:08:16 +0000682static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000683builtin_globals(PyObject *self)
Guido van Rossum872537c1995-07-07 22:43:42 +0000684{
Guido van Rossum79f25d91997-04-29 20:08:16 +0000685 PyObject *d;
Guido van Rossum872537c1995-07-07 22:43:42 +0000686
Guido van Rossum79f25d91997-04-29 20:08:16 +0000687 d = PyEval_GetGlobals();
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000688 Py_XINCREF(d);
Guido van Rossum872537c1995-07-07 22:43:42 +0000689 return d;
690}
691
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000692PyDoc_STRVAR(globals_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000693"globals() -> dictionary\n\
694\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000695Return the dictionary containing the current scope's global variables.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000696
697
Guido van Rossum79f25d91997-04-29 20:08:16 +0000698static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000699builtin_hasattr(PyObject *self, PyObject *args)
Guido van Rossum9bfef441993-03-29 10:43:31 +0000700{
Guido van Rossum79f25d91997-04-29 20:08:16 +0000701 PyObject *v;
702 PyObject *name;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000703
Raymond Hettingerea3fdf42002-12-29 16:33:45 +0000704 if (!PyArg_UnpackTuple(args, "hasattr", 2, 2, &v, &name))
Guido van Rossum9bfef441993-03-29 10:43:31 +0000705 return NULL;
Martin v. Löwis5b222132007-06-10 09:51:05 +0000706 if (!PyUnicode_Check(name)) {
Jeremy Hylton302b54a2001-07-30 22:45:19 +0000707 PyErr_SetString(PyExc_TypeError,
Alex Martellia9b9c9f2003-04-23 13:34:35 +0000708 "hasattr(): attribute name must be string");
Jeremy Hylton302b54a2001-07-30 22:45:19 +0000709 return NULL;
710 }
Guido van Rossum79f25d91997-04-29 20:08:16 +0000711 v = PyObject_GetAttr(v, name);
Guido van Rossum9bfef441993-03-29 10:43:31 +0000712 if (v == NULL) {
Guido van Rossum79f25d91997-04-29 20:08:16 +0000713 PyErr_Clear();
Guido van Rossum09df08a1998-05-22 00:51:39 +0000714 Py_INCREF(Py_False);
715 return Py_False;
Guido van Rossum9bfef441993-03-29 10:43:31 +0000716 }
Guido van Rossum79f25d91997-04-29 20:08:16 +0000717 Py_DECREF(v);
Guido van Rossum09df08a1998-05-22 00:51:39 +0000718 Py_INCREF(Py_True);
719 return Py_True;
Guido van Rossum33894be1992-01-27 16:53:09 +0000720}
721
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000722PyDoc_STRVAR(hasattr_doc,
Guido van Rossum77f6a652002-04-03 22:41:51 +0000723"hasattr(object, name) -> bool\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000724\n\
725Return whether the object has an attribute with the given name.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000726(This is done by calling getattr(object, name) and catching exceptions.)");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000727
728
Guido van Rossum79f25d91997-04-29 20:08:16 +0000729static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000730builtin_id(PyObject *self, PyObject *v)
Guido van Rossum5b722181993-03-30 17:46:03 +0000731{
Guido van Rossum106f2da2000-06-28 21:12:25 +0000732 return PyLong_FromVoidPtr(v);
Guido van Rossum5b722181993-03-30 17:46:03 +0000733}
734
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000735PyDoc_STRVAR(id_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000736"id(object) -> integer\n\
737\n\
738Return the identity of an object. This is guaranteed to be unique among\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000739simultaneously existing objects. (Hint: it's the object's memory address.)");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000740
741
Guido van Rossum79f25d91997-04-29 20:08:16 +0000742static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000743builtin_map(PyObject *self, PyObject *args)
Guido van Rossum12d12c51993-10-26 17:58:25 +0000744{
Guido van Rossumc1f779c2007-07-03 08:25:58 +0000745 PyObject *itertools, *imap, *result;
746 itertools = PyImport_ImportModule("itertools");
747 if (itertools == NULL)
Guido van Rossum12d12c51993-10-26 17:58:25 +0000748 return NULL;
Guido van Rossumc1f779c2007-07-03 08:25:58 +0000749 imap = PyObject_GetAttrString(itertools, "imap");
750 Py_DECREF(itertools);
751 if (imap == NULL)
Tim Peters4e9afdc2001-05-03 23:54:49 +0000752 return NULL;
Guido van Rossumc1f779c2007-07-03 08:25:58 +0000753 result = PyObject_Call(imap, args, NULL);
754 Py_DECREF(imap);
Tim Peters4e9afdc2001-05-03 23:54:49 +0000755 return result;
Guido van Rossum12d12c51993-10-26 17:58:25 +0000756}
757
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000758PyDoc_STRVAR(map_doc,
Guido van Rossumc1f779c2007-07-03 08:25:58 +0000759"map(function, iterable[, iterable, ...]) -> iterator\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000760\n\
Guido van Rossumc1f779c2007-07-03 08:25:58 +0000761Return an iterator yielding the results of applying the function to the\n\
762items of the argument iterables(s). If more than one iterable is given,\n\
763the function is called with an argument list consisting of the\n\
764corresponding item of each iterable, until an iterable is exhausted.\n\
765If the function is None, 'lambda *a: a' is assumed.\n\
766(This is identical to itertools.imap().)");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000767
768
Guido van Rossum79f25d91997-04-29 20:08:16 +0000769static PyObject *
Georg Brandla18af4e2007-04-21 15:47:16 +0000770builtin_next(PyObject *self, PyObject *args)
771{
772 PyObject *it, *res;
773 PyObject *def = NULL;
774
775 if (!PyArg_UnpackTuple(args, "next", 1, 2, &it, &def))
776 return NULL;
777 if (!PyIter_Check(it)) {
778 PyErr_Format(PyExc_TypeError,
779 "%.200s object is not an iterator", it->ob_type->tp_name);
780 return NULL;
781 }
782
783 res = (*it->ob_type->tp_iternext)(it);
784 if (res == NULL) {
785 if (def) {
786 if (PyErr_Occurred() &&
787 !PyErr_ExceptionMatches(PyExc_StopIteration))
788 return NULL;
789 PyErr_Clear();
790 Py_INCREF(def);
791 return def;
792 } else if (PyErr_Occurred()) {
793 return NULL;
794 } else {
795 PyErr_SetNone(PyExc_StopIteration);
796 return NULL;
797 }
798 }
799 return res;
800}
801
802PyDoc_STRVAR(next_doc,
803"next(iterator[, default])\n\
804\n\
805Return the next item from the iterator. If default is given and the iterator\n\
806is exhausted, it is returned instead of raising StopIteration.");
807
808
809static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000810builtin_setattr(PyObject *self, PyObject *args)
Guido van Rossum33894be1992-01-27 16:53:09 +0000811{
Guido van Rossum79f25d91997-04-29 20:08:16 +0000812 PyObject *v;
813 PyObject *name;
814 PyObject *value;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000815
Raymond Hettingerea3fdf42002-12-29 16:33:45 +0000816 if (!PyArg_UnpackTuple(args, "setattr", 3, 3, &v, &name, &value))
Guido van Rossum33894be1992-01-27 16:53:09 +0000817 return NULL;
Guido van Rossum79f25d91997-04-29 20:08:16 +0000818 if (PyObject_SetAttr(v, name, value) != 0)
Guido van Rossum33894be1992-01-27 16:53:09 +0000819 return NULL;
Guido van Rossum79f25d91997-04-29 20:08:16 +0000820 Py_INCREF(Py_None);
821 return Py_None;
Guido van Rossum33894be1992-01-27 16:53:09 +0000822}
823
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000824PyDoc_STRVAR(setattr_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000825"setattr(object, name, value)\n\
826\n\
827Set a named attribute on an object; setattr(x, 'y', v) is equivalent to\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000828``x.y = v''.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000829
830
Guido van Rossum79f25d91997-04-29 20:08:16 +0000831static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000832builtin_delattr(PyObject *self, PyObject *args)
Guido van Rossum14144fc1994-08-29 12:53:40 +0000833{
Guido van Rossum79f25d91997-04-29 20:08:16 +0000834 PyObject *v;
835 PyObject *name;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000836
Raymond Hettingerea3fdf42002-12-29 16:33:45 +0000837 if (!PyArg_UnpackTuple(args, "delattr", 2, 2, &v, &name))
Guido van Rossum14144fc1994-08-29 12:53:40 +0000838 return NULL;
Guido van Rossum79f25d91997-04-29 20:08:16 +0000839 if (PyObject_SetAttr(v, name, (PyObject *)NULL) != 0)
Guido van Rossum14144fc1994-08-29 12:53:40 +0000840 return NULL;
Guido van Rossum79f25d91997-04-29 20:08:16 +0000841 Py_INCREF(Py_None);
842 return Py_None;
Guido van Rossum14144fc1994-08-29 12:53:40 +0000843}
844
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000845PyDoc_STRVAR(delattr_doc,
Guido van Rossumdf12a591998-11-23 22:13:04 +0000846"delattr(object, name)\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000847\n\
848Delete a named attribute on an object; delattr(x, 'y') is equivalent to\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000849``del x.y''.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000850
851
Guido van Rossum79f25d91997-04-29 20:08:16 +0000852static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000853builtin_hash(PyObject *self, PyObject *v)
Guido van Rossum9bfef441993-03-29 10:43:31 +0000854{
Guido van Rossum9bfef441993-03-29 10:43:31 +0000855 long x;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000856
Guido van Rossum79f25d91997-04-29 20:08:16 +0000857 x = PyObject_Hash(v);
Guido van Rossum9bfef441993-03-29 10:43:31 +0000858 if (x == -1)
859 return NULL;
Guido van Rossum79f25d91997-04-29 20:08:16 +0000860 return PyInt_FromLong(x);
Guido van Rossum9bfef441993-03-29 10:43:31 +0000861}
862
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000863PyDoc_STRVAR(hash_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000864"hash(object) -> integer\n\
865\n\
866Return a hash value for the object. Two objects with the same value have\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000867the same hash value. The reverse is not necessarily true, but likely.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000868
869
Guido van Rossum79f25d91997-04-29 20:08:16 +0000870static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000871builtin_hex(PyObject *self, PyObject *v)
Guido van Rossum006bcd41991-10-24 14:54:44 +0000872{
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000873 return PyNumber_ToBase(v, 16);
Guido van Rossum006bcd41991-10-24 14:54:44 +0000874}
875
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000876PyDoc_STRVAR(hex_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000877"hex(number) -> string\n\
878\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000879Return the hexadecimal representation of an integer or long integer.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000880
881
Guido van Rossum79f25d91997-04-29 20:08:16 +0000882static PyObject *
Guido van Rossum59d1d2b2001-04-20 19:13:02 +0000883builtin_iter(PyObject *self, PyObject *args)
884{
885 PyObject *v, *w = NULL;
886
Raymond Hettingerea3fdf42002-12-29 16:33:45 +0000887 if (!PyArg_UnpackTuple(args, "iter", 1, 2, &v, &w))
Guido van Rossum59d1d2b2001-04-20 19:13:02 +0000888 return NULL;
889 if (w == NULL)
890 return PyObject_GetIter(v);
891 if (!PyCallable_Check(v)) {
892 PyErr_SetString(PyExc_TypeError,
893 "iter(v, w): v must be callable");
894 return NULL;
895 }
896 return PyCallIter_New(v, w);
897}
898
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000899PyDoc_STRVAR(iter_doc,
Guido van Rossum59d1d2b2001-04-20 19:13:02 +0000900"iter(collection) -> iterator\n\
901iter(callable, sentinel) -> iterator\n\
902\n\
903Get an iterator from an object. In the first form, the argument must\n\
904supply its own iterator, or be a sequence.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000905In the second form, the callable is called until it returns the sentinel.");
Guido van Rossum59d1d2b2001-04-20 19:13:02 +0000906
907
908static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000909builtin_len(PyObject *self, PyObject *v)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000910{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000911 Py_ssize_t res;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000912
Jeremy Hylton03657cf2000-07-12 13:05:33 +0000913 res = PyObject_Size(v);
Guido van Rossum8ea9f4d1998-06-29 22:26:50 +0000914 if (res < 0 && PyErr_Occurred())
915 return NULL;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000916 return PyInt_FromSsize_t(res);
Guido van Rossum3f5da241990-12-20 15:06:42 +0000917}
918
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000919PyDoc_STRVAR(len_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000920"len(object) -> integer\n\
921\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000922Return the number of items of a sequence or mapping.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000923
924
Guido van Rossum79f25d91997-04-29 20:08:16 +0000925static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000926builtin_locals(PyObject *self)
Guido van Rossum872537c1995-07-07 22:43:42 +0000927{
Guido van Rossum79f25d91997-04-29 20:08:16 +0000928 PyObject *d;
Guido van Rossum872537c1995-07-07 22:43:42 +0000929
Guido van Rossum79f25d91997-04-29 20:08:16 +0000930 d = PyEval_GetLocals();
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000931 Py_XINCREF(d);
Guido van Rossum872537c1995-07-07 22:43:42 +0000932 return d;
933}
934
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000935PyDoc_STRVAR(locals_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000936"locals() -> dictionary\n\
937\n\
Raymond Hettinger69bf8f32003-01-04 02:16:22 +0000938Update and return a dictionary containing the current scope's local variables.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000939
940
Guido van Rossum79f25d91997-04-29 20:08:16 +0000941static PyObject *
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +0000942min_max(PyObject *args, PyObject *kwds, int op)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000943{
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +0000944 PyObject *v, *it, *item, *val, *maxitem, *maxval, *keyfunc=NULL;
Martin v. Löwisfd39ad42004-08-12 14:42:37 +0000945 const char *name = op == Py_LT ? "min" : "max";
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000946
Guido van Rossum79f25d91997-04-29 20:08:16 +0000947 if (PyTuple_Size(args) > 1)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000948 v = args;
Martin v. Löwisfd39ad42004-08-12 14:42:37 +0000949 else if (!PyArg_UnpackTuple(args, (char *)name, 1, 1, &v))
Guido van Rossum3f5da241990-12-20 15:06:42 +0000950 return NULL;
Tim Peters67d687a2002-04-29 21:27:32 +0000951
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +0000952 if (kwds != NULL && PyDict_Check(kwds) && PyDict_Size(kwds)) {
953 keyfunc = PyDict_GetItemString(kwds, "key");
954 if (PyDict_Size(kwds)!=1 || keyfunc == NULL) {
Georg Brandl99d7e4e2005-08-31 22:21:15 +0000955 PyErr_Format(PyExc_TypeError,
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +0000956 "%s() got an unexpected keyword argument", name);
957 return NULL;
958 }
Georg Brandl99d7e4e2005-08-31 22:21:15 +0000959 }
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +0000960
Tim Petersc3074532001-05-03 07:00:32 +0000961 it = PyObject_GetIter(v);
962 if (it == NULL)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000963 return NULL;
Tim Petersc3074532001-05-03 07:00:32 +0000964
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +0000965 maxitem = NULL; /* the result */
966 maxval = NULL; /* the value associated with the result */
Brett Cannon9e635cf2004-12-07 00:25:35 +0000967 while (( item = PyIter_Next(it) )) {
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +0000968 /* get the value from the key function */
969 if (keyfunc != NULL) {
970 val = PyObject_CallFunctionObjArgs(keyfunc, item, NULL);
971 if (val == NULL)
972 goto Fail_it_item;
973 }
974 /* no key function; the value is the item */
975 else {
976 val = item;
977 Py_INCREF(val);
Guido van Rossum3f5da241990-12-20 15:06:42 +0000978 }
Tim Petersc3074532001-05-03 07:00:32 +0000979
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +0000980 /* maximum value and item are unset; set them */
981 if (maxval == NULL) {
982 maxitem = item;
983 maxval = val;
984 }
985 /* maximum value and item are set; update them as necessary */
Guido van Rossum2d951851994-08-29 12:52:16 +0000986 else {
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +0000987 int cmp = PyObject_RichCompareBool(val, maxval, op);
988 if (cmp < 0)
989 goto Fail_it_item_and_val;
990 else if (cmp > 0) {
991 Py_DECREF(maxval);
992 Py_DECREF(maxitem);
993 maxval = val;
994 maxitem = item;
Guido van Rossum53451b32001-01-17 15:47:24 +0000995 }
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +0000996 else {
997 Py_DECREF(item);
998 Py_DECREF(val);
Guido van Rossumc8b6df91997-05-23 00:06:51 +0000999 }
Guido van Rossum2d951851994-08-29 12:52:16 +00001000 }
Guido van Rossum3f5da241990-12-20 15:06:42 +00001001 }
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001002 if (PyErr_Occurred())
1003 goto Fail_it;
1004 if (maxval == NULL) {
Martin v. Löwisfd39ad42004-08-12 14:42:37 +00001005 PyErr_Format(PyExc_ValueError,
1006 "%s() arg is an empty sequence", name);
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001007 assert(maxitem == NULL);
1008 }
1009 else
1010 Py_DECREF(maxval);
Tim Petersc3074532001-05-03 07:00:32 +00001011 Py_DECREF(it);
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001012 return maxitem;
1013
1014Fail_it_item_and_val:
1015 Py_DECREF(val);
1016Fail_it_item:
1017 Py_DECREF(item);
1018Fail_it:
1019 Py_XDECREF(maxval);
1020 Py_XDECREF(maxitem);
1021 Py_DECREF(it);
1022 return NULL;
Guido van Rossum3f5da241990-12-20 15:06:42 +00001023}
1024
Guido van Rossum79f25d91997-04-29 20:08:16 +00001025static PyObject *
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001026builtin_min(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001027{
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001028 return min_max(args, kwds, Py_LT);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001029}
1030
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001031PyDoc_STRVAR(min_doc,
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001032"min(iterable[, key=func]) -> value\n\
1033min(a, b, c, ...[, key=func]) -> value\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001034\n\
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001035With a single iterable argument, return its smallest item.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001036With two or more arguments, return the smallest argument.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001037
1038
Guido van Rossum79f25d91997-04-29 20:08:16 +00001039static PyObject *
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001040builtin_max(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001041{
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001042 return min_max(args, kwds, Py_GT);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001043}
1044
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001045PyDoc_STRVAR(max_doc,
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001046"max(iterable[, key=func]) -> value\n\
1047max(a, b, c, ...[, key=func]) -> value\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001048\n\
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001049With a single iterable argument, return its largest item.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001050With two or more arguments, return the largest argument.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001051
1052
Guido van Rossum79f25d91997-04-29 20:08:16 +00001053static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001054builtin_oct(PyObject *self, PyObject *v)
Guido van Rossum006bcd41991-10-24 14:54:44 +00001055{
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001056 return PyNumber_ToBase(v, 8);
Guido van Rossum006bcd41991-10-24 14:54:44 +00001057}
1058
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001059PyDoc_STRVAR(oct_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001060"oct(number) -> string\n\
1061\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001062Return the octal representation of an integer or long integer.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001063
1064
Guido van Rossum79f25d91997-04-29 20:08:16 +00001065static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001066builtin_ord(PyObject *self, PyObject* obj)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001067{
Guido van Rossum09095f32000-03-10 23:00:52 +00001068 long ord;
Martin v. Löwisd96ee902006-02-16 14:37:16 +00001069 Py_ssize_t size;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001070
Jeremy Hylton394b54d2000-04-12 21:19:47 +00001071 if (PyString_Check(obj)) {
1072 size = PyString_GET_SIZE(obj);
Andrew M. Kuchling34c20cf2000-12-20 14:36:56 +00001073 if (size == 1) {
Jeremy Hylton394b54d2000-04-12 21:19:47 +00001074 ord = (long)((unsigned char)*PyString_AS_STRING(obj));
Andrew M. Kuchling34c20cf2000-12-20 14:36:56 +00001075 return PyInt_FromLong(ord);
1076 }
Guido van Rossum98f97462007-04-13 03:31:13 +00001077 }
1078 else if (PyUnicode_Check(obj)) {
Jeremy Hylton394b54d2000-04-12 21:19:47 +00001079 size = PyUnicode_GET_SIZE(obj);
Andrew M. Kuchling34c20cf2000-12-20 14:36:56 +00001080 if (size == 1) {
Jeremy Hylton394b54d2000-04-12 21:19:47 +00001081 ord = (long)*PyUnicode_AS_UNICODE(obj);
Andrew M. Kuchling34c20cf2000-12-20 14:36:56 +00001082 return PyInt_FromLong(ord);
1083 }
Guido van Rossum8ac004e2007-07-15 13:00:05 +00001084#ifndef Py_UNICODE_WIDE
1085 if (size == 2) {
1086 /* Decode a valid surrogate pair */
1087 int c0 = PyUnicode_AS_UNICODE(obj)[0];
1088 int c1 = PyUnicode_AS_UNICODE(obj)[1];
1089 if (0xD800 <= c0 && c0 <= 0xDBFF &&
1090 0xDC00 <= c1 && c1 <= 0xDFFF) {
1091 ord = ((((c0 & 0x03FF) << 10) | (c1 & 0x03FF)) +
1092 0x00010000);
1093 return PyInt_FromLong(ord);
1094 }
1095 }
1096#endif
Guido van Rossum6f376c42007-05-24 14:31:33 +00001097 }
Guido van Rossum98f97462007-04-13 03:31:13 +00001098 else if (PyBytes_Check(obj)) {
1099 /* XXX Hopefully this is temporary */
1100 size = PyBytes_GET_SIZE(obj);
1101 if (size == 1) {
Guido van Rossumf9e91c92007-05-08 21:05:48 +00001102 ord = (long)((unsigned char)*PyBytes_AS_STRING(obj));
Guido van Rossum98f97462007-04-13 03:31:13 +00001103 return PyInt_FromLong(ord);
1104 }
1105 }
1106 else {
Jeremy Hylton394b54d2000-04-12 21:19:47 +00001107 PyErr_Format(PyExc_TypeError,
Andrew M. Kuchlingf07aad12000-12-23 14:11:28 +00001108 "ord() expected string of length 1, but " \
Jeremy Hylton394b54d2000-04-12 21:19:47 +00001109 "%.200s found", obj->ob_type->tp_name);
Guido van Rossum09095f32000-03-10 23:00:52 +00001110 return NULL;
1111 }
1112
Guido van Rossumad991772001-01-12 16:03:05 +00001113 PyErr_Format(PyExc_TypeError,
Andrew M. Kuchlingf07aad12000-12-23 14:11:28 +00001114 "ord() expected a character, "
Martin v. Löwisd96ee902006-02-16 14:37:16 +00001115 "but string of length %zd found",
Jeremy Hylton394b54d2000-04-12 21:19:47 +00001116 size);
1117 return NULL;
Guido van Rossum3f5da241990-12-20 15:06:42 +00001118}
1119
Guido van Rossum307fa8c2007-07-16 20:46:27 +00001120PyDoc_VAR(ord_doc) = PyDoc_STR(
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001121"ord(c) -> integer\n\
1122\n\
Guido van Rossum8ac004e2007-07-15 13:00:05 +00001123Return the integer ordinal of a one-character string."
Guido van Rossum307fa8c2007-07-16 20:46:27 +00001124)
Guido van Rossum8ac004e2007-07-15 13:00:05 +00001125#ifndef Py_UNICODE_WIDE
Guido van Rossum307fa8c2007-07-16 20:46:27 +00001126PyDoc_STR(
Guido van Rossum8ac004e2007-07-15 13:00:05 +00001127"\nA valid surrogate pair is also accepted."
Guido van Rossum307fa8c2007-07-16 20:46:27 +00001128)
Guido van Rossum8ac004e2007-07-15 13:00:05 +00001129#endif
Guido van Rossum307fa8c2007-07-16 20:46:27 +00001130;
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001131
1132
Guido van Rossum79f25d91997-04-29 20:08:16 +00001133static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001134builtin_pow(PyObject *self, PyObject *args)
Guido van Rossum6a00cd81995-01-07 12:39:01 +00001135{
Guido van Rossum09df08a1998-05-22 00:51:39 +00001136 PyObject *v, *w, *z = Py_None;
Guido van Rossum6a00cd81995-01-07 12:39:01 +00001137
Raymond Hettingerea3fdf42002-12-29 16:33:45 +00001138 if (!PyArg_UnpackTuple(args, "pow", 2, 3, &v, &w, &z))
Guido van Rossum6a00cd81995-01-07 12:39:01 +00001139 return NULL;
Guido van Rossum09df08a1998-05-22 00:51:39 +00001140 return PyNumber_Power(v, w, z);
Guido van Rossumd4905451991-05-05 20:00:36 +00001141}
1142
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001143PyDoc_STRVAR(pow_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001144"pow(x, y[, z]) -> number\n\
1145\n\
1146With two arguments, equivalent to x**y. With three arguments,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001147equivalent to (x**y) % z, but may be more efficient (e.g. for longs).");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001148
1149
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001150
Guido van Rossum34343512006-11-30 22:13:52 +00001151static PyObject *
1152builtin_print(PyObject *self, PyObject *args, PyObject *kwds)
1153{
1154 static char *kwlist[] = {"sep", "end", "file", 0};
Georg Brandl257d3d92007-02-26 10:35:10 +00001155 static PyObject *dummy_args;
Guido van Rossum34343512006-11-30 22:13:52 +00001156 PyObject *sep = NULL, *end = NULL, *file = NULL;
1157 int i, err;
1158
Georg Brandl257d3d92007-02-26 10:35:10 +00001159 if (dummy_args == NULL) {
1160 if (!(dummy_args = PyTuple_New(0)))
1161 return NULL;
1162 }
Georg Brandl88fc6642007-02-09 21:28:07 +00001163 if (!PyArg_ParseTupleAndKeywords(dummy_args, kwds, "|OOO:print",
Guido van Rossum34343512006-11-30 22:13:52 +00001164 kwlist, &sep, &end, &file))
1165 return NULL;
1166 if (file == NULL || file == Py_None)
1167 file = PySys_GetObject("stdout");
1168
Georg Brandl16f3e032006-11-30 22:46:03 +00001169 if (sep && sep != Py_None && !PyString_Check(sep) &&
1170 !PyUnicode_Check(sep)) {
1171 PyErr_Format(PyExc_TypeError,
1172 "sep must be None, str or unicode, not %.200s",
1173 sep->ob_type->tp_name);
1174 return NULL;
1175 }
1176 if (end && end != Py_None && !PyString_Check(end) &&
1177 !PyUnicode_Check(end)) {
1178 PyErr_Format(PyExc_TypeError,
1179 "end must be None, str or unicode, not %.200s",
1180 end->ob_type->tp_name);
1181 return NULL;
1182 }
Guido van Rossum34343512006-11-30 22:13:52 +00001183
1184 for (i = 0; i < PyTuple_Size(args); i++) {
1185 if (i > 0) {
1186 if (sep == NULL || sep == Py_None)
1187 err = PyFile_WriteString(" ", file);
1188 else
1189 err = PyFile_WriteObject(sep, file,
1190 Py_PRINT_RAW);
1191 if (err)
1192 return NULL;
1193 }
1194 err = PyFile_WriteObject(PyTuple_GetItem(args, i), file,
1195 Py_PRINT_RAW);
1196 if (err)
1197 return NULL;
1198 }
1199
1200 if (end == NULL || end == Py_None)
1201 err = PyFile_WriteString("\n", file);
1202 else
1203 err = PyFile_WriteObject(end, file, Py_PRINT_RAW);
1204 if (err)
1205 return NULL;
1206
1207 Py_RETURN_NONE;
1208}
1209
1210PyDoc_STRVAR(print_doc,
Guido van Rossum452bf512007-02-09 05:32:43 +00001211"print(value, ..., file=None, sep=' ', end='\\n')\n\
Guido van Rossum34343512006-11-30 22:13:52 +00001212\n\
1213Prints the values to a stream, or to sys.stdout by default.\n\
1214Optional keyword arguments:\n\
1215file: a file-like object (stream); defaults to the current sys.stdout.\n\
1216sep: string inserted between values, default a space.\n\
1217end: string appended after the last value, default a newline.");
1218
1219
Guido van Rossuma88a0332007-02-26 16:59:55 +00001220static PyObject *
1221builtin_input(PyObject *self, PyObject *args)
1222{
Guido van Rossumeba76962007-05-27 09:13:28 +00001223 PyObject *promptarg = NULL;
Guido van Rossuma88a0332007-02-26 16:59:55 +00001224 PyObject *fin = PySys_GetObject("stdin");
1225 PyObject *fout = PySys_GetObject("stdout");
Guido van Rossumeba76962007-05-27 09:13:28 +00001226 PyObject *ferr = PySys_GetObject("stderr");
1227 PyObject *tmp;
1228 long fd;
1229 int tty;
Guido van Rossuma88a0332007-02-26 16:59:55 +00001230
Guido van Rossumeba76962007-05-27 09:13:28 +00001231 /* Parse arguments */
1232 if (!PyArg_UnpackTuple(args, "input", 0, 1, &promptarg))
Guido van Rossuma88a0332007-02-26 16:59:55 +00001233 return NULL;
1234
Guido van Rossumeba76962007-05-27 09:13:28 +00001235 /* Check that stdin/out/err are intact */
Guido van Rossuma88a0332007-02-26 16:59:55 +00001236 if (fin == NULL) {
Guido van Rossumeba76962007-05-27 09:13:28 +00001237 PyErr_SetString(PyExc_RuntimeError,
1238 "input(): lost sys.stdin");
Guido van Rossuma88a0332007-02-26 16:59:55 +00001239 return NULL;
1240 }
1241 if (fout == NULL) {
Guido van Rossumeba76962007-05-27 09:13:28 +00001242 PyErr_SetString(PyExc_RuntimeError,
1243 "input(): lost sys.stdout");
Guido van Rossuma88a0332007-02-26 16:59:55 +00001244 return NULL;
1245 }
Guido van Rossumeba76962007-05-27 09:13:28 +00001246 if (ferr == NULL) {
1247 PyErr_SetString(PyExc_RuntimeError,
1248 "input(): lost sys.stderr");
1249 return NULL;
1250 }
1251
1252 /* First of all, flush stderr */
1253 tmp = PyObject_CallMethod(ferr, "flush", "");
1254 if (tmp == NULL)
Guido van Rossumc1f779c2007-07-03 08:25:58 +00001255 PyErr_Clear();
1256 else
1257 Py_DECREF(tmp);
Guido van Rossumeba76962007-05-27 09:13:28 +00001258
1259 /* We should only use (GNU) readline if Python's sys.stdin and
1260 sys.stdout are the same as C's stdin and stdout, because we
1261 need to pass it those. */
1262 tmp = PyObject_CallMethod(fin, "fileno", "");
Guido van Rossumc1f779c2007-07-03 08:25:58 +00001263 if (tmp == NULL) {
1264 PyErr_Clear();
1265 tty = 0;
1266 }
1267 else {
Guido van Rossumeba76962007-05-27 09:13:28 +00001268 fd = PyInt_AsLong(tmp);
1269 Py_DECREF(tmp);
1270 if (fd < 0 && PyErr_Occurred())
1271 return NULL;
Guido van Rossumc1f779c2007-07-03 08:25:58 +00001272 tty = fd == fileno(stdin) && isatty(fd);
1273 }
1274 if (tty) {
1275 tmp = PyObject_CallMethod(fout, "fileno", "");
1276 if (tmp == NULL)
1277 PyErr_Clear();
1278 else {
1279 fd = PyInt_AsLong(tmp);
1280 Py_DECREF(tmp);
1281 if (fd < 0 && PyErr_Occurred())
1282 return NULL;
1283 tty = fd == fileno(stdout) && isatty(fd);
1284 }
Guido van Rossumeba76962007-05-27 09:13:28 +00001285 }
1286
1287 /* If we're interactive, use (GNU) readline */
1288 if (tty) {
Guido van Rossuma88a0332007-02-26 16:59:55 +00001289 PyObject *po;
1290 char *prompt;
1291 char *s;
1292 PyObject *result;
Guido van Rossumeba76962007-05-27 09:13:28 +00001293 tmp = PyObject_CallMethod(fout, "flush", "");
1294 if (tmp == NULL)
Guido van Rossumc1f779c2007-07-03 08:25:58 +00001295 PyErr_Clear();
1296 else
1297 Py_DECREF(tmp);
Guido van Rossumeba76962007-05-27 09:13:28 +00001298 if (promptarg != NULL) {
1299 po = PyObject_Str(promptarg);
Guido van Rossuma88a0332007-02-26 16:59:55 +00001300 if (po == NULL)
1301 return NULL;
1302 prompt = PyString_AsString(po);
Guido van Rossumeba76962007-05-27 09:13:28 +00001303 if (prompt == NULL) {
1304 Py_DECREF(po);
Guido van Rossuma88a0332007-02-26 16:59:55 +00001305 return NULL;
Guido van Rossumeba76962007-05-27 09:13:28 +00001306 }
Guido van Rossuma88a0332007-02-26 16:59:55 +00001307 }
1308 else {
1309 po = NULL;
1310 prompt = "";
1311 }
Guido van Rossumeba76962007-05-27 09:13:28 +00001312 s = PyOS_Readline(stdin, stdout, prompt);
Guido van Rossuma88a0332007-02-26 16:59:55 +00001313 Py_XDECREF(po);
1314 if (s == NULL) {
1315 if (!PyErr_Occurred())
1316 PyErr_SetNone(PyExc_KeyboardInterrupt);
1317 return NULL;
1318 }
1319 if (*s == '\0') {
1320 PyErr_SetNone(PyExc_EOFError);
1321 result = NULL;
1322 }
1323 else { /* strip trailing '\n' */
1324 size_t len = strlen(s);
1325 if (len > PY_SSIZE_T_MAX) {
1326 PyErr_SetString(PyExc_OverflowError,
1327 "input: input too long");
1328 result = NULL;
1329 }
1330 else {
1331 result = PyString_FromStringAndSize(s, len-1);
1332 }
1333 }
1334 PyMem_FREE(s);
1335 return result;
1336 }
Guido van Rossumeba76962007-05-27 09:13:28 +00001337
1338 /* Fallback if we're not interactive */
1339 if (promptarg != NULL) {
1340 if (PyFile_WriteObject(promptarg, fout, Py_PRINT_RAW) != 0)
Guido van Rossuma88a0332007-02-26 16:59:55 +00001341 return NULL;
1342 }
Guido van Rossumeba76962007-05-27 09:13:28 +00001343 tmp = PyObject_CallMethod(fout, "flush", "");
1344 if (tmp == NULL)
Guido van Rossumc1f779c2007-07-03 08:25:58 +00001345 PyErr_Clear();
1346 else
1347 Py_DECREF(tmp);
Guido van Rossuma88a0332007-02-26 16:59:55 +00001348 return PyFile_GetLine(fin, -1);
1349}
1350
1351PyDoc_STRVAR(input_doc,
1352"input([prompt]) -> string\n\
1353\n\
1354Read a string from standard input. The trailing newline is stripped.\n\
1355If the user hits EOF (Unix: Ctl-D, Windows: Ctl-Z+Return), raise EOFError.\n\
1356On Unix, GNU readline is used if enabled. The prompt string, if given,\n\
1357is printed without a trailing newline before reading.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001358
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001359
Guido van Rossum79f25d91997-04-29 20:08:16 +00001360static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001361builtin_repr(PyObject *self, PyObject *v)
Guido van Rossumc89705d1992-11-26 08:54:07 +00001362{
Guido van Rossum79f25d91997-04-29 20:08:16 +00001363 return PyObject_Repr(v);
Guido van Rossumc89705d1992-11-26 08:54:07 +00001364}
1365
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001366PyDoc_STRVAR(repr_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001367"repr(object) -> string\n\
1368\n\
1369Return the canonical string representation of the object.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001370For most object types, eval(repr(object)) == object.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001371
1372
Guido van Rossum79f25d91997-04-29 20:08:16 +00001373static PyObject *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001374builtin_round(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum9e51f9b1993-02-12 16:29:05 +00001375{
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001376#define UNDEF_NDIGITS (-0x7fffffff) /* Unlikely ndigits value */
1377 static PyObject *round_str = NULL;
1378 int ndigits = UNDEF_NDIGITS;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001379 static char *kwlist[] = {"number", "ndigits", 0};
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001380 PyObject *number, *round;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001381
Alex Martelliae211f92007-08-22 23:21:33 +00001382 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|i:round",
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001383 kwlist, &number, &ndigits))
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001384 return NULL;
Alex Martelliae211f92007-08-22 23:21:33 +00001385
Guido van Rossum15d3d042007-08-24 02:02:45 +00001386 if (Py_Type(number)->tp_dict == NULL) {
1387 if (PyType_Ready(Py_Type(number)) < 0)
1388 return NULL;
1389 }
1390
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001391 if (round_str == NULL) {
1392 round_str = PyUnicode_FromString("__round__");
1393 if (round_str == NULL)
Alex Martelliae211f92007-08-22 23:21:33 +00001394 return NULL;
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001395 }
1396
1397 round = _PyType_Lookup(Py_Type(number), round_str);
1398 if (round == NULL) {
1399 PyErr_Format(PyExc_TypeError,
1400 "type %.100s doesn't define __round__ method",
1401 Py_Type(number)->tp_name);
Alex Martelliae211f92007-08-22 23:21:33 +00001402 return NULL;
1403 }
1404
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001405 if (ndigits == UNDEF_NDIGITS)
1406 return PyObject_CallFunction(round, "O", number);
Guido van Rossum9e51f9b1993-02-12 16:29:05 +00001407 else
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001408 return PyObject_CallFunction(round, "Oi", number, ndigits);
1409#undef UNDEF_NDIGITS
Guido van Rossum9e51f9b1993-02-12 16:29:05 +00001410}
1411
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001412PyDoc_STRVAR(round_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001413"round(number[, ndigits]) -> floating point number\n\
1414\n\
1415Round a number to a given precision in decimal digits (default 0 digits).\n\
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001416This returns an int when called with one argument, otherwise a float.\n\
1417Precision may be negative.");
1418
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001419
Raymond Hettinger64958a12003-12-17 20:43:33 +00001420static PyObject *
1421builtin_sorted(PyObject *self, PyObject *args, PyObject *kwds)
1422{
1423 PyObject *newlist, *v, *seq, *compare=NULL, *keyfunc=NULL, *newargs;
1424 PyObject *callable;
Martin v. Löwis15e62742006-02-27 16:46:16 +00001425 static char *kwlist[] = {"iterable", "cmp", "key", "reverse", 0};
Neal Norwitz6f0d4792005-12-15 06:40:36 +00001426 int reverse;
Raymond Hettinger64958a12003-12-17 20:43:33 +00001427
Neal Norwitz6f0d4792005-12-15 06:40:36 +00001428 /* args 1-4 should match listsort in Objects/listobject.c */
Armin Rigo71d7e702005-09-20 18:13:03 +00001429 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|OOi:sorted",
1430 kwlist, &seq, &compare, &keyfunc, &reverse))
1431 return NULL;
Raymond Hettinger64958a12003-12-17 20:43:33 +00001432
1433 newlist = PySequence_List(seq);
1434 if (newlist == NULL)
1435 return NULL;
1436
1437 callable = PyObject_GetAttrString(newlist, "sort");
1438 if (callable == NULL) {
1439 Py_DECREF(newlist);
1440 return NULL;
1441 }
Georg Brandl99d7e4e2005-08-31 22:21:15 +00001442
Raymond Hettinger64958a12003-12-17 20:43:33 +00001443 newargs = PyTuple_GetSlice(args, 1, 4);
1444 if (newargs == NULL) {
1445 Py_DECREF(newlist);
1446 Py_DECREF(callable);
1447 return NULL;
1448 }
1449
1450 v = PyObject_Call(callable, newargs, kwds);
1451 Py_DECREF(newargs);
1452 Py_DECREF(callable);
1453 if (v == NULL) {
1454 Py_DECREF(newlist);
1455 return NULL;
1456 }
1457 Py_DECREF(v);
1458 return newlist;
1459}
1460
1461PyDoc_STRVAR(sorted_doc,
1462"sorted(iterable, cmp=None, key=None, reverse=False) --> new sorted list");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001463
Guido van Rossum79f25d91997-04-29 20:08:16 +00001464static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001465builtin_vars(PyObject *self, PyObject *args)
Guido van Rossum2d951851994-08-29 12:52:16 +00001466{
Guido van Rossum79f25d91997-04-29 20:08:16 +00001467 PyObject *v = NULL;
1468 PyObject *d;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001469
Raymond Hettingerea3fdf42002-12-29 16:33:45 +00001470 if (!PyArg_UnpackTuple(args, "vars", 0, 1, &v))
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001471 return NULL;
Guido van Rossum2d951851994-08-29 12:52:16 +00001472 if (v == NULL) {
Guido van Rossum79f25d91997-04-29 20:08:16 +00001473 d = PyEval_GetLocals();
Guido van Rossum53bb7ff1995-07-26 16:26:31 +00001474 if (d == NULL) {
Guido van Rossum79f25d91997-04-29 20:08:16 +00001475 if (!PyErr_Occurred())
1476 PyErr_SetString(PyExc_SystemError,
Alex Martellia9b9c9f2003-04-23 13:34:35 +00001477 "vars(): no locals!?");
Guido van Rossum53bb7ff1995-07-26 16:26:31 +00001478 }
1479 else
Guido van Rossum79f25d91997-04-29 20:08:16 +00001480 Py_INCREF(d);
Guido van Rossum2d951851994-08-29 12:52:16 +00001481 }
1482 else {
Guido van Rossum79f25d91997-04-29 20:08:16 +00001483 d = PyObject_GetAttrString(v, "__dict__");
Guido van Rossum2d951851994-08-29 12:52:16 +00001484 if (d == NULL) {
Guido van Rossum79f25d91997-04-29 20:08:16 +00001485 PyErr_SetString(PyExc_TypeError,
Guido van Rossum2d951851994-08-29 12:52:16 +00001486 "vars() argument must have __dict__ attribute");
1487 return NULL;
1488 }
1489 }
1490 return d;
1491}
1492
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001493PyDoc_STRVAR(vars_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001494"vars([object]) -> dictionary\n\
1495\n\
1496Without arguments, equivalent to locals().\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001497With an argument, equivalent to object.__dict__.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001498
Alex Martelli86d8b342007-08-22 22:39:42 +00001499static PyObject *
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001500builtin_trunc(PyObject *self, PyObject *number)
Alex Martelli86d8b342007-08-22 22:39:42 +00001501{
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001502 static PyObject *trunc_str = NULL;
1503 PyObject *trunc;
1504
Guido van Rossum15d3d042007-08-24 02:02:45 +00001505 if (Py_Type(number)->tp_dict == NULL) {
1506 if (PyType_Ready(Py_Type(number)) < 0)
1507 return NULL;
1508 }
1509
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001510 if (trunc_str == NULL) {
1511 trunc_str = PyUnicode_FromString("__trunc__");
1512 if (trunc_str == NULL)
1513 return NULL;
1514 }
1515
1516 trunc = _PyType_Lookup(Py_Type(number), trunc_str);
1517 if (trunc == NULL) {
1518 PyErr_Format(PyExc_TypeError,
1519 "type %.100s doesn't define __trunc__ method",
1520 Py_Type(number)->tp_name);
Alex Martelli86d8b342007-08-22 22:39:42 +00001521 return NULL;
1522 }
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001523 return PyObject_CallFunction(trunc, "O", number);
Alex Martelli86d8b342007-08-22 22:39:42 +00001524}
1525
1526PyDoc_STRVAR(trunc_doc,
1527"trunc(Real) -> Integral\n\
1528\n\
1529returns the integral closest to x between 0 and x.");
1530
1531
Alex Martellia70b1912003-04-22 08:12:33 +00001532
1533static PyObject*
1534builtin_sum(PyObject *self, PyObject *args)
1535{
1536 PyObject *seq;
1537 PyObject *result = NULL;
1538 PyObject *temp, *item, *iter;
1539
Raymond Hettinger5cf63942003-10-25 06:41:37 +00001540 if (!PyArg_UnpackTuple(args, "sum", 1, 2, &seq, &result))
Alex Martellia70b1912003-04-22 08:12:33 +00001541 return NULL;
1542
1543 iter = PyObject_GetIter(seq);
1544 if (iter == NULL)
1545 return NULL;
1546
1547 if (result == NULL) {
1548 result = PyInt_FromLong(0);
1549 if (result == NULL) {
1550 Py_DECREF(iter);
1551 return NULL;
1552 }
1553 } else {
1554 /* reject string values for 'start' parameter */
1555 if (PyObject_TypeCheck(result, &PyBaseString_Type)) {
1556 PyErr_SetString(PyExc_TypeError,
Alex Martellia9b9c9f2003-04-23 13:34:35 +00001557 "sum() can't sum strings [use ''.join(seq) instead]");
Alex Martellia70b1912003-04-22 08:12:33 +00001558 Py_DECREF(iter);
1559 return NULL;
1560 }
Alex Martelli41c9f882003-04-22 09:24:48 +00001561 Py_INCREF(result);
Alex Martellia70b1912003-04-22 08:12:33 +00001562 }
1563
1564 for(;;) {
1565 item = PyIter_Next(iter);
1566 if (item == NULL) {
1567 /* error, or end-of-sequence */
1568 if (PyErr_Occurred()) {
1569 Py_DECREF(result);
1570 result = NULL;
1571 }
1572 break;
1573 }
Alex Martellia253e182003-10-25 23:24:14 +00001574 temp = PyNumber_Add(result, item);
Alex Martellia70b1912003-04-22 08:12:33 +00001575 Py_DECREF(result);
1576 Py_DECREF(item);
1577 result = temp;
1578 if (result == NULL)
1579 break;
1580 }
1581 Py_DECREF(iter);
1582 return result;
1583}
1584
1585PyDoc_STRVAR(sum_doc,
Thomas Wouters89f507f2006-12-13 04:49:30 +00001586"sum(sequence[, start]) -> value\n\
Alex Martellia70b1912003-04-22 08:12:33 +00001587\n\
1588Returns the sum of a sequence of numbers (NOT strings) plus the value\n\
Thomas Wouters89f507f2006-12-13 04:49:30 +00001589of parameter 'start' (which defaults to 0). When the sequence is\n\
1590empty, returns start.");
Alex Martellia70b1912003-04-22 08:12:33 +00001591
1592
Barry Warsawcde8b1b1997-08-22 21:14:38 +00001593static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001594builtin_isinstance(PyObject *self, PyObject *args)
Barry Warsawcde8b1b1997-08-22 21:14:38 +00001595{
1596 PyObject *inst;
1597 PyObject *cls;
Guido van Rossum823649d2001-03-21 18:40:58 +00001598 int retval;
Barry Warsawcde8b1b1997-08-22 21:14:38 +00001599
Raymond Hettingerea3fdf42002-12-29 16:33:45 +00001600 if (!PyArg_UnpackTuple(args, "isinstance", 2, 2, &inst, &cls))
Barry Warsawcde8b1b1997-08-22 21:14:38 +00001601 return NULL;
Guido van Rossumf5dd9141997-12-02 19:11:45 +00001602
Guido van Rossum823649d2001-03-21 18:40:58 +00001603 retval = PyObject_IsInstance(inst, cls);
1604 if (retval < 0)
Guido van Rossumad991772001-01-12 16:03:05 +00001605 return NULL;
Guido van Rossum77f6a652002-04-03 22:41:51 +00001606 return PyBool_FromLong(retval);
Barry Warsawcde8b1b1997-08-22 21:14:38 +00001607}
1608
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001609PyDoc_STRVAR(isinstance_doc,
Guido van Rossum77f6a652002-04-03 22:41:51 +00001610"isinstance(object, class-or-type-or-tuple) -> bool\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001611\n\
1612Return whether an object is an instance of a class or of a subclass thereof.\n\
Guido van Rossum03290ec2001-10-07 20:54:12 +00001613With a type as second argument, return whether that is the object's type.\n\
1614The form using a tuple, isinstance(x, (A, B, ...)), is a shortcut for\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001615isinstance(x, A) or isinstance(x, B) or ... (etc.).");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001616
Barry Warsawcde8b1b1997-08-22 21:14:38 +00001617
1618static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001619builtin_issubclass(PyObject *self, PyObject *args)
Barry Warsawcde8b1b1997-08-22 21:14:38 +00001620{
1621 PyObject *derived;
1622 PyObject *cls;
1623 int retval;
1624
Raymond Hettingerea3fdf42002-12-29 16:33:45 +00001625 if (!PyArg_UnpackTuple(args, "issubclass", 2, 2, &derived, &cls))
Barry Warsawcde8b1b1997-08-22 21:14:38 +00001626 return NULL;
Guido van Rossum668213d1999-06-16 17:28:37 +00001627
Guido van Rossum823649d2001-03-21 18:40:58 +00001628 retval = PyObject_IsSubclass(derived, cls);
1629 if (retval < 0)
1630 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(issubclass_doc,
Guido van Rossum77f6a652002-04-03 22:41:51 +00001635"issubclass(C, B) -> bool\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001636\n\
Walter Dörwaldd9a6ad32002-12-12 16:41:44 +00001637Return whether class C is a subclass (i.e., a derived class) of class B.\n\
1638When using a tuple as the second argument issubclass(X, (A, B, ...)),\n\
1639is a shortcut for issubclass(X, A) or issubclass(X, B) or ... (etc.).");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001640
Barry Warsawcde8b1b1997-08-22 21:14:38 +00001641
Barry Warsawbd599b52000-08-03 15:45:29 +00001642static PyObject*
1643builtin_zip(PyObject *self, PyObject *args)
1644{
Guido van Rossumb65fb332006-08-25 23:26:40 +00001645 /* args must be a tuple */
1646 assert(PyTuple_Check(args));
Barry Warsawbd599b52000-08-03 15:45:29 +00001647
Guido van Rossumb65fb332006-08-25 23:26:40 +00001648 return _PyZip_CreateIter(args);
Barry Warsawbd599b52000-08-03 15:45:29 +00001649}
1650
1651
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001652PyDoc_STRVAR(zip_doc,
Guido van Rossum801f0d72006-08-24 19:48:10 +00001653"zip(it1 [, it2 [...]]) -> iter([(it1[0], it2[0] ...), ...])\n\
Barry Warsawbd599b52000-08-03 15:45:29 +00001654\n\
Guido van Rossum801f0d72006-08-24 19:48:10 +00001655Return an iterator yielding tuples, where each tuple contains the\n\
1656corresponding element from each of the argument iterables.\n\
1657The returned iterator ends when the shortest argument iterable is exhausted.\n\
Guido van Rossumc1f779c2007-07-03 08:25:58 +00001658(This is identical to itertools.izip().)");
Barry Warsawbd599b52000-08-03 15:45:29 +00001659
1660
Guido van Rossum79f25d91997-04-29 20:08:16 +00001661static PyMethodDef builtin_methods[] = {
Guido van Rossum52cc1d82007-03-18 15:41:51 +00001662 {"__build_class__", (PyCFunction)builtin___build_class__,
1663 METH_VARARGS | METH_KEYWORDS, build_class_doc},
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001664 {"__import__", (PyCFunction)builtin___import__, METH_VARARGS | METH_KEYWORDS, import_doc},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001665 {"abs", builtin_abs, METH_O, abs_doc},
Raymond Hettinger96229b12005-03-11 06:49:40 +00001666 {"all", builtin_all, METH_O, all_doc},
1667 {"any", builtin_any, METH_O, any_doc},
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001668 {"bin", builtin_bin, METH_O, bin_doc},
Walter Dörwalde7efd592007-06-05 20:07:21 +00001669 {"chr", builtin_chr, METH_VARARGS, chr_doc},
1670 {"chr8", builtin_chr8, METH_VARARGS, chr8_doc},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001671 {"cmp", builtin_cmp, METH_VARARGS, cmp_doc},
Guido van Rossumd8faa362007-04-27 19:54:29 +00001672 {"compile", (PyCFunction)builtin_compile, METH_VARARGS | METH_KEYWORDS, compile_doc},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001673 {"delattr", builtin_delattr, METH_VARARGS, delattr_doc},
1674 {"dir", builtin_dir, METH_VARARGS, dir_doc},
1675 {"divmod", builtin_divmod, METH_VARARGS, divmod_doc},
1676 {"eval", builtin_eval, METH_VARARGS, eval_doc},
Georg Brandl7cae87c2006-09-06 06:51:57 +00001677 {"exec", builtin_exec, METH_VARARGS, exec_doc},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001678 {"filter", builtin_filter, METH_VARARGS, filter_doc},
1679 {"getattr", builtin_getattr, METH_VARARGS, getattr_doc},
1680 {"globals", (PyCFunction)builtin_globals, METH_NOARGS, globals_doc},
1681 {"hasattr", builtin_hasattr, METH_VARARGS, hasattr_doc},
1682 {"hash", builtin_hash, METH_O, hash_doc},
1683 {"hex", builtin_hex, METH_O, hex_doc},
1684 {"id", builtin_id, METH_O, id_doc},
Guido van Rossuma88a0332007-02-26 16:59:55 +00001685 {"input", builtin_input, METH_VARARGS, input_doc},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001686 {"isinstance", builtin_isinstance, METH_VARARGS, isinstance_doc},
1687 {"issubclass", builtin_issubclass, METH_VARARGS, issubclass_doc},
1688 {"iter", builtin_iter, METH_VARARGS, iter_doc},
1689 {"len", builtin_len, METH_O, len_doc},
1690 {"locals", (PyCFunction)builtin_locals, METH_NOARGS, locals_doc},
1691 {"map", builtin_map, METH_VARARGS, map_doc},
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001692 {"max", (PyCFunction)builtin_max, METH_VARARGS | METH_KEYWORDS, max_doc},
1693 {"min", (PyCFunction)builtin_min, METH_VARARGS | METH_KEYWORDS, min_doc},
Georg Brandla18af4e2007-04-21 15:47:16 +00001694 {"next", (PyCFunction)builtin_next, METH_VARARGS, next_doc},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001695 {"oct", builtin_oct, METH_O, oct_doc},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001696 {"ord", builtin_ord, METH_O, ord_doc},
1697 {"pow", builtin_pow, METH_VARARGS, pow_doc},
Guido van Rossum452bf512007-02-09 05:32:43 +00001698 {"print", (PyCFunction)builtin_print, METH_VARARGS | METH_KEYWORDS, print_doc},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001699 {"repr", builtin_repr, METH_O, repr_doc},
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001700 {"round", (PyCFunction)builtin_round, METH_VARARGS | METH_KEYWORDS, round_doc},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001701 {"setattr", builtin_setattr, METH_VARARGS, setattr_doc},
Raymond Hettinger64958a12003-12-17 20:43:33 +00001702 {"sorted", (PyCFunction)builtin_sorted, METH_VARARGS | METH_KEYWORDS, sorted_doc},
Alex Martellia70b1912003-04-22 08:12:33 +00001703 {"sum", builtin_sum, METH_VARARGS, sum_doc},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001704 {"vars", builtin_vars, METH_VARARGS, vars_doc},
Alex Martelli86d8b342007-08-22 22:39:42 +00001705 {"trunc", builtin_trunc, METH_O, trunc_doc},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001706 {"zip", builtin_zip, METH_VARARGS, zip_doc},
Guido van Rossumc02e15c1991-12-16 13:03:00 +00001707 {NULL, NULL},
Guido van Rossum3f5da241990-12-20 15:06:42 +00001708};
1709
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001710PyDoc_STRVAR(builtin_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001711"Built-in functions, exceptions, and other objects.\n\
1712\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001713Noteworthy: None is the `nil' object; Ellipsis represents `...' in slices.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001714
Guido van Rossum25ce5661997-08-02 03:10:38 +00001715PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001716_PyBuiltin_Init(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +00001717{
Fred Drake5550de32000-06-20 04:54:19 +00001718 PyObject *mod, *dict, *debug;
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001719 mod = Py_InitModule4("__builtin__", builtin_methods,
1720 builtin_doc, (PyObject *)NULL,
1721 PYTHON_API_VERSION);
Guido van Rossum25ce5661997-08-02 03:10:38 +00001722 if (mod == NULL)
1723 return NULL;
1724 dict = PyModule_GetDict(mod);
Tim Peters4b7625e2001-09-13 21:37:17 +00001725
Tim Peters7571a0f2003-03-23 17:52:28 +00001726#ifdef Py_TRACE_REFS
1727 /* __builtin__ exposes a number of statically allocated objects
1728 * that, before this code was added in 2.3, never showed up in
1729 * the list of "all objects" maintained by Py_TRACE_REFS. As a
1730 * result, programs leaking references to None and False (etc)
1731 * couldn't be diagnosed by examining sys.getobjects(0).
1732 */
1733#define ADD_TO_ALL(OBJECT) _Py_AddToAllObjects((PyObject *)(OBJECT), 0)
1734#else
1735#define ADD_TO_ALL(OBJECT) (void)0
1736#endif
1737
Tim Peters4b7625e2001-09-13 21:37:17 +00001738#define SETBUILTIN(NAME, OBJECT) \
Tim Peters7571a0f2003-03-23 17:52:28 +00001739 if (PyDict_SetItemString(dict, NAME, (PyObject *)OBJECT) < 0) \
1740 return NULL; \
1741 ADD_TO_ALL(OBJECT)
Tim Peters4b7625e2001-09-13 21:37:17 +00001742
1743 SETBUILTIN("None", Py_None);
1744 SETBUILTIN("Ellipsis", Py_Ellipsis);
1745 SETBUILTIN("NotImplemented", Py_NotImplemented);
Guido van Rossum77f6a652002-04-03 22:41:51 +00001746 SETBUILTIN("False", Py_False);
1747 SETBUILTIN("True", Py_True);
Neal Norwitz32a7e7f2002-05-31 19:58:02 +00001748 SETBUILTIN("basestring", &PyBaseString_Type);
Guido van Rossum77f6a652002-04-03 22:41:51 +00001749 SETBUILTIN("bool", &PyBool_Type);
Guido van Rossumbea18cc2002-06-14 20:41:17 +00001750 SETBUILTIN("buffer", &PyBuffer_Type);
Travis E. Oliphantb99f7622007-08-18 11:21:56 +00001751 SETBUILTIN("memoryview", &PyMemoryView_Type);
Guido van Rossum4dfe8a12006-04-22 23:28:04 +00001752 SETBUILTIN("bytes", &PyBytes_Type);
Tim Peters4b7625e2001-09-13 21:37:17 +00001753 SETBUILTIN("classmethod", &PyClassMethod_Type);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001754#ifndef WITHOUT_COMPLEX
Tim Peters4b7625e2001-09-13 21:37:17 +00001755 SETBUILTIN("complex", &PyComplex_Type);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001756#endif
Tim Petersa427a2b2001-10-29 22:25:45 +00001757 SETBUILTIN("dict", &PyDict_Type);
Tim Peters67d687a2002-04-29 21:27:32 +00001758 SETBUILTIN("enumerate", &PyEnum_Type);
Tim Peters4b7625e2001-09-13 21:37:17 +00001759 SETBUILTIN("float", &PyFloat_Type);
Raymond Hettingera690a992003-11-16 16:17:49 +00001760 SETBUILTIN("frozenset", &PyFrozenSet_Type);
Tim Peters4b7625e2001-09-13 21:37:17 +00001761 SETBUILTIN("property", &PyProperty_Type);
Guido van Rossumddefaf32007-01-14 03:31:43 +00001762 SETBUILTIN("int", &PyLong_Type);
Tim Peters4b7625e2001-09-13 21:37:17 +00001763 SETBUILTIN("list", &PyList_Type);
Tim Peters4b7625e2001-09-13 21:37:17 +00001764 SETBUILTIN("object", &PyBaseObject_Type);
Guido van Rossum805365e2007-05-07 22:24:25 +00001765 SETBUILTIN("range", &PyRange_Type);
Raymond Hettinger85c20a42003-11-06 14:06:48 +00001766 SETBUILTIN("reversed", &PyReversed_Type);
Raymond Hettingera690a992003-11-16 16:17:49 +00001767 SETBUILTIN("set", &PySet_Type);
Guido van Rossumbea18cc2002-06-14 20:41:17 +00001768 SETBUILTIN("slice", &PySlice_Type);
Tim Peters4b7625e2001-09-13 21:37:17 +00001769 SETBUILTIN("staticmethod", &PyStaticMethod_Type);
Guido van Rossum572dbf82007-04-27 23:53:51 +00001770 SETBUILTIN("str", &PyUnicode_Type);
Guido van Rossum84fc66d2007-05-03 17:18:26 +00001771 SETBUILTIN("str8", &PyString_Type);
Tim Peters4b7625e2001-09-13 21:37:17 +00001772 SETBUILTIN("super", &PySuper_Type);
1773 SETBUILTIN("tuple", &PyTuple_Type);
1774 SETBUILTIN("type", &PyType_Type);
Guido van Rossum77f6a652002-04-03 22:41:51 +00001775 debug = PyBool_FromLong(Py_OptimizeFlag == 0);
Fred Drake5550de32000-06-20 04:54:19 +00001776 if (PyDict_SetItemString(dict, "__debug__", debug) < 0) {
1777 Py_XDECREF(debug);
Guido van Rossum25ce5661997-08-02 03:10:38 +00001778 return NULL;
Fred Drake5550de32000-06-20 04:54:19 +00001779 }
1780 Py_XDECREF(debug);
Barry Warsaw757af0e1997-08-29 22:13:51 +00001781
Guido van Rossum25ce5661997-08-02 03:10:38 +00001782 return mod;
Tim Peters7571a0f2003-03-23 17:52:28 +00001783#undef ADD_TO_ALL
Tim Peters4b7625e2001-09-13 21:37:17 +00001784#undef SETBUILTIN
Guido van Rossum3f5da241990-12-20 15:06:42 +00001785}