blob: 70f1170239330cd026e75be6bf64736d323bd1b0 [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
Guido van Rossum00bc0e02007-10-15 02:52:41 +000013
14 Don't forget to modify PyUnicode_DecodeFSDefault() if you touch any of the
15 values for Py_FileSystemDefaultEncoding!
Mark Hammond26cffde42001-05-14 12:17:34 +000016*/
Martin v. Löwis6238d2b2002-06-30 15:26:10 +000017#if defined(MS_WINDOWS) && defined(HAVE_USABLE_WCHAR_T)
Mark Hammond26cffde42001-05-14 12:17:34 +000018const char *Py_FileSystemDefaultEncoding = "mbcs";
Just van Rossumb9b8e9c2003-02-10 09:22:01 +000019#elif defined(__APPLE__)
20const char *Py_FileSystemDefaultEncoding = "utf-8";
Mark Hammond26cffde42001-05-14 12:17:34 +000021#else
22const char *Py_FileSystemDefaultEncoding = NULL; /* use default */
23#endif
Mark Hammondef8b6542001-05-13 08:04:26 +000024
Guido van Rossum79f25d91997-04-29 20:08:16 +000025static PyObject *
Guido van Rossum52cc1d82007-03-18 15:41:51 +000026builtin___build_class__(PyObject *self, PyObject *args, PyObject *kwds)
27{
Guido van Rossumcd16bf62007-06-13 18:07:49 +000028 PyObject *func, *name, *bases, *mkw, *meta, *prep, *ns, *cell;
29 PyObject *cls = NULL;
Guido van Rossum52cc1d82007-03-18 15:41:51 +000030 Py_ssize_t nargs, nbases;
31
32 assert(args != NULL);
33 if (!PyTuple_Check(args)) {
34 PyErr_SetString(PyExc_TypeError,
35 "__build_class__: args is not a tuple");
36 return NULL;
37 }
38 nargs = PyTuple_GET_SIZE(args);
39 if (nargs < 2) {
40 PyErr_SetString(PyExc_TypeError,
41 "__build_class__: not enough arguments");
42 return NULL;
43 }
44 func = PyTuple_GET_ITEM(args, 0); /* Better be callable */
45 name = PyTuple_GET_ITEM(args, 1);
Neal Norwitz6ea45d32007-08-26 04:19:43 +000046 if (!PyUnicode_Check(name)) {
Guido van Rossum52cc1d82007-03-18 15:41:51 +000047 PyErr_SetString(PyExc_TypeError,
48 "__build_class__: name is not a string");
49 return NULL;
50 }
51 bases = PyTuple_GetSlice(args, 2, nargs);
52 if (bases == NULL)
53 return NULL;
54 nbases = nargs - 2;
55
56 if (kwds == NULL) {
57 meta = NULL;
58 mkw = NULL;
59 }
60 else {
61 mkw = PyDict_Copy(kwds); /* Don't modify kwds passed in! */
62 if (mkw == NULL) {
63 Py_DECREF(bases);
64 return NULL;
65 }
66 meta = PyDict_GetItemString(mkw, "metaclass");
67 if (meta != NULL) {
68 Py_INCREF(meta);
69 if (PyDict_DelItemString(mkw, "metaclass") < 0) {
70 Py_DECREF(meta);
71 Py_DECREF(mkw);
72 Py_DECREF(bases);
73 return NULL;
74 }
75 }
76 }
77 if (meta == NULL) {
78 if (PyTuple_GET_SIZE(bases) == 0)
79 meta = (PyObject *) (&PyType_Type);
80 else {
81 PyObject *base0 = PyTuple_GET_ITEM(bases, 0);
82 meta = (PyObject *) (base0->ob_type);
83 }
84 Py_INCREF(meta);
85 }
86 prep = PyObject_GetAttrString(meta, "__prepare__");
87 if (prep == NULL) {
88 PyErr_Clear();
89 ns = PyDict_New();
90 }
91 else {
92 PyObject *pargs = Py_BuildValue("OO", name, bases);
93 if (pargs == NULL) {
94 Py_DECREF(prep);
95 Py_DECREF(meta);
96 Py_XDECREF(mkw);
97 Py_DECREF(bases);
98 return NULL;
99 }
100 ns = PyEval_CallObjectWithKeywords(prep, pargs, mkw);
101 Py_DECREF(pargs);
102 Py_DECREF(prep);
103 if (ns == NULL) {
104 Py_DECREF(meta);
105 Py_XDECREF(mkw);
106 Py_DECREF(bases);
107 return NULL;
108 }
109 }
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000110 cell = PyObject_CallFunctionObjArgs(func, ns, NULL);
111 if (cell != NULL) {
Guido van Rossum52cc1d82007-03-18 15:41:51 +0000112 PyObject *margs;
Guido van Rossum52cc1d82007-03-18 15:41:51 +0000113 margs = Py_BuildValue("OOO", name, bases, ns);
114 if (margs != NULL) {
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000115 cls = PyEval_CallObjectWithKeywords(meta, margs, mkw);
Guido van Rossum52cc1d82007-03-18 15:41:51 +0000116 Py_DECREF(margs);
117 }
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000118 if (cls != NULL && PyCell_Check(cell)) {
119 Py_INCREF(cls);
120 PyCell_SET(cell, cls);
121 }
122 Py_DECREF(cell);
Guido van Rossum52cc1d82007-03-18 15:41:51 +0000123 }
124 Py_DECREF(ns);
125 Py_DECREF(meta);
126 Py_XDECREF(mkw);
127 Py_DECREF(bases);
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000128 return cls;
Guido van Rossum52cc1d82007-03-18 15:41:51 +0000129}
130
131PyDoc_STRVAR(build_class_doc,
132"__build_class__(func, name, *bases, metaclass=None, **kwds) -> class\n\
133\n\
134Internal helper function used by the class statement.");
135
136static PyObject *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000137builtin___import__(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000138{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000139 static char *kwlist[] = {"name", "globals", "locals", "fromlist",
140 "level", 0};
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000141 char *name;
Guido van Rossum79f25d91997-04-29 20:08:16 +0000142 PyObject *globals = NULL;
143 PyObject *locals = NULL;
144 PyObject *fromlist = NULL;
Thomas Woutersf7f438b2006-02-28 16:09:29 +0000145 int level = -1;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000146
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000147 if (!PyArg_ParseTupleAndKeywords(args, kwds, "s|OOOi:__import__",
148 kwlist, &name, &globals, &locals, &fromlist, &level))
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000149 return NULL;
Thomas Woutersf7f438b2006-02-28 16:09:29 +0000150 return PyImport_ImportModuleLevel(name, globals, locals,
151 fromlist, level);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000152}
153
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000154PyDoc_STRVAR(import_doc,
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000155"__import__(name, globals={}, locals={}, fromlist=[], level=-1) -> module\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000156\n\
157Import a module. The globals are only used to determine the context;\n\
158they are not modified. The locals are currently unused. The fromlist\n\
159should be a list of names to emulate ``from name import ...'', or an\n\
160empty list to emulate ``import name''.\n\
161When importing a module from a package, note that __import__('A.B', ...)\n\
162returns package A when fromlist is empty, but its submodule B when\n\
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000163fromlist is not empty. Level is used to determine whether to perform \n\
164absolute or relative imports. -1 is the original strategy of attempting\n\
165both absolute and relative imports, 0 is absolute, a positive number\n\
166is the number of parent directories to search relative to the current module.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000167
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000168
Guido van Rossum79f25d91997-04-29 20:08:16 +0000169static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000170builtin_abs(PyObject *self, PyObject *v)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000171{
Guido van Rossum09df08a1998-05-22 00:51:39 +0000172 return PyNumber_Absolute(v);
Guido van Rossum3f5da241990-12-20 15:06:42 +0000173}
174
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000175PyDoc_STRVAR(abs_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000176"abs(number) -> number\n\
177\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000178Return the absolute value of the argument.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000179
Raymond Hettinger96229b12005-03-11 06:49:40 +0000180static PyObject *
181builtin_all(PyObject *self, PyObject *v)
182{
183 PyObject *it, *item;
184
185 it = PyObject_GetIter(v);
186 if (it == NULL)
187 return NULL;
188
189 while ((item = PyIter_Next(it)) != NULL) {
190 int cmp = PyObject_IsTrue(item);
191 Py_DECREF(item);
192 if (cmp < 0) {
193 Py_DECREF(it);
194 return NULL;
195 }
196 if (cmp == 0) {
197 Py_DECREF(it);
198 Py_RETURN_FALSE;
199 }
200 }
201 Py_DECREF(it);
202 if (PyErr_Occurred())
203 return NULL;
204 Py_RETURN_TRUE;
205}
206
207PyDoc_STRVAR(all_doc,
208"all(iterable) -> bool\n\
209\n\
210Return True if bool(x) is True for all values x in the iterable.");
211
212static PyObject *
213builtin_any(PyObject *self, PyObject *v)
214{
215 PyObject *it, *item;
216
217 it = PyObject_GetIter(v);
218 if (it == NULL)
219 return NULL;
220
221 while ((item = PyIter_Next(it)) != NULL) {
222 int cmp = PyObject_IsTrue(item);
223 Py_DECREF(item);
224 if (cmp < 0) {
225 Py_DECREF(it);
226 return NULL;
227 }
228 if (cmp == 1) {
229 Py_DECREF(it);
230 Py_RETURN_TRUE;
231 }
232 }
233 Py_DECREF(it);
234 if (PyErr_Occurred())
235 return NULL;
236 Py_RETURN_FALSE;
237}
238
239PyDoc_STRVAR(any_doc,
240"any(iterable) -> bool\n\
241\n\
242Return True if bool(x) is True for any x in the iterable.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000243
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000244
Guido van Rossum79f25d91997-04-29 20:08:16 +0000245static PyObject *
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000246builtin_bin(PyObject *self, PyObject *v)
247{
248 return PyNumber_ToBase(v, 2);
249}
250
251PyDoc_STRVAR(bin_doc,
252"bin(number) -> string\n\
253\n\
254Return the binary representation of an integer or long integer.");
255
256
257static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000258builtin_filter(PyObject *self, PyObject *args)
Guido van Rossum12d12c51993-10-26 17:58:25 +0000259{
Guido van Rossumc1f779c2007-07-03 08:25:58 +0000260 PyObject *itertools, *ifilter, *result;
261 itertools = PyImport_ImportModule("itertools");
262 if (itertools == NULL)
Guido van Rossum12d12c51993-10-26 17:58:25 +0000263 return NULL;
Guido van Rossumc1f779c2007-07-03 08:25:58 +0000264 ifilter = PyObject_GetAttrString(itertools, "ifilter");
265 Py_DECREF(itertools);
266 if (ifilter == NULL)
Georg Brandle35b6572005-07-19 22:20:20 +0000267 return NULL;
Guido van Rossumc1f779c2007-07-03 08:25:58 +0000268 result = PyObject_Call(ifilter, args, NULL);
269 Py_DECREF(ifilter);
Guido van Rossum12d12c51993-10-26 17:58:25 +0000270 return result;
Guido van Rossum12d12c51993-10-26 17:58:25 +0000271}
272
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000273PyDoc_STRVAR(filter_doc,
Guido van Rossumc1f779c2007-07-03 08:25:58 +0000274"filter(predicate, iterable) -> iterator\n\
275\n\
276Return an iterator yielding only those elements of the input iterable\n\
277for which the predicate (a Boolean function) returns true.\n\
278If the predicate is None, 'lambda x: bool(x)' is assumed.\n\
279(This is identical to itertools.ifilter().)");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000280
Eric Smith8c663262007-08-25 02:26:07 +0000281static PyObject *
282builtin_format(PyObject *self, PyObject *args)
283{
284 static PyObject * format_str = NULL;
285 PyObject *value;
Eric Smith81936692007-08-31 01:14:01 +0000286 PyObject *spec = NULL;
Eric Smith8c663262007-08-25 02:26:07 +0000287 PyObject *meth;
Eric Smith81936692007-08-31 01:14:01 +0000288 PyObject *empty = NULL;
289 PyObject *result = NULL;
Eric Smith8c663262007-08-25 02:26:07 +0000290
291 /* Initialize cached value */
292 if (format_str == NULL) {
293 /* Initialize static variable needed by _PyType_Lookup */
294 format_str = PyUnicode_FromString("__format__");
295 if (format_str == NULL)
Eric Smith81936692007-08-31 01:14:01 +0000296 goto done;
Eric Smith8c663262007-08-25 02:26:07 +0000297 }
298
Eric Smith37f10382007-09-01 10:56:01 +0000299 if (!PyArg_ParseTuple(args, "O|U:format", &value, &spec))
Eric Smith81936692007-08-31 01:14:01 +0000300 goto done;
301
302 /* initialize the default value */
303 if (spec == NULL) {
304 empty = PyUnicode_FromUnicode(NULL, 0);
305 spec = empty;
306 }
Eric Smith8c663262007-08-25 02:26:07 +0000307
308 /* Make sure the type is initialized. float gets initialized late */
309 if (Py_Type(value)->tp_dict == NULL)
310 if (PyType_Ready(Py_Type(value)) < 0)
Eric Smith81936692007-08-31 01:14:01 +0000311 goto done;
Eric Smith8c663262007-08-25 02:26:07 +0000312
313 /* Find the (unbound!) __format__ method (a borrowed reference) */
314 meth = _PyType_Lookup(Py_Type(value), format_str);
315 if (meth == NULL) {
316 PyErr_Format(PyExc_TypeError,
317 "Type %.100s doesn't define __format__",
318 Py_Type(value)->tp_name);
Eric Smith81936692007-08-31 01:14:01 +0000319 goto done;
Eric Smith8c663262007-08-25 02:26:07 +0000320 }
321
322 /* And call it, binding it to the value */
323 result = PyObject_CallFunctionObjArgs(meth, value, spec, NULL);
324
Eric Smith81936692007-08-31 01:14:01 +0000325 if (result && !PyUnicode_Check(result)) {
Eric Smith8c663262007-08-25 02:26:07 +0000326 PyErr_SetString(PyExc_TypeError,
327 "__format__ method did not return string");
328 Py_DECREF(result);
Eric Smith81936692007-08-31 01:14:01 +0000329 result = NULL;
330 goto done;
Eric Smith8c663262007-08-25 02:26:07 +0000331 }
Eric Smith8c663262007-08-25 02:26:07 +0000332
Eric Smith81936692007-08-31 01:14:01 +0000333done:
334 Py_XDECREF(empty);
Eric Smith8c663262007-08-25 02:26:07 +0000335 return result;
336}
337
Eric Smith8c663262007-08-25 02:26:07 +0000338PyDoc_STRVAR(format_doc,
Eric Smith81936692007-08-31 01:14:01 +0000339"format(value[, format_spec]) -> string\n\
Eric Smith8c663262007-08-25 02:26:07 +0000340\n\
Eric Smith81936692007-08-31 01:14:01 +0000341Returns value.__format__(format_spec)\n\
342format_spec defaults to \"\"");
343
Guido van Rossum7fcf2242007-05-04 17:43:11 +0000344static PyObject *
Walter Dörwalde7efd592007-06-05 20:07:21 +0000345builtin_chr(PyObject *self, PyObject *args)
Guido van Rossum09095f32000-03-10 23:00:52 +0000346{
347 long x;
Guido van Rossum09095f32000-03-10 23:00:52 +0000348
Walter Dörwalde7efd592007-06-05 20:07:21 +0000349 if (!PyArg_ParseTuple(args, "l:chr", &x))
Guido van Rossum09095f32000-03-10 23:00:52 +0000350 return NULL;
Fredrik Lundh0dcf67e2001-06-26 20:01:56 +0000351
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +0000352 return PyUnicode_FromOrdinal(x);
Guido van Rossum09095f32000-03-10 23:00:52 +0000353}
354
Guido van Rossum307fa8c2007-07-16 20:46:27 +0000355PyDoc_VAR(chr_doc) = PyDoc_STR(
Guido van Rossum84fc66d2007-05-03 17:18:26 +0000356"chr(i) -> Unicode character\n\
Guido van Rossum09095f32000-03-10 23:00:52 +0000357\n\
Guido van Rossum8ac004e2007-07-15 13:00:05 +0000358Return a Unicode string of one character with ordinal i; 0 <= i <= 0x10ffff."
Guido van Rossum307fa8c2007-07-16 20:46:27 +0000359)
Guido van Rossum8ac004e2007-07-15 13:00:05 +0000360#ifndef Py_UNICODE_WIDE
Guido van Rossum307fa8c2007-07-16 20:46:27 +0000361PyDoc_STR(
Guido van Rossum8ac004e2007-07-15 13:00:05 +0000362"\nIf 0x10000 <= i, a surrogate pair is returned."
Guido van Rossum307fa8c2007-07-16 20:46:27 +0000363)
Guido van Rossum8ac004e2007-07-15 13:00:05 +0000364#endif
Guido van Rossum307fa8c2007-07-16 20:46:27 +0000365;
Guido van Rossum09095f32000-03-10 23:00:52 +0000366
367
368static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000369builtin_cmp(PyObject *self, PyObject *args)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +0000370{
Guido van Rossum79f25d91997-04-29 20:08:16 +0000371 PyObject *a, *b;
Guido van Rossum09df08a1998-05-22 00:51:39 +0000372 int c;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000373
Raymond Hettingerea3fdf42002-12-29 16:33:45 +0000374 if (!PyArg_UnpackTuple(args, "cmp", 2, 2, &a, &b))
Guido van Rossuma9e7dc11992-10-18 18:53:57 +0000375 return NULL;
Guido van Rossum09df08a1998-05-22 00:51:39 +0000376 if (PyObject_Cmp(a, b, &c) < 0)
Guido van Rossumc8b6df91997-05-23 00:06:51 +0000377 return NULL;
Guido van Rossum09df08a1998-05-22 00:51:39 +0000378 return PyInt_FromLong((long)c);
Guido van Rossuma9e7dc11992-10-18 18:53:57 +0000379}
380
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000381PyDoc_STRVAR(cmp_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000382"cmp(x, y) -> integer\n\
383\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000384Return negative if x<y, zero if x==y, positive if x>y.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000385
Guido van Rossumf15a29f2007-05-04 00:41:39 +0000386
387static char *
388source_as_string(PyObject *cmd)
389{
390 char *str;
391 Py_ssize_t size;
392
Guido van Rossumf15a29f2007-05-04 00:41:39 +0000393 if (PyUnicode_Check(cmd)) {
394 cmd = _PyUnicode_AsDefaultEncodedString(cmd, NULL);
395 if (cmd == NULL)
396 return NULL;
397 }
Guido van Rossuma4b8d1d2007-08-27 15:02:28 +0000398 else if (!PyObject_CheckReadBuffer(cmd)) {
399 PyErr_SetString(PyExc_TypeError,
400 "eval()/exec() arg 1 must be a string, bytes or code object");
401 return NULL;
402 }
Guido van Rossumf15a29f2007-05-04 00:41:39 +0000403 if (PyObject_AsReadBuffer(cmd, (const void **)&str, &size) < 0) {
404 return NULL;
405 }
406 if (strlen(str) != size) {
407 PyErr_SetString(PyExc_TypeError,
408 "source code string cannot contain null bytes");
409 return NULL;
410 }
411 return str;
412}
413
Guido van Rossum79f25d91997-04-29 20:08:16 +0000414static PyObject *
Guido van Rossumd8faa362007-04-27 19:54:29 +0000415builtin_compile(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum5b722181993-03-30 17:46:03 +0000416{
417 char *str;
418 char *filename;
419 char *startstr;
420 int start;
Tim Peters6cd6a822001-08-17 22:11:27 +0000421 int dont_inherit = 0;
422 int supplied_flags = 0;
Tim Peters5ba58662001-07-16 02:29:45 +0000423 PyCompilerFlags cf;
Guido van Rossumf15a29f2007-05-04 00:41:39 +0000424 PyObject *cmd;
Guido van Rossumd8faa362007-04-27 19:54:29 +0000425 static char *kwlist[] = {"source", "filename", "mode", "flags",
426 "dont_inherit", NULL};
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000427
Guido van Rossumd8faa362007-04-27 19:54:29 +0000428 if (!PyArg_ParseTupleAndKeywords(args, kwds, "Oss|ii:compile",
429 kwlist, &cmd, &filename, &startstr,
430 &supplied_flags, &dont_inherit))
Guido van Rossum5b722181993-03-30 17:46:03 +0000431 return NULL;
Tim Peters6cd6a822001-08-17 22:11:27 +0000432
Guido van Rossumf15a29f2007-05-04 00:41:39 +0000433 cf.cf_flags = supplied_flags | PyCF_SOURCE_IS_UTF8;
Just van Rossum3aaf42c2003-02-10 08:21:10 +0000434
Guido van Rossumf15a29f2007-05-04 00:41:39 +0000435 str = source_as_string(cmd);
436 if (str == NULL)
Just van Rossumb9b8e9c2003-02-10 09:22:01 +0000437 return NULL;
Just van Rossum3aaf42c2003-02-10 08:21:10 +0000438
Guido van Rossum5b722181993-03-30 17:46:03 +0000439 if (strcmp(startstr, "exec") == 0)
Guido van Rossumb05a5c71997-05-07 17:46:13 +0000440 start = Py_file_input;
Guido van Rossum5b722181993-03-30 17:46:03 +0000441 else if (strcmp(startstr, "eval") == 0)
Guido van Rossumb05a5c71997-05-07 17:46:13 +0000442 start = Py_eval_input;
Guido van Rossum872537c1995-07-07 22:43:42 +0000443 else if (strcmp(startstr, "single") == 0)
Guido van Rossumb05a5c71997-05-07 17:46:13 +0000444 start = Py_single_input;
Guido van Rossum5b722181993-03-30 17:46:03 +0000445 else {
Guido van Rossum79f25d91997-04-29 20:08:16 +0000446 PyErr_SetString(PyExc_ValueError,
Fred Drake661ea262000-10-24 19:57:45 +0000447 "compile() arg 3 must be 'exec' or 'eval' or 'single'");
Guido van Rossumf15a29f2007-05-04 00:41:39 +0000448 return NULL;
Guido van Rossum5b722181993-03-30 17:46:03 +0000449 }
Tim Peters6cd6a822001-08-17 22:11:27 +0000450
Guido van Rossum4b499dd32003-02-13 22:07:59 +0000451 if (supplied_flags &
Martin v. Löwisbd260da2006-02-26 19:42:26 +0000452 ~(PyCF_MASK | PyCF_MASK_OBSOLETE | PyCF_DONT_IMPLY_DEDENT | PyCF_ONLY_AST))
Guido van Rossum4b499dd32003-02-13 22:07:59 +0000453 {
Tim Peters6cd6a822001-08-17 22:11:27 +0000454 PyErr_SetString(PyExc_ValueError,
455 "compile(): unrecognised flags");
Guido van Rossumf15a29f2007-05-04 00:41:39 +0000456 return NULL;
Tim Peters6cd6a822001-08-17 22:11:27 +0000457 }
458 /* XXX Warn if (supplied_flags & PyCF_MASK_OBSOLETE) != 0? */
459
Tim Peters6cd6a822001-08-17 22:11:27 +0000460 if (!dont_inherit) {
461 PyEval_MergeCompilerFlags(&cf);
462 }
Guido van Rossumf15a29f2007-05-04 00:41:39 +0000463 return Py_CompileStringFlags(str, filename, start, &cf);
Guido van Rossum5b722181993-03-30 17:46:03 +0000464}
465
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000466PyDoc_STRVAR(compile_doc,
Tim Peters6cd6a822001-08-17 22:11:27 +0000467"compile(source, filename, mode[, flags[, dont_inherit]]) -> code object\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000468\n\
469Compile the source string (a Python module, statement or expression)\n\
Georg Brandl7cae87c2006-09-06 06:51:57 +0000470into a code object that can be executed by exec() or eval().\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000471The filename will be used for run-time error messages.\n\
472The mode must be 'exec' to compile a module, 'single' to compile a\n\
Tim Peters6cd6a822001-08-17 22:11:27 +0000473single (interactive) statement, or 'eval' to compile an expression.\n\
474The flags argument, if present, controls which future statements influence\n\
475the compilation of the code.\n\
476The dont_inherit argument, if non-zero, stops the compilation inheriting\n\
477the effects of any future statements in effect in the code calling\n\
478compile; if absent or zero these statements do influence the compilation,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000479in addition to any features explicitly specified.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000480
Guido van Rossum79f25d91997-04-29 20:08:16 +0000481static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000482builtin_dir(PyObject *self, PyObject *args)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000483{
Tim Peters5d2b77c2001-09-03 05:47:38 +0000484 PyObject *arg = NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000485
Raymond Hettingerea3fdf42002-12-29 16:33:45 +0000486 if (!PyArg_UnpackTuple(args, "dir", 0, 1, &arg))
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000487 return NULL;
Tim Peters7eea37e2001-09-04 22:08:56 +0000488 return PyObject_Dir(arg);
Guido van Rossum3f5da241990-12-20 15:06:42 +0000489}
490
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000491PyDoc_STRVAR(dir_doc,
Tim Peters5d2b77c2001-09-03 05:47:38 +0000492"dir([object]) -> list of strings\n"
493"\n"
Georg Brandle32b4222007-03-10 22:13:27 +0000494"If called without an argument, return the names in the current scope.\n"
495"Else, return an alphabetized list of names comprising (some of) the attributes\n"
496"of the given object, and of attributes reachable from it.\n"
497"If the object supplies a method named __dir__, it will be used; otherwise\n"
498"the default dir() logic is used and returns:\n"
499" for a module object: the module's attributes.\n"
500" for a class object: its attributes, and recursively the attributes\n"
501" of its bases.\n"
Guido van Rossumd8faa362007-04-27 19:54:29 +0000502" for any other object: its attributes, its class's attributes, and\n"
Georg Brandle32b4222007-03-10 22:13:27 +0000503" recursively the attributes of its class's base classes.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000504
Guido van Rossum79f25d91997-04-29 20:08:16 +0000505static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000506builtin_divmod(PyObject *self, PyObject *args)
Guido van Rossum6a00cd81995-01-07 12:39:01 +0000507{
Guido van Rossum79f25d91997-04-29 20:08:16 +0000508 PyObject *v, *w;
Guido van Rossum6a00cd81995-01-07 12:39:01 +0000509
Raymond Hettingerea3fdf42002-12-29 16:33:45 +0000510 if (!PyArg_UnpackTuple(args, "divmod", 2, 2, &v, &w))
Guido van Rossum6a00cd81995-01-07 12:39:01 +0000511 return NULL;
Guido van Rossum09df08a1998-05-22 00:51:39 +0000512 return PyNumber_Divmod(v, w);
Guido van Rossum3f5da241990-12-20 15:06:42 +0000513}
514
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000515PyDoc_STRVAR(divmod_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000516"divmod(x, y) -> (div, mod)\n\
517\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000518Return the tuple ((x-x%y)/y, x%y). Invariant: div*y + mod == x.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000519
520
Guido van Rossum79f25d91997-04-29 20:08:16 +0000521static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000522builtin_eval(PyObject *self, PyObject *args)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000523{
Just van Rossum3aaf42c2003-02-10 08:21:10 +0000524 PyObject *cmd, *result, *tmp = NULL;
Guido van Rossum79f25d91997-04-29 20:08:16 +0000525 PyObject *globals = Py_None, *locals = Py_None;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000526 char *str;
Tim Peters9fa96be2001-08-17 23:04:59 +0000527 PyCompilerFlags cf;
Guido van Rossum590baa41993-11-30 13:40:46 +0000528
Raymond Hettinger214b1c32004-07-02 06:41:07 +0000529 if (!PyArg_UnpackTuple(args, "eval", 1, 3, &cmd, &globals, &locals))
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000530 return NULL;
Raymond Hettinger214b1c32004-07-02 06:41:07 +0000531 if (locals != Py_None && !PyMapping_Check(locals)) {
532 PyErr_SetString(PyExc_TypeError, "locals must be a mapping");
Raymond Hettinger513ffe82004-07-06 13:44:41 +0000533 return NULL;
Raymond Hettinger214b1c32004-07-02 06:41:07 +0000534 }
535 if (globals != Py_None && !PyDict_Check(globals)) {
Georg Brandl99d7e4e2005-08-31 22:21:15 +0000536 PyErr_SetString(PyExc_TypeError, PyMapping_Check(globals) ?
Raymond Hettinger214b1c32004-07-02 06:41:07 +0000537 "globals must be a real dict; try eval(expr, {}, mapping)"
538 : "globals must be a dict");
Raymond Hettinger513ffe82004-07-06 13:44:41 +0000539 return NULL;
Raymond Hettinger214b1c32004-07-02 06:41:07 +0000540 }
Guido van Rossum79f25d91997-04-29 20:08:16 +0000541 if (globals == Py_None) {
542 globals = PyEval_GetGlobals();
543 if (locals == Py_None)
544 locals = PyEval_GetLocals();
Guido van Rossum6135a871995-01-09 17:53:26 +0000545 }
Guido van Rossum79f25d91997-04-29 20:08:16 +0000546 else if (locals == Py_None)
Guido van Rossum6135a871995-01-09 17:53:26 +0000547 locals = globals;
Tim Peters9fa96be2001-08-17 23:04:59 +0000548
Georg Brandl77c85e62005-09-15 10:46:13 +0000549 if (globals == NULL || locals == NULL) {
550 PyErr_SetString(PyExc_TypeError,
551 "eval must be given globals and locals "
552 "when called without a frame");
553 return NULL;
554 }
555
Guido van Rossum79f25d91997-04-29 20:08:16 +0000556 if (PyDict_GetItemString(globals, "__builtins__") == NULL) {
557 if (PyDict_SetItemString(globals, "__builtins__",
558 PyEval_GetBuiltins()) != 0)
Guido van Rossum6135a871995-01-09 17:53:26 +0000559 return NULL;
560 }
Tim Peters9fa96be2001-08-17 23:04:59 +0000561
Jeremy Hylton15c1c4f2001-07-30 21:50:55 +0000562 if (PyCode_Check(cmd)) {
Jeremy Hylton733c8932001-12-13 19:51:56 +0000563 if (PyCode_GetNumFree((PyCodeObject *)cmd) > 0) {
Jeremy Hylton15c1c4f2001-07-30 21:50:55 +0000564 PyErr_SetString(PyExc_TypeError,
565 "code object passed to eval() may not contain free variables");
566 return NULL;
567 }
Guido van Rossum79f25d91997-04-29 20:08:16 +0000568 return PyEval_EvalCode((PyCodeObject *) cmd, globals, locals);
Jeremy Hylton15c1c4f2001-07-30 21:50:55 +0000569 }
Tim Peters9fa96be2001-08-17 23:04:59 +0000570
Guido van Rossumf15a29f2007-05-04 00:41:39 +0000571 str = source_as_string(cmd);
572 if (str == NULL)
Guido van Rossum94390a41992-08-14 15:14:30 +0000573 return NULL;
Just van Rossum3aaf42c2003-02-10 08:21:10 +0000574
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000575 while (*str == ' ' || *str == '\t')
576 str++;
Tim Peters9fa96be2001-08-17 23:04:59 +0000577
Guido van Rossumf15a29f2007-05-04 00:41:39 +0000578 cf.cf_flags = PyCF_SOURCE_IS_UTF8;
Tim Peters9fa96be2001-08-17 23:04:59 +0000579 (void)PyEval_MergeCompilerFlags(&cf);
Just van Rossum3aaf42c2003-02-10 08:21:10 +0000580 result = PyRun_StringFlags(str, Py_eval_input, globals, locals, &cf);
581 Py_XDECREF(tmp);
582 return result;
Guido van Rossum3f5da241990-12-20 15:06:42 +0000583}
584
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000585PyDoc_STRVAR(eval_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000586"eval(source[, globals[, locals]]) -> value\n\
587\n\
588Evaluate the source in the context of globals and locals.\n\
589The source may be a string representing a Python expression\n\
590or a code object as returned by compile().\n\
Thomas Wouters89f507f2006-12-13 04:49:30 +0000591The globals must be a dictionary and locals can be any mapping,\n\
Raymond Hettinger214b1c32004-07-02 06:41:07 +0000592defaulting to the current globals and locals.\n\
593If only globals is given, locals defaults to it.\n");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000594
Georg Brandl7cae87c2006-09-06 06:51:57 +0000595static PyObject *
596builtin_exec(PyObject *self, PyObject *args)
597{
598 PyObject *v;
599 PyObject *prog, *globals = Py_None, *locals = Py_None;
600 int plain = 0;
601
602 if (!PyArg_ParseTuple(args, "O|OO:exec", &prog, &globals, &locals))
603 return NULL;
604
605 if (globals == Py_None) {
606 globals = PyEval_GetGlobals();
607 if (locals == Py_None) {
608 locals = PyEval_GetLocals();
609 plain = 1;
610 }
611 if (!globals || !locals) {
612 PyErr_SetString(PyExc_SystemError,
613 "globals and locals cannot be NULL");
614 return NULL;
615 }
616 }
617 else if (locals == Py_None)
618 locals = globals;
Neal Norwitz6ea45d32007-08-26 04:19:43 +0000619 if (!PyUnicode_Check(prog) &&
Guido van Rossumda5b8f22007-06-12 23:30:11 +0000620 !PyCode_Check(prog)) {
Georg Brandl7cae87c2006-09-06 06:51:57 +0000621 PyErr_Format(PyExc_TypeError,
622 "exec() arg 1 must be a string, file, or code "
623 "object, not %.100s", prog->ob_type->tp_name);
624 return NULL;
625 }
626 if (!PyDict_Check(globals)) {
627 PyErr_Format(PyExc_TypeError, "exec() arg 2 must be a dict, not %.100s",
628 globals->ob_type->tp_name);
629 return NULL;
630 }
631 if (!PyMapping_Check(locals)) {
632 PyErr_Format(PyExc_TypeError,
633 "arg 3 must be a mapping or None, not %.100s",
634 locals->ob_type->tp_name);
635 return NULL;
636 }
637 if (PyDict_GetItemString(globals, "__builtins__") == NULL) {
638 if (PyDict_SetItemString(globals, "__builtins__",
639 PyEval_GetBuiltins()) != 0)
640 return NULL;
641 }
642
643 if (PyCode_Check(prog)) {
644 if (PyCode_GetNumFree((PyCodeObject *)prog) > 0) {
645 PyErr_SetString(PyExc_TypeError,
646 "code object passed to exec() may not "
647 "contain free variables");
648 return NULL;
649 }
650 v = PyEval_EvalCode((PyCodeObject *) prog, globals, locals);
651 }
Georg Brandl7cae87c2006-09-06 06:51:57 +0000652 else {
Guido van Rossumf15a29f2007-05-04 00:41:39 +0000653 char *str = source_as_string(prog);
Georg Brandl7cae87c2006-09-06 06:51:57 +0000654 PyCompilerFlags cf;
Guido van Rossumf15a29f2007-05-04 00:41:39 +0000655 if (str == NULL)
Georg Brandl7cae87c2006-09-06 06:51:57 +0000656 return NULL;
Guido van Rossumf15a29f2007-05-04 00:41:39 +0000657 cf.cf_flags = PyCF_SOURCE_IS_UTF8;
Georg Brandl7cae87c2006-09-06 06:51:57 +0000658 if (PyEval_MergeCompilerFlags(&cf))
659 v = PyRun_StringFlags(str, Py_file_input, globals,
660 locals, &cf);
661 else
662 v = PyRun_String(str, Py_file_input, globals, locals);
Georg Brandl7cae87c2006-09-06 06:51:57 +0000663 }
664 if (v == NULL)
665 return NULL;
666 Py_DECREF(v);
667 Py_RETURN_NONE;
668}
669
670PyDoc_STRVAR(exec_doc,
671"exec(object[, globals[, locals]])\n\
672\n\
673Read and execute code from a object, which can be a string, a code\n\
674object or a file object.\n\
675The globals and locals are dictionaries, defaulting to the current\n\
676globals and locals. If only globals is given, locals defaults to it.");
677
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000678
Guido van Rossum79f25d91997-04-29 20:08:16 +0000679static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000680builtin_getattr(PyObject *self, PyObject *args)
Guido van Rossum33894be1992-01-27 16:53:09 +0000681{
Neal Norwitz6ea45d32007-08-26 04:19:43 +0000682 PyObject *v, *result, *dflt = NULL;
Guido van Rossum79f25d91997-04-29 20:08:16 +0000683 PyObject *name;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000684
Raymond Hettingerea3fdf42002-12-29 16:33:45 +0000685 if (!PyArg_UnpackTuple(args, "getattr", 2, 3, &v, &name, &dflt))
Guido van Rossum33894be1992-01-27 16:53:09 +0000686 return NULL;
Martin v. Löwis5b222132007-06-10 09:51:05 +0000687
Martin v. Löwis5b222132007-06-10 09:51:05 +0000688 if (!PyUnicode_Check(name)) {
Jeremy Hylton0eb11152001-07-30 22:39:31 +0000689 PyErr_SetString(PyExc_TypeError,
Alex Martellia9b9c9f2003-04-23 13:34:35 +0000690 "getattr(): attribute name must be string");
Jeremy Hylton0eb11152001-07-30 22:39:31 +0000691 return NULL;
692 }
Guido van Rossum950ff291998-06-29 13:38:57 +0000693 result = PyObject_GetAttr(v, name);
Guido van Rossumd8923572001-10-16 21:31:32 +0000694 if (result == NULL && dflt != NULL &&
695 PyErr_ExceptionMatches(PyExc_AttributeError))
696 {
Guido van Rossum950ff291998-06-29 13:38:57 +0000697 PyErr_Clear();
698 Py_INCREF(dflt);
699 result = dflt;
700 }
701 return result;
Guido van Rossum9bfef441993-03-29 10:43:31 +0000702}
703
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000704PyDoc_STRVAR(getattr_doc,
Guido van Rossum950ff291998-06-29 13:38:57 +0000705"getattr(object, name[, default]) -> value\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000706\n\
Guido van Rossum950ff291998-06-29 13:38:57 +0000707Get a named attribute from an object; getattr(x, 'y') is equivalent to x.y.\n\
708When a default argument is given, it is returned when the attribute doesn't\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000709exist; without it, an exception is raised in that case.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000710
711
Guido van Rossum79f25d91997-04-29 20:08:16 +0000712static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000713builtin_globals(PyObject *self)
Guido van Rossum872537c1995-07-07 22:43:42 +0000714{
Guido van Rossum79f25d91997-04-29 20:08:16 +0000715 PyObject *d;
Guido van Rossum872537c1995-07-07 22:43:42 +0000716
Guido van Rossum79f25d91997-04-29 20:08:16 +0000717 d = PyEval_GetGlobals();
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000718 Py_XINCREF(d);
Guido van Rossum872537c1995-07-07 22:43:42 +0000719 return d;
720}
721
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000722PyDoc_STRVAR(globals_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000723"globals() -> dictionary\n\
724\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000725Return the dictionary containing the current scope's global variables.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000726
727
Guido van Rossum79f25d91997-04-29 20:08:16 +0000728static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000729builtin_hasattr(PyObject *self, PyObject *args)
Guido van Rossum9bfef441993-03-29 10:43:31 +0000730{
Guido van Rossum79f25d91997-04-29 20:08:16 +0000731 PyObject *v;
732 PyObject *name;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000733
Raymond Hettingerea3fdf42002-12-29 16:33:45 +0000734 if (!PyArg_UnpackTuple(args, "hasattr", 2, 2, &v, &name))
Guido van Rossum9bfef441993-03-29 10:43:31 +0000735 return NULL;
Martin v. Löwis5b222132007-06-10 09:51:05 +0000736 if (!PyUnicode_Check(name)) {
Jeremy Hylton302b54a2001-07-30 22:45:19 +0000737 PyErr_SetString(PyExc_TypeError,
Alex Martellia9b9c9f2003-04-23 13:34:35 +0000738 "hasattr(): attribute name must be string");
Jeremy Hylton302b54a2001-07-30 22:45:19 +0000739 return NULL;
740 }
Guido van Rossum79f25d91997-04-29 20:08:16 +0000741 v = PyObject_GetAttr(v, name);
Guido van Rossum9bfef441993-03-29 10:43:31 +0000742 if (v == NULL) {
Guido van Rossum79f25d91997-04-29 20:08:16 +0000743 PyErr_Clear();
Guido van Rossum09df08a1998-05-22 00:51:39 +0000744 Py_INCREF(Py_False);
745 return Py_False;
Guido van Rossum9bfef441993-03-29 10:43:31 +0000746 }
Guido van Rossum79f25d91997-04-29 20:08:16 +0000747 Py_DECREF(v);
Guido van Rossum09df08a1998-05-22 00:51:39 +0000748 Py_INCREF(Py_True);
749 return Py_True;
Guido van Rossum33894be1992-01-27 16:53:09 +0000750}
751
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000752PyDoc_STRVAR(hasattr_doc,
Guido van Rossum77f6a652002-04-03 22:41:51 +0000753"hasattr(object, name) -> bool\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000754\n\
755Return whether the object has an attribute with the given name.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000756(This is done by calling getattr(object, name) and catching exceptions.)");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000757
758
Guido van Rossum79f25d91997-04-29 20:08:16 +0000759static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000760builtin_id(PyObject *self, PyObject *v)
Guido van Rossum5b722181993-03-30 17:46:03 +0000761{
Guido van Rossum106f2da2000-06-28 21:12:25 +0000762 return PyLong_FromVoidPtr(v);
Guido van Rossum5b722181993-03-30 17:46:03 +0000763}
764
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000765PyDoc_STRVAR(id_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000766"id(object) -> integer\n\
767\n\
768Return the identity of an object. This is guaranteed to be unique among\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000769simultaneously existing objects. (Hint: it's the object's memory address.)");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000770
771
Guido van Rossum79f25d91997-04-29 20:08:16 +0000772static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000773builtin_map(PyObject *self, PyObject *args)
Guido van Rossum12d12c51993-10-26 17:58:25 +0000774{
Guido van Rossumc1f779c2007-07-03 08:25:58 +0000775 PyObject *itertools, *imap, *result;
776 itertools = PyImport_ImportModule("itertools");
777 if (itertools == NULL)
Guido van Rossum12d12c51993-10-26 17:58:25 +0000778 return NULL;
Guido van Rossumc1f779c2007-07-03 08:25:58 +0000779 imap = PyObject_GetAttrString(itertools, "imap");
780 Py_DECREF(itertools);
781 if (imap == NULL)
Tim Peters4e9afdc2001-05-03 23:54:49 +0000782 return NULL;
Guido van Rossumc1f779c2007-07-03 08:25:58 +0000783 result = PyObject_Call(imap, args, NULL);
784 Py_DECREF(imap);
Tim Peters4e9afdc2001-05-03 23:54:49 +0000785 return result;
Guido van Rossum12d12c51993-10-26 17:58:25 +0000786}
787
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000788PyDoc_STRVAR(map_doc,
Guido van Rossumc1f779c2007-07-03 08:25:58 +0000789"map(function, iterable[, iterable, ...]) -> iterator\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000790\n\
Guido van Rossumc1f779c2007-07-03 08:25:58 +0000791Return an iterator yielding the results of applying the function to the\n\
792items of the argument iterables(s). If more than one iterable is given,\n\
793the function is called with an argument list consisting of the\n\
794corresponding item of each iterable, until an iterable is exhausted.\n\
795If the function is None, 'lambda *a: a' is assumed.\n\
796(This is identical to itertools.imap().)");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000797
798
Guido van Rossum79f25d91997-04-29 20:08:16 +0000799static PyObject *
Georg Brandla18af4e2007-04-21 15:47:16 +0000800builtin_next(PyObject *self, PyObject *args)
801{
802 PyObject *it, *res;
803 PyObject *def = NULL;
804
805 if (!PyArg_UnpackTuple(args, "next", 1, 2, &it, &def))
806 return NULL;
807 if (!PyIter_Check(it)) {
808 PyErr_Format(PyExc_TypeError,
809 "%.200s object is not an iterator", it->ob_type->tp_name);
810 return NULL;
811 }
812
813 res = (*it->ob_type->tp_iternext)(it);
814 if (res == NULL) {
815 if (def) {
816 if (PyErr_Occurred() &&
817 !PyErr_ExceptionMatches(PyExc_StopIteration))
818 return NULL;
819 PyErr_Clear();
820 Py_INCREF(def);
821 return def;
822 } else if (PyErr_Occurred()) {
823 return NULL;
824 } else {
825 PyErr_SetNone(PyExc_StopIteration);
826 return NULL;
827 }
828 }
829 return res;
830}
831
832PyDoc_STRVAR(next_doc,
833"next(iterator[, default])\n\
834\n\
835Return the next item from the iterator. If default is given and the iterator\n\
836is exhausted, it is returned instead of raising StopIteration.");
837
838
839static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000840builtin_setattr(PyObject *self, PyObject *args)
Guido van Rossum33894be1992-01-27 16:53:09 +0000841{
Guido van Rossum79f25d91997-04-29 20:08:16 +0000842 PyObject *v;
843 PyObject *name;
844 PyObject *value;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000845
Raymond Hettingerea3fdf42002-12-29 16:33:45 +0000846 if (!PyArg_UnpackTuple(args, "setattr", 3, 3, &v, &name, &value))
Guido van Rossum33894be1992-01-27 16:53:09 +0000847 return NULL;
Guido van Rossum79f25d91997-04-29 20:08:16 +0000848 if (PyObject_SetAttr(v, name, value) != 0)
Guido van Rossum33894be1992-01-27 16:53:09 +0000849 return NULL;
Guido van Rossum79f25d91997-04-29 20:08:16 +0000850 Py_INCREF(Py_None);
851 return Py_None;
Guido van Rossum33894be1992-01-27 16:53:09 +0000852}
853
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000854PyDoc_STRVAR(setattr_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000855"setattr(object, name, value)\n\
856\n\
857Set a named attribute on an object; setattr(x, 'y', v) is equivalent to\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000858``x.y = v''.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000859
860
Guido van Rossum79f25d91997-04-29 20:08:16 +0000861static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000862builtin_delattr(PyObject *self, PyObject *args)
Guido van Rossum14144fc1994-08-29 12:53:40 +0000863{
Guido van Rossum79f25d91997-04-29 20:08:16 +0000864 PyObject *v;
865 PyObject *name;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000866
Raymond Hettingerea3fdf42002-12-29 16:33:45 +0000867 if (!PyArg_UnpackTuple(args, "delattr", 2, 2, &v, &name))
Guido van Rossum14144fc1994-08-29 12:53:40 +0000868 return NULL;
Guido van Rossum79f25d91997-04-29 20:08:16 +0000869 if (PyObject_SetAttr(v, name, (PyObject *)NULL) != 0)
Guido van Rossum14144fc1994-08-29 12:53:40 +0000870 return NULL;
Guido van Rossum79f25d91997-04-29 20:08:16 +0000871 Py_INCREF(Py_None);
872 return Py_None;
Guido van Rossum14144fc1994-08-29 12:53:40 +0000873}
874
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000875PyDoc_STRVAR(delattr_doc,
Guido van Rossumdf12a591998-11-23 22:13:04 +0000876"delattr(object, name)\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000877\n\
878Delete a named attribute on an object; delattr(x, 'y') is equivalent to\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000879``del x.y''.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000880
881
Guido van Rossum79f25d91997-04-29 20:08:16 +0000882static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000883builtin_hash(PyObject *self, PyObject *v)
Guido van Rossum9bfef441993-03-29 10:43:31 +0000884{
Guido van Rossum9bfef441993-03-29 10:43:31 +0000885 long x;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000886
Guido van Rossum79f25d91997-04-29 20:08:16 +0000887 x = PyObject_Hash(v);
Guido van Rossum9bfef441993-03-29 10:43:31 +0000888 if (x == -1)
889 return NULL;
Guido van Rossum79f25d91997-04-29 20:08:16 +0000890 return PyInt_FromLong(x);
Guido van Rossum9bfef441993-03-29 10:43:31 +0000891}
892
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000893PyDoc_STRVAR(hash_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000894"hash(object) -> integer\n\
895\n\
896Return a hash value for the object. Two objects with the same value have\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000897the same hash value. The reverse is not necessarily true, but likely.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000898
899
Guido van Rossum79f25d91997-04-29 20:08:16 +0000900static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000901builtin_hex(PyObject *self, PyObject *v)
Guido van Rossum006bcd41991-10-24 14:54:44 +0000902{
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000903 return PyNumber_ToBase(v, 16);
Guido van Rossum006bcd41991-10-24 14:54:44 +0000904}
905
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000906PyDoc_STRVAR(hex_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000907"hex(number) -> string\n\
908\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000909Return the hexadecimal representation of an integer or long integer.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000910
911
Guido van Rossum79f25d91997-04-29 20:08:16 +0000912static PyObject *
Guido van Rossum59d1d2b2001-04-20 19:13:02 +0000913builtin_iter(PyObject *self, PyObject *args)
914{
915 PyObject *v, *w = NULL;
916
Raymond Hettingerea3fdf42002-12-29 16:33:45 +0000917 if (!PyArg_UnpackTuple(args, "iter", 1, 2, &v, &w))
Guido van Rossum59d1d2b2001-04-20 19:13:02 +0000918 return NULL;
919 if (w == NULL)
920 return PyObject_GetIter(v);
921 if (!PyCallable_Check(v)) {
922 PyErr_SetString(PyExc_TypeError,
923 "iter(v, w): v must be callable");
924 return NULL;
925 }
926 return PyCallIter_New(v, w);
927}
928
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000929PyDoc_STRVAR(iter_doc,
Guido van Rossum59d1d2b2001-04-20 19:13:02 +0000930"iter(collection) -> iterator\n\
931iter(callable, sentinel) -> iterator\n\
932\n\
933Get an iterator from an object. In the first form, the argument must\n\
934supply its own iterator, or be a sequence.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000935In the second form, the callable is called until it returns the sentinel.");
Guido van Rossum59d1d2b2001-04-20 19:13:02 +0000936
937
938static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000939builtin_len(PyObject *self, PyObject *v)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000940{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000941 Py_ssize_t res;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000942
Jeremy Hylton03657cf2000-07-12 13:05:33 +0000943 res = PyObject_Size(v);
Guido van Rossum8ea9f4d1998-06-29 22:26:50 +0000944 if (res < 0 && PyErr_Occurred())
945 return NULL;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000946 return PyInt_FromSsize_t(res);
Guido van Rossum3f5da241990-12-20 15:06:42 +0000947}
948
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000949PyDoc_STRVAR(len_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000950"len(object) -> integer\n\
951\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000952Return the number of items of a sequence or mapping.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000953
954
Guido van Rossum79f25d91997-04-29 20:08:16 +0000955static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000956builtin_locals(PyObject *self)
Guido van Rossum872537c1995-07-07 22:43:42 +0000957{
Guido van Rossum79f25d91997-04-29 20:08:16 +0000958 PyObject *d;
Guido van Rossum872537c1995-07-07 22:43:42 +0000959
Guido van Rossum79f25d91997-04-29 20:08:16 +0000960 d = PyEval_GetLocals();
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000961 Py_XINCREF(d);
Guido van Rossum872537c1995-07-07 22:43:42 +0000962 return d;
963}
964
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000965PyDoc_STRVAR(locals_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000966"locals() -> dictionary\n\
967\n\
Raymond Hettinger69bf8f32003-01-04 02:16:22 +0000968Update and return a dictionary containing the current scope's local variables.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000969
970
Guido van Rossum79f25d91997-04-29 20:08:16 +0000971static PyObject *
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +0000972min_max(PyObject *args, PyObject *kwds, int op)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000973{
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +0000974 PyObject *v, *it, *item, *val, *maxitem, *maxval, *keyfunc=NULL;
Martin v. Löwisfd39ad42004-08-12 14:42:37 +0000975 const char *name = op == Py_LT ? "min" : "max";
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000976
Guido van Rossum79f25d91997-04-29 20:08:16 +0000977 if (PyTuple_Size(args) > 1)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000978 v = args;
Martin v. Löwisfd39ad42004-08-12 14:42:37 +0000979 else if (!PyArg_UnpackTuple(args, (char *)name, 1, 1, &v))
Guido van Rossum3f5da241990-12-20 15:06:42 +0000980 return NULL;
Tim Peters67d687a2002-04-29 21:27:32 +0000981
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +0000982 if (kwds != NULL && PyDict_Check(kwds) && PyDict_Size(kwds)) {
983 keyfunc = PyDict_GetItemString(kwds, "key");
984 if (PyDict_Size(kwds)!=1 || keyfunc == NULL) {
Georg Brandl99d7e4e2005-08-31 22:21:15 +0000985 PyErr_Format(PyExc_TypeError,
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +0000986 "%s() got an unexpected keyword argument", name);
987 return NULL;
988 }
Georg Brandl99d7e4e2005-08-31 22:21:15 +0000989 }
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +0000990
Tim Petersc3074532001-05-03 07:00:32 +0000991 it = PyObject_GetIter(v);
992 if (it == NULL)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000993 return NULL;
Tim Petersc3074532001-05-03 07:00:32 +0000994
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +0000995 maxitem = NULL; /* the result */
996 maxval = NULL; /* the value associated with the result */
Brett Cannon9e635cf2004-12-07 00:25:35 +0000997 while (( item = PyIter_Next(it) )) {
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +0000998 /* get the value from the key function */
999 if (keyfunc != NULL) {
1000 val = PyObject_CallFunctionObjArgs(keyfunc, item, NULL);
1001 if (val == NULL)
1002 goto Fail_it_item;
1003 }
1004 /* no key function; the value is the item */
1005 else {
1006 val = item;
1007 Py_INCREF(val);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001008 }
Tim Petersc3074532001-05-03 07:00:32 +00001009
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001010 /* maximum value and item are unset; set them */
1011 if (maxval == NULL) {
1012 maxitem = item;
1013 maxval = val;
1014 }
1015 /* maximum value and item are set; update them as necessary */
Guido van Rossum2d951851994-08-29 12:52:16 +00001016 else {
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001017 int cmp = PyObject_RichCompareBool(val, maxval, op);
1018 if (cmp < 0)
1019 goto Fail_it_item_and_val;
1020 else if (cmp > 0) {
1021 Py_DECREF(maxval);
1022 Py_DECREF(maxitem);
1023 maxval = val;
1024 maxitem = item;
Guido van Rossum53451b32001-01-17 15:47:24 +00001025 }
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001026 else {
1027 Py_DECREF(item);
1028 Py_DECREF(val);
Guido van Rossumc8b6df91997-05-23 00:06:51 +00001029 }
Guido van Rossum2d951851994-08-29 12:52:16 +00001030 }
Guido van Rossum3f5da241990-12-20 15:06:42 +00001031 }
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001032 if (PyErr_Occurred())
1033 goto Fail_it;
1034 if (maxval == NULL) {
Martin v. Löwisfd39ad42004-08-12 14:42:37 +00001035 PyErr_Format(PyExc_ValueError,
1036 "%s() arg is an empty sequence", name);
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001037 assert(maxitem == NULL);
1038 }
1039 else
1040 Py_DECREF(maxval);
Tim Petersc3074532001-05-03 07:00:32 +00001041 Py_DECREF(it);
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001042 return maxitem;
1043
1044Fail_it_item_and_val:
1045 Py_DECREF(val);
1046Fail_it_item:
1047 Py_DECREF(item);
1048Fail_it:
1049 Py_XDECREF(maxval);
1050 Py_XDECREF(maxitem);
1051 Py_DECREF(it);
1052 return NULL;
Guido van Rossum3f5da241990-12-20 15:06:42 +00001053}
1054
Guido van Rossum79f25d91997-04-29 20:08:16 +00001055static PyObject *
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001056builtin_min(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001057{
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001058 return min_max(args, kwds, Py_LT);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001059}
1060
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001061PyDoc_STRVAR(min_doc,
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001062"min(iterable[, key=func]) -> value\n\
1063min(a, b, c, ...[, key=func]) -> value\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001064\n\
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001065With a single iterable argument, return its smallest item.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001066With two or more arguments, return the smallest argument.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001067
1068
Guido van Rossum79f25d91997-04-29 20:08:16 +00001069static PyObject *
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001070builtin_max(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001071{
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001072 return min_max(args, kwds, Py_GT);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001073}
1074
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001075PyDoc_STRVAR(max_doc,
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001076"max(iterable[, key=func]) -> value\n\
1077max(a, b, c, ...[, key=func]) -> value\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001078\n\
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001079With a single iterable argument, return its largest item.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001080With two or more arguments, return the largest argument.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001081
1082
Guido van Rossum79f25d91997-04-29 20:08:16 +00001083static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001084builtin_oct(PyObject *self, PyObject *v)
Guido van Rossum006bcd41991-10-24 14:54:44 +00001085{
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001086 return PyNumber_ToBase(v, 8);
Guido van Rossum006bcd41991-10-24 14:54:44 +00001087}
1088
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001089PyDoc_STRVAR(oct_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001090"oct(number) -> string\n\
1091\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001092Return the octal representation of an integer or long integer.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001093
1094
Guido van Rossum79f25d91997-04-29 20:08:16 +00001095static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001096builtin_ord(PyObject *self, PyObject* obj)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001097{
Guido van Rossum09095f32000-03-10 23:00:52 +00001098 long ord;
Martin v. Löwisd96ee902006-02-16 14:37:16 +00001099 Py_ssize_t size;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001100
Jeremy Hylton394b54d2000-04-12 21:19:47 +00001101 if (PyString_Check(obj)) {
1102 size = PyString_GET_SIZE(obj);
Andrew M. Kuchling34c20cf2000-12-20 14:36:56 +00001103 if (size == 1) {
Jeremy Hylton394b54d2000-04-12 21:19:47 +00001104 ord = (long)((unsigned char)*PyString_AS_STRING(obj));
Andrew M. Kuchling34c20cf2000-12-20 14:36:56 +00001105 return PyInt_FromLong(ord);
1106 }
Guido van Rossum98f97462007-04-13 03:31:13 +00001107 }
1108 else if (PyUnicode_Check(obj)) {
Jeremy Hylton394b54d2000-04-12 21:19:47 +00001109 size = PyUnicode_GET_SIZE(obj);
Andrew M. Kuchling34c20cf2000-12-20 14:36:56 +00001110 if (size == 1) {
Jeremy Hylton394b54d2000-04-12 21:19:47 +00001111 ord = (long)*PyUnicode_AS_UNICODE(obj);
Andrew M. Kuchling34c20cf2000-12-20 14:36:56 +00001112 return PyInt_FromLong(ord);
1113 }
Guido van Rossum8ac004e2007-07-15 13:00:05 +00001114#ifndef Py_UNICODE_WIDE
1115 if (size == 2) {
1116 /* Decode a valid surrogate pair */
1117 int c0 = PyUnicode_AS_UNICODE(obj)[0];
1118 int c1 = PyUnicode_AS_UNICODE(obj)[1];
1119 if (0xD800 <= c0 && c0 <= 0xDBFF &&
1120 0xDC00 <= c1 && c1 <= 0xDFFF) {
1121 ord = ((((c0 & 0x03FF) << 10) | (c1 & 0x03FF)) +
1122 0x00010000);
1123 return PyInt_FromLong(ord);
1124 }
1125 }
1126#endif
Guido van Rossum6f376c42007-05-24 14:31:33 +00001127 }
Guido van Rossum98f97462007-04-13 03:31:13 +00001128 else if (PyBytes_Check(obj)) {
1129 /* XXX Hopefully this is temporary */
1130 size = PyBytes_GET_SIZE(obj);
1131 if (size == 1) {
Guido van Rossumf9e91c92007-05-08 21:05:48 +00001132 ord = (long)((unsigned char)*PyBytes_AS_STRING(obj));
Guido van Rossum98f97462007-04-13 03:31:13 +00001133 return PyInt_FromLong(ord);
1134 }
1135 }
1136 else {
Jeremy Hylton394b54d2000-04-12 21:19:47 +00001137 PyErr_Format(PyExc_TypeError,
Andrew M. Kuchlingf07aad12000-12-23 14:11:28 +00001138 "ord() expected string of length 1, but " \
Jeremy Hylton394b54d2000-04-12 21:19:47 +00001139 "%.200s found", obj->ob_type->tp_name);
Guido van Rossum09095f32000-03-10 23:00:52 +00001140 return NULL;
1141 }
1142
Guido van Rossumad991772001-01-12 16:03:05 +00001143 PyErr_Format(PyExc_TypeError,
Andrew M. Kuchlingf07aad12000-12-23 14:11:28 +00001144 "ord() expected a character, "
Martin v. Löwisd96ee902006-02-16 14:37:16 +00001145 "but string of length %zd found",
Jeremy Hylton394b54d2000-04-12 21:19:47 +00001146 size);
1147 return NULL;
Guido van Rossum3f5da241990-12-20 15:06:42 +00001148}
1149
Guido van Rossum307fa8c2007-07-16 20:46:27 +00001150PyDoc_VAR(ord_doc) = PyDoc_STR(
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001151"ord(c) -> integer\n\
1152\n\
Guido van Rossum8ac004e2007-07-15 13:00:05 +00001153Return the integer ordinal of a one-character string."
Guido van Rossum307fa8c2007-07-16 20:46:27 +00001154)
Guido van Rossum8ac004e2007-07-15 13:00:05 +00001155#ifndef Py_UNICODE_WIDE
Guido van Rossum307fa8c2007-07-16 20:46:27 +00001156PyDoc_STR(
Guido van Rossum8ac004e2007-07-15 13:00:05 +00001157"\nA valid surrogate pair is also accepted."
Guido van Rossum307fa8c2007-07-16 20:46:27 +00001158)
Guido van Rossum8ac004e2007-07-15 13:00:05 +00001159#endif
Guido van Rossum307fa8c2007-07-16 20:46:27 +00001160;
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001161
1162
Guido van Rossum79f25d91997-04-29 20:08:16 +00001163static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001164builtin_pow(PyObject *self, PyObject *args)
Guido van Rossum6a00cd81995-01-07 12:39:01 +00001165{
Guido van Rossum09df08a1998-05-22 00:51:39 +00001166 PyObject *v, *w, *z = Py_None;
Guido van Rossum6a00cd81995-01-07 12:39:01 +00001167
Raymond Hettingerea3fdf42002-12-29 16:33:45 +00001168 if (!PyArg_UnpackTuple(args, "pow", 2, 3, &v, &w, &z))
Guido van Rossum6a00cd81995-01-07 12:39:01 +00001169 return NULL;
Guido van Rossum09df08a1998-05-22 00:51:39 +00001170 return PyNumber_Power(v, w, z);
Guido van Rossumd4905451991-05-05 20:00:36 +00001171}
1172
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001173PyDoc_STRVAR(pow_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001174"pow(x, y[, z]) -> number\n\
1175\n\
1176With two arguments, equivalent to x**y. With three arguments,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001177equivalent to (x**y) % z, but may be more efficient (e.g. for longs).");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001178
1179
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001180
Guido van Rossum34343512006-11-30 22:13:52 +00001181static PyObject *
1182builtin_print(PyObject *self, PyObject *args, PyObject *kwds)
1183{
1184 static char *kwlist[] = {"sep", "end", "file", 0};
Georg Brandl257d3d92007-02-26 10:35:10 +00001185 static PyObject *dummy_args;
Guido van Rossum34343512006-11-30 22:13:52 +00001186 PyObject *sep = NULL, *end = NULL, *file = NULL;
1187 int i, err;
1188
Georg Brandl257d3d92007-02-26 10:35:10 +00001189 if (dummy_args == NULL) {
1190 if (!(dummy_args = PyTuple_New(0)))
1191 return NULL;
1192 }
Georg Brandl88fc6642007-02-09 21:28:07 +00001193 if (!PyArg_ParseTupleAndKeywords(dummy_args, kwds, "|OOO:print",
Guido van Rossum34343512006-11-30 22:13:52 +00001194 kwlist, &sep, &end, &file))
1195 return NULL;
1196 if (file == NULL || file == Py_None)
1197 file = PySys_GetObject("stdout");
1198
Neal Norwitz6ea45d32007-08-26 04:19:43 +00001199 if (sep && sep != Py_None && !PyUnicode_Check(sep)) {
Georg Brandl16f3e032006-11-30 22:46:03 +00001200 PyErr_Format(PyExc_TypeError,
Neal Norwitz6ea45d32007-08-26 04:19:43 +00001201 "sep must be None or a string, not %.200s",
Georg Brandl16f3e032006-11-30 22:46:03 +00001202 sep->ob_type->tp_name);
1203 return NULL;
1204 }
Neal Norwitz6ea45d32007-08-26 04:19:43 +00001205 if (end && end != Py_None && !PyUnicode_Check(end)) {
Georg Brandl16f3e032006-11-30 22:46:03 +00001206 PyErr_Format(PyExc_TypeError,
Neal Norwitz6ea45d32007-08-26 04:19:43 +00001207 "end must be None or a string, not %.200s",
Georg Brandl16f3e032006-11-30 22:46:03 +00001208 end->ob_type->tp_name);
1209 return NULL;
1210 }
Guido van Rossum34343512006-11-30 22:13:52 +00001211
1212 for (i = 0; i < PyTuple_Size(args); i++) {
1213 if (i > 0) {
1214 if (sep == NULL || sep == Py_None)
1215 err = PyFile_WriteString(" ", file);
1216 else
1217 err = PyFile_WriteObject(sep, file,
1218 Py_PRINT_RAW);
1219 if (err)
1220 return NULL;
1221 }
1222 err = PyFile_WriteObject(PyTuple_GetItem(args, i), file,
1223 Py_PRINT_RAW);
1224 if (err)
1225 return NULL;
1226 }
1227
1228 if (end == NULL || end == Py_None)
1229 err = PyFile_WriteString("\n", file);
1230 else
1231 err = PyFile_WriteObject(end, file, Py_PRINT_RAW);
1232 if (err)
1233 return NULL;
1234
1235 Py_RETURN_NONE;
1236}
1237
1238PyDoc_STRVAR(print_doc,
Guido van Rossum452bf512007-02-09 05:32:43 +00001239"print(value, ..., file=None, sep=' ', end='\\n')\n\
Guido van Rossum34343512006-11-30 22:13:52 +00001240\n\
1241Prints the values to a stream, or to sys.stdout by default.\n\
1242Optional keyword arguments:\n\
1243file: a file-like object (stream); defaults to the current sys.stdout.\n\
1244sep: string inserted between values, default a space.\n\
1245end: string appended after the last value, default a newline.");
1246
1247
Guido van Rossuma88a0332007-02-26 16:59:55 +00001248static PyObject *
1249builtin_input(PyObject *self, PyObject *args)
1250{
Guido van Rossumeba76962007-05-27 09:13:28 +00001251 PyObject *promptarg = NULL;
Guido van Rossuma88a0332007-02-26 16:59:55 +00001252 PyObject *fin = PySys_GetObject("stdin");
1253 PyObject *fout = PySys_GetObject("stdout");
Guido van Rossumeba76962007-05-27 09:13:28 +00001254 PyObject *ferr = PySys_GetObject("stderr");
1255 PyObject *tmp;
1256 long fd;
1257 int tty;
Guido van Rossuma88a0332007-02-26 16:59:55 +00001258
Guido van Rossumeba76962007-05-27 09:13:28 +00001259 /* Parse arguments */
1260 if (!PyArg_UnpackTuple(args, "input", 0, 1, &promptarg))
Guido van Rossuma88a0332007-02-26 16:59:55 +00001261 return NULL;
1262
Guido van Rossumeba76962007-05-27 09:13:28 +00001263 /* Check that stdin/out/err are intact */
Guido van Rossuma88a0332007-02-26 16:59:55 +00001264 if (fin == NULL) {
Guido van Rossumeba76962007-05-27 09:13:28 +00001265 PyErr_SetString(PyExc_RuntimeError,
1266 "input(): lost sys.stdin");
Guido van Rossuma88a0332007-02-26 16:59:55 +00001267 return NULL;
1268 }
1269 if (fout == NULL) {
Guido van Rossumeba76962007-05-27 09:13:28 +00001270 PyErr_SetString(PyExc_RuntimeError,
1271 "input(): lost sys.stdout");
Guido van Rossuma88a0332007-02-26 16:59:55 +00001272 return NULL;
1273 }
Guido van Rossumeba76962007-05-27 09:13:28 +00001274 if (ferr == NULL) {
1275 PyErr_SetString(PyExc_RuntimeError,
1276 "input(): lost sys.stderr");
1277 return NULL;
1278 }
1279
1280 /* First of all, flush stderr */
1281 tmp = PyObject_CallMethod(ferr, "flush", "");
1282 if (tmp == NULL)
Guido van Rossumc1f779c2007-07-03 08:25:58 +00001283 PyErr_Clear();
1284 else
1285 Py_DECREF(tmp);
Guido van Rossumeba76962007-05-27 09:13:28 +00001286
1287 /* We should only use (GNU) readline if Python's sys.stdin and
1288 sys.stdout are the same as C's stdin and stdout, because we
1289 need to pass it those. */
1290 tmp = PyObject_CallMethod(fin, "fileno", "");
Guido van Rossumc1f779c2007-07-03 08:25:58 +00001291 if (tmp == NULL) {
1292 PyErr_Clear();
1293 tty = 0;
1294 }
1295 else {
Guido van Rossumeba76962007-05-27 09:13:28 +00001296 fd = PyInt_AsLong(tmp);
1297 Py_DECREF(tmp);
1298 if (fd < 0 && PyErr_Occurred())
1299 return NULL;
Guido van Rossumc1f779c2007-07-03 08:25:58 +00001300 tty = fd == fileno(stdin) && isatty(fd);
1301 }
1302 if (tty) {
1303 tmp = PyObject_CallMethod(fout, "fileno", "");
1304 if (tmp == NULL)
1305 PyErr_Clear();
1306 else {
1307 fd = PyInt_AsLong(tmp);
1308 Py_DECREF(tmp);
1309 if (fd < 0 && PyErr_Occurred())
1310 return NULL;
1311 tty = fd == fileno(stdout) && isatty(fd);
1312 }
Guido van Rossumeba76962007-05-27 09:13:28 +00001313 }
1314
1315 /* If we're interactive, use (GNU) readline */
1316 if (tty) {
Guido van Rossuma88a0332007-02-26 16:59:55 +00001317 PyObject *po;
1318 char *prompt;
1319 char *s;
Martin v. Löwis4a7b5d52007-09-04 05:24:49 +00001320 PyObject *stdin_encoding;
Guido van Rossuma88a0332007-02-26 16:59:55 +00001321 PyObject *result;
Martin v. Löwis4a7b5d52007-09-04 05:24:49 +00001322
1323 stdin_encoding = PyObject_GetAttrString(fin, "encoding");
1324 if (!stdin_encoding)
1325 /* stdin is a text stream, so it must have an
1326 encoding. */
1327 return NULL;
Guido van Rossumeba76962007-05-27 09:13:28 +00001328 tmp = PyObject_CallMethod(fout, "flush", "");
1329 if (tmp == NULL)
Guido van Rossumc1f779c2007-07-03 08:25:58 +00001330 PyErr_Clear();
1331 else
1332 Py_DECREF(tmp);
Guido van Rossumeba76962007-05-27 09:13:28 +00001333 if (promptarg != NULL) {
1334 po = PyObject_Str(promptarg);
Martin v. Löwis4a7b5d52007-09-04 05:24:49 +00001335 if (po == NULL) {
1336 Py_DECREF(stdin_encoding);
Guido van Rossuma88a0332007-02-26 16:59:55 +00001337 return NULL;
Martin v. Löwis4a7b5d52007-09-04 05:24:49 +00001338 }
Guido van Rossuma88a0332007-02-26 16:59:55 +00001339 prompt = PyString_AsString(po);
Guido van Rossumeba76962007-05-27 09:13:28 +00001340 if (prompt == NULL) {
Martin v. Löwis4a7b5d52007-09-04 05:24:49 +00001341 Py_DECREF(stdin_encoding);
Guido van Rossumeba76962007-05-27 09:13:28 +00001342 Py_DECREF(po);
Guido van Rossuma88a0332007-02-26 16:59:55 +00001343 return NULL;
Guido van Rossumeba76962007-05-27 09:13:28 +00001344 }
Guido van Rossuma88a0332007-02-26 16:59:55 +00001345 }
1346 else {
1347 po = NULL;
1348 prompt = "";
1349 }
Guido van Rossumeba76962007-05-27 09:13:28 +00001350 s = PyOS_Readline(stdin, stdout, prompt);
Guido van Rossuma88a0332007-02-26 16:59:55 +00001351 Py_XDECREF(po);
1352 if (s == NULL) {
1353 if (!PyErr_Occurred())
1354 PyErr_SetNone(PyExc_KeyboardInterrupt);
Martin v. Löwis4a7b5d52007-09-04 05:24:49 +00001355 Py_DECREF(stdin_encoding);
Guido van Rossuma88a0332007-02-26 16:59:55 +00001356 return NULL;
1357 }
1358 if (*s == '\0') {
1359 PyErr_SetNone(PyExc_EOFError);
1360 result = NULL;
1361 }
1362 else { /* strip trailing '\n' */
1363 size_t len = strlen(s);
1364 if (len > PY_SSIZE_T_MAX) {
1365 PyErr_SetString(PyExc_OverflowError,
1366 "input: input too long");
1367 result = NULL;
1368 }
1369 else {
Martin v. Löwis4a7b5d52007-09-04 05:24:49 +00001370 result = PyUnicode_Decode
1371 (s, len-1,
1372 PyUnicode_AsString(stdin_encoding),
1373 NULL);
Guido van Rossuma88a0332007-02-26 16:59:55 +00001374 }
1375 }
Martin v. Löwis4a7b5d52007-09-04 05:24:49 +00001376 Py_DECREF(stdin_encoding);
Guido van Rossuma88a0332007-02-26 16:59:55 +00001377 PyMem_FREE(s);
1378 return result;
1379 }
Guido van Rossumeba76962007-05-27 09:13:28 +00001380
1381 /* Fallback if we're not interactive */
1382 if (promptarg != NULL) {
1383 if (PyFile_WriteObject(promptarg, fout, Py_PRINT_RAW) != 0)
Guido van Rossuma88a0332007-02-26 16:59:55 +00001384 return NULL;
1385 }
Guido van Rossumeba76962007-05-27 09:13:28 +00001386 tmp = PyObject_CallMethod(fout, "flush", "");
1387 if (tmp == NULL)
Guido van Rossumc1f779c2007-07-03 08:25:58 +00001388 PyErr_Clear();
1389 else
1390 Py_DECREF(tmp);
Guido van Rossuma88a0332007-02-26 16:59:55 +00001391 return PyFile_GetLine(fin, -1);
1392}
1393
1394PyDoc_STRVAR(input_doc,
1395"input([prompt]) -> string\n\
1396\n\
1397Read a string from standard input. The trailing newline is stripped.\n\
1398If the user hits EOF (Unix: Ctl-D, Windows: Ctl-Z+Return), raise EOFError.\n\
1399On Unix, GNU readline is used if enabled. The prompt string, if given,\n\
1400is printed without a trailing newline before reading.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001401
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001402
Guido van Rossum79f25d91997-04-29 20:08:16 +00001403static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001404builtin_repr(PyObject *self, PyObject *v)
Guido van Rossumc89705d1992-11-26 08:54:07 +00001405{
Guido van Rossum79f25d91997-04-29 20:08:16 +00001406 return PyObject_Repr(v);
Guido van Rossumc89705d1992-11-26 08:54:07 +00001407}
1408
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001409PyDoc_STRVAR(repr_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001410"repr(object) -> string\n\
1411\n\
1412Return the canonical string representation of the object.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001413For most object types, eval(repr(object)) == object.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001414
1415
Guido van Rossum79f25d91997-04-29 20:08:16 +00001416static PyObject *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001417builtin_round(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum9e51f9b1993-02-12 16:29:05 +00001418{
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001419#define UNDEF_NDIGITS (-0x7fffffff) /* Unlikely ndigits value */
1420 static PyObject *round_str = NULL;
1421 int ndigits = UNDEF_NDIGITS;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001422 static char *kwlist[] = {"number", "ndigits", 0};
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001423 PyObject *number, *round;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001424
Alex Martelliae211f92007-08-22 23:21:33 +00001425 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|i:round",
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001426 kwlist, &number, &ndigits))
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001427 return NULL;
Alex Martelliae211f92007-08-22 23:21:33 +00001428
Guido van Rossum15d3d042007-08-24 02:02:45 +00001429 if (Py_Type(number)->tp_dict == NULL) {
1430 if (PyType_Ready(Py_Type(number)) < 0)
1431 return NULL;
1432 }
1433
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001434 if (round_str == NULL) {
1435 round_str = PyUnicode_FromString("__round__");
1436 if (round_str == NULL)
Alex Martelliae211f92007-08-22 23:21:33 +00001437 return NULL;
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001438 }
1439
1440 round = _PyType_Lookup(Py_Type(number), round_str);
1441 if (round == NULL) {
1442 PyErr_Format(PyExc_TypeError,
1443 "type %.100s doesn't define __round__ method",
1444 Py_Type(number)->tp_name);
Alex Martelliae211f92007-08-22 23:21:33 +00001445 return NULL;
1446 }
1447
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001448 if (ndigits == UNDEF_NDIGITS)
1449 return PyObject_CallFunction(round, "O", number);
Guido van Rossum9e51f9b1993-02-12 16:29:05 +00001450 else
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001451 return PyObject_CallFunction(round, "Oi", number, ndigits);
1452#undef UNDEF_NDIGITS
Guido van Rossum9e51f9b1993-02-12 16:29:05 +00001453}
1454
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001455PyDoc_STRVAR(round_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001456"round(number[, ndigits]) -> floating point number\n\
1457\n\
1458Round a number to a given precision in decimal digits (default 0 digits).\n\
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001459This returns an int when called with one argument, otherwise a float.\n\
1460Precision may be negative.");
1461
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001462
Raymond Hettinger64958a12003-12-17 20:43:33 +00001463static PyObject *
1464builtin_sorted(PyObject *self, PyObject *args, PyObject *kwds)
1465{
1466 PyObject *newlist, *v, *seq, *compare=NULL, *keyfunc=NULL, *newargs;
1467 PyObject *callable;
Martin v. Löwis15e62742006-02-27 16:46:16 +00001468 static char *kwlist[] = {"iterable", "cmp", "key", "reverse", 0};
Neal Norwitz6f0d4792005-12-15 06:40:36 +00001469 int reverse;
Raymond Hettinger64958a12003-12-17 20:43:33 +00001470
Neal Norwitz6f0d4792005-12-15 06:40:36 +00001471 /* args 1-4 should match listsort in Objects/listobject.c */
Armin Rigo71d7e702005-09-20 18:13:03 +00001472 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|OOi:sorted",
1473 kwlist, &seq, &compare, &keyfunc, &reverse))
1474 return NULL;
Raymond Hettinger64958a12003-12-17 20:43:33 +00001475
1476 newlist = PySequence_List(seq);
1477 if (newlist == NULL)
1478 return NULL;
1479
1480 callable = PyObject_GetAttrString(newlist, "sort");
1481 if (callable == NULL) {
1482 Py_DECREF(newlist);
1483 return NULL;
1484 }
Georg Brandl99d7e4e2005-08-31 22:21:15 +00001485
Raymond Hettinger64958a12003-12-17 20:43:33 +00001486 newargs = PyTuple_GetSlice(args, 1, 4);
1487 if (newargs == NULL) {
1488 Py_DECREF(newlist);
1489 Py_DECREF(callable);
1490 return NULL;
1491 }
1492
1493 v = PyObject_Call(callable, newargs, kwds);
1494 Py_DECREF(newargs);
1495 Py_DECREF(callable);
1496 if (v == NULL) {
1497 Py_DECREF(newlist);
1498 return NULL;
1499 }
1500 Py_DECREF(v);
1501 return newlist;
1502}
1503
1504PyDoc_STRVAR(sorted_doc,
1505"sorted(iterable, cmp=None, key=None, reverse=False) --> new sorted list");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001506
Guido van Rossum79f25d91997-04-29 20:08:16 +00001507static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001508builtin_vars(PyObject *self, PyObject *args)
Guido van Rossum2d951851994-08-29 12:52:16 +00001509{
Guido van Rossum79f25d91997-04-29 20:08:16 +00001510 PyObject *v = NULL;
1511 PyObject *d;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001512
Raymond Hettingerea3fdf42002-12-29 16:33:45 +00001513 if (!PyArg_UnpackTuple(args, "vars", 0, 1, &v))
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001514 return NULL;
Guido van Rossum2d951851994-08-29 12:52:16 +00001515 if (v == NULL) {
Guido van Rossum79f25d91997-04-29 20:08:16 +00001516 d = PyEval_GetLocals();
Guido van Rossum53bb7ff1995-07-26 16:26:31 +00001517 if (d == NULL) {
Guido van Rossum79f25d91997-04-29 20:08:16 +00001518 if (!PyErr_Occurred())
1519 PyErr_SetString(PyExc_SystemError,
Alex Martellia9b9c9f2003-04-23 13:34:35 +00001520 "vars(): no locals!?");
Guido van Rossum53bb7ff1995-07-26 16:26:31 +00001521 }
1522 else
Guido van Rossum79f25d91997-04-29 20:08:16 +00001523 Py_INCREF(d);
Guido van Rossum2d951851994-08-29 12:52:16 +00001524 }
1525 else {
Guido van Rossum79f25d91997-04-29 20:08:16 +00001526 d = PyObject_GetAttrString(v, "__dict__");
Guido van Rossum2d951851994-08-29 12:52:16 +00001527 if (d == NULL) {
Guido van Rossum79f25d91997-04-29 20:08:16 +00001528 PyErr_SetString(PyExc_TypeError,
Guido van Rossum2d951851994-08-29 12:52:16 +00001529 "vars() argument must have __dict__ attribute");
1530 return NULL;
1531 }
1532 }
1533 return d;
1534}
1535
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001536PyDoc_STRVAR(vars_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001537"vars([object]) -> dictionary\n\
1538\n\
1539Without arguments, equivalent to locals().\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001540With an argument, equivalent to object.__dict__.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001541
Alex Martelli86d8b342007-08-22 22:39:42 +00001542static PyObject *
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001543builtin_trunc(PyObject *self, PyObject *number)
Alex Martelli86d8b342007-08-22 22:39:42 +00001544{
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001545 static PyObject *trunc_str = NULL;
1546 PyObject *trunc;
1547
Guido van Rossum15d3d042007-08-24 02:02:45 +00001548 if (Py_Type(number)->tp_dict == NULL) {
1549 if (PyType_Ready(Py_Type(number)) < 0)
1550 return NULL;
1551 }
1552
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001553 if (trunc_str == NULL) {
1554 trunc_str = PyUnicode_FromString("__trunc__");
1555 if (trunc_str == NULL)
1556 return NULL;
1557 }
1558
1559 trunc = _PyType_Lookup(Py_Type(number), trunc_str);
1560 if (trunc == NULL) {
1561 PyErr_Format(PyExc_TypeError,
1562 "type %.100s doesn't define __trunc__ method",
1563 Py_Type(number)->tp_name);
Alex Martelli86d8b342007-08-22 22:39:42 +00001564 return NULL;
1565 }
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001566 return PyObject_CallFunction(trunc, "O", number);
Alex Martelli86d8b342007-08-22 22:39:42 +00001567}
1568
1569PyDoc_STRVAR(trunc_doc,
1570"trunc(Real) -> Integral\n\
1571\n\
1572returns the integral closest to x between 0 and x.");
1573
1574
Alex Martellia70b1912003-04-22 08:12:33 +00001575
1576static PyObject*
1577builtin_sum(PyObject *self, PyObject *args)
1578{
1579 PyObject *seq;
1580 PyObject *result = NULL;
1581 PyObject *temp, *item, *iter;
1582
Raymond Hettinger5cf63942003-10-25 06:41:37 +00001583 if (!PyArg_UnpackTuple(args, "sum", 1, 2, &seq, &result))
Alex Martellia70b1912003-04-22 08:12:33 +00001584 return NULL;
1585
1586 iter = PyObject_GetIter(seq);
1587 if (iter == NULL)
1588 return NULL;
1589
1590 if (result == NULL) {
1591 result = PyInt_FromLong(0);
1592 if (result == NULL) {
1593 Py_DECREF(iter);
1594 return NULL;
1595 }
1596 } else {
1597 /* reject string values for 'start' parameter */
Guido van Rossum3172c5d2007-10-16 18:12:55 +00001598 if (PyUnicode_Check(result)) {
Alex Martellia70b1912003-04-22 08:12:33 +00001599 PyErr_SetString(PyExc_TypeError,
Alex Martellia9b9c9f2003-04-23 13:34:35 +00001600 "sum() can't sum strings [use ''.join(seq) instead]");
Alex Martellia70b1912003-04-22 08:12:33 +00001601 Py_DECREF(iter);
1602 return NULL;
1603 }
Guido van Rossum3172c5d2007-10-16 18:12:55 +00001604 if (PyBytes_Check(result)) {
1605 PyErr_SetString(PyExc_TypeError,
1606 "sum() can't sum bytes [use b''.join(seq) instead]");
1607 Py_DECREF(iter);
1608 return NULL;
1609 }
1610
Alex Martelli41c9f882003-04-22 09:24:48 +00001611 Py_INCREF(result);
Alex Martellia70b1912003-04-22 08:12:33 +00001612 }
1613
1614 for(;;) {
1615 item = PyIter_Next(iter);
1616 if (item == NULL) {
1617 /* error, or end-of-sequence */
1618 if (PyErr_Occurred()) {
1619 Py_DECREF(result);
1620 result = NULL;
1621 }
1622 break;
1623 }
Alex Martellia253e182003-10-25 23:24:14 +00001624 temp = PyNumber_Add(result, item);
Alex Martellia70b1912003-04-22 08:12:33 +00001625 Py_DECREF(result);
1626 Py_DECREF(item);
1627 result = temp;
1628 if (result == NULL)
1629 break;
1630 }
1631 Py_DECREF(iter);
1632 return result;
1633}
1634
1635PyDoc_STRVAR(sum_doc,
Thomas Wouters89f507f2006-12-13 04:49:30 +00001636"sum(sequence[, start]) -> value\n\
Alex Martellia70b1912003-04-22 08:12:33 +00001637\n\
1638Returns the sum of a sequence of numbers (NOT strings) plus the value\n\
Thomas Wouters89f507f2006-12-13 04:49:30 +00001639of parameter 'start' (which defaults to 0). When the sequence is\n\
1640empty, returns start.");
Alex Martellia70b1912003-04-22 08:12:33 +00001641
1642
Barry Warsawcde8b1b1997-08-22 21:14:38 +00001643static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001644builtin_isinstance(PyObject *self, PyObject *args)
Barry Warsawcde8b1b1997-08-22 21:14:38 +00001645{
1646 PyObject *inst;
1647 PyObject *cls;
Guido van Rossum823649d2001-03-21 18:40:58 +00001648 int retval;
Barry Warsawcde8b1b1997-08-22 21:14:38 +00001649
Raymond Hettingerea3fdf42002-12-29 16:33:45 +00001650 if (!PyArg_UnpackTuple(args, "isinstance", 2, 2, &inst, &cls))
Barry Warsawcde8b1b1997-08-22 21:14:38 +00001651 return NULL;
Guido van Rossumf5dd9141997-12-02 19:11:45 +00001652
Guido van Rossum823649d2001-03-21 18:40:58 +00001653 retval = PyObject_IsInstance(inst, cls);
1654 if (retval < 0)
Guido van Rossumad991772001-01-12 16:03:05 +00001655 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(isinstance_doc,
Guido van Rossum77f6a652002-04-03 22:41:51 +00001660"isinstance(object, class-or-type-or-tuple) -> bool\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001661\n\
1662Return whether an object is an instance of a class or of a subclass thereof.\n\
Guido van Rossum03290ec2001-10-07 20:54:12 +00001663With a type as second argument, return whether that is the object's type.\n\
1664The form using a tuple, isinstance(x, (A, B, ...)), is a shortcut for\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001665isinstance(x, A) or isinstance(x, B) or ... (etc.).");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001666
Barry Warsawcde8b1b1997-08-22 21:14:38 +00001667
1668static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001669builtin_issubclass(PyObject *self, PyObject *args)
Barry Warsawcde8b1b1997-08-22 21:14:38 +00001670{
1671 PyObject *derived;
1672 PyObject *cls;
1673 int retval;
1674
Raymond Hettingerea3fdf42002-12-29 16:33:45 +00001675 if (!PyArg_UnpackTuple(args, "issubclass", 2, 2, &derived, &cls))
Barry Warsawcde8b1b1997-08-22 21:14:38 +00001676 return NULL;
Guido van Rossum668213d1999-06-16 17:28:37 +00001677
Guido van Rossum823649d2001-03-21 18:40:58 +00001678 retval = PyObject_IsSubclass(derived, cls);
1679 if (retval < 0)
1680 return NULL;
Guido van Rossum77f6a652002-04-03 22:41:51 +00001681 return PyBool_FromLong(retval);
Barry Warsawcde8b1b1997-08-22 21:14:38 +00001682}
1683
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001684PyDoc_STRVAR(issubclass_doc,
Guido van Rossum77f6a652002-04-03 22:41:51 +00001685"issubclass(C, B) -> bool\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001686\n\
Walter Dörwaldd9a6ad32002-12-12 16:41:44 +00001687Return whether class C is a subclass (i.e., a derived class) of class B.\n\
1688When using a tuple as the second argument issubclass(X, (A, B, ...)),\n\
1689is a shortcut for issubclass(X, A) or issubclass(X, B) or ... (etc.).");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001690
Barry Warsawcde8b1b1997-08-22 21:14:38 +00001691
Barry Warsawbd599b52000-08-03 15:45:29 +00001692static PyObject*
1693builtin_zip(PyObject *self, PyObject *args)
1694{
Guido van Rossumb65fb332006-08-25 23:26:40 +00001695 /* args must be a tuple */
1696 assert(PyTuple_Check(args));
Barry Warsawbd599b52000-08-03 15:45:29 +00001697
Guido van Rossumb65fb332006-08-25 23:26:40 +00001698 return _PyZip_CreateIter(args);
Barry Warsawbd599b52000-08-03 15:45:29 +00001699}
1700
1701
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001702PyDoc_STRVAR(zip_doc,
Guido van Rossum801f0d72006-08-24 19:48:10 +00001703"zip(it1 [, it2 [...]]) -> iter([(it1[0], it2[0] ...), ...])\n\
Barry Warsawbd599b52000-08-03 15:45:29 +00001704\n\
Guido van Rossum801f0d72006-08-24 19:48:10 +00001705Return an iterator yielding tuples, where each tuple contains the\n\
1706corresponding element from each of the argument iterables.\n\
1707The returned iterator ends when the shortest argument iterable is exhausted.\n\
Guido van Rossumc1f779c2007-07-03 08:25:58 +00001708(This is identical to itertools.izip().)");
Barry Warsawbd599b52000-08-03 15:45:29 +00001709
1710
Guido van Rossum79f25d91997-04-29 20:08:16 +00001711static PyMethodDef builtin_methods[] = {
Guido van Rossum52cc1d82007-03-18 15:41:51 +00001712 {"__build_class__", (PyCFunction)builtin___build_class__,
1713 METH_VARARGS | METH_KEYWORDS, build_class_doc},
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001714 {"__import__", (PyCFunction)builtin___import__, METH_VARARGS | METH_KEYWORDS, import_doc},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001715 {"abs", builtin_abs, METH_O, abs_doc},
Raymond Hettinger96229b12005-03-11 06:49:40 +00001716 {"all", builtin_all, METH_O, all_doc},
1717 {"any", builtin_any, METH_O, any_doc},
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001718 {"bin", builtin_bin, METH_O, bin_doc},
Neal Norwitzc2550c72007-08-31 04:17:51 +00001719 {"chr", builtin_chr, METH_VARARGS, chr_doc},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001720 {"cmp", builtin_cmp, METH_VARARGS, cmp_doc},
Guido van Rossumd8faa362007-04-27 19:54:29 +00001721 {"compile", (PyCFunction)builtin_compile, METH_VARARGS | METH_KEYWORDS, compile_doc},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001722 {"delattr", builtin_delattr, METH_VARARGS, delattr_doc},
1723 {"dir", builtin_dir, METH_VARARGS, dir_doc},
1724 {"divmod", builtin_divmod, METH_VARARGS, divmod_doc},
1725 {"eval", builtin_eval, METH_VARARGS, eval_doc},
Georg Brandl7cae87c2006-09-06 06:51:57 +00001726 {"exec", builtin_exec, METH_VARARGS, exec_doc},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001727 {"filter", builtin_filter, METH_VARARGS, filter_doc},
Eric Smith8c663262007-08-25 02:26:07 +00001728 {"format", builtin_format, METH_VARARGS, format_doc},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001729 {"getattr", builtin_getattr, METH_VARARGS, getattr_doc},
1730 {"globals", (PyCFunction)builtin_globals, METH_NOARGS, globals_doc},
1731 {"hasattr", builtin_hasattr, METH_VARARGS, hasattr_doc},
1732 {"hash", builtin_hash, METH_O, hash_doc},
1733 {"hex", builtin_hex, METH_O, hex_doc},
1734 {"id", builtin_id, METH_O, id_doc},
Guido van Rossuma88a0332007-02-26 16:59:55 +00001735 {"input", builtin_input, METH_VARARGS, input_doc},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001736 {"isinstance", builtin_isinstance, METH_VARARGS, isinstance_doc},
1737 {"issubclass", builtin_issubclass, METH_VARARGS, issubclass_doc},
1738 {"iter", builtin_iter, METH_VARARGS, iter_doc},
1739 {"len", builtin_len, METH_O, len_doc},
1740 {"locals", (PyCFunction)builtin_locals, METH_NOARGS, locals_doc},
1741 {"map", builtin_map, METH_VARARGS, map_doc},
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001742 {"max", (PyCFunction)builtin_max, METH_VARARGS | METH_KEYWORDS, max_doc},
1743 {"min", (PyCFunction)builtin_min, METH_VARARGS | METH_KEYWORDS, min_doc},
Georg Brandla18af4e2007-04-21 15:47:16 +00001744 {"next", (PyCFunction)builtin_next, METH_VARARGS, next_doc},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001745 {"oct", builtin_oct, METH_O, oct_doc},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001746 {"ord", builtin_ord, METH_O, ord_doc},
1747 {"pow", builtin_pow, METH_VARARGS, pow_doc},
Guido van Rossum452bf512007-02-09 05:32:43 +00001748 {"print", (PyCFunction)builtin_print, METH_VARARGS | METH_KEYWORDS, print_doc},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001749 {"repr", builtin_repr, METH_O, repr_doc},
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001750 {"round", (PyCFunction)builtin_round, METH_VARARGS | METH_KEYWORDS, round_doc},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001751 {"setattr", builtin_setattr, METH_VARARGS, setattr_doc},
Raymond Hettinger64958a12003-12-17 20:43:33 +00001752 {"sorted", (PyCFunction)builtin_sorted, METH_VARARGS | METH_KEYWORDS, sorted_doc},
Alex Martellia70b1912003-04-22 08:12:33 +00001753 {"sum", builtin_sum, METH_VARARGS, sum_doc},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001754 {"vars", builtin_vars, METH_VARARGS, vars_doc},
Alex Martelli86d8b342007-08-22 22:39:42 +00001755 {"trunc", builtin_trunc, METH_O, trunc_doc},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001756 {"zip", builtin_zip, METH_VARARGS, zip_doc},
Guido van Rossumc02e15c1991-12-16 13:03:00 +00001757 {NULL, NULL},
Guido van Rossum3f5da241990-12-20 15:06:42 +00001758};
1759
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001760PyDoc_STRVAR(builtin_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001761"Built-in functions, exceptions, and other objects.\n\
1762\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001763Noteworthy: None is the `nil' object; Ellipsis represents `...' in slices.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001764
Guido van Rossum25ce5661997-08-02 03:10:38 +00001765PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001766_PyBuiltin_Init(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +00001767{
Fred Drake5550de32000-06-20 04:54:19 +00001768 PyObject *mod, *dict, *debug;
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001769 mod = Py_InitModule4("__builtin__", builtin_methods,
1770 builtin_doc, (PyObject *)NULL,
1771 PYTHON_API_VERSION);
Guido van Rossum25ce5661997-08-02 03:10:38 +00001772 if (mod == NULL)
1773 return NULL;
1774 dict = PyModule_GetDict(mod);
Tim Peters4b7625e2001-09-13 21:37:17 +00001775
Tim Peters7571a0f2003-03-23 17:52:28 +00001776#ifdef Py_TRACE_REFS
1777 /* __builtin__ exposes a number of statically allocated objects
1778 * that, before this code was added in 2.3, never showed up in
1779 * the list of "all objects" maintained by Py_TRACE_REFS. As a
1780 * result, programs leaking references to None and False (etc)
1781 * couldn't be diagnosed by examining sys.getobjects(0).
1782 */
1783#define ADD_TO_ALL(OBJECT) _Py_AddToAllObjects((PyObject *)(OBJECT), 0)
1784#else
1785#define ADD_TO_ALL(OBJECT) (void)0
1786#endif
1787
Tim Peters4b7625e2001-09-13 21:37:17 +00001788#define SETBUILTIN(NAME, OBJECT) \
Tim Peters7571a0f2003-03-23 17:52:28 +00001789 if (PyDict_SetItemString(dict, NAME, (PyObject *)OBJECT) < 0) \
1790 return NULL; \
1791 ADD_TO_ALL(OBJECT)
Tim Peters4b7625e2001-09-13 21:37:17 +00001792
1793 SETBUILTIN("None", Py_None);
1794 SETBUILTIN("Ellipsis", Py_Ellipsis);
1795 SETBUILTIN("NotImplemented", Py_NotImplemented);
Guido van Rossum77f6a652002-04-03 22:41:51 +00001796 SETBUILTIN("False", Py_False);
1797 SETBUILTIN("True", Py_True);
1798 SETBUILTIN("bool", &PyBool_Type);
Guido van Rossumbae07c92007-10-08 02:46:15 +00001799 SETBUILTIN("memoryview", &PyMemoryView_Type);
Guido van Rossum4dfe8a12006-04-22 23:28:04 +00001800 SETBUILTIN("bytes", &PyBytes_Type);
Tim Peters4b7625e2001-09-13 21:37:17 +00001801 SETBUILTIN("classmethod", &PyClassMethod_Type);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001802#ifndef WITHOUT_COMPLEX
Tim Peters4b7625e2001-09-13 21:37:17 +00001803 SETBUILTIN("complex", &PyComplex_Type);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001804#endif
Tim Petersa427a2b2001-10-29 22:25:45 +00001805 SETBUILTIN("dict", &PyDict_Type);
Tim Peters67d687a2002-04-29 21:27:32 +00001806 SETBUILTIN("enumerate", &PyEnum_Type);
Tim Peters4b7625e2001-09-13 21:37:17 +00001807 SETBUILTIN("float", &PyFloat_Type);
Raymond Hettingera690a992003-11-16 16:17:49 +00001808 SETBUILTIN("frozenset", &PyFrozenSet_Type);
Tim Peters4b7625e2001-09-13 21:37:17 +00001809 SETBUILTIN("property", &PyProperty_Type);
Guido van Rossumddefaf32007-01-14 03:31:43 +00001810 SETBUILTIN("int", &PyLong_Type);
Tim Peters4b7625e2001-09-13 21:37:17 +00001811 SETBUILTIN("list", &PyList_Type);
Tim Peters4b7625e2001-09-13 21:37:17 +00001812 SETBUILTIN("object", &PyBaseObject_Type);
Guido van Rossum805365e2007-05-07 22:24:25 +00001813 SETBUILTIN("range", &PyRange_Type);
Raymond Hettinger85c20a42003-11-06 14:06:48 +00001814 SETBUILTIN("reversed", &PyReversed_Type);
Raymond Hettingera690a992003-11-16 16:17:49 +00001815 SETBUILTIN("set", &PySet_Type);
Guido van Rossumbea18cc2002-06-14 20:41:17 +00001816 SETBUILTIN("slice", &PySlice_Type);
Tim Peters4b7625e2001-09-13 21:37:17 +00001817 SETBUILTIN("staticmethod", &PyStaticMethod_Type);
Guido van Rossum572dbf82007-04-27 23:53:51 +00001818 SETBUILTIN("str", &PyUnicode_Type);
Guido van Rossum84fc66d2007-05-03 17:18:26 +00001819 SETBUILTIN("str8", &PyString_Type);
Tim Peters4b7625e2001-09-13 21:37:17 +00001820 SETBUILTIN("super", &PySuper_Type);
1821 SETBUILTIN("tuple", &PyTuple_Type);
1822 SETBUILTIN("type", &PyType_Type);
Guido van Rossum77f6a652002-04-03 22:41:51 +00001823 debug = PyBool_FromLong(Py_OptimizeFlag == 0);
Fred Drake5550de32000-06-20 04:54:19 +00001824 if (PyDict_SetItemString(dict, "__debug__", debug) < 0) {
1825 Py_XDECREF(debug);
Guido van Rossum25ce5661997-08-02 03:10:38 +00001826 return NULL;
Fred Drake5550de32000-06-20 04:54:19 +00001827 }
1828 Py_XDECREF(debug);
Barry Warsaw757af0e1997-08-29 22:13:51 +00001829
Guido van Rossum25ce5661997-08-02 03:10:38 +00001830 return mod;
Tim Peters7571a0f2003-03-23 17:52:28 +00001831#undef ADD_TO_ALL
Tim Peters4b7625e2001-09-13 21:37:17 +00001832#undef SETBUILTIN
Guido van Rossum3f5da241990-12-20 15:06:42 +00001833}