blob: d32b0099471b621d79a65623eca5e80d4e002216 [file] [log] [blame]
Guido van Rossum3f5da241990-12-20 15:06:42 +00001/* Built-in functions */
2
Guido van Rossum79f25d91997-04-29 20:08:16 +00003#include "Python.h"
Guido van Rossum3f5da241990-12-20 15:06:42 +00004
5#include "node.h"
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00006#include "code.h"
Guido van Rossum5b722181993-03-30 17:46:03 +00007#include "eval.h"
Guido van Rossum3f5da241990-12-20 15:06:42 +00008
Guido van Rossum6bf62da1997-04-11 20:37:35 +00009#include <ctype.h>
10
Mark Hammond26cffde42001-05-14 12:17:34 +000011/* The default encoding used by the platform file system APIs
12 Can remain NULL for all platforms that don't have such a concept
13*/
Martin v. Löwis6238d2b2002-06-30 15:26:10 +000014#if defined(MS_WINDOWS) && defined(HAVE_USABLE_WCHAR_T)
Mark Hammond26cffde42001-05-14 12:17:34 +000015const char *Py_FileSystemDefaultEncoding = "mbcs";
Just van Rossumb9b8e9c2003-02-10 09:22:01 +000016#elif defined(__APPLE__)
17const char *Py_FileSystemDefaultEncoding = "utf-8";
Mark Hammond26cffde42001-05-14 12:17:34 +000018#else
19const char *Py_FileSystemDefaultEncoding = NULL; /* use default */
20#endif
Mark Hammondef8b6542001-05-13 08:04:26 +000021
Guido van Rossum79f25d91997-04-29 20:08:16 +000022static PyObject *
Guido van Rossum52cc1d82007-03-18 15:41:51 +000023builtin___build_class__(PyObject *self, PyObject *args, PyObject *kwds)
24{
Guido van Rossumcd16bf62007-06-13 18:07:49 +000025 PyObject *func, *name, *bases, *mkw, *meta, *prep, *ns, *cell;
26 PyObject *cls = NULL;
Guido van Rossum52cc1d82007-03-18 15:41:51 +000027 Py_ssize_t nargs, nbases;
28
29 assert(args != NULL);
30 if (!PyTuple_Check(args)) {
31 PyErr_SetString(PyExc_TypeError,
32 "__build_class__: args is not a tuple");
33 return NULL;
34 }
35 nargs = PyTuple_GET_SIZE(args);
36 if (nargs < 2) {
37 PyErr_SetString(PyExc_TypeError,
38 "__build_class__: not enough arguments");
39 return NULL;
40 }
41 func = PyTuple_GET_ITEM(args, 0); /* Better be callable */
42 name = PyTuple_GET_ITEM(args, 1);
Neal Norwitz6ea45d32007-08-26 04:19:43 +000043 if (!PyUnicode_Check(name)) {
Guido van Rossum52cc1d82007-03-18 15:41:51 +000044 PyErr_SetString(PyExc_TypeError,
45 "__build_class__: name is not a string");
46 return NULL;
47 }
48 bases = PyTuple_GetSlice(args, 2, nargs);
49 if (bases == NULL)
50 return NULL;
51 nbases = nargs - 2;
52
53 if (kwds == NULL) {
54 meta = NULL;
55 mkw = NULL;
56 }
57 else {
58 mkw = PyDict_Copy(kwds); /* Don't modify kwds passed in! */
59 if (mkw == NULL) {
60 Py_DECREF(bases);
61 return NULL;
62 }
63 meta = PyDict_GetItemString(mkw, "metaclass");
64 if (meta != NULL) {
65 Py_INCREF(meta);
66 if (PyDict_DelItemString(mkw, "metaclass") < 0) {
67 Py_DECREF(meta);
68 Py_DECREF(mkw);
69 Py_DECREF(bases);
70 return NULL;
71 }
72 }
73 }
74 if (meta == NULL) {
75 if (PyTuple_GET_SIZE(bases) == 0)
76 meta = (PyObject *) (&PyType_Type);
77 else {
78 PyObject *base0 = PyTuple_GET_ITEM(bases, 0);
79 meta = (PyObject *) (base0->ob_type);
80 }
81 Py_INCREF(meta);
82 }
83 prep = PyObject_GetAttrString(meta, "__prepare__");
84 if (prep == NULL) {
85 PyErr_Clear();
86 ns = PyDict_New();
87 }
88 else {
89 PyObject *pargs = Py_BuildValue("OO", name, bases);
90 if (pargs == NULL) {
91 Py_DECREF(prep);
92 Py_DECREF(meta);
93 Py_XDECREF(mkw);
94 Py_DECREF(bases);
95 return NULL;
96 }
97 ns = PyEval_CallObjectWithKeywords(prep, pargs, mkw);
98 Py_DECREF(pargs);
99 Py_DECREF(prep);
100 if (ns == NULL) {
101 Py_DECREF(meta);
102 Py_XDECREF(mkw);
103 Py_DECREF(bases);
104 return NULL;
105 }
106 }
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000107 cell = PyObject_CallFunctionObjArgs(func, ns, NULL);
108 if (cell != NULL) {
Guido van Rossum52cc1d82007-03-18 15:41:51 +0000109 PyObject *margs;
Guido van Rossum52cc1d82007-03-18 15:41:51 +0000110 margs = Py_BuildValue("OOO", name, bases, ns);
111 if (margs != NULL) {
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000112 cls = PyEval_CallObjectWithKeywords(meta, margs, mkw);
Guido van Rossum52cc1d82007-03-18 15:41:51 +0000113 Py_DECREF(margs);
114 }
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000115 if (cls != NULL && PyCell_Check(cell)) {
116 Py_INCREF(cls);
117 PyCell_SET(cell, cls);
118 }
119 Py_DECREF(cell);
Guido van Rossum52cc1d82007-03-18 15:41:51 +0000120 }
121 Py_DECREF(ns);
122 Py_DECREF(meta);
123 Py_XDECREF(mkw);
124 Py_DECREF(bases);
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000125 return cls;
Guido van Rossum52cc1d82007-03-18 15:41:51 +0000126}
127
128PyDoc_STRVAR(build_class_doc,
129"__build_class__(func, name, *bases, metaclass=None, **kwds) -> class\n\
130\n\
131Internal helper function used by the class statement.");
132
133static PyObject *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000134builtin___import__(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000135{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000136 static char *kwlist[] = {"name", "globals", "locals", "fromlist",
137 "level", 0};
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000138 char *name;
Guido van Rossum79f25d91997-04-29 20:08:16 +0000139 PyObject *globals = NULL;
140 PyObject *locals = NULL;
141 PyObject *fromlist = NULL;
Thomas Woutersf7f438b2006-02-28 16:09:29 +0000142 int level = -1;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000143
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000144 if (!PyArg_ParseTupleAndKeywords(args, kwds, "s|OOOi:__import__",
145 kwlist, &name, &globals, &locals, &fromlist, &level))
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000146 return NULL;
Thomas Woutersf7f438b2006-02-28 16:09:29 +0000147 return PyImport_ImportModuleLevel(name, globals, locals,
148 fromlist, level);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000149}
150
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000151PyDoc_STRVAR(import_doc,
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000152"__import__(name, globals={}, locals={}, fromlist=[], level=-1) -> module\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000153\n\
154Import a module. The globals are only used to determine the context;\n\
155they are not modified. The locals are currently unused. The fromlist\n\
156should be a list of names to emulate ``from name import ...'', or an\n\
157empty list to emulate ``import name''.\n\
158When importing a module from a package, note that __import__('A.B', ...)\n\
159returns package A when fromlist is empty, but its submodule B when\n\
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000160fromlist is not empty. Level is used to determine whether to perform \n\
161absolute or relative imports. -1 is the original strategy of attempting\n\
162both absolute and relative imports, 0 is absolute, a positive number\n\
163is the number of parent directories to search relative to the current module.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000164
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000165
Guido van Rossum79f25d91997-04-29 20:08:16 +0000166static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000167builtin_abs(PyObject *self, PyObject *v)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000168{
Guido van Rossum09df08a1998-05-22 00:51:39 +0000169 return PyNumber_Absolute(v);
Guido van Rossum3f5da241990-12-20 15:06:42 +0000170}
171
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000172PyDoc_STRVAR(abs_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000173"abs(number) -> number\n\
174\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000175Return the absolute value of the argument.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000176
Raymond Hettinger96229b12005-03-11 06:49:40 +0000177static PyObject *
178builtin_all(PyObject *self, PyObject *v)
179{
180 PyObject *it, *item;
181
182 it = PyObject_GetIter(v);
183 if (it == NULL)
184 return NULL;
185
186 while ((item = PyIter_Next(it)) != NULL) {
187 int cmp = PyObject_IsTrue(item);
188 Py_DECREF(item);
189 if (cmp < 0) {
190 Py_DECREF(it);
191 return NULL;
192 }
193 if (cmp == 0) {
194 Py_DECREF(it);
195 Py_RETURN_FALSE;
196 }
197 }
198 Py_DECREF(it);
199 if (PyErr_Occurred())
200 return NULL;
201 Py_RETURN_TRUE;
202}
203
204PyDoc_STRVAR(all_doc,
205"all(iterable) -> bool\n\
206\n\
207Return True if bool(x) is True for all values x in the iterable.");
208
209static PyObject *
210builtin_any(PyObject *self, PyObject *v)
211{
212 PyObject *it, *item;
213
214 it = PyObject_GetIter(v);
215 if (it == NULL)
216 return NULL;
217
218 while ((item = PyIter_Next(it)) != NULL) {
219 int cmp = PyObject_IsTrue(item);
220 Py_DECREF(item);
221 if (cmp < 0) {
222 Py_DECREF(it);
223 return NULL;
224 }
225 if (cmp == 1) {
226 Py_DECREF(it);
227 Py_RETURN_TRUE;
228 }
229 }
230 Py_DECREF(it);
231 if (PyErr_Occurred())
232 return NULL;
233 Py_RETURN_FALSE;
234}
235
236PyDoc_STRVAR(any_doc,
237"any(iterable) -> bool\n\
238\n\
239Return True if bool(x) is True for any x in the iterable.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000240
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000241
Guido van Rossum79f25d91997-04-29 20:08:16 +0000242static PyObject *
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000243builtin_bin(PyObject *self, PyObject *v)
244{
245 return PyNumber_ToBase(v, 2);
246}
247
248PyDoc_STRVAR(bin_doc,
249"bin(number) -> string\n\
250\n\
251Return the binary representation of an integer or long integer.");
252
253
254static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000255builtin_filter(PyObject *self, PyObject *args)
Guido van Rossum12d12c51993-10-26 17:58:25 +0000256{
Guido van Rossumc1f779c2007-07-03 08:25:58 +0000257 PyObject *itertools, *ifilter, *result;
258 itertools = PyImport_ImportModule("itertools");
259 if (itertools == NULL)
Guido van Rossum12d12c51993-10-26 17:58:25 +0000260 return NULL;
Guido van Rossumc1f779c2007-07-03 08:25:58 +0000261 ifilter = PyObject_GetAttrString(itertools, "ifilter");
262 Py_DECREF(itertools);
263 if (ifilter == NULL)
Georg Brandle35b6572005-07-19 22:20:20 +0000264 return NULL;
Guido van Rossumc1f779c2007-07-03 08:25:58 +0000265 result = PyObject_Call(ifilter, args, NULL);
266 Py_DECREF(ifilter);
Guido van Rossum12d12c51993-10-26 17:58:25 +0000267 return result;
Guido van Rossum12d12c51993-10-26 17:58:25 +0000268}
269
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000270PyDoc_STRVAR(filter_doc,
Guido van Rossumc1f779c2007-07-03 08:25:58 +0000271"filter(predicate, iterable) -> iterator\n\
272\n\
273Return an iterator yielding only those elements of the input iterable\n\
274for which the predicate (a Boolean function) returns true.\n\
275If the predicate is None, 'lambda x: bool(x)' is assumed.\n\
276(This is identical to itertools.ifilter().)");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000277
Eric Smith8c663262007-08-25 02:26:07 +0000278static PyObject *
279builtin_format(PyObject *self, PyObject *args)
280{
281 static PyObject * format_str = NULL;
282 PyObject *value;
Eric Smith81936692007-08-31 01:14:01 +0000283 PyObject *spec = NULL;
Eric Smith8c663262007-08-25 02:26:07 +0000284 PyObject *meth;
Eric Smith81936692007-08-31 01:14:01 +0000285 PyObject *empty = NULL;
286 PyObject *result = NULL;
Eric Smith8c663262007-08-25 02:26:07 +0000287
288 /* Initialize cached value */
289 if (format_str == NULL) {
290 /* Initialize static variable needed by _PyType_Lookup */
291 format_str = PyUnicode_FromString("__format__");
292 if (format_str == NULL)
Eric Smith81936692007-08-31 01:14:01 +0000293 goto done;
Eric Smith8c663262007-08-25 02:26:07 +0000294 }
295
Eric Smith81936692007-08-31 01:14:01 +0000296 if (!PyArg_ParseTuple(args, "O|O:format", &value, &spec))
297 goto done;
298
299 /* initialize the default value */
300 if (spec == NULL) {
301 empty = PyUnicode_FromUnicode(NULL, 0);
302 spec = empty;
303 }
Eric Smith8c663262007-08-25 02:26:07 +0000304
305 /* Make sure the type is initialized. float gets initialized late */
306 if (Py_Type(value)->tp_dict == NULL)
307 if (PyType_Ready(Py_Type(value)) < 0)
Eric Smith81936692007-08-31 01:14:01 +0000308 goto done;
Eric Smith8c663262007-08-25 02:26:07 +0000309
310 /* Find the (unbound!) __format__ method (a borrowed reference) */
311 meth = _PyType_Lookup(Py_Type(value), format_str);
312 if (meth == NULL) {
313 PyErr_Format(PyExc_TypeError,
314 "Type %.100s doesn't define __format__",
315 Py_Type(value)->tp_name);
Eric Smith81936692007-08-31 01:14:01 +0000316 goto done;
Eric Smith8c663262007-08-25 02:26:07 +0000317 }
318
319 /* And call it, binding it to the value */
320 result = PyObject_CallFunctionObjArgs(meth, value, spec, NULL);
321
Eric Smith81936692007-08-31 01:14:01 +0000322 if (result && !PyUnicode_Check(result)) {
Eric Smith8c663262007-08-25 02:26:07 +0000323 PyErr_SetString(PyExc_TypeError,
324 "__format__ method did not return string");
325 Py_DECREF(result);
Eric Smith81936692007-08-31 01:14:01 +0000326 result = NULL;
327 goto done;
Eric Smith8c663262007-08-25 02:26:07 +0000328 }
Eric Smith8c663262007-08-25 02:26:07 +0000329
Eric Smith81936692007-08-31 01:14:01 +0000330done:
331 Py_XDECREF(empty);
Eric Smith8c663262007-08-25 02:26:07 +0000332 return result;
333}
334
Eric Smith8c663262007-08-25 02:26:07 +0000335PyDoc_STRVAR(format_doc,
Eric Smith81936692007-08-31 01:14:01 +0000336"format(value[, format_spec]) -> string\n\
Eric Smith8c663262007-08-25 02:26:07 +0000337\n\
Eric Smith81936692007-08-31 01:14:01 +0000338Returns value.__format__(format_spec)\n\
339format_spec defaults to \"\"");
340
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000341
Guido van Rossum79f25d91997-04-29 20:08:16 +0000342static PyObject *
Walter Dörwalde7efd592007-06-05 20:07:21 +0000343builtin_chr8(PyObject *self, PyObject *args)
Guido van Rossum7fcf2242007-05-04 17:43:11 +0000344{
345 long x;
346 char s[1];
347
348 if (!PyArg_ParseTuple(args, "l:chr8", &x))
349 return NULL;
350 if (x < 0 || x >= 256) {
351 PyErr_SetString(PyExc_ValueError,
352 "chr8() arg not in range(256)");
353 return NULL;
354 }
355 s[0] = (char)x;
356 return PyString_FromStringAndSize(s, 1);
357}
358
Walter Dörwalde7efd592007-06-05 20:07:21 +0000359PyDoc_STRVAR(chr8_doc,
Guido van Rossum7fcf2242007-05-04 17:43:11 +0000360"chr8(i) -> 8-bit character\n\
361\n\
362Return a string of one character with ordinal i; 0 <= i < 256.");
363
364
365static PyObject *
Walter Dörwalde7efd592007-06-05 20:07:21 +0000366builtin_chr(PyObject *self, PyObject *args)
Guido van Rossum09095f32000-03-10 23:00:52 +0000367{
368 long x;
Guido van Rossum09095f32000-03-10 23:00:52 +0000369
Walter Dörwalde7efd592007-06-05 20:07:21 +0000370 if (!PyArg_ParseTuple(args, "l:chr", &x))
Guido van Rossum09095f32000-03-10 23:00:52 +0000371 return NULL;
Fredrik Lundh0dcf67e2001-06-26 20:01:56 +0000372
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +0000373 return PyUnicode_FromOrdinal(x);
Guido van Rossum09095f32000-03-10 23:00:52 +0000374}
375
Guido van Rossum307fa8c2007-07-16 20:46:27 +0000376PyDoc_VAR(chr_doc) = PyDoc_STR(
Guido van Rossum84fc66d2007-05-03 17:18:26 +0000377"chr(i) -> Unicode character\n\
Guido van Rossum09095f32000-03-10 23:00:52 +0000378\n\
Guido van Rossum8ac004e2007-07-15 13:00:05 +0000379Return a Unicode string of one character with ordinal i; 0 <= i <= 0x10ffff."
Guido van Rossum307fa8c2007-07-16 20:46:27 +0000380)
Guido van Rossum8ac004e2007-07-15 13:00:05 +0000381#ifndef Py_UNICODE_WIDE
Guido van Rossum307fa8c2007-07-16 20:46:27 +0000382PyDoc_STR(
Guido van Rossum8ac004e2007-07-15 13:00:05 +0000383"\nIf 0x10000 <= i, a surrogate pair is returned."
Guido van Rossum307fa8c2007-07-16 20:46:27 +0000384)
Guido van Rossum8ac004e2007-07-15 13:00:05 +0000385#endif
Guido van Rossum307fa8c2007-07-16 20:46:27 +0000386;
Guido van Rossum09095f32000-03-10 23:00:52 +0000387
388
389static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000390builtin_cmp(PyObject *self, PyObject *args)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +0000391{
Guido van Rossum79f25d91997-04-29 20:08:16 +0000392 PyObject *a, *b;
Guido van Rossum09df08a1998-05-22 00:51:39 +0000393 int c;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000394
Raymond Hettingerea3fdf42002-12-29 16:33:45 +0000395 if (!PyArg_UnpackTuple(args, "cmp", 2, 2, &a, &b))
Guido van Rossuma9e7dc11992-10-18 18:53:57 +0000396 return NULL;
Guido van Rossum09df08a1998-05-22 00:51:39 +0000397 if (PyObject_Cmp(a, b, &c) < 0)
Guido van Rossumc8b6df91997-05-23 00:06:51 +0000398 return NULL;
Guido van Rossum09df08a1998-05-22 00:51:39 +0000399 return PyInt_FromLong((long)c);
Guido van Rossuma9e7dc11992-10-18 18:53:57 +0000400}
401
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000402PyDoc_STRVAR(cmp_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000403"cmp(x, y) -> integer\n\
404\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000405Return negative if x<y, zero if x==y, positive if x>y.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000406
Guido van Rossumf15a29f2007-05-04 00:41:39 +0000407
408static char *
409source_as_string(PyObject *cmd)
410{
411 char *str;
412 Py_ssize_t size;
413
Guido van Rossumf15a29f2007-05-04 00:41:39 +0000414 if (PyUnicode_Check(cmd)) {
415 cmd = _PyUnicode_AsDefaultEncodedString(cmd, NULL);
416 if (cmd == NULL)
417 return NULL;
418 }
Guido van Rossuma4b8d1d2007-08-27 15:02:28 +0000419 else if (!PyObject_CheckReadBuffer(cmd)) {
420 PyErr_SetString(PyExc_TypeError,
421 "eval()/exec() arg 1 must be a string, bytes or code object");
422 return NULL;
423 }
Guido van Rossumf15a29f2007-05-04 00:41:39 +0000424 if (PyObject_AsReadBuffer(cmd, (const void **)&str, &size) < 0) {
425 return NULL;
426 }
427 if (strlen(str) != size) {
428 PyErr_SetString(PyExc_TypeError,
429 "source code string cannot contain null bytes");
430 return NULL;
431 }
432 return str;
433}
434
Guido van Rossum79f25d91997-04-29 20:08:16 +0000435static PyObject *
Guido van Rossumd8faa362007-04-27 19:54:29 +0000436builtin_compile(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum5b722181993-03-30 17:46:03 +0000437{
438 char *str;
439 char *filename;
440 char *startstr;
441 int start;
Tim Peters6cd6a822001-08-17 22:11:27 +0000442 int dont_inherit = 0;
443 int supplied_flags = 0;
Tim Peters5ba58662001-07-16 02:29:45 +0000444 PyCompilerFlags cf;
Guido van Rossumf15a29f2007-05-04 00:41:39 +0000445 PyObject *cmd;
Guido van Rossumd8faa362007-04-27 19:54:29 +0000446 static char *kwlist[] = {"source", "filename", "mode", "flags",
447 "dont_inherit", NULL};
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000448
Guido van Rossumd8faa362007-04-27 19:54:29 +0000449 if (!PyArg_ParseTupleAndKeywords(args, kwds, "Oss|ii:compile",
450 kwlist, &cmd, &filename, &startstr,
451 &supplied_flags, &dont_inherit))
Guido van Rossum5b722181993-03-30 17:46:03 +0000452 return NULL;
Tim Peters6cd6a822001-08-17 22:11:27 +0000453
Guido van Rossumf15a29f2007-05-04 00:41:39 +0000454 cf.cf_flags = supplied_flags | PyCF_SOURCE_IS_UTF8;
Just van Rossum3aaf42c2003-02-10 08:21:10 +0000455
Guido van Rossumf15a29f2007-05-04 00:41:39 +0000456 str = source_as_string(cmd);
457 if (str == NULL)
Just van Rossumb9b8e9c2003-02-10 09:22:01 +0000458 return NULL;
Just van Rossum3aaf42c2003-02-10 08:21:10 +0000459
Guido van Rossum5b722181993-03-30 17:46:03 +0000460 if (strcmp(startstr, "exec") == 0)
Guido van Rossumb05a5c71997-05-07 17:46:13 +0000461 start = Py_file_input;
Guido van Rossum5b722181993-03-30 17:46:03 +0000462 else if (strcmp(startstr, "eval") == 0)
Guido van Rossumb05a5c71997-05-07 17:46:13 +0000463 start = Py_eval_input;
Guido van Rossum872537c1995-07-07 22:43:42 +0000464 else if (strcmp(startstr, "single") == 0)
Guido van Rossumb05a5c71997-05-07 17:46:13 +0000465 start = Py_single_input;
Guido van Rossum5b722181993-03-30 17:46:03 +0000466 else {
Guido van Rossum79f25d91997-04-29 20:08:16 +0000467 PyErr_SetString(PyExc_ValueError,
Fred Drake661ea262000-10-24 19:57:45 +0000468 "compile() arg 3 must be 'exec' or 'eval' or 'single'");
Guido van Rossumf15a29f2007-05-04 00:41:39 +0000469 return NULL;
Guido van Rossum5b722181993-03-30 17:46:03 +0000470 }
Tim Peters6cd6a822001-08-17 22:11:27 +0000471
Guido van Rossum4b499dd32003-02-13 22:07:59 +0000472 if (supplied_flags &
Martin v. Löwisbd260da2006-02-26 19:42:26 +0000473 ~(PyCF_MASK | PyCF_MASK_OBSOLETE | PyCF_DONT_IMPLY_DEDENT | PyCF_ONLY_AST))
Guido van Rossum4b499dd32003-02-13 22:07:59 +0000474 {
Tim Peters6cd6a822001-08-17 22:11:27 +0000475 PyErr_SetString(PyExc_ValueError,
476 "compile(): unrecognised flags");
Guido van Rossumf15a29f2007-05-04 00:41:39 +0000477 return NULL;
Tim Peters6cd6a822001-08-17 22:11:27 +0000478 }
479 /* XXX Warn if (supplied_flags & PyCF_MASK_OBSOLETE) != 0? */
480
Tim Peters6cd6a822001-08-17 22:11:27 +0000481 if (!dont_inherit) {
482 PyEval_MergeCompilerFlags(&cf);
483 }
Guido van Rossumf15a29f2007-05-04 00:41:39 +0000484 return Py_CompileStringFlags(str, filename, start, &cf);
Guido van Rossum5b722181993-03-30 17:46:03 +0000485}
486
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000487PyDoc_STRVAR(compile_doc,
Tim Peters6cd6a822001-08-17 22:11:27 +0000488"compile(source, filename, mode[, flags[, dont_inherit]]) -> code object\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000489\n\
490Compile the source string (a Python module, statement or expression)\n\
Georg Brandl7cae87c2006-09-06 06:51:57 +0000491into a code object that can be executed by exec() or eval().\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000492The filename will be used for run-time error messages.\n\
493The mode must be 'exec' to compile a module, 'single' to compile a\n\
Tim Peters6cd6a822001-08-17 22:11:27 +0000494single (interactive) statement, or 'eval' to compile an expression.\n\
495The flags argument, if present, controls which future statements influence\n\
496the compilation of the code.\n\
497The dont_inherit argument, if non-zero, stops the compilation inheriting\n\
498the effects of any future statements in effect in the code calling\n\
499compile; if absent or zero these statements do influence the compilation,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000500in addition to any features explicitly specified.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000501
Guido van Rossum79f25d91997-04-29 20:08:16 +0000502static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000503builtin_dir(PyObject *self, PyObject *args)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000504{
Tim Peters5d2b77c2001-09-03 05:47:38 +0000505 PyObject *arg = NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000506
Raymond Hettingerea3fdf42002-12-29 16:33:45 +0000507 if (!PyArg_UnpackTuple(args, "dir", 0, 1, &arg))
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000508 return NULL;
Tim Peters7eea37e2001-09-04 22:08:56 +0000509 return PyObject_Dir(arg);
Guido van Rossum3f5da241990-12-20 15:06:42 +0000510}
511
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000512PyDoc_STRVAR(dir_doc,
Tim Peters5d2b77c2001-09-03 05:47:38 +0000513"dir([object]) -> list of strings\n"
514"\n"
Georg Brandle32b4222007-03-10 22:13:27 +0000515"If called without an argument, return the names in the current scope.\n"
516"Else, return an alphabetized list of names comprising (some of) the attributes\n"
517"of the given object, and of attributes reachable from it.\n"
518"If the object supplies a method named __dir__, it will be used; otherwise\n"
519"the default dir() logic is used and returns:\n"
520" for a module object: the module's attributes.\n"
521" for a class object: its attributes, and recursively the attributes\n"
522" of its bases.\n"
Guido van Rossumd8faa362007-04-27 19:54:29 +0000523" for any other object: its attributes, its class's attributes, and\n"
Georg Brandle32b4222007-03-10 22:13:27 +0000524" recursively the attributes of its class's base classes.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000525
Guido van Rossum79f25d91997-04-29 20:08:16 +0000526static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000527builtin_divmod(PyObject *self, PyObject *args)
Guido van Rossum6a00cd81995-01-07 12:39:01 +0000528{
Guido van Rossum79f25d91997-04-29 20:08:16 +0000529 PyObject *v, *w;
Guido van Rossum6a00cd81995-01-07 12:39:01 +0000530
Raymond Hettingerea3fdf42002-12-29 16:33:45 +0000531 if (!PyArg_UnpackTuple(args, "divmod", 2, 2, &v, &w))
Guido van Rossum6a00cd81995-01-07 12:39:01 +0000532 return NULL;
Guido van Rossum09df08a1998-05-22 00:51:39 +0000533 return PyNumber_Divmod(v, w);
Guido van Rossum3f5da241990-12-20 15:06:42 +0000534}
535
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000536PyDoc_STRVAR(divmod_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000537"divmod(x, y) -> (div, mod)\n\
538\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000539Return the tuple ((x-x%y)/y, x%y). Invariant: div*y + mod == x.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000540
541
Guido van Rossum79f25d91997-04-29 20:08:16 +0000542static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000543builtin_eval(PyObject *self, PyObject *args)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000544{
Just van Rossum3aaf42c2003-02-10 08:21:10 +0000545 PyObject *cmd, *result, *tmp = NULL;
Guido van Rossum79f25d91997-04-29 20:08:16 +0000546 PyObject *globals = Py_None, *locals = Py_None;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000547 char *str;
Tim Peters9fa96be2001-08-17 23:04:59 +0000548 PyCompilerFlags cf;
Guido van Rossum590baa41993-11-30 13:40:46 +0000549
Raymond Hettinger214b1c32004-07-02 06:41:07 +0000550 if (!PyArg_UnpackTuple(args, "eval", 1, 3, &cmd, &globals, &locals))
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000551 return NULL;
Raymond Hettinger214b1c32004-07-02 06:41:07 +0000552 if (locals != Py_None && !PyMapping_Check(locals)) {
553 PyErr_SetString(PyExc_TypeError, "locals must be a mapping");
Raymond Hettinger513ffe82004-07-06 13:44:41 +0000554 return NULL;
Raymond Hettinger214b1c32004-07-02 06:41:07 +0000555 }
556 if (globals != Py_None && !PyDict_Check(globals)) {
Georg Brandl99d7e4e2005-08-31 22:21:15 +0000557 PyErr_SetString(PyExc_TypeError, PyMapping_Check(globals) ?
Raymond Hettinger214b1c32004-07-02 06:41:07 +0000558 "globals must be a real dict; try eval(expr, {}, mapping)"
559 : "globals must be a dict");
Raymond Hettinger513ffe82004-07-06 13:44:41 +0000560 return NULL;
Raymond Hettinger214b1c32004-07-02 06:41:07 +0000561 }
Guido van Rossum79f25d91997-04-29 20:08:16 +0000562 if (globals == Py_None) {
563 globals = PyEval_GetGlobals();
564 if (locals == Py_None)
565 locals = PyEval_GetLocals();
Guido van Rossum6135a871995-01-09 17:53:26 +0000566 }
Guido van Rossum79f25d91997-04-29 20:08:16 +0000567 else if (locals == Py_None)
Guido van Rossum6135a871995-01-09 17:53:26 +0000568 locals = globals;
Tim Peters9fa96be2001-08-17 23:04:59 +0000569
Georg Brandl77c85e62005-09-15 10:46:13 +0000570 if (globals == NULL || locals == NULL) {
571 PyErr_SetString(PyExc_TypeError,
572 "eval must be given globals and locals "
573 "when called without a frame");
574 return NULL;
575 }
576
Guido van Rossum79f25d91997-04-29 20:08:16 +0000577 if (PyDict_GetItemString(globals, "__builtins__") == NULL) {
578 if (PyDict_SetItemString(globals, "__builtins__",
579 PyEval_GetBuiltins()) != 0)
Guido van Rossum6135a871995-01-09 17:53:26 +0000580 return NULL;
581 }
Tim Peters9fa96be2001-08-17 23:04:59 +0000582
Jeremy Hylton15c1c4f2001-07-30 21:50:55 +0000583 if (PyCode_Check(cmd)) {
Jeremy Hylton733c8932001-12-13 19:51:56 +0000584 if (PyCode_GetNumFree((PyCodeObject *)cmd) > 0) {
Jeremy Hylton15c1c4f2001-07-30 21:50:55 +0000585 PyErr_SetString(PyExc_TypeError,
586 "code object passed to eval() may not contain free variables");
587 return NULL;
588 }
Guido van Rossum79f25d91997-04-29 20:08:16 +0000589 return PyEval_EvalCode((PyCodeObject *) cmd, globals, locals);
Jeremy Hylton15c1c4f2001-07-30 21:50:55 +0000590 }
Tim Peters9fa96be2001-08-17 23:04:59 +0000591
Guido van Rossumf15a29f2007-05-04 00:41:39 +0000592 str = source_as_string(cmd);
593 if (str == NULL)
Guido van Rossum94390a41992-08-14 15:14:30 +0000594 return NULL;
Just van Rossum3aaf42c2003-02-10 08:21:10 +0000595
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000596 while (*str == ' ' || *str == '\t')
597 str++;
Tim Peters9fa96be2001-08-17 23:04:59 +0000598
Guido van Rossumf15a29f2007-05-04 00:41:39 +0000599 cf.cf_flags = PyCF_SOURCE_IS_UTF8;
Tim Peters9fa96be2001-08-17 23:04:59 +0000600 (void)PyEval_MergeCompilerFlags(&cf);
Just van Rossum3aaf42c2003-02-10 08:21:10 +0000601 result = PyRun_StringFlags(str, Py_eval_input, globals, locals, &cf);
602 Py_XDECREF(tmp);
603 return result;
Guido van Rossum3f5da241990-12-20 15:06:42 +0000604}
605
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000606PyDoc_STRVAR(eval_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000607"eval(source[, globals[, locals]]) -> value\n\
608\n\
609Evaluate the source in the context of globals and locals.\n\
610The source may be a string representing a Python expression\n\
611or a code object as returned by compile().\n\
Thomas Wouters89f507f2006-12-13 04:49:30 +0000612The globals must be a dictionary and locals can be any mapping,\n\
Raymond Hettinger214b1c32004-07-02 06:41:07 +0000613defaulting to the current globals and locals.\n\
614If only globals is given, locals defaults to it.\n");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000615
Georg Brandl7cae87c2006-09-06 06:51:57 +0000616static PyObject *
617builtin_exec(PyObject *self, PyObject *args)
618{
619 PyObject *v;
620 PyObject *prog, *globals = Py_None, *locals = Py_None;
621 int plain = 0;
622
623 if (!PyArg_ParseTuple(args, "O|OO:exec", &prog, &globals, &locals))
624 return NULL;
625
626 if (globals == Py_None) {
627 globals = PyEval_GetGlobals();
628 if (locals == Py_None) {
629 locals = PyEval_GetLocals();
630 plain = 1;
631 }
632 if (!globals || !locals) {
633 PyErr_SetString(PyExc_SystemError,
634 "globals and locals cannot be NULL");
635 return NULL;
636 }
637 }
638 else if (locals == Py_None)
639 locals = globals;
Neal Norwitz6ea45d32007-08-26 04:19:43 +0000640 if (!PyUnicode_Check(prog) &&
Guido van Rossumda5b8f22007-06-12 23:30:11 +0000641 !PyCode_Check(prog)) {
Georg Brandl7cae87c2006-09-06 06:51:57 +0000642 PyErr_Format(PyExc_TypeError,
643 "exec() arg 1 must be a string, file, or code "
644 "object, not %.100s", prog->ob_type->tp_name);
645 return NULL;
646 }
647 if (!PyDict_Check(globals)) {
648 PyErr_Format(PyExc_TypeError, "exec() arg 2 must be a dict, not %.100s",
649 globals->ob_type->tp_name);
650 return NULL;
651 }
652 if (!PyMapping_Check(locals)) {
653 PyErr_Format(PyExc_TypeError,
654 "arg 3 must be a mapping or None, not %.100s",
655 locals->ob_type->tp_name);
656 return NULL;
657 }
658 if (PyDict_GetItemString(globals, "__builtins__") == NULL) {
659 if (PyDict_SetItemString(globals, "__builtins__",
660 PyEval_GetBuiltins()) != 0)
661 return NULL;
662 }
663
664 if (PyCode_Check(prog)) {
665 if (PyCode_GetNumFree((PyCodeObject *)prog) > 0) {
666 PyErr_SetString(PyExc_TypeError,
667 "code object passed to exec() may not "
668 "contain free variables");
669 return NULL;
670 }
671 v = PyEval_EvalCode((PyCodeObject *) prog, globals, locals);
672 }
Georg Brandl7cae87c2006-09-06 06:51:57 +0000673 else {
Guido van Rossumf15a29f2007-05-04 00:41:39 +0000674 char *str = source_as_string(prog);
Georg Brandl7cae87c2006-09-06 06:51:57 +0000675 PyCompilerFlags cf;
Guido van Rossumf15a29f2007-05-04 00:41:39 +0000676 if (str == NULL)
Georg Brandl7cae87c2006-09-06 06:51:57 +0000677 return NULL;
Guido van Rossumf15a29f2007-05-04 00:41:39 +0000678 cf.cf_flags = PyCF_SOURCE_IS_UTF8;
Georg Brandl7cae87c2006-09-06 06:51:57 +0000679 if (PyEval_MergeCompilerFlags(&cf))
680 v = PyRun_StringFlags(str, Py_file_input, globals,
681 locals, &cf);
682 else
683 v = PyRun_String(str, Py_file_input, globals, locals);
Georg Brandl7cae87c2006-09-06 06:51:57 +0000684 }
685 if (v == NULL)
686 return NULL;
687 Py_DECREF(v);
688 Py_RETURN_NONE;
689}
690
691PyDoc_STRVAR(exec_doc,
692"exec(object[, globals[, locals]])\n\
693\n\
694Read and execute code from a object, which can be a string, a code\n\
695object or a file object.\n\
696The globals and locals are dictionaries, defaulting to the current\n\
697globals and locals. If only globals is given, locals defaults to it.");
698
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000699
Guido van Rossum79f25d91997-04-29 20:08:16 +0000700static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000701builtin_getattr(PyObject *self, PyObject *args)
Guido van Rossum33894be1992-01-27 16:53:09 +0000702{
Neal Norwitz6ea45d32007-08-26 04:19:43 +0000703 PyObject *v, *result, *dflt = NULL;
Guido van Rossum79f25d91997-04-29 20:08:16 +0000704 PyObject *name;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000705
Raymond Hettingerea3fdf42002-12-29 16:33:45 +0000706 if (!PyArg_UnpackTuple(args, "getattr", 2, 3, &v, &name, &dflt))
Guido van Rossum33894be1992-01-27 16:53:09 +0000707 return NULL;
Martin v. Löwis5b222132007-06-10 09:51:05 +0000708
Martin v. Löwis5b222132007-06-10 09:51:05 +0000709 if (!PyUnicode_Check(name)) {
Jeremy Hylton0eb11152001-07-30 22:39:31 +0000710 PyErr_SetString(PyExc_TypeError,
Alex Martellia9b9c9f2003-04-23 13:34:35 +0000711 "getattr(): attribute name must be string");
Jeremy Hylton0eb11152001-07-30 22:39:31 +0000712 return NULL;
713 }
Guido van Rossum950ff291998-06-29 13:38:57 +0000714 result = PyObject_GetAttr(v, name);
Guido van Rossumd8923572001-10-16 21:31:32 +0000715 if (result == NULL && dflt != NULL &&
716 PyErr_ExceptionMatches(PyExc_AttributeError))
717 {
Guido van Rossum950ff291998-06-29 13:38:57 +0000718 PyErr_Clear();
719 Py_INCREF(dflt);
720 result = dflt;
721 }
722 return result;
Guido van Rossum9bfef441993-03-29 10:43:31 +0000723}
724
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000725PyDoc_STRVAR(getattr_doc,
Guido van Rossum950ff291998-06-29 13:38:57 +0000726"getattr(object, name[, default]) -> value\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000727\n\
Guido van Rossum950ff291998-06-29 13:38:57 +0000728Get a named attribute from an object; getattr(x, 'y') is equivalent to x.y.\n\
729When a default argument is given, it is returned when the attribute doesn't\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000730exist; without it, an exception is raised in that case.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000731
732
Guido van Rossum79f25d91997-04-29 20:08:16 +0000733static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000734builtin_globals(PyObject *self)
Guido van Rossum872537c1995-07-07 22:43:42 +0000735{
Guido van Rossum79f25d91997-04-29 20:08:16 +0000736 PyObject *d;
Guido van Rossum872537c1995-07-07 22:43:42 +0000737
Guido van Rossum79f25d91997-04-29 20:08:16 +0000738 d = PyEval_GetGlobals();
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000739 Py_XINCREF(d);
Guido van Rossum872537c1995-07-07 22:43:42 +0000740 return d;
741}
742
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000743PyDoc_STRVAR(globals_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000744"globals() -> dictionary\n\
745\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000746Return the dictionary containing the current scope's global variables.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000747
748
Guido van Rossum79f25d91997-04-29 20:08:16 +0000749static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000750builtin_hasattr(PyObject *self, PyObject *args)
Guido van Rossum9bfef441993-03-29 10:43:31 +0000751{
Guido van Rossum79f25d91997-04-29 20:08:16 +0000752 PyObject *v;
753 PyObject *name;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000754
Raymond Hettingerea3fdf42002-12-29 16:33:45 +0000755 if (!PyArg_UnpackTuple(args, "hasattr", 2, 2, &v, &name))
Guido van Rossum9bfef441993-03-29 10:43:31 +0000756 return NULL;
Martin v. Löwis5b222132007-06-10 09:51:05 +0000757 if (!PyUnicode_Check(name)) {
Jeremy Hylton302b54a2001-07-30 22:45:19 +0000758 PyErr_SetString(PyExc_TypeError,
Alex Martellia9b9c9f2003-04-23 13:34:35 +0000759 "hasattr(): attribute name must be string");
Jeremy Hylton302b54a2001-07-30 22:45:19 +0000760 return NULL;
761 }
Guido van Rossum79f25d91997-04-29 20:08:16 +0000762 v = PyObject_GetAttr(v, name);
Guido van Rossum9bfef441993-03-29 10:43:31 +0000763 if (v == NULL) {
Guido van Rossum79f25d91997-04-29 20:08:16 +0000764 PyErr_Clear();
Guido van Rossum09df08a1998-05-22 00:51:39 +0000765 Py_INCREF(Py_False);
766 return Py_False;
Guido van Rossum9bfef441993-03-29 10:43:31 +0000767 }
Guido van Rossum79f25d91997-04-29 20:08:16 +0000768 Py_DECREF(v);
Guido van Rossum09df08a1998-05-22 00:51:39 +0000769 Py_INCREF(Py_True);
770 return Py_True;
Guido van Rossum33894be1992-01-27 16:53:09 +0000771}
772
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000773PyDoc_STRVAR(hasattr_doc,
Guido van Rossum77f6a652002-04-03 22:41:51 +0000774"hasattr(object, name) -> bool\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000775\n\
776Return whether the object has an attribute with the given name.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000777(This is done by calling getattr(object, name) and catching exceptions.)");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000778
779
Guido van Rossum79f25d91997-04-29 20:08:16 +0000780static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000781builtin_id(PyObject *self, PyObject *v)
Guido van Rossum5b722181993-03-30 17:46:03 +0000782{
Guido van Rossum106f2da2000-06-28 21:12:25 +0000783 return PyLong_FromVoidPtr(v);
Guido van Rossum5b722181993-03-30 17:46:03 +0000784}
785
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000786PyDoc_STRVAR(id_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000787"id(object) -> integer\n\
788\n\
789Return the identity of an object. This is guaranteed to be unique among\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000790simultaneously existing objects. (Hint: it's the object's memory address.)");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000791
792
Guido van Rossum79f25d91997-04-29 20:08:16 +0000793static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000794builtin_map(PyObject *self, PyObject *args)
Guido van Rossum12d12c51993-10-26 17:58:25 +0000795{
Guido van Rossumc1f779c2007-07-03 08:25:58 +0000796 PyObject *itertools, *imap, *result;
797 itertools = PyImport_ImportModule("itertools");
798 if (itertools == NULL)
Guido van Rossum12d12c51993-10-26 17:58:25 +0000799 return NULL;
Guido van Rossumc1f779c2007-07-03 08:25:58 +0000800 imap = PyObject_GetAttrString(itertools, "imap");
801 Py_DECREF(itertools);
802 if (imap == NULL)
Tim Peters4e9afdc2001-05-03 23:54:49 +0000803 return NULL;
Guido van Rossumc1f779c2007-07-03 08:25:58 +0000804 result = PyObject_Call(imap, args, NULL);
805 Py_DECREF(imap);
Tim Peters4e9afdc2001-05-03 23:54:49 +0000806 return result;
Guido van Rossum12d12c51993-10-26 17:58:25 +0000807}
808
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000809PyDoc_STRVAR(map_doc,
Guido van Rossumc1f779c2007-07-03 08:25:58 +0000810"map(function, iterable[, iterable, ...]) -> iterator\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000811\n\
Guido van Rossumc1f779c2007-07-03 08:25:58 +0000812Return an iterator yielding the results of applying the function to the\n\
813items of the argument iterables(s). If more than one iterable is given,\n\
814the function is called with an argument list consisting of the\n\
815corresponding item of each iterable, until an iterable is exhausted.\n\
816If the function is None, 'lambda *a: a' is assumed.\n\
817(This is identical to itertools.imap().)");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000818
819
Guido van Rossum79f25d91997-04-29 20:08:16 +0000820static PyObject *
Georg Brandla18af4e2007-04-21 15:47:16 +0000821builtin_next(PyObject *self, PyObject *args)
822{
823 PyObject *it, *res;
824 PyObject *def = NULL;
825
826 if (!PyArg_UnpackTuple(args, "next", 1, 2, &it, &def))
827 return NULL;
828 if (!PyIter_Check(it)) {
829 PyErr_Format(PyExc_TypeError,
830 "%.200s object is not an iterator", it->ob_type->tp_name);
831 return NULL;
832 }
833
834 res = (*it->ob_type->tp_iternext)(it);
835 if (res == NULL) {
836 if (def) {
837 if (PyErr_Occurred() &&
838 !PyErr_ExceptionMatches(PyExc_StopIteration))
839 return NULL;
840 PyErr_Clear();
841 Py_INCREF(def);
842 return def;
843 } else if (PyErr_Occurred()) {
844 return NULL;
845 } else {
846 PyErr_SetNone(PyExc_StopIteration);
847 return NULL;
848 }
849 }
850 return res;
851}
852
853PyDoc_STRVAR(next_doc,
854"next(iterator[, default])\n\
855\n\
856Return the next item from the iterator. If default is given and the iterator\n\
857is exhausted, it is returned instead of raising StopIteration.");
858
859
860static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000861builtin_setattr(PyObject *self, PyObject *args)
Guido van Rossum33894be1992-01-27 16:53:09 +0000862{
Guido van Rossum79f25d91997-04-29 20:08:16 +0000863 PyObject *v;
864 PyObject *name;
865 PyObject *value;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000866
Raymond Hettingerea3fdf42002-12-29 16:33:45 +0000867 if (!PyArg_UnpackTuple(args, "setattr", 3, 3, &v, &name, &value))
Guido van Rossum33894be1992-01-27 16:53:09 +0000868 return NULL;
Guido van Rossum79f25d91997-04-29 20:08:16 +0000869 if (PyObject_SetAttr(v, name, value) != 0)
Guido van Rossum33894be1992-01-27 16:53:09 +0000870 return NULL;
Guido van Rossum79f25d91997-04-29 20:08:16 +0000871 Py_INCREF(Py_None);
872 return Py_None;
Guido van Rossum33894be1992-01-27 16:53:09 +0000873}
874
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000875PyDoc_STRVAR(setattr_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000876"setattr(object, name, value)\n\
877\n\
878Set a named attribute on an object; setattr(x, 'y', v) is equivalent to\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000879``x.y = v''.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000880
881
Guido van Rossum79f25d91997-04-29 20:08:16 +0000882static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000883builtin_delattr(PyObject *self, PyObject *args)
Guido van Rossum14144fc1994-08-29 12:53:40 +0000884{
Guido van Rossum79f25d91997-04-29 20:08:16 +0000885 PyObject *v;
886 PyObject *name;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000887
Raymond Hettingerea3fdf42002-12-29 16:33:45 +0000888 if (!PyArg_UnpackTuple(args, "delattr", 2, 2, &v, &name))
Guido van Rossum14144fc1994-08-29 12:53:40 +0000889 return NULL;
Guido van Rossum79f25d91997-04-29 20:08:16 +0000890 if (PyObject_SetAttr(v, name, (PyObject *)NULL) != 0)
Guido van Rossum14144fc1994-08-29 12:53:40 +0000891 return NULL;
Guido van Rossum79f25d91997-04-29 20:08:16 +0000892 Py_INCREF(Py_None);
893 return Py_None;
Guido van Rossum14144fc1994-08-29 12:53:40 +0000894}
895
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000896PyDoc_STRVAR(delattr_doc,
Guido van Rossumdf12a591998-11-23 22:13:04 +0000897"delattr(object, name)\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000898\n\
899Delete a named attribute on an object; delattr(x, 'y') is equivalent to\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000900``del x.y''.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000901
902
Guido van Rossum79f25d91997-04-29 20:08:16 +0000903static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000904builtin_hash(PyObject *self, PyObject *v)
Guido van Rossum9bfef441993-03-29 10:43:31 +0000905{
Guido van Rossum9bfef441993-03-29 10:43:31 +0000906 long x;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000907
Guido van Rossum79f25d91997-04-29 20:08:16 +0000908 x = PyObject_Hash(v);
Guido van Rossum9bfef441993-03-29 10:43:31 +0000909 if (x == -1)
910 return NULL;
Guido van Rossum79f25d91997-04-29 20:08:16 +0000911 return PyInt_FromLong(x);
Guido van Rossum9bfef441993-03-29 10:43:31 +0000912}
913
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000914PyDoc_STRVAR(hash_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000915"hash(object) -> integer\n\
916\n\
917Return a hash value for the object. Two objects with the same value have\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000918the same hash value. The reverse is not necessarily true, but likely.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000919
920
Guido van Rossum79f25d91997-04-29 20:08:16 +0000921static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000922builtin_hex(PyObject *self, PyObject *v)
Guido van Rossum006bcd41991-10-24 14:54:44 +0000923{
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000924 return PyNumber_ToBase(v, 16);
Guido van Rossum006bcd41991-10-24 14:54:44 +0000925}
926
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000927PyDoc_STRVAR(hex_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000928"hex(number) -> string\n\
929\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000930Return the hexadecimal representation of an integer or long integer.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000931
932
Guido van Rossum79f25d91997-04-29 20:08:16 +0000933static PyObject *
Guido van Rossum59d1d2b2001-04-20 19:13:02 +0000934builtin_iter(PyObject *self, PyObject *args)
935{
936 PyObject *v, *w = NULL;
937
Raymond Hettingerea3fdf42002-12-29 16:33:45 +0000938 if (!PyArg_UnpackTuple(args, "iter", 1, 2, &v, &w))
Guido van Rossum59d1d2b2001-04-20 19:13:02 +0000939 return NULL;
940 if (w == NULL)
941 return PyObject_GetIter(v);
942 if (!PyCallable_Check(v)) {
943 PyErr_SetString(PyExc_TypeError,
944 "iter(v, w): v must be callable");
945 return NULL;
946 }
947 return PyCallIter_New(v, w);
948}
949
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000950PyDoc_STRVAR(iter_doc,
Guido van Rossum59d1d2b2001-04-20 19:13:02 +0000951"iter(collection) -> iterator\n\
952iter(callable, sentinel) -> iterator\n\
953\n\
954Get an iterator from an object. In the first form, the argument must\n\
955supply its own iterator, or be a sequence.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000956In the second form, the callable is called until it returns the sentinel.");
Guido van Rossum59d1d2b2001-04-20 19:13:02 +0000957
958
959static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000960builtin_len(PyObject *self, PyObject *v)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000961{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000962 Py_ssize_t res;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000963
Jeremy Hylton03657cf2000-07-12 13:05:33 +0000964 res = PyObject_Size(v);
Guido van Rossum8ea9f4d1998-06-29 22:26:50 +0000965 if (res < 0 && PyErr_Occurred())
966 return NULL;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000967 return PyInt_FromSsize_t(res);
Guido van Rossum3f5da241990-12-20 15:06:42 +0000968}
969
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000970PyDoc_STRVAR(len_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000971"len(object) -> integer\n\
972\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000973Return the number of items of a sequence or mapping.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000974
975
Guido van Rossum79f25d91997-04-29 20:08:16 +0000976static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000977builtin_locals(PyObject *self)
Guido van Rossum872537c1995-07-07 22:43:42 +0000978{
Guido van Rossum79f25d91997-04-29 20:08:16 +0000979 PyObject *d;
Guido van Rossum872537c1995-07-07 22:43:42 +0000980
Guido van Rossum79f25d91997-04-29 20:08:16 +0000981 d = PyEval_GetLocals();
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000982 Py_XINCREF(d);
Guido van Rossum872537c1995-07-07 22:43:42 +0000983 return d;
984}
985
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000986PyDoc_STRVAR(locals_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000987"locals() -> dictionary\n\
988\n\
Raymond Hettinger69bf8f32003-01-04 02:16:22 +0000989Update and return a dictionary containing the current scope's local variables.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000990
991
Guido van Rossum79f25d91997-04-29 20:08:16 +0000992static PyObject *
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +0000993min_max(PyObject *args, PyObject *kwds, int op)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000994{
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +0000995 PyObject *v, *it, *item, *val, *maxitem, *maxval, *keyfunc=NULL;
Martin v. Löwisfd39ad42004-08-12 14:42:37 +0000996 const char *name = op == Py_LT ? "min" : "max";
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000997
Guido van Rossum79f25d91997-04-29 20:08:16 +0000998 if (PyTuple_Size(args) > 1)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000999 v = args;
Martin v. Löwisfd39ad42004-08-12 14:42:37 +00001000 else if (!PyArg_UnpackTuple(args, (char *)name, 1, 1, &v))
Guido van Rossum3f5da241990-12-20 15:06:42 +00001001 return NULL;
Tim Peters67d687a2002-04-29 21:27:32 +00001002
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001003 if (kwds != NULL && PyDict_Check(kwds) && PyDict_Size(kwds)) {
1004 keyfunc = PyDict_GetItemString(kwds, "key");
1005 if (PyDict_Size(kwds)!=1 || keyfunc == NULL) {
Georg Brandl99d7e4e2005-08-31 22:21:15 +00001006 PyErr_Format(PyExc_TypeError,
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001007 "%s() got an unexpected keyword argument", name);
1008 return NULL;
1009 }
Georg Brandl99d7e4e2005-08-31 22:21:15 +00001010 }
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001011
Tim Petersc3074532001-05-03 07:00:32 +00001012 it = PyObject_GetIter(v);
1013 if (it == NULL)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001014 return NULL;
Tim Petersc3074532001-05-03 07:00:32 +00001015
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001016 maxitem = NULL; /* the result */
1017 maxval = NULL; /* the value associated with the result */
Brett Cannon9e635cf2004-12-07 00:25:35 +00001018 while (( item = PyIter_Next(it) )) {
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001019 /* get the value from the key function */
1020 if (keyfunc != NULL) {
1021 val = PyObject_CallFunctionObjArgs(keyfunc, item, NULL);
1022 if (val == NULL)
1023 goto Fail_it_item;
1024 }
1025 /* no key function; the value is the item */
1026 else {
1027 val = item;
1028 Py_INCREF(val);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001029 }
Tim Petersc3074532001-05-03 07:00:32 +00001030
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001031 /* maximum value and item are unset; set them */
1032 if (maxval == NULL) {
1033 maxitem = item;
1034 maxval = val;
1035 }
1036 /* maximum value and item are set; update them as necessary */
Guido van Rossum2d951851994-08-29 12:52:16 +00001037 else {
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001038 int cmp = PyObject_RichCompareBool(val, maxval, op);
1039 if (cmp < 0)
1040 goto Fail_it_item_and_val;
1041 else if (cmp > 0) {
1042 Py_DECREF(maxval);
1043 Py_DECREF(maxitem);
1044 maxval = val;
1045 maxitem = item;
Guido van Rossum53451b32001-01-17 15:47:24 +00001046 }
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001047 else {
1048 Py_DECREF(item);
1049 Py_DECREF(val);
Guido van Rossumc8b6df91997-05-23 00:06:51 +00001050 }
Guido van Rossum2d951851994-08-29 12:52:16 +00001051 }
Guido van Rossum3f5da241990-12-20 15:06:42 +00001052 }
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001053 if (PyErr_Occurred())
1054 goto Fail_it;
1055 if (maxval == NULL) {
Martin v. Löwisfd39ad42004-08-12 14:42:37 +00001056 PyErr_Format(PyExc_ValueError,
1057 "%s() arg is an empty sequence", name);
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001058 assert(maxitem == NULL);
1059 }
1060 else
1061 Py_DECREF(maxval);
Tim Petersc3074532001-05-03 07:00:32 +00001062 Py_DECREF(it);
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001063 return maxitem;
1064
1065Fail_it_item_and_val:
1066 Py_DECREF(val);
1067Fail_it_item:
1068 Py_DECREF(item);
1069Fail_it:
1070 Py_XDECREF(maxval);
1071 Py_XDECREF(maxitem);
1072 Py_DECREF(it);
1073 return NULL;
Guido van Rossum3f5da241990-12-20 15:06:42 +00001074}
1075
Guido van Rossum79f25d91997-04-29 20:08:16 +00001076static PyObject *
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001077builtin_min(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001078{
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001079 return min_max(args, kwds, Py_LT);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001080}
1081
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001082PyDoc_STRVAR(min_doc,
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001083"min(iterable[, key=func]) -> value\n\
1084min(a, b, c, ...[, key=func]) -> value\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001085\n\
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001086With a single iterable argument, return its smallest item.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001087With two or more arguments, return the smallest argument.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001088
1089
Guido van Rossum79f25d91997-04-29 20:08:16 +00001090static PyObject *
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001091builtin_max(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001092{
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001093 return min_max(args, kwds, Py_GT);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001094}
1095
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001096PyDoc_STRVAR(max_doc,
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001097"max(iterable[, key=func]) -> value\n\
1098max(a, b, c, ...[, key=func]) -> value\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001099\n\
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001100With a single iterable argument, return its largest item.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001101With two or more arguments, return the largest argument.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001102
1103
Guido van Rossum79f25d91997-04-29 20:08:16 +00001104static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001105builtin_oct(PyObject *self, PyObject *v)
Guido van Rossum006bcd41991-10-24 14:54:44 +00001106{
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001107 return PyNumber_ToBase(v, 8);
Guido van Rossum006bcd41991-10-24 14:54:44 +00001108}
1109
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001110PyDoc_STRVAR(oct_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001111"oct(number) -> string\n\
1112\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001113Return the octal representation of an integer or long integer.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001114
1115
Guido van Rossum79f25d91997-04-29 20:08:16 +00001116static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001117builtin_ord(PyObject *self, PyObject* obj)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001118{
Guido van Rossum09095f32000-03-10 23:00:52 +00001119 long ord;
Martin v. Löwisd96ee902006-02-16 14:37:16 +00001120 Py_ssize_t size;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001121
Jeremy Hylton394b54d2000-04-12 21:19:47 +00001122 if (PyString_Check(obj)) {
1123 size = PyString_GET_SIZE(obj);
Andrew M. Kuchling34c20cf2000-12-20 14:36:56 +00001124 if (size == 1) {
Jeremy Hylton394b54d2000-04-12 21:19:47 +00001125 ord = (long)((unsigned char)*PyString_AS_STRING(obj));
Andrew M. Kuchling34c20cf2000-12-20 14:36:56 +00001126 return PyInt_FromLong(ord);
1127 }
Guido van Rossum98f97462007-04-13 03:31:13 +00001128 }
1129 else if (PyUnicode_Check(obj)) {
Jeremy Hylton394b54d2000-04-12 21:19:47 +00001130 size = PyUnicode_GET_SIZE(obj);
Andrew M. Kuchling34c20cf2000-12-20 14:36:56 +00001131 if (size == 1) {
Jeremy Hylton394b54d2000-04-12 21:19:47 +00001132 ord = (long)*PyUnicode_AS_UNICODE(obj);
Andrew M. Kuchling34c20cf2000-12-20 14:36:56 +00001133 return PyInt_FromLong(ord);
1134 }
Guido van Rossum8ac004e2007-07-15 13:00:05 +00001135#ifndef Py_UNICODE_WIDE
1136 if (size == 2) {
1137 /* Decode a valid surrogate pair */
1138 int c0 = PyUnicode_AS_UNICODE(obj)[0];
1139 int c1 = PyUnicode_AS_UNICODE(obj)[1];
1140 if (0xD800 <= c0 && c0 <= 0xDBFF &&
1141 0xDC00 <= c1 && c1 <= 0xDFFF) {
1142 ord = ((((c0 & 0x03FF) << 10) | (c1 & 0x03FF)) +
1143 0x00010000);
1144 return PyInt_FromLong(ord);
1145 }
1146 }
1147#endif
Guido van Rossum6f376c42007-05-24 14:31:33 +00001148 }
Guido van Rossum98f97462007-04-13 03:31:13 +00001149 else if (PyBytes_Check(obj)) {
1150 /* XXX Hopefully this is temporary */
1151 size = PyBytes_GET_SIZE(obj);
1152 if (size == 1) {
Guido van Rossumf9e91c92007-05-08 21:05:48 +00001153 ord = (long)((unsigned char)*PyBytes_AS_STRING(obj));
Guido van Rossum98f97462007-04-13 03:31:13 +00001154 return PyInt_FromLong(ord);
1155 }
1156 }
1157 else {
Jeremy Hylton394b54d2000-04-12 21:19:47 +00001158 PyErr_Format(PyExc_TypeError,
Andrew M. Kuchlingf07aad12000-12-23 14:11:28 +00001159 "ord() expected string of length 1, but " \
Jeremy Hylton394b54d2000-04-12 21:19:47 +00001160 "%.200s found", obj->ob_type->tp_name);
Guido van Rossum09095f32000-03-10 23:00:52 +00001161 return NULL;
1162 }
1163
Guido van Rossumad991772001-01-12 16:03:05 +00001164 PyErr_Format(PyExc_TypeError,
Andrew M. Kuchlingf07aad12000-12-23 14:11:28 +00001165 "ord() expected a character, "
Martin v. Löwisd96ee902006-02-16 14:37:16 +00001166 "but string of length %zd found",
Jeremy Hylton394b54d2000-04-12 21:19:47 +00001167 size);
1168 return NULL;
Guido van Rossum3f5da241990-12-20 15:06:42 +00001169}
1170
Guido van Rossum307fa8c2007-07-16 20:46:27 +00001171PyDoc_VAR(ord_doc) = PyDoc_STR(
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001172"ord(c) -> integer\n\
1173\n\
Guido van Rossum8ac004e2007-07-15 13:00:05 +00001174Return the integer ordinal of a one-character string."
Guido van Rossum307fa8c2007-07-16 20:46:27 +00001175)
Guido van Rossum8ac004e2007-07-15 13:00:05 +00001176#ifndef Py_UNICODE_WIDE
Guido van Rossum307fa8c2007-07-16 20:46:27 +00001177PyDoc_STR(
Guido van Rossum8ac004e2007-07-15 13:00:05 +00001178"\nA valid surrogate pair is also accepted."
Guido van Rossum307fa8c2007-07-16 20:46:27 +00001179)
Guido van Rossum8ac004e2007-07-15 13:00:05 +00001180#endif
Guido van Rossum307fa8c2007-07-16 20:46:27 +00001181;
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001182
1183
Guido van Rossum79f25d91997-04-29 20:08:16 +00001184static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001185builtin_pow(PyObject *self, PyObject *args)
Guido van Rossum6a00cd81995-01-07 12:39:01 +00001186{
Guido van Rossum09df08a1998-05-22 00:51:39 +00001187 PyObject *v, *w, *z = Py_None;
Guido van Rossum6a00cd81995-01-07 12:39:01 +00001188
Raymond Hettingerea3fdf42002-12-29 16:33:45 +00001189 if (!PyArg_UnpackTuple(args, "pow", 2, 3, &v, &w, &z))
Guido van Rossum6a00cd81995-01-07 12:39:01 +00001190 return NULL;
Guido van Rossum09df08a1998-05-22 00:51:39 +00001191 return PyNumber_Power(v, w, z);
Guido van Rossumd4905451991-05-05 20:00:36 +00001192}
1193
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001194PyDoc_STRVAR(pow_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001195"pow(x, y[, z]) -> number\n\
1196\n\
1197With two arguments, equivalent to x**y. With three arguments,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001198equivalent to (x**y) % z, but may be more efficient (e.g. for longs).");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001199
1200
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001201
Guido van Rossum34343512006-11-30 22:13:52 +00001202static PyObject *
1203builtin_print(PyObject *self, PyObject *args, PyObject *kwds)
1204{
1205 static char *kwlist[] = {"sep", "end", "file", 0};
Georg Brandl257d3d92007-02-26 10:35:10 +00001206 static PyObject *dummy_args;
Guido van Rossum34343512006-11-30 22:13:52 +00001207 PyObject *sep = NULL, *end = NULL, *file = NULL;
1208 int i, err;
1209
Georg Brandl257d3d92007-02-26 10:35:10 +00001210 if (dummy_args == NULL) {
1211 if (!(dummy_args = PyTuple_New(0)))
1212 return NULL;
1213 }
Georg Brandl88fc6642007-02-09 21:28:07 +00001214 if (!PyArg_ParseTupleAndKeywords(dummy_args, kwds, "|OOO:print",
Guido van Rossum34343512006-11-30 22:13:52 +00001215 kwlist, &sep, &end, &file))
1216 return NULL;
1217 if (file == NULL || file == Py_None)
1218 file = PySys_GetObject("stdout");
1219
Neal Norwitz6ea45d32007-08-26 04:19:43 +00001220 if (sep && sep != Py_None && !PyUnicode_Check(sep)) {
Georg Brandl16f3e032006-11-30 22:46:03 +00001221 PyErr_Format(PyExc_TypeError,
Neal Norwitz6ea45d32007-08-26 04:19:43 +00001222 "sep must be None or a string, not %.200s",
Georg Brandl16f3e032006-11-30 22:46:03 +00001223 sep->ob_type->tp_name);
1224 return NULL;
1225 }
Neal Norwitz6ea45d32007-08-26 04:19:43 +00001226 if (end && end != Py_None && !PyUnicode_Check(end)) {
Georg Brandl16f3e032006-11-30 22:46:03 +00001227 PyErr_Format(PyExc_TypeError,
Neal Norwitz6ea45d32007-08-26 04:19:43 +00001228 "end must be None or a string, not %.200s",
Georg Brandl16f3e032006-11-30 22:46:03 +00001229 end->ob_type->tp_name);
1230 return NULL;
1231 }
Guido van Rossum34343512006-11-30 22:13:52 +00001232
1233 for (i = 0; i < PyTuple_Size(args); i++) {
1234 if (i > 0) {
1235 if (sep == NULL || sep == Py_None)
1236 err = PyFile_WriteString(" ", file);
1237 else
1238 err = PyFile_WriteObject(sep, file,
1239 Py_PRINT_RAW);
1240 if (err)
1241 return NULL;
1242 }
1243 err = PyFile_WriteObject(PyTuple_GetItem(args, i), file,
1244 Py_PRINT_RAW);
1245 if (err)
1246 return NULL;
1247 }
1248
1249 if (end == NULL || end == Py_None)
1250 err = PyFile_WriteString("\n", file);
1251 else
1252 err = PyFile_WriteObject(end, file, Py_PRINT_RAW);
1253 if (err)
1254 return NULL;
1255
1256 Py_RETURN_NONE;
1257}
1258
1259PyDoc_STRVAR(print_doc,
Guido van Rossum452bf512007-02-09 05:32:43 +00001260"print(value, ..., file=None, sep=' ', end='\\n')\n\
Guido van Rossum34343512006-11-30 22:13:52 +00001261\n\
1262Prints the values to a stream, or to sys.stdout by default.\n\
1263Optional keyword arguments:\n\
1264file: a file-like object (stream); defaults to the current sys.stdout.\n\
1265sep: string inserted between values, default a space.\n\
1266end: string appended after the last value, default a newline.");
1267
1268
Guido van Rossuma88a0332007-02-26 16:59:55 +00001269static PyObject *
1270builtin_input(PyObject *self, PyObject *args)
1271{
Guido van Rossumeba76962007-05-27 09:13:28 +00001272 PyObject *promptarg = NULL;
Guido van Rossuma88a0332007-02-26 16:59:55 +00001273 PyObject *fin = PySys_GetObject("stdin");
1274 PyObject *fout = PySys_GetObject("stdout");
Guido van Rossumeba76962007-05-27 09:13:28 +00001275 PyObject *ferr = PySys_GetObject("stderr");
1276 PyObject *tmp;
1277 long fd;
1278 int tty;
Guido van Rossuma88a0332007-02-26 16:59:55 +00001279
Guido van Rossumeba76962007-05-27 09:13:28 +00001280 /* Parse arguments */
1281 if (!PyArg_UnpackTuple(args, "input", 0, 1, &promptarg))
Guido van Rossuma88a0332007-02-26 16:59:55 +00001282 return NULL;
1283
Guido van Rossumeba76962007-05-27 09:13:28 +00001284 /* Check that stdin/out/err are intact */
Guido van Rossuma88a0332007-02-26 16:59:55 +00001285 if (fin == NULL) {
Guido van Rossumeba76962007-05-27 09:13:28 +00001286 PyErr_SetString(PyExc_RuntimeError,
1287 "input(): lost sys.stdin");
Guido van Rossuma88a0332007-02-26 16:59:55 +00001288 return NULL;
1289 }
1290 if (fout == NULL) {
Guido van Rossumeba76962007-05-27 09:13:28 +00001291 PyErr_SetString(PyExc_RuntimeError,
1292 "input(): lost sys.stdout");
Guido van Rossuma88a0332007-02-26 16:59:55 +00001293 return NULL;
1294 }
Guido van Rossumeba76962007-05-27 09:13:28 +00001295 if (ferr == NULL) {
1296 PyErr_SetString(PyExc_RuntimeError,
1297 "input(): lost sys.stderr");
1298 return NULL;
1299 }
1300
1301 /* First of all, flush stderr */
1302 tmp = PyObject_CallMethod(ferr, "flush", "");
1303 if (tmp == NULL)
Guido van Rossumc1f779c2007-07-03 08:25:58 +00001304 PyErr_Clear();
1305 else
1306 Py_DECREF(tmp);
Guido van Rossumeba76962007-05-27 09:13:28 +00001307
1308 /* We should only use (GNU) readline if Python's sys.stdin and
1309 sys.stdout are the same as C's stdin and stdout, because we
1310 need to pass it those. */
1311 tmp = PyObject_CallMethod(fin, "fileno", "");
Guido van Rossumc1f779c2007-07-03 08:25:58 +00001312 if (tmp == NULL) {
1313 PyErr_Clear();
1314 tty = 0;
1315 }
1316 else {
Guido van Rossumeba76962007-05-27 09:13:28 +00001317 fd = PyInt_AsLong(tmp);
1318 Py_DECREF(tmp);
1319 if (fd < 0 && PyErr_Occurred())
1320 return NULL;
Guido van Rossumc1f779c2007-07-03 08:25:58 +00001321 tty = fd == fileno(stdin) && isatty(fd);
1322 }
1323 if (tty) {
1324 tmp = PyObject_CallMethod(fout, "fileno", "");
1325 if (tmp == NULL)
1326 PyErr_Clear();
1327 else {
1328 fd = PyInt_AsLong(tmp);
1329 Py_DECREF(tmp);
1330 if (fd < 0 && PyErr_Occurred())
1331 return NULL;
1332 tty = fd == fileno(stdout) && isatty(fd);
1333 }
Guido van Rossumeba76962007-05-27 09:13:28 +00001334 }
1335
1336 /* If we're interactive, use (GNU) readline */
1337 if (tty) {
Guido van Rossuma88a0332007-02-26 16:59:55 +00001338 PyObject *po;
1339 char *prompt;
1340 char *s;
1341 PyObject *result;
Guido van Rossumeba76962007-05-27 09:13:28 +00001342 tmp = PyObject_CallMethod(fout, "flush", "");
1343 if (tmp == NULL)
Guido van Rossumc1f779c2007-07-03 08:25:58 +00001344 PyErr_Clear();
1345 else
1346 Py_DECREF(tmp);
Guido van Rossumeba76962007-05-27 09:13:28 +00001347 if (promptarg != NULL) {
1348 po = PyObject_Str(promptarg);
Guido van Rossuma88a0332007-02-26 16:59:55 +00001349 if (po == NULL)
1350 return NULL;
1351 prompt = PyString_AsString(po);
Guido van Rossumeba76962007-05-27 09:13:28 +00001352 if (prompt == NULL) {
1353 Py_DECREF(po);
Guido van Rossuma88a0332007-02-26 16:59:55 +00001354 return NULL;
Guido van Rossumeba76962007-05-27 09:13:28 +00001355 }
Guido van Rossuma88a0332007-02-26 16:59:55 +00001356 }
1357 else {
1358 po = NULL;
1359 prompt = "";
1360 }
Guido van Rossumeba76962007-05-27 09:13:28 +00001361 s = PyOS_Readline(stdin, stdout, prompt);
Guido van Rossuma88a0332007-02-26 16:59:55 +00001362 Py_XDECREF(po);
1363 if (s == NULL) {
1364 if (!PyErr_Occurred())
1365 PyErr_SetNone(PyExc_KeyboardInterrupt);
1366 return NULL;
1367 }
1368 if (*s == '\0') {
1369 PyErr_SetNone(PyExc_EOFError);
1370 result = NULL;
1371 }
1372 else { /* strip trailing '\n' */
1373 size_t len = strlen(s);
1374 if (len > PY_SSIZE_T_MAX) {
1375 PyErr_SetString(PyExc_OverflowError,
1376 "input: input too long");
1377 result = NULL;
1378 }
1379 else {
Neal Norwitz6ea45d32007-08-26 04:19:43 +00001380 result = PyUnicode_FromStringAndSize(s, len-1);
Guido van Rossuma88a0332007-02-26 16:59:55 +00001381 }
1382 }
1383 PyMem_FREE(s);
1384 return result;
1385 }
Guido van Rossumeba76962007-05-27 09:13:28 +00001386
1387 /* Fallback if we're not interactive */
1388 if (promptarg != NULL) {
1389 if (PyFile_WriteObject(promptarg, fout, Py_PRINT_RAW) != 0)
Guido van Rossuma88a0332007-02-26 16:59:55 +00001390 return NULL;
1391 }
Guido van Rossumeba76962007-05-27 09:13:28 +00001392 tmp = PyObject_CallMethod(fout, "flush", "");
1393 if (tmp == NULL)
Guido van Rossumc1f779c2007-07-03 08:25:58 +00001394 PyErr_Clear();
1395 else
1396 Py_DECREF(tmp);
Guido van Rossuma88a0332007-02-26 16:59:55 +00001397 return PyFile_GetLine(fin, -1);
1398}
1399
1400PyDoc_STRVAR(input_doc,
1401"input([prompt]) -> string\n\
1402\n\
1403Read a string from standard input. The trailing newline is stripped.\n\
1404If the user hits EOF (Unix: Ctl-D, Windows: Ctl-Z+Return), raise EOFError.\n\
1405On Unix, GNU readline is used if enabled. The prompt string, if given,\n\
1406is printed without a trailing newline before reading.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001407
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001408
Guido van Rossum79f25d91997-04-29 20:08:16 +00001409static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001410builtin_repr(PyObject *self, PyObject *v)
Guido van Rossumc89705d1992-11-26 08:54:07 +00001411{
Guido van Rossum79f25d91997-04-29 20:08:16 +00001412 return PyObject_Repr(v);
Guido van Rossumc89705d1992-11-26 08:54:07 +00001413}
1414
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001415PyDoc_STRVAR(repr_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001416"repr(object) -> string\n\
1417\n\
1418Return the canonical string representation of the object.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001419For most object types, eval(repr(object)) == object.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001420
1421
Guido van Rossum79f25d91997-04-29 20:08:16 +00001422static PyObject *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001423builtin_round(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum9e51f9b1993-02-12 16:29:05 +00001424{
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001425#define UNDEF_NDIGITS (-0x7fffffff) /* Unlikely ndigits value */
1426 static PyObject *round_str = NULL;
1427 int ndigits = UNDEF_NDIGITS;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001428 static char *kwlist[] = {"number", "ndigits", 0};
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001429 PyObject *number, *round;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001430
Alex Martelliae211f92007-08-22 23:21:33 +00001431 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|i:round",
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001432 kwlist, &number, &ndigits))
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001433 return NULL;
Alex Martelliae211f92007-08-22 23:21:33 +00001434
Guido van Rossum15d3d042007-08-24 02:02:45 +00001435 if (Py_Type(number)->tp_dict == NULL) {
1436 if (PyType_Ready(Py_Type(number)) < 0)
1437 return NULL;
1438 }
1439
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001440 if (round_str == NULL) {
1441 round_str = PyUnicode_FromString("__round__");
1442 if (round_str == NULL)
Alex Martelliae211f92007-08-22 23:21:33 +00001443 return NULL;
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001444 }
1445
1446 round = _PyType_Lookup(Py_Type(number), round_str);
1447 if (round == NULL) {
1448 PyErr_Format(PyExc_TypeError,
1449 "type %.100s doesn't define __round__ method",
1450 Py_Type(number)->tp_name);
Alex Martelliae211f92007-08-22 23:21:33 +00001451 return NULL;
1452 }
1453
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001454 if (ndigits == UNDEF_NDIGITS)
1455 return PyObject_CallFunction(round, "O", number);
Guido van Rossum9e51f9b1993-02-12 16:29:05 +00001456 else
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001457 return PyObject_CallFunction(round, "Oi", number, ndigits);
1458#undef UNDEF_NDIGITS
Guido van Rossum9e51f9b1993-02-12 16:29:05 +00001459}
1460
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001461PyDoc_STRVAR(round_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001462"round(number[, ndigits]) -> floating point number\n\
1463\n\
1464Round a number to a given precision in decimal digits (default 0 digits).\n\
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001465This returns an int when called with one argument, otherwise a float.\n\
1466Precision may be negative.");
1467
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001468
Raymond Hettinger64958a12003-12-17 20:43:33 +00001469static PyObject *
1470builtin_sorted(PyObject *self, PyObject *args, PyObject *kwds)
1471{
1472 PyObject *newlist, *v, *seq, *compare=NULL, *keyfunc=NULL, *newargs;
1473 PyObject *callable;
Martin v. Löwis15e62742006-02-27 16:46:16 +00001474 static char *kwlist[] = {"iterable", "cmp", "key", "reverse", 0};
Neal Norwitz6f0d4792005-12-15 06:40:36 +00001475 int reverse;
Raymond Hettinger64958a12003-12-17 20:43:33 +00001476
Neal Norwitz6f0d4792005-12-15 06:40:36 +00001477 /* args 1-4 should match listsort in Objects/listobject.c */
Armin Rigo71d7e702005-09-20 18:13:03 +00001478 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|OOi:sorted",
1479 kwlist, &seq, &compare, &keyfunc, &reverse))
1480 return NULL;
Raymond Hettinger64958a12003-12-17 20:43:33 +00001481
1482 newlist = PySequence_List(seq);
1483 if (newlist == NULL)
1484 return NULL;
1485
1486 callable = PyObject_GetAttrString(newlist, "sort");
1487 if (callable == NULL) {
1488 Py_DECREF(newlist);
1489 return NULL;
1490 }
Georg Brandl99d7e4e2005-08-31 22:21:15 +00001491
Raymond Hettinger64958a12003-12-17 20:43:33 +00001492 newargs = PyTuple_GetSlice(args, 1, 4);
1493 if (newargs == NULL) {
1494 Py_DECREF(newlist);
1495 Py_DECREF(callable);
1496 return NULL;
1497 }
1498
1499 v = PyObject_Call(callable, newargs, kwds);
1500 Py_DECREF(newargs);
1501 Py_DECREF(callable);
1502 if (v == NULL) {
1503 Py_DECREF(newlist);
1504 return NULL;
1505 }
1506 Py_DECREF(v);
1507 return newlist;
1508}
1509
1510PyDoc_STRVAR(sorted_doc,
1511"sorted(iterable, cmp=None, key=None, reverse=False) --> new sorted list");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001512
Guido van Rossum79f25d91997-04-29 20:08:16 +00001513static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001514builtin_vars(PyObject *self, PyObject *args)
Guido van Rossum2d951851994-08-29 12:52:16 +00001515{
Guido van Rossum79f25d91997-04-29 20:08:16 +00001516 PyObject *v = NULL;
1517 PyObject *d;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001518
Raymond Hettingerea3fdf42002-12-29 16:33:45 +00001519 if (!PyArg_UnpackTuple(args, "vars", 0, 1, &v))
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001520 return NULL;
Guido van Rossum2d951851994-08-29 12:52:16 +00001521 if (v == NULL) {
Guido van Rossum79f25d91997-04-29 20:08:16 +00001522 d = PyEval_GetLocals();
Guido van Rossum53bb7ff1995-07-26 16:26:31 +00001523 if (d == NULL) {
Guido van Rossum79f25d91997-04-29 20:08:16 +00001524 if (!PyErr_Occurred())
1525 PyErr_SetString(PyExc_SystemError,
Alex Martellia9b9c9f2003-04-23 13:34:35 +00001526 "vars(): no locals!?");
Guido van Rossum53bb7ff1995-07-26 16:26:31 +00001527 }
1528 else
Guido van Rossum79f25d91997-04-29 20:08:16 +00001529 Py_INCREF(d);
Guido van Rossum2d951851994-08-29 12:52:16 +00001530 }
1531 else {
Guido van Rossum79f25d91997-04-29 20:08:16 +00001532 d = PyObject_GetAttrString(v, "__dict__");
Guido van Rossum2d951851994-08-29 12:52:16 +00001533 if (d == NULL) {
Guido van Rossum79f25d91997-04-29 20:08:16 +00001534 PyErr_SetString(PyExc_TypeError,
Guido van Rossum2d951851994-08-29 12:52:16 +00001535 "vars() argument must have __dict__ attribute");
1536 return NULL;
1537 }
1538 }
1539 return d;
1540}
1541
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001542PyDoc_STRVAR(vars_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001543"vars([object]) -> dictionary\n\
1544\n\
1545Without arguments, equivalent to locals().\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001546With an argument, equivalent to object.__dict__.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001547
Alex Martelli86d8b342007-08-22 22:39:42 +00001548static PyObject *
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001549builtin_trunc(PyObject *self, PyObject *number)
Alex Martelli86d8b342007-08-22 22:39:42 +00001550{
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001551 static PyObject *trunc_str = NULL;
1552 PyObject *trunc;
1553
Guido van Rossum15d3d042007-08-24 02:02:45 +00001554 if (Py_Type(number)->tp_dict == NULL) {
1555 if (PyType_Ready(Py_Type(number)) < 0)
1556 return NULL;
1557 }
1558
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001559 if (trunc_str == NULL) {
1560 trunc_str = PyUnicode_FromString("__trunc__");
1561 if (trunc_str == NULL)
1562 return NULL;
1563 }
1564
1565 trunc = _PyType_Lookup(Py_Type(number), trunc_str);
1566 if (trunc == NULL) {
1567 PyErr_Format(PyExc_TypeError,
1568 "type %.100s doesn't define __trunc__ method",
1569 Py_Type(number)->tp_name);
Alex Martelli86d8b342007-08-22 22:39:42 +00001570 return NULL;
1571 }
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001572 return PyObject_CallFunction(trunc, "O", number);
Alex Martelli86d8b342007-08-22 22:39:42 +00001573}
1574
1575PyDoc_STRVAR(trunc_doc,
1576"trunc(Real) -> Integral\n\
1577\n\
1578returns the integral closest to x between 0 and x.");
1579
1580
Alex Martellia70b1912003-04-22 08:12:33 +00001581
1582static PyObject*
1583builtin_sum(PyObject *self, PyObject *args)
1584{
1585 PyObject *seq;
1586 PyObject *result = NULL;
1587 PyObject *temp, *item, *iter;
1588
Raymond Hettinger5cf63942003-10-25 06:41:37 +00001589 if (!PyArg_UnpackTuple(args, "sum", 1, 2, &seq, &result))
Alex Martellia70b1912003-04-22 08:12:33 +00001590 return NULL;
1591
1592 iter = PyObject_GetIter(seq);
1593 if (iter == NULL)
1594 return NULL;
1595
1596 if (result == NULL) {
1597 result = PyInt_FromLong(0);
1598 if (result == NULL) {
1599 Py_DECREF(iter);
1600 return NULL;
1601 }
1602 } else {
1603 /* reject string values for 'start' parameter */
1604 if (PyObject_TypeCheck(result, &PyBaseString_Type)) {
1605 PyErr_SetString(PyExc_TypeError,
Alex Martellia9b9c9f2003-04-23 13:34:35 +00001606 "sum() can't sum strings [use ''.join(seq) instead]");
Alex Martellia70b1912003-04-22 08:12:33 +00001607 Py_DECREF(iter);
1608 return NULL;
1609 }
Alex Martelli41c9f882003-04-22 09:24:48 +00001610 Py_INCREF(result);
Alex Martellia70b1912003-04-22 08:12:33 +00001611 }
1612
1613 for(;;) {
1614 item = PyIter_Next(iter);
1615 if (item == NULL) {
1616 /* error, or end-of-sequence */
1617 if (PyErr_Occurred()) {
1618 Py_DECREF(result);
1619 result = NULL;
1620 }
1621 break;
1622 }
Alex Martellia253e182003-10-25 23:24:14 +00001623 temp = PyNumber_Add(result, item);
Alex Martellia70b1912003-04-22 08:12:33 +00001624 Py_DECREF(result);
1625 Py_DECREF(item);
1626 result = temp;
1627 if (result == NULL)
1628 break;
1629 }
1630 Py_DECREF(iter);
1631 return result;
1632}
1633
1634PyDoc_STRVAR(sum_doc,
Thomas Wouters89f507f2006-12-13 04:49:30 +00001635"sum(sequence[, start]) -> value\n\
Alex Martellia70b1912003-04-22 08:12:33 +00001636\n\
1637Returns the sum of a sequence of numbers (NOT strings) plus the value\n\
Thomas Wouters89f507f2006-12-13 04:49:30 +00001638of parameter 'start' (which defaults to 0). When the sequence is\n\
1639empty, returns start.");
Alex Martellia70b1912003-04-22 08:12:33 +00001640
1641
Barry Warsawcde8b1b1997-08-22 21:14:38 +00001642static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001643builtin_isinstance(PyObject *self, PyObject *args)
Barry Warsawcde8b1b1997-08-22 21:14:38 +00001644{
1645 PyObject *inst;
1646 PyObject *cls;
Guido van Rossum823649d2001-03-21 18:40:58 +00001647 int retval;
Barry Warsawcde8b1b1997-08-22 21:14:38 +00001648
Raymond Hettingerea3fdf42002-12-29 16:33:45 +00001649 if (!PyArg_UnpackTuple(args, "isinstance", 2, 2, &inst, &cls))
Barry Warsawcde8b1b1997-08-22 21:14:38 +00001650 return NULL;
Guido van Rossumf5dd9141997-12-02 19:11:45 +00001651
Guido van Rossum823649d2001-03-21 18:40:58 +00001652 retval = PyObject_IsInstance(inst, cls);
1653 if (retval < 0)
Guido van Rossumad991772001-01-12 16:03:05 +00001654 return NULL;
Guido van Rossum77f6a652002-04-03 22:41:51 +00001655 return PyBool_FromLong(retval);
Barry Warsawcde8b1b1997-08-22 21:14:38 +00001656}
1657
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001658PyDoc_STRVAR(isinstance_doc,
Guido van Rossum77f6a652002-04-03 22:41:51 +00001659"isinstance(object, class-or-type-or-tuple) -> bool\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001660\n\
1661Return whether an object is an instance of a class or of a subclass thereof.\n\
Guido van Rossum03290ec2001-10-07 20:54:12 +00001662With a type as second argument, return whether that is the object's type.\n\
1663The form using a tuple, isinstance(x, (A, B, ...)), is a shortcut for\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001664isinstance(x, A) or isinstance(x, B) or ... (etc.).");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001665
Barry Warsawcde8b1b1997-08-22 21:14:38 +00001666
1667static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001668builtin_issubclass(PyObject *self, PyObject *args)
Barry Warsawcde8b1b1997-08-22 21:14:38 +00001669{
1670 PyObject *derived;
1671 PyObject *cls;
1672 int retval;
1673
Raymond Hettingerea3fdf42002-12-29 16:33:45 +00001674 if (!PyArg_UnpackTuple(args, "issubclass", 2, 2, &derived, &cls))
Barry Warsawcde8b1b1997-08-22 21:14:38 +00001675 return NULL;
Guido van Rossum668213d1999-06-16 17:28:37 +00001676
Guido van Rossum823649d2001-03-21 18:40:58 +00001677 retval = PyObject_IsSubclass(derived, cls);
1678 if (retval < 0)
1679 return NULL;
Guido van Rossum77f6a652002-04-03 22:41:51 +00001680 return PyBool_FromLong(retval);
Barry Warsawcde8b1b1997-08-22 21:14:38 +00001681}
1682
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001683PyDoc_STRVAR(issubclass_doc,
Guido van Rossum77f6a652002-04-03 22:41:51 +00001684"issubclass(C, B) -> bool\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001685\n\
Walter Dörwaldd9a6ad32002-12-12 16:41:44 +00001686Return whether class C is a subclass (i.e., a derived class) of class B.\n\
1687When using a tuple as the second argument issubclass(X, (A, B, ...)),\n\
1688is a shortcut for issubclass(X, A) or issubclass(X, B) or ... (etc.).");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001689
Barry Warsawcde8b1b1997-08-22 21:14:38 +00001690
Barry Warsawbd599b52000-08-03 15:45:29 +00001691static PyObject*
1692builtin_zip(PyObject *self, PyObject *args)
1693{
Guido van Rossumb65fb332006-08-25 23:26:40 +00001694 /* args must be a tuple */
1695 assert(PyTuple_Check(args));
Barry Warsawbd599b52000-08-03 15:45:29 +00001696
Guido van Rossumb65fb332006-08-25 23:26:40 +00001697 return _PyZip_CreateIter(args);
Barry Warsawbd599b52000-08-03 15:45:29 +00001698}
1699
1700
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001701PyDoc_STRVAR(zip_doc,
Guido van Rossum801f0d72006-08-24 19:48:10 +00001702"zip(it1 [, it2 [...]]) -> iter([(it1[0], it2[0] ...), ...])\n\
Barry Warsawbd599b52000-08-03 15:45:29 +00001703\n\
Guido van Rossum801f0d72006-08-24 19:48:10 +00001704Return an iterator yielding tuples, where each tuple contains the\n\
1705corresponding element from each of the argument iterables.\n\
1706The returned iterator ends when the shortest argument iterable is exhausted.\n\
Guido van Rossumc1f779c2007-07-03 08:25:58 +00001707(This is identical to itertools.izip().)");
Barry Warsawbd599b52000-08-03 15:45:29 +00001708
1709
Guido van Rossum79f25d91997-04-29 20:08:16 +00001710static PyMethodDef builtin_methods[] = {
Guido van Rossum52cc1d82007-03-18 15:41:51 +00001711 {"__build_class__", (PyCFunction)builtin___build_class__,
1712 METH_VARARGS | METH_KEYWORDS, build_class_doc},
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001713 {"__import__", (PyCFunction)builtin___import__, METH_VARARGS | METH_KEYWORDS, import_doc},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001714 {"abs", builtin_abs, METH_O, abs_doc},
Raymond Hettinger96229b12005-03-11 06:49:40 +00001715 {"all", builtin_all, METH_O, all_doc},
1716 {"any", builtin_any, METH_O, any_doc},
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001717 {"bin", builtin_bin, METH_O, bin_doc},
Walter Dörwalde7efd592007-06-05 20:07:21 +00001718 {"chr", builtin_chr, METH_VARARGS, chr_doc},
1719 {"chr8", builtin_chr8, METH_VARARGS, chr8_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);
Neal Norwitz32a7e7f2002-05-31 19:58:02 +00001798 SETBUILTIN("basestring", &PyBaseString_Type);
Guido van Rossum77f6a652002-04-03 22:41:51 +00001799 SETBUILTIN("bool", &PyBool_Type);
Guido van Rossumbea18cc2002-06-14 20:41:17 +00001800 SETBUILTIN("buffer", &PyBuffer_Type);
Travis E. Oliphantb99f7622007-08-18 11:21:56 +00001801 SETBUILTIN("memoryview", &PyMemoryView_Type);
Guido van Rossum4dfe8a12006-04-22 23:28:04 +00001802 SETBUILTIN("bytes", &PyBytes_Type);
Tim Peters4b7625e2001-09-13 21:37:17 +00001803 SETBUILTIN("classmethod", &PyClassMethod_Type);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001804#ifndef WITHOUT_COMPLEX
Tim Peters4b7625e2001-09-13 21:37:17 +00001805 SETBUILTIN("complex", &PyComplex_Type);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001806#endif
Tim Petersa427a2b2001-10-29 22:25:45 +00001807 SETBUILTIN("dict", &PyDict_Type);
Tim Peters67d687a2002-04-29 21:27:32 +00001808 SETBUILTIN("enumerate", &PyEnum_Type);
Tim Peters4b7625e2001-09-13 21:37:17 +00001809 SETBUILTIN("float", &PyFloat_Type);
Raymond Hettingera690a992003-11-16 16:17:49 +00001810 SETBUILTIN("frozenset", &PyFrozenSet_Type);
Tim Peters4b7625e2001-09-13 21:37:17 +00001811 SETBUILTIN("property", &PyProperty_Type);
Guido van Rossumddefaf32007-01-14 03:31:43 +00001812 SETBUILTIN("int", &PyLong_Type);
Tim Peters4b7625e2001-09-13 21:37:17 +00001813 SETBUILTIN("list", &PyList_Type);
Tim Peters4b7625e2001-09-13 21:37:17 +00001814 SETBUILTIN("object", &PyBaseObject_Type);
Guido van Rossum805365e2007-05-07 22:24:25 +00001815 SETBUILTIN("range", &PyRange_Type);
Raymond Hettinger85c20a42003-11-06 14:06:48 +00001816 SETBUILTIN("reversed", &PyReversed_Type);
Raymond Hettingera690a992003-11-16 16:17:49 +00001817 SETBUILTIN("set", &PySet_Type);
Guido van Rossumbea18cc2002-06-14 20:41:17 +00001818 SETBUILTIN("slice", &PySlice_Type);
Tim Peters4b7625e2001-09-13 21:37:17 +00001819 SETBUILTIN("staticmethod", &PyStaticMethod_Type);
Guido van Rossum572dbf82007-04-27 23:53:51 +00001820 SETBUILTIN("str", &PyUnicode_Type);
Guido van Rossum84fc66d2007-05-03 17:18:26 +00001821 SETBUILTIN("str8", &PyString_Type);
Tim Peters4b7625e2001-09-13 21:37:17 +00001822 SETBUILTIN("super", &PySuper_Type);
1823 SETBUILTIN("tuple", &PyTuple_Type);
1824 SETBUILTIN("type", &PyType_Type);
Guido van Rossum77f6a652002-04-03 22:41:51 +00001825 debug = PyBool_FromLong(Py_OptimizeFlag == 0);
Fred Drake5550de32000-06-20 04:54:19 +00001826 if (PyDict_SetItemString(dict, "__debug__", debug) < 0) {
1827 Py_XDECREF(debug);
Guido van Rossum25ce5661997-08-02 03:10:38 +00001828 return NULL;
Fred Drake5550de32000-06-20 04:54:19 +00001829 }
1830 Py_XDECREF(debug);
Barry Warsaw757af0e1997-08-29 22:13:51 +00001831
Guido van Rossum25ce5661997-08-02 03:10:38 +00001832 return mod;
Tim Peters7571a0f2003-03-23 17:52:28 +00001833#undef ADD_TO_ALL
Tim Peters4b7625e2001-09-13 21:37:17 +00001834#undef SETBUILTIN
Guido van Rossum3f5da241990-12-20 15:06:42 +00001835}