blob: 08c1a0061ab57c0d42ed73e9fda9f17b9ee55586 [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
Guido van Rossume2ae77b2001-10-24 20:42:55 +000011#ifdef RISCOS
12#include "unixstuff.h"
13#endif
14
Mark Hammond26cffde42001-05-14 12:17:34 +000015/* The default encoding used by the platform file system APIs
16 Can remain NULL for all platforms that don't have such a concept
17*/
Martin v. Löwis6238d2b2002-06-30 15:26:10 +000018#if defined(MS_WINDOWS) && defined(HAVE_USABLE_WCHAR_T)
Mark Hammond26cffde42001-05-14 12:17:34 +000019const char *Py_FileSystemDefaultEncoding = "mbcs";
Just van Rossumb9b8e9c2003-02-10 09:22:01 +000020#elif defined(__APPLE__)
21const char *Py_FileSystemDefaultEncoding = "utf-8";
Mark Hammond26cffde42001-05-14 12:17:34 +000022#else
23const char *Py_FileSystemDefaultEncoding = NULL; /* use default */
24#endif
Mark Hammondef8b6542001-05-13 08:04:26 +000025
Guido van Rossum79f25d91997-04-29 20:08:16 +000026static PyObject *
Guido van Rossum52cc1d82007-03-18 15:41:51 +000027builtin___build_class__(PyObject *self, PyObject *args, PyObject *kwds)
28{
Guido van Rossumcd16bf62007-06-13 18:07:49 +000029 PyObject *func, *name, *bases, *mkw, *meta, *prep, *ns, *cell;
30 PyObject *cls = NULL;
Guido van Rossum52cc1d82007-03-18 15:41:51 +000031 Py_ssize_t nargs, nbases;
32
33 assert(args != NULL);
34 if (!PyTuple_Check(args)) {
35 PyErr_SetString(PyExc_TypeError,
36 "__build_class__: args is not a tuple");
37 return NULL;
38 }
39 nargs = PyTuple_GET_SIZE(args);
40 if (nargs < 2) {
41 PyErr_SetString(PyExc_TypeError,
42 "__build_class__: not enough arguments");
43 return NULL;
44 }
45 func = PyTuple_GET_ITEM(args, 0); /* Better be callable */
46 name = PyTuple_GET_ITEM(args, 1);
Martin v. Löwis5b222132007-06-10 09:51:05 +000047 if ((!PyString_Check(name) && !PyUnicode_Check(name))) {
Guido van Rossum52cc1d82007-03-18 15:41:51 +000048 PyErr_SetString(PyExc_TypeError,
49 "__build_class__: name is not a string");
50 return NULL;
51 }
52 bases = PyTuple_GetSlice(args, 2, nargs);
53 if (bases == NULL)
54 return NULL;
55 nbases = nargs - 2;
56
57 if (kwds == NULL) {
58 meta = NULL;
59 mkw = NULL;
60 }
61 else {
62 mkw = PyDict_Copy(kwds); /* Don't modify kwds passed in! */
63 if (mkw == NULL) {
64 Py_DECREF(bases);
65 return NULL;
66 }
67 meta = PyDict_GetItemString(mkw, "metaclass");
68 if (meta != NULL) {
69 Py_INCREF(meta);
70 if (PyDict_DelItemString(mkw, "metaclass") < 0) {
71 Py_DECREF(meta);
72 Py_DECREF(mkw);
73 Py_DECREF(bases);
74 return NULL;
75 }
76 }
77 }
78 if (meta == NULL) {
79 if (PyTuple_GET_SIZE(bases) == 0)
80 meta = (PyObject *) (&PyType_Type);
81 else {
82 PyObject *base0 = PyTuple_GET_ITEM(bases, 0);
83 meta = (PyObject *) (base0->ob_type);
84 }
85 Py_INCREF(meta);
86 }
87 prep = PyObject_GetAttrString(meta, "__prepare__");
88 if (prep == NULL) {
89 PyErr_Clear();
90 ns = PyDict_New();
91 }
92 else {
93 PyObject *pargs = Py_BuildValue("OO", name, bases);
94 if (pargs == NULL) {
95 Py_DECREF(prep);
96 Py_DECREF(meta);
97 Py_XDECREF(mkw);
98 Py_DECREF(bases);
99 return NULL;
100 }
101 ns = PyEval_CallObjectWithKeywords(prep, pargs, mkw);
102 Py_DECREF(pargs);
103 Py_DECREF(prep);
104 if (ns == NULL) {
105 Py_DECREF(meta);
106 Py_XDECREF(mkw);
107 Py_DECREF(bases);
108 return NULL;
109 }
110 }
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000111 cell = PyObject_CallFunctionObjArgs(func, ns, NULL);
112 if (cell != NULL) {
Guido van Rossum52cc1d82007-03-18 15:41:51 +0000113 PyObject *margs;
Guido van Rossum52cc1d82007-03-18 15:41:51 +0000114 margs = Py_BuildValue("OOO", name, bases, ns);
115 if (margs != NULL) {
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000116 cls = PyEval_CallObjectWithKeywords(meta, margs, mkw);
Guido van Rossum52cc1d82007-03-18 15:41:51 +0000117 Py_DECREF(margs);
118 }
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000119 if (cls != NULL && PyCell_Check(cell)) {
120 Py_INCREF(cls);
121 PyCell_SET(cell, cls);
122 }
123 Py_DECREF(cell);
Guido van Rossum52cc1d82007-03-18 15:41:51 +0000124 }
125 Py_DECREF(ns);
126 Py_DECREF(meta);
127 Py_XDECREF(mkw);
128 Py_DECREF(bases);
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000129 return cls;
Guido van Rossum52cc1d82007-03-18 15:41:51 +0000130}
131
132PyDoc_STRVAR(build_class_doc,
133"__build_class__(func, name, *bases, metaclass=None, **kwds) -> class\n\
134\n\
135Internal helper function used by the class statement.");
136
137static PyObject *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000138builtin___import__(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000139{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000140 static char *kwlist[] = {"name", "globals", "locals", "fromlist",
141 "level", 0};
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000142 char *name;
Guido van Rossum79f25d91997-04-29 20:08:16 +0000143 PyObject *globals = NULL;
144 PyObject *locals = NULL;
145 PyObject *fromlist = NULL;
Thomas Woutersf7f438b2006-02-28 16:09:29 +0000146 int level = -1;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000147
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000148 if (!PyArg_ParseTupleAndKeywords(args, kwds, "s|OOOi:__import__",
149 kwlist, &name, &globals, &locals, &fromlist, &level))
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000150 return NULL;
Thomas Woutersf7f438b2006-02-28 16:09:29 +0000151 return PyImport_ImportModuleLevel(name, globals, locals,
152 fromlist, level);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000153}
154
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000155PyDoc_STRVAR(import_doc,
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000156"__import__(name, globals={}, locals={}, fromlist=[], level=-1) -> module\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000157\n\
158Import a module. The globals are only used to determine the context;\n\
159they are not modified. The locals are currently unused. The fromlist\n\
160should be a list of names to emulate ``from name import ...'', or an\n\
161empty list to emulate ``import name''.\n\
162When importing a module from a package, note that __import__('A.B', ...)\n\
163returns package A when fromlist is empty, but its submodule B when\n\
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000164fromlist is not empty. Level is used to determine whether to perform \n\
165absolute or relative imports. -1 is the original strategy of attempting\n\
166both absolute and relative imports, 0 is absolute, a positive number\n\
167is the number of parent directories to search relative to the current module.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000168
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000169
Guido van Rossum79f25d91997-04-29 20:08:16 +0000170static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000171builtin_abs(PyObject *self, PyObject *v)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000172{
Guido van Rossum09df08a1998-05-22 00:51:39 +0000173 return PyNumber_Absolute(v);
Guido van Rossum3f5da241990-12-20 15:06:42 +0000174}
175
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000176PyDoc_STRVAR(abs_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000177"abs(number) -> number\n\
178\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000179Return the absolute value of the argument.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000180
Raymond Hettinger96229b12005-03-11 06:49:40 +0000181static PyObject *
182builtin_all(PyObject *self, PyObject *v)
183{
184 PyObject *it, *item;
185
186 it = PyObject_GetIter(v);
187 if (it == NULL)
188 return NULL;
189
190 while ((item = PyIter_Next(it)) != NULL) {
191 int cmp = PyObject_IsTrue(item);
192 Py_DECREF(item);
193 if (cmp < 0) {
194 Py_DECREF(it);
195 return NULL;
196 }
197 if (cmp == 0) {
198 Py_DECREF(it);
199 Py_RETURN_FALSE;
200 }
201 }
202 Py_DECREF(it);
203 if (PyErr_Occurred())
204 return NULL;
205 Py_RETURN_TRUE;
206}
207
208PyDoc_STRVAR(all_doc,
209"all(iterable) -> bool\n\
210\n\
211Return True if bool(x) is True for all values x in the iterable.");
212
213static PyObject *
214builtin_any(PyObject *self, PyObject *v)
215{
216 PyObject *it, *item;
217
218 it = PyObject_GetIter(v);
219 if (it == NULL)
220 return NULL;
221
222 while ((item = PyIter_Next(it)) != NULL) {
223 int cmp = PyObject_IsTrue(item);
224 Py_DECREF(item);
225 if (cmp < 0) {
226 Py_DECREF(it);
227 return NULL;
228 }
229 if (cmp == 1) {
230 Py_DECREF(it);
231 Py_RETURN_TRUE;
232 }
233 }
234 Py_DECREF(it);
235 if (PyErr_Occurred())
236 return NULL;
237 Py_RETURN_FALSE;
238}
239
240PyDoc_STRVAR(any_doc,
241"any(iterable) -> bool\n\
242\n\
243Return True if bool(x) is True for any x in the iterable.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000244
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000245
Guido van Rossum79f25d91997-04-29 20:08:16 +0000246static PyObject *
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000247builtin_bin(PyObject *self, PyObject *v)
248{
249 return PyNumber_ToBase(v, 2);
250}
251
252PyDoc_STRVAR(bin_doc,
253"bin(number) -> string\n\
254\n\
255Return the binary representation of an integer or long integer.");
256
257
258static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000259builtin_filter(PyObject *self, PyObject *args)
Guido van Rossum12d12c51993-10-26 17:58:25 +0000260{
Guido van Rossumc1f779c2007-07-03 08:25:58 +0000261 PyObject *itertools, *ifilter, *result;
262 itertools = PyImport_ImportModule("itertools");
263 if (itertools == NULL)
Guido van Rossum12d12c51993-10-26 17:58:25 +0000264 return NULL;
Guido van Rossumc1f779c2007-07-03 08:25:58 +0000265 ifilter = PyObject_GetAttrString(itertools, "ifilter");
266 Py_DECREF(itertools);
267 if (ifilter == NULL)
Georg Brandle35b6572005-07-19 22:20:20 +0000268 return NULL;
Guido van Rossumc1f779c2007-07-03 08:25:58 +0000269 result = PyObject_Call(ifilter, args, NULL);
270 Py_DECREF(ifilter);
Guido van Rossum12d12c51993-10-26 17:58:25 +0000271 return result;
Guido van Rossum12d12c51993-10-26 17:58:25 +0000272}
273
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000274PyDoc_STRVAR(filter_doc,
Guido van Rossumc1f779c2007-07-03 08:25:58 +0000275"filter(predicate, iterable) -> iterator\n\
276\n\
277Return an iterator yielding only those elements of the input iterable\n\
278for which the predicate (a Boolean function) returns true.\n\
279If the predicate is None, 'lambda x: bool(x)' is assumed.\n\
280(This is identical to itertools.ifilter().)");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000281
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000282
Guido van Rossum79f25d91997-04-29 20:08:16 +0000283static PyObject *
Walter Dörwalde7efd592007-06-05 20:07:21 +0000284builtin_chr8(PyObject *self, PyObject *args)
Guido van Rossum7fcf2242007-05-04 17:43:11 +0000285{
286 long x;
287 char s[1];
288
289 if (!PyArg_ParseTuple(args, "l:chr8", &x))
290 return NULL;
291 if (x < 0 || x >= 256) {
292 PyErr_SetString(PyExc_ValueError,
293 "chr8() arg not in range(256)");
294 return NULL;
295 }
296 s[0] = (char)x;
297 return PyString_FromStringAndSize(s, 1);
298}
299
Walter Dörwalde7efd592007-06-05 20:07:21 +0000300PyDoc_STRVAR(chr8_doc,
Guido van Rossum7fcf2242007-05-04 17:43:11 +0000301"chr8(i) -> 8-bit character\n\
302\n\
303Return a string of one character with ordinal i; 0 <= i < 256.");
304
305
306static PyObject *
Walter Dörwalde7efd592007-06-05 20:07:21 +0000307builtin_chr(PyObject *self, PyObject *args)
Guido van Rossum09095f32000-03-10 23:00:52 +0000308{
309 long x;
Guido van Rossum09095f32000-03-10 23:00:52 +0000310
Walter Dörwalde7efd592007-06-05 20:07:21 +0000311 if (!PyArg_ParseTuple(args, "l:chr", &x))
Guido van Rossum09095f32000-03-10 23:00:52 +0000312 return NULL;
Fredrik Lundh0dcf67e2001-06-26 20:01:56 +0000313
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +0000314 return PyUnicode_FromOrdinal(x);
Guido van Rossum09095f32000-03-10 23:00:52 +0000315}
316
Walter Dörwalde7efd592007-06-05 20:07:21 +0000317PyDoc_STRVAR(chr_doc,
Guido van Rossum84fc66d2007-05-03 17:18:26 +0000318"chr(i) -> Unicode character\n\
Guido van Rossum09095f32000-03-10 23:00:52 +0000319\n\
Guido van Rossum8ac004e2007-07-15 13:00:05 +0000320Return a Unicode string of one character with ordinal i; 0 <= i <= 0x10ffff."
321#ifndef Py_UNICODE_WIDE
322"\nIf 0x10000 <= i, a surrogate pair is returned."
323#endif
324);
Guido van Rossum09095f32000-03-10 23:00:52 +0000325
326
327static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000328builtin_cmp(PyObject *self, PyObject *args)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +0000329{
Guido van Rossum79f25d91997-04-29 20:08:16 +0000330 PyObject *a, *b;
Guido van Rossum09df08a1998-05-22 00:51:39 +0000331 int c;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000332
Raymond Hettingerea3fdf42002-12-29 16:33:45 +0000333 if (!PyArg_UnpackTuple(args, "cmp", 2, 2, &a, &b))
Guido van Rossuma9e7dc11992-10-18 18:53:57 +0000334 return NULL;
Guido van Rossum09df08a1998-05-22 00:51:39 +0000335 if (PyObject_Cmp(a, b, &c) < 0)
Guido van Rossumc8b6df91997-05-23 00:06:51 +0000336 return NULL;
Guido van Rossum09df08a1998-05-22 00:51:39 +0000337 return PyInt_FromLong((long)c);
Guido van Rossuma9e7dc11992-10-18 18:53:57 +0000338}
339
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000340PyDoc_STRVAR(cmp_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000341"cmp(x, y) -> integer\n\
342\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000343Return negative if x<y, zero if x==y, positive if x>y.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000344
Guido van Rossumf15a29f2007-05-04 00:41:39 +0000345
346static char *
347source_as_string(PyObject *cmd)
348{
349 char *str;
350 Py_ssize_t size;
351
352 if (!PyObject_CheckReadBuffer(cmd) &&
353 !PyUnicode_Check(cmd)) {
354 PyErr_SetString(PyExc_TypeError,
355 "eval()/exec() arg 1 must be a string, bytes or code object");
356 return NULL;
357 }
358
359 if (PyUnicode_Check(cmd)) {
360 cmd = _PyUnicode_AsDefaultEncodedString(cmd, NULL);
361 if (cmd == NULL)
362 return NULL;
363 }
364 if (PyObject_AsReadBuffer(cmd, (const void **)&str, &size) < 0) {
365 return NULL;
366 }
367 if (strlen(str) != size) {
368 PyErr_SetString(PyExc_TypeError,
369 "source code string cannot contain null bytes");
370 return NULL;
371 }
372 return str;
373}
374
Guido van Rossum79f25d91997-04-29 20:08:16 +0000375static PyObject *
Guido van Rossumd8faa362007-04-27 19:54:29 +0000376builtin_compile(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum5b722181993-03-30 17:46:03 +0000377{
378 char *str;
379 char *filename;
380 char *startstr;
381 int start;
Tim Peters6cd6a822001-08-17 22:11:27 +0000382 int dont_inherit = 0;
383 int supplied_flags = 0;
Tim Peters5ba58662001-07-16 02:29:45 +0000384 PyCompilerFlags cf;
Guido van Rossumf15a29f2007-05-04 00:41:39 +0000385 PyObject *cmd;
Guido van Rossumd8faa362007-04-27 19:54:29 +0000386 static char *kwlist[] = {"source", "filename", "mode", "flags",
387 "dont_inherit", NULL};
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000388
Guido van Rossumd8faa362007-04-27 19:54:29 +0000389 if (!PyArg_ParseTupleAndKeywords(args, kwds, "Oss|ii:compile",
390 kwlist, &cmd, &filename, &startstr,
391 &supplied_flags, &dont_inherit))
Guido van Rossum5b722181993-03-30 17:46:03 +0000392 return NULL;
Tim Peters6cd6a822001-08-17 22:11:27 +0000393
Guido van Rossumf15a29f2007-05-04 00:41:39 +0000394 cf.cf_flags = supplied_flags | PyCF_SOURCE_IS_UTF8;
Just van Rossum3aaf42c2003-02-10 08:21:10 +0000395
Guido van Rossumf15a29f2007-05-04 00:41:39 +0000396 str = source_as_string(cmd);
397 if (str == NULL)
Just van Rossumb9b8e9c2003-02-10 09:22:01 +0000398 return NULL;
Just van Rossum3aaf42c2003-02-10 08:21:10 +0000399
Guido van Rossum5b722181993-03-30 17:46:03 +0000400 if (strcmp(startstr, "exec") == 0)
Guido van Rossumb05a5c71997-05-07 17:46:13 +0000401 start = Py_file_input;
Guido van Rossum5b722181993-03-30 17:46:03 +0000402 else if (strcmp(startstr, "eval") == 0)
Guido van Rossumb05a5c71997-05-07 17:46:13 +0000403 start = Py_eval_input;
Guido van Rossum872537c1995-07-07 22:43:42 +0000404 else if (strcmp(startstr, "single") == 0)
Guido van Rossumb05a5c71997-05-07 17:46:13 +0000405 start = Py_single_input;
Guido van Rossum5b722181993-03-30 17:46:03 +0000406 else {
Guido van Rossum79f25d91997-04-29 20:08:16 +0000407 PyErr_SetString(PyExc_ValueError,
Fred Drake661ea262000-10-24 19:57:45 +0000408 "compile() arg 3 must be 'exec' or 'eval' or 'single'");
Guido van Rossumf15a29f2007-05-04 00:41:39 +0000409 return NULL;
Guido van Rossum5b722181993-03-30 17:46:03 +0000410 }
Tim Peters6cd6a822001-08-17 22:11:27 +0000411
Guido van Rossum4b499dd32003-02-13 22:07:59 +0000412 if (supplied_flags &
Martin v. Löwisbd260da2006-02-26 19:42:26 +0000413 ~(PyCF_MASK | PyCF_MASK_OBSOLETE | PyCF_DONT_IMPLY_DEDENT | PyCF_ONLY_AST))
Guido van Rossum4b499dd32003-02-13 22:07:59 +0000414 {
Tim Peters6cd6a822001-08-17 22:11:27 +0000415 PyErr_SetString(PyExc_ValueError,
416 "compile(): unrecognised flags");
Guido van Rossumf15a29f2007-05-04 00:41:39 +0000417 return NULL;
Tim Peters6cd6a822001-08-17 22:11:27 +0000418 }
419 /* XXX Warn if (supplied_flags & PyCF_MASK_OBSOLETE) != 0? */
420
Tim Peters6cd6a822001-08-17 22:11:27 +0000421 if (!dont_inherit) {
422 PyEval_MergeCompilerFlags(&cf);
423 }
Guido van Rossumf15a29f2007-05-04 00:41:39 +0000424 return Py_CompileStringFlags(str, filename, start, &cf);
Guido van Rossum5b722181993-03-30 17:46:03 +0000425}
426
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000427PyDoc_STRVAR(compile_doc,
Tim Peters6cd6a822001-08-17 22:11:27 +0000428"compile(source, filename, mode[, flags[, dont_inherit]]) -> code object\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000429\n\
430Compile the source string (a Python module, statement or expression)\n\
Georg Brandl7cae87c2006-09-06 06:51:57 +0000431into a code object that can be executed by exec() or eval().\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000432The filename will be used for run-time error messages.\n\
433The mode must be 'exec' to compile a module, 'single' to compile a\n\
Tim Peters6cd6a822001-08-17 22:11:27 +0000434single (interactive) statement, or 'eval' to compile an expression.\n\
435The flags argument, if present, controls which future statements influence\n\
436the compilation of the code.\n\
437The dont_inherit argument, if non-zero, stops the compilation inheriting\n\
438the effects of any future statements in effect in the code calling\n\
439compile; if absent or zero these statements do influence the compilation,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000440in addition to any features explicitly specified.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000441
Guido van Rossum79f25d91997-04-29 20:08:16 +0000442static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000443builtin_dir(PyObject *self, PyObject *args)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000444{
Tim Peters5d2b77c2001-09-03 05:47:38 +0000445 PyObject *arg = NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000446
Raymond Hettingerea3fdf42002-12-29 16:33:45 +0000447 if (!PyArg_UnpackTuple(args, "dir", 0, 1, &arg))
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000448 return NULL;
Tim Peters7eea37e2001-09-04 22:08:56 +0000449 return PyObject_Dir(arg);
Guido van Rossum3f5da241990-12-20 15:06:42 +0000450}
451
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000452PyDoc_STRVAR(dir_doc,
Tim Peters5d2b77c2001-09-03 05:47:38 +0000453"dir([object]) -> list of strings\n"
454"\n"
Georg Brandle32b4222007-03-10 22:13:27 +0000455"If called without an argument, return the names in the current scope.\n"
456"Else, return an alphabetized list of names comprising (some of) the attributes\n"
457"of the given object, and of attributes reachable from it.\n"
458"If the object supplies a method named __dir__, it will be used; otherwise\n"
459"the default dir() logic is used and returns:\n"
460" for a module object: the module's attributes.\n"
461" for a class object: its attributes, and recursively the attributes\n"
462" of its bases.\n"
Guido van Rossumd8faa362007-04-27 19:54:29 +0000463" for any other object: its attributes, its class's attributes, and\n"
Georg Brandle32b4222007-03-10 22:13:27 +0000464" recursively the attributes of its class's base classes.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000465
Guido van Rossum79f25d91997-04-29 20:08:16 +0000466static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000467builtin_divmod(PyObject *self, PyObject *args)
Guido van Rossum6a00cd81995-01-07 12:39:01 +0000468{
Guido van Rossum79f25d91997-04-29 20:08:16 +0000469 PyObject *v, *w;
Guido van Rossum6a00cd81995-01-07 12:39:01 +0000470
Raymond Hettingerea3fdf42002-12-29 16:33:45 +0000471 if (!PyArg_UnpackTuple(args, "divmod", 2, 2, &v, &w))
Guido van Rossum6a00cd81995-01-07 12:39:01 +0000472 return NULL;
Guido van Rossum09df08a1998-05-22 00:51:39 +0000473 return PyNumber_Divmod(v, w);
Guido van Rossum3f5da241990-12-20 15:06:42 +0000474}
475
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000476PyDoc_STRVAR(divmod_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000477"divmod(x, y) -> (div, mod)\n\
478\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000479Return the tuple ((x-x%y)/y, x%y). Invariant: div*y + mod == x.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000480
481
Guido van Rossum79f25d91997-04-29 20:08:16 +0000482static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000483builtin_eval(PyObject *self, PyObject *args)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000484{
Just van Rossum3aaf42c2003-02-10 08:21:10 +0000485 PyObject *cmd, *result, *tmp = NULL;
Guido van Rossum79f25d91997-04-29 20:08:16 +0000486 PyObject *globals = Py_None, *locals = Py_None;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000487 char *str;
Tim Peters9fa96be2001-08-17 23:04:59 +0000488 PyCompilerFlags cf;
Guido van Rossum590baa41993-11-30 13:40:46 +0000489
Raymond Hettinger214b1c32004-07-02 06:41:07 +0000490 if (!PyArg_UnpackTuple(args, "eval", 1, 3, &cmd, &globals, &locals))
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000491 return NULL;
Raymond Hettinger214b1c32004-07-02 06:41:07 +0000492 if (locals != Py_None && !PyMapping_Check(locals)) {
493 PyErr_SetString(PyExc_TypeError, "locals must be a mapping");
Raymond Hettinger513ffe82004-07-06 13:44:41 +0000494 return NULL;
Raymond Hettinger214b1c32004-07-02 06:41:07 +0000495 }
496 if (globals != Py_None && !PyDict_Check(globals)) {
Georg Brandl99d7e4e2005-08-31 22:21:15 +0000497 PyErr_SetString(PyExc_TypeError, PyMapping_Check(globals) ?
Raymond Hettinger214b1c32004-07-02 06:41:07 +0000498 "globals must be a real dict; try eval(expr, {}, mapping)"
499 : "globals must be a dict");
Raymond Hettinger513ffe82004-07-06 13:44:41 +0000500 return NULL;
Raymond Hettinger214b1c32004-07-02 06:41:07 +0000501 }
Guido van Rossum79f25d91997-04-29 20:08:16 +0000502 if (globals == Py_None) {
503 globals = PyEval_GetGlobals();
504 if (locals == Py_None)
505 locals = PyEval_GetLocals();
Guido van Rossum6135a871995-01-09 17:53:26 +0000506 }
Guido van Rossum79f25d91997-04-29 20:08:16 +0000507 else if (locals == Py_None)
Guido van Rossum6135a871995-01-09 17:53:26 +0000508 locals = globals;
Tim Peters9fa96be2001-08-17 23:04:59 +0000509
Georg Brandl77c85e62005-09-15 10:46:13 +0000510 if (globals == NULL || locals == NULL) {
511 PyErr_SetString(PyExc_TypeError,
512 "eval must be given globals and locals "
513 "when called without a frame");
514 return NULL;
515 }
516
Guido van Rossum79f25d91997-04-29 20:08:16 +0000517 if (PyDict_GetItemString(globals, "__builtins__") == NULL) {
518 if (PyDict_SetItemString(globals, "__builtins__",
519 PyEval_GetBuiltins()) != 0)
Guido van Rossum6135a871995-01-09 17:53:26 +0000520 return NULL;
521 }
Tim Peters9fa96be2001-08-17 23:04:59 +0000522
Jeremy Hylton15c1c4f2001-07-30 21:50:55 +0000523 if (PyCode_Check(cmd)) {
Jeremy Hylton733c8932001-12-13 19:51:56 +0000524 if (PyCode_GetNumFree((PyCodeObject *)cmd) > 0) {
Jeremy Hylton15c1c4f2001-07-30 21:50:55 +0000525 PyErr_SetString(PyExc_TypeError,
526 "code object passed to eval() may not contain free variables");
527 return NULL;
528 }
Guido van Rossum79f25d91997-04-29 20:08:16 +0000529 return PyEval_EvalCode((PyCodeObject *) cmd, globals, locals);
Jeremy Hylton15c1c4f2001-07-30 21:50:55 +0000530 }
Tim Peters9fa96be2001-08-17 23:04:59 +0000531
Guido van Rossumf15a29f2007-05-04 00:41:39 +0000532 str = source_as_string(cmd);
533 if (str == NULL)
Guido van Rossum94390a41992-08-14 15:14:30 +0000534 return NULL;
Just van Rossum3aaf42c2003-02-10 08:21:10 +0000535
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000536 while (*str == ' ' || *str == '\t')
537 str++;
Tim Peters9fa96be2001-08-17 23:04:59 +0000538
Guido van Rossumf15a29f2007-05-04 00:41:39 +0000539 cf.cf_flags = PyCF_SOURCE_IS_UTF8;
Tim Peters9fa96be2001-08-17 23:04:59 +0000540 (void)PyEval_MergeCompilerFlags(&cf);
Just van Rossum3aaf42c2003-02-10 08:21:10 +0000541 result = PyRun_StringFlags(str, Py_eval_input, globals, locals, &cf);
542 Py_XDECREF(tmp);
543 return result;
Guido van Rossum3f5da241990-12-20 15:06:42 +0000544}
545
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000546PyDoc_STRVAR(eval_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000547"eval(source[, globals[, locals]]) -> value\n\
548\n\
549Evaluate the source in the context of globals and locals.\n\
550The source may be a string representing a Python expression\n\
551or a code object as returned by compile().\n\
Thomas Wouters89f507f2006-12-13 04:49:30 +0000552The globals must be a dictionary and locals can be any mapping,\n\
Raymond Hettinger214b1c32004-07-02 06:41:07 +0000553defaulting to the current globals and locals.\n\
554If only globals is given, locals defaults to it.\n");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000555
Georg Brandl7cae87c2006-09-06 06:51:57 +0000556static PyObject *
557builtin_exec(PyObject *self, PyObject *args)
558{
559 PyObject *v;
560 PyObject *prog, *globals = Py_None, *locals = Py_None;
561 int plain = 0;
562
563 if (!PyArg_ParseTuple(args, "O|OO:exec", &prog, &globals, &locals))
564 return NULL;
565
566 if (globals == Py_None) {
567 globals = PyEval_GetGlobals();
568 if (locals == Py_None) {
569 locals = PyEval_GetLocals();
570 plain = 1;
571 }
572 if (!globals || !locals) {
573 PyErr_SetString(PyExc_SystemError,
574 "globals and locals cannot be NULL");
575 return NULL;
576 }
577 }
578 else if (locals == Py_None)
579 locals = globals;
580 if (!PyString_Check(prog) &&
581 !PyUnicode_Check(prog) &&
Guido van Rossumda5b8f22007-06-12 23:30:11 +0000582 !PyCode_Check(prog)) {
Georg Brandl7cae87c2006-09-06 06:51:57 +0000583 PyErr_Format(PyExc_TypeError,
584 "exec() arg 1 must be a string, file, or code "
585 "object, not %.100s", prog->ob_type->tp_name);
586 return NULL;
587 }
588 if (!PyDict_Check(globals)) {
589 PyErr_Format(PyExc_TypeError, "exec() arg 2 must be a dict, not %.100s",
590 globals->ob_type->tp_name);
591 return NULL;
592 }
593 if (!PyMapping_Check(locals)) {
594 PyErr_Format(PyExc_TypeError,
595 "arg 3 must be a mapping or None, not %.100s",
596 locals->ob_type->tp_name);
597 return NULL;
598 }
599 if (PyDict_GetItemString(globals, "__builtins__") == NULL) {
600 if (PyDict_SetItemString(globals, "__builtins__",
601 PyEval_GetBuiltins()) != 0)
602 return NULL;
603 }
604
605 if (PyCode_Check(prog)) {
606 if (PyCode_GetNumFree((PyCodeObject *)prog) > 0) {
607 PyErr_SetString(PyExc_TypeError,
608 "code object passed to exec() may not "
609 "contain free variables");
610 return NULL;
611 }
612 v = PyEval_EvalCode((PyCodeObject *) prog, globals, locals);
613 }
Georg Brandl7cae87c2006-09-06 06:51:57 +0000614 else {
Guido van Rossumf15a29f2007-05-04 00:41:39 +0000615 char *str = source_as_string(prog);
Georg Brandl7cae87c2006-09-06 06:51:57 +0000616 PyCompilerFlags cf;
Guido van Rossumf15a29f2007-05-04 00:41:39 +0000617 if (str == NULL)
Georg Brandl7cae87c2006-09-06 06:51:57 +0000618 return NULL;
Guido van Rossumf15a29f2007-05-04 00:41:39 +0000619 cf.cf_flags = PyCF_SOURCE_IS_UTF8;
Georg Brandl7cae87c2006-09-06 06:51:57 +0000620 if (PyEval_MergeCompilerFlags(&cf))
621 v = PyRun_StringFlags(str, Py_file_input, globals,
622 locals, &cf);
623 else
624 v = PyRun_String(str, Py_file_input, globals, locals);
Georg Brandl7cae87c2006-09-06 06:51:57 +0000625 }
626 if (v == NULL)
627 return NULL;
628 Py_DECREF(v);
629 Py_RETURN_NONE;
630}
631
632PyDoc_STRVAR(exec_doc,
633"exec(object[, globals[, locals]])\n\
634\n\
635Read and execute code from a object, which can be a string, a code\n\
636object or a file object.\n\
637The globals and locals are dictionaries, defaulting to the current\n\
638globals and locals. If only globals is given, locals defaults to it.");
639
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000640
Guido van Rossum79f25d91997-04-29 20:08:16 +0000641static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000642builtin_execfile(PyObject *self, PyObject *args)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000643{
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000644 char *filename;
Guido van Rossum79f25d91997-04-29 20:08:16 +0000645 PyObject *globals = Py_None, *locals = Py_None;
646 PyObject *res;
Guido van Rossumb3a639e2001-09-05 13:37:47 +0000647 FILE* fp = NULL;
Tim Peters5ba58662001-07-16 02:29:45 +0000648 PyCompilerFlags cf;
Martin v. Löwis6b3a2c42001-08-08 05:30:36 +0000649 int exists;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000650
Raymond Hettinger66bd2332004-08-02 08:30:07 +0000651 if (!PyArg_ParseTuple(args, "s|O!O:execfile",
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000652 &filename,
Guido van Rossum79f25d91997-04-29 20:08:16 +0000653 &PyDict_Type, &globals,
Raymond Hettinger66bd2332004-08-02 08:30:07 +0000654 &locals))
Guido van Rossum0f61f8a1992-02-25 18:55:05 +0000655 return NULL;
Raymond Hettinger66bd2332004-08-02 08:30:07 +0000656 if (locals != Py_None && !PyMapping_Check(locals)) {
657 PyErr_SetString(PyExc_TypeError, "locals must be a mapping");
658 return NULL;
659 }
Guido van Rossum79f25d91997-04-29 20:08:16 +0000660 if (globals == Py_None) {
661 globals = PyEval_GetGlobals();
662 if (locals == Py_None)
663 locals = PyEval_GetLocals();
Guido van Rossum6135a871995-01-09 17:53:26 +0000664 }
Guido van Rossum79f25d91997-04-29 20:08:16 +0000665 else if (locals == Py_None)
Guido van Rossum6135a871995-01-09 17:53:26 +0000666 locals = globals;
Guido van Rossum79f25d91997-04-29 20:08:16 +0000667 if (PyDict_GetItemString(globals, "__builtins__") == NULL) {
668 if (PyDict_SetItemString(globals, "__builtins__",
669 PyEval_GetBuiltins()) != 0)
Guido van Rossum6135a871995-01-09 17:53:26 +0000670 return NULL;
671 }
Martin v. Löwis6b3a2c42001-08-08 05:30:36 +0000672
673 exists = 0;
674 /* Test for existence or directory. */
Martin v. Löwis3484a182002-03-09 12:07:51 +0000675#if defined(PLAN9)
676 {
677 Dir *d;
678
679 if ((d = dirstat(filename))!=nil) {
680 if(d->mode & DMDIR)
681 werrstr("is a directory");
682 else
683 exists = 1;
684 free(d);
685 }
Martin v. Löwis6b3a2c42001-08-08 05:30:36 +0000686 }
Martin v. Löwis3484a182002-03-09 12:07:51 +0000687#elif defined(RISCOS)
Guido van Rossume2ae77b2001-10-24 20:42:55 +0000688 if (object_exists(filename)) {
689 if (isdir(filename))
690 errno = EISDIR;
691 else
692 exists = 1;
693 }
Martin v. Löwis3484a182002-03-09 12:07:51 +0000694#else /* standard Posix */
695 {
696 struct stat s;
697 if (stat(filename, &s) == 0) {
698 if (S_ISDIR(s.st_mode))
Andrew MacIntyreda4d6cb2004-03-29 11:53:38 +0000699# if defined(PYOS_OS2) && defined(PYCC_VACPP)
Martin v. Löwis3484a182002-03-09 12:07:51 +0000700 errno = EOS2ERR;
701# else
702 errno = EISDIR;
703# endif
704 else
705 exists = 1;
706 }
707 }
708#endif
Martin v. Löwis6b3a2c42001-08-08 05:30:36 +0000709
710 if (exists) {
711 Py_BEGIN_ALLOW_THREADS
Jack Jansen7b8c7542002-04-14 20:12:41 +0000712 fp = fopen(filename, "r" PY_STDIOTEXTMODE);
Martin v. Löwis6b3a2c42001-08-08 05:30:36 +0000713 Py_END_ALLOW_THREADS
714
715 if (fp == NULL) {
716 exists = 0;
717 }
718 }
719
720 if (!exists) {
Peter Schneider-Kamp4c013422002-08-27 16:58:00 +0000721 PyErr_SetFromErrnoWithFilename(PyExc_IOError, filename);
Guido van Rossum0f61f8a1992-02-25 18:55:05 +0000722 return NULL;
723 }
Tim Peters5ba58662001-07-16 02:29:45 +0000724 cf.cf_flags = 0;
725 if (PyEval_MergeCompilerFlags(&cf))
Tim Peters748b8bb2001-04-28 08:20:22 +0000726 res = PyRun_FileExFlags(fp, filename, Py_file_input, globals,
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000727 locals, 1, &cf);
Tim Peters5ba58662001-07-16 02:29:45 +0000728 else
Tim Peters748b8bb2001-04-28 08:20:22 +0000729 res = PyRun_FileEx(fp, filename, Py_file_input, globals,
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000730 locals, 1);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000731 return res;
Guido van Rossum0f61f8a1992-02-25 18:55:05 +0000732}
733
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000734PyDoc_STRVAR(execfile_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000735"execfile(filename[, globals[, locals]])\n\
736\n\
737Read and execute a Python script from a file.\n\
738The globals and locals are dictionaries, defaulting to the current\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000739globals and locals. If only globals is given, locals defaults to it.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000740
741
Guido van Rossum79f25d91997-04-29 20:08:16 +0000742static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000743builtin_getattr(PyObject *self, PyObject *args)
Guido van Rossum33894be1992-01-27 16:53:09 +0000744{
Martin v. Löwis5b222132007-06-10 09:51:05 +0000745 PyObject *v, *result, *dflt = NULL, *release = NULL;
Guido van Rossum79f25d91997-04-29 20:08:16 +0000746 PyObject *name;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000747
Raymond Hettingerea3fdf42002-12-29 16:33:45 +0000748 if (!PyArg_UnpackTuple(args, "getattr", 2, 3, &v, &name, &dflt))
Guido van Rossum33894be1992-01-27 16:53:09 +0000749 return NULL;
Martin v. Löwis5b222132007-06-10 09:51:05 +0000750
751 if (PyString_Check(name)) {
752 release = PyString_AsDecodedObject(name, NULL, NULL);
753 if (!release)
Jeremy Hylton0eb11152001-07-30 22:39:31 +0000754 return NULL;
Martin v. Löwis5b222132007-06-10 09:51:05 +0000755 name = release;
Jeremy Hylton0eb11152001-07-30 22:39:31 +0000756 }
757
Martin v. Löwis5b222132007-06-10 09:51:05 +0000758 if (!PyUnicode_Check(name)) {
Jeremy Hylton0eb11152001-07-30 22:39:31 +0000759 PyErr_SetString(PyExc_TypeError,
Alex Martellia9b9c9f2003-04-23 13:34:35 +0000760 "getattr(): attribute name must be string");
Martin v. Löwis5b222132007-06-10 09:51:05 +0000761 Py_XDECREF(release);
Jeremy Hylton0eb11152001-07-30 22:39:31 +0000762 return NULL;
763 }
Guido van Rossum950ff291998-06-29 13:38:57 +0000764 result = PyObject_GetAttr(v, name);
Guido van Rossumd8923572001-10-16 21:31:32 +0000765 if (result == NULL && dflt != NULL &&
766 PyErr_ExceptionMatches(PyExc_AttributeError))
767 {
Guido van Rossum950ff291998-06-29 13:38:57 +0000768 PyErr_Clear();
769 Py_INCREF(dflt);
770 result = dflt;
771 }
Martin v. Löwis5b222132007-06-10 09:51:05 +0000772 Py_XDECREF(release);
Guido van Rossum950ff291998-06-29 13:38:57 +0000773 return result;
Guido van Rossum9bfef441993-03-29 10:43:31 +0000774}
775
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000776PyDoc_STRVAR(getattr_doc,
Guido van Rossum950ff291998-06-29 13:38:57 +0000777"getattr(object, name[, default]) -> value\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000778\n\
Guido van Rossum950ff291998-06-29 13:38:57 +0000779Get a named attribute from an object; getattr(x, 'y') is equivalent to x.y.\n\
780When a default argument is given, it is returned when the attribute doesn't\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000781exist; without it, an exception is raised in that case.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000782
783
Guido van Rossum79f25d91997-04-29 20:08:16 +0000784static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000785builtin_globals(PyObject *self)
Guido van Rossum872537c1995-07-07 22:43:42 +0000786{
Guido van Rossum79f25d91997-04-29 20:08:16 +0000787 PyObject *d;
Guido van Rossum872537c1995-07-07 22:43:42 +0000788
Guido van Rossum79f25d91997-04-29 20:08:16 +0000789 d = PyEval_GetGlobals();
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000790 Py_XINCREF(d);
Guido van Rossum872537c1995-07-07 22:43:42 +0000791 return d;
792}
793
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000794PyDoc_STRVAR(globals_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000795"globals() -> dictionary\n\
796\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000797Return the dictionary containing the current scope's global variables.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000798
799
Guido van Rossum79f25d91997-04-29 20:08:16 +0000800static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000801builtin_hasattr(PyObject *self, PyObject *args)
Guido van Rossum9bfef441993-03-29 10:43:31 +0000802{
Guido van Rossum79f25d91997-04-29 20:08:16 +0000803 PyObject *v;
804 PyObject *name;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000805
Raymond Hettingerea3fdf42002-12-29 16:33:45 +0000806 if (!PyArg_UnpackTuple(args, "hasattr", 2, 2, &v, &name))
Guido van Rossum9bfef441993-03-29 10:43:31 +0000807 return NULL;
Martin v. Löwis5b222132007-06-10 09:51:05 +0000808 if (!PyUnicode_Check(name)) {
Jeremy Hylton302b54a2001-07-30 22:45:19 +0000809 PyErr_SetString(PyExc_TypeError,
Alex Martellia9b9c9f2003-04-23 13:34:35 +0000810 "hasattr(): attribute name must be string");
Jeremy Hylton302b54a2001-07-30 22:45:19 +0000811 return NULL;
812 }
Guido van Rossum79f25d91997-04-29 20:08:16 +0000813 v = PyObject_GetAttr(v, name);
Guido van Rossum9bfef441993-03-29 10:43:31 +0000814 if (v == NULL) {
Guido van Rossum79f25d91997-04-29 20:08:16 +0000815 PyErr_Clear();
Guido van Rossum09df08a1998-05-22 00:51:39 +0000816 Py_INCREF(Py_False);
817 return Py_False;
Guido van Rossum9bfef441993-03-29 10:43:31 +0000818 }
Guido van Rossum79f25d91997-04-29 20:08:16 +0000819 Py_DECREF(v);
Guido van Rossum09df08a1998-05-22 00:51:39 +0000820 Py_INCREF(Py_True);
821 return Py_True;
Guido van Rossum33894be1992-01-27 16:53:09 +0000822}
823
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000824PyDoc_STRVAR(hasattr_doc,
Guido van Rossum77f6a652002-04-03 22:41:51 +0000825"hasattr(object, name) -> bool\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000826\n\
827Return whether the object has an attribute with the given name.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000828(This is done by calling getattr(object, name) and catching exceptions.)");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000829
830
Guido van Rossum79f25d91997-04-29 20:08:16 +0000831static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000832builtin_id(PyObject *self, PyObject *v)
Guido van Rossum5b722181993-03-30 17:46:03 +0000833{
Guido van Rossum106f2da2000-06-28 21:12:25 +0000834 return PyLong_FromVoidPtr(v);
Guido van Rossum5b722181993-03-30 17:46:03 +0000835}
836
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000837PyDoc_STRVAR(id_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000838"id(object) -> integer\n\
839\n\
840Return the identity of an object. This is guaranteed to be unique among\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000841simultaneously existing objects. (Hint: it's the object's memory address.)");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000842
843
Guido van Rossum79f25d91997-04-29 20:08:16 +0000844static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000845builtin_map(PyObject *self, PyObject *args)
Guido van Rossum12d12c51993-10-26 17:58:25 +0000846{
Guido van Rossumc1f779c2007-07-03 08:25:58 +0000847 PyObject *itertools, *imap, *result;
848 itertools = PyImport_ImportModule("itertools");
849 if (itertools == NULL)
Guido van Rossum12d12c51993-10-26 17:58:25 +0000850 return NULL;
Guido van Rossumc1f779c2007-07-03 08:25:58 +0000851 imap = PyObject_GetAttrString(itertools, "imap");
852 Py_DECREF(itertools);
853 if (imap == NULL)
Tim Peters4e9afdc2001-05-03 23:54:49 +0000854 return NULL;
Guido van Rossumc1f779c2007-07-03 08:25:58 +0000855 result = PyObject_Call(imap, args, NULL);
856 Py_DECREF(imap);
Tim Peters4e9afdc2001-05-03 23:54:49 +0000857 return result;
Guido van Rossum12d12c51993-10-26 17:58:25 +0000858}
859
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000860PyDoc_STRVAR(map_doc,
Guido van Rossumc1f779c2007-07-03 08:25:58 +0000861"map(function, iterable[, iterable, ...]) -> iterator\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000862\n\
Guido van Rossumc1f779c2007-07-03 08:25:58 +0000863Return an iterator yielding the results of applying the function to the\n\
864items of the argument iterables(s). If more than one iterable is given,\n\
865the function is called with an argument list consisting of the\n\
866corresponding item of each iterable, until an iterable is exhausted.\n\
867If the function is None, 'lambda *a: a' is assumed.\n\
868(This is identical to itertools.imap().)");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000869
870
Guido van Rossum79f25d91997-04-29 20:08:16 +0000871static PyObject *
Georg Brandla18af4e2007-04-21 15:47:16 +0000872builtin_next(PyObject *self, PyObject *args)
873{
874 PyObject *it, *res;
875 PyObject *def = NULL;
876
877 if (!PyArg_UnpackTuple(args, "next", 1, 2, &it, &def))
878 return NULL;
879 if (!PyIter_Check(it)) {
880 PyErr_Format(PyExc_TypeError,
881 "%.200s object is not an iterator", it->ob_type->tp_name);
882 return NULL;
883 }
884
885 res = (*it->ob_type->tp_iternext)(it);
886 if (res == NULL) {
887 if (def) {
888 if (PyErr_Occurred() &&
889 !PyErr_ExceptionMatches(PyExc_StopIteration))
890 return NULL;
891 PyErr_Clear();
892 Py_INCREF(def);
893 return def;
894 } else if (PyErr_Occurred()) {
895 return NULL;
896 } else {
897 PyErr_SetNone(PyExc_StopIteration);
898 return NULL;
899 }
900 }
901 return res;
902}
903
904PyDoc_STRVAR(next_doc,
905"next(iterator[, default])\n\
906\n\
907Return the next item from the iterator. If default is given and the iterator\n\
908is exhausted, it is returned instead of raising StopIteration.");
909
910
911static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000912builtin_setattr(PyObject *self, PyObject *args)
Guido van Rossum33894be1992-01-27 16:53:09 +0000913{
Guido van Rossum79f25d91997-04-29 20:08:16 +0000914 PyObject *v;
915 PyObject *name;
916 PyObject *value;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000917
Raymond Hettingerea3fdf42002-12-29 16:33:45 +0000918 if (!PyArg_UnpackTuple(args, "setattr", 3, 3, &v, &name, &value))
Guido van Rossum33894be1992-01-27 16:53:09 +0000919 return NULL;
Guido van Rossum79f25d91997-04-29 20:08:16 +0000920 if (PyObject_SetAttr(v, name, value) != 0)
Guido van Rossum33894be1992-01-27 16:53:09 +0000921 return NULL;
Guido van Rossum79f25d91997-04-29 20:08:16 +0000922 Py_INCREF(Py_None);
923 return Py_None;
Guido van Rossum33894be1992-01-27 16:53:09 +0000924}
925
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000926PyDoc_STRVAR(setattr_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000927"setattr(object, name, value)\n\
928\n\
929Set a named attribute on an object; setattr(x, 'y', v) is equivalent to\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000930``x.y = v''.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000931
932
Guido van Rossum79f25d91997-04-29 20:08:16 +0000933static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000934builtin_delattr(PyObject *self, PyObject *args)
Guido van Rossum14144fc1994-08-29 12:53:40 +0000935{
Guido van Rossum79f25d91997-04-29 20:08:16 +0000936 PyObject *v;
937 PyObject *name;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000938
Raymond Hettingerea3fdf42002-12-29 16:33:45 +0000939 if (!PyArg_UnpackTuple(args, "delattr", 2, 2, &v, &name))
Guido van Rossum14144fc1994-08-29 12:53:40 +0000940 return NULL;
Guido van Rossum79f25d91997-04-29 20:08:16 +0000941 if (PyObject_SetAttr(v, name, (PyObject *)NULL) != 0)
Guido van Rossum14144fc1994-08-29 12:53:40 +0000942 return NULL;
Guido van Rossum79f25d91997-04-29 20:08:16 +0000943 Py_INCREF(Py_None);
944 return Py_None;
Guido van Rossum14144fc1994-08-29 12:53:40 +0000945}
946
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000947PyDoc_STRVAR(delattr_doc,
Guido van Rossumdf12a591998-11-23 22:13:04 +0000948"delattr(object, name)\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000949\n\
950Delete a named attribute on an object; delattr(x, 'y') is equivalent to\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000951``del x.y''.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000952
953
Guido van Rossum79f25d91997-04-29 20:08:16 +0000954static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000955builtin_hash(PyObject *self, PyObject *v)
Guido van Rossum9bfef441993-03-29 10:43:31 +0000956{
Guido van Rossum9bfef441993-03-29 10:43:31 +0000957 long x;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000958
Guido van Rossum79f25d91997-04-29 20:08:16 +0000959 x = PyObject_Hash(v);
Guido van Rossum9bfef441993-03-29 10:43:31 +0000960 if (x == -1)
961 return NULL;
Guido van Rossum79f25d91997-04-29 20:08:16 +0000962 return PyInt_FromLong(x);
Guido van Rossum9bfef441993-03-29 10:43:31 +0000963}
964
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000965PyDoc_STRVAR(hash_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000966"hash(object) -> integer\n\
967\n\
968Return a hash value for the object. Two objects with the same value have\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000969the same hash value. The reverse is not necessarily true, but likely.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000970
971
Guido van Rossum79f25d91997-04-29 20:08:16 +0000972static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000973builtin_hex(PyObject *self, PyObject *v)
Guido van Rossum006bcd41991-10-24 14:54:44 +0000974{
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000975 return PyNumber_ToBase(v, 16);
Guido van Rossum006bcd41991-10-24 14:54:44 +0000976}
977
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000978PyDoc_STRVAR(hex_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000979"hex(number) -> string\n\
980\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000981Return the hexadecimal representation of an integer or long integer.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000982
983
Guido van Rossum79f25d91997-04-29 20:08:16 +0000984static PyObject *
Guido van Rossum59d1d2b2001-04-20 19:13:02 +0000985builtin_iter(PyObject *self, PyObject *args)
986{
987 PyObject *v, *w = NULL;
988
Raymond Hettingerea3fdf42002-12-29 16:33:45 +0000989 if (!PyArg_UnpackTuple(args, "iter", 1, 2, &v, &w))
Guido van Rossum59d1d2b2001-04-20 19:13:02 +0000990 return NULL;
991 if (w == NULL)
992 return PyObject_GetIter(v);
993 if (!PyCallable_Check(v)) {
994 PyErr_SetString(PyExc_TypeError,
995 "iter(v, w): v must be callable");
996 return NULL;
997 }
998 return PyCallIter_New(v, w);
999}
1000
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001001PyDoc_STRVAR(iter_doc,
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001002"iter(collection) -> iterator\n\
1003iter(callable, sentinel) -> iterator\n\
1004\n\
1005Get an iterator from an object. In the first form, the argument must\n\
1006supply its own iterator, or be a sequence.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001007In the second form, the callable is called until it returns the sentinel.");
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001008
1009
1010static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001011builtin_len(PyObject *self, PyObject *v)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001012{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001013 Py_ssize_t res;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001014
Jeremy Hylton03657cf2000-07-12 13:05:33 +00001015 res = PyObject_Size(v);
Guido van Rossum8ea9f4d1998-06-29 22:26:50 +00001016 if (res < 0 && PyErr_Occurred())
1017 return NULL;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001018 return PyInt_FromSsize_t(res);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001019}
1020
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001021PyDoc_STRVAR(len_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001022"len(object) -> integer\n\
1023\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001024Return the number of items of a sequence or mapping.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001025
1026
Guido van Rossum79f25d91997-04-29 20:08:16 +00001027static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001028builtin_locals(PyObject *self)
Guido van Rossum872537c1995-07-07 22:43:42 +00001029{
Guido van Rossum79f25d91997-04-29 20:08:16 +00001030 PyObject *d;
Guido van Rossum872537c1995-07-07 22:43:42 +00001031
Guido van Rossum79f25d91997-04-29 20:08:16 +00001032 d = PyEval_GetLocals();
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00001033 Py_XINCREF(d);
Guido van Rossum872537c1995-07-07 22:43:42 +00001034 return d;
1035}
1036
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001037PyDoc_STRVAR(locals_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001038"locals() -> dictionary\n\
1039\n\
Raymond Hettinger69bf8f32003-01-04 02:16:22 +00001040Update and return a dictionary containing the current scope's local variables.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001041
1042
Guido van Rossum79f25d91997-04-29 20:08:16 +00001043static PyObject *
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001044min_max(PyObject *args, PyObject *kwds, int op)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001045{
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001046 PyObject *v, *it, *item, *val, *maxitem, *maxval, *keyfunc=NULL;
Martin v. Löwisfd39ad42004-08-12 14:42:37 +00001047 const char *name = op == Py_LT ? "min" : "max";
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001048
Guido van Rossum79f25d91997-04-29 20:08:16 +00001049 if (PyTuple_Size(args) > 1)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001050 v = args;
Martin v. Löwisfd39ad42004-08-12 14:42:37 +00001051 else if (!PyArg_UnpackTuple(args, (char *)name, 1, 1, &v))
Guido van Rossum3f5da241990-12-20 15:06:42 +00001052 return NULL;
Tim Peters67d687a2002-04-29 21:27:32 +00001053
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001054 if (kwds != NULL && PyDict_Check(kwds) && PyDict_Size(kwds)) {
1055 keyfunc = PyDict_GetItemString(kwds, "key");
1056 if (PyDict_Size(kwds)!=1 || keyfunc == NULL) {
Georg Brandl99d7e4e2005-08-31 22:21:15 +00001057 PyErr_Format(PyExc_TypeError,
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001058 "%s() got an unexpected keyword argument", name);
1059 return NULL;
1060 }
Georg Brandl99d7e4e2005-08-31 22:21:15 +00001061 }
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001062
Tim Petersc3074532001-05-03 07:00:32 +00001063 it = PyObject_GetIter(v);
1064 if (it == NULL)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001065 return NULL;
Tim Petersc3074532001-05-03 07:00:32 +00001066
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001067 maxitem = NULL; /* the result */
1068 maxval = NULL; /* the value associated with the result */
Brett Cannon9e635cf2004-12-07 00:25:35 +00001069 while (( item = PyIter_Next(it) )) {
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001070 /* get the value from the key function */
1071 if (keyfunc != NULL) {
1072 val = PyObject_CallFunctionObjArgs(keyfunc, item, NULL);
1073 if (val == NULL)
1074 goto Fail_it_item;
1075 }
1076 /* no key function; the value is the item */
1077 else {
1078 val = item;
1079 Py_INCREF(val);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001080 }
Tim Petersc3074532001-05-03 07:00:32 +00001081
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001082 /* maximum value and item are unset; set them */
1083 if (maxval == NULL) {
1084 maxitem = item;
1085 maxval = val;
1086 }
1087 /* maximum value and item are set; update them as necessary */
Guido van Rossum2d951851994-08-29 12:52:16 +00001088 else {
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001089 int cmp = PyObject_RichCompareBool(val, maxval, op);
1090 if (cmp < 0)
1091 goto Fail_it_item_and_val;
1092 else if (cmp > 0) {
1093 Py_DECREF(maxval);
1094 Py_DECREF(maxitem);
1095 maxval = val;
1096 maxitem = item;
Guido van Rossum53451b32001-01-17 15:47:24 +00001097 }
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001098 else {
1099 Py_DECREF(item);
1100 Py_DECREF(val);
Guido van Rossumc8b6df91997-05-23 00:06:51 +00001101 }
Guido van Rossum2d951851994-08-29 12:52:16 +00001102 }
Guido van Rossum3f5da241990-12-20 15:06:42 +00001103 }
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001104 if (PyErr_Occurred())
1105 goto Fail_it;
1106 if (maxval == NULL) {
Martin v. Löwisfd39ad42004-08-12 14:42:37 +00001107 PyErr_Format(PyExc_ValueError,
1108 "%s() arg is an empty sequence", name);
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001109 assert(maxitem == NULL);
1110 }
1111 else
1112 Py_DECREF(maxval);
Tim Petersc3074532001-05-03 07:00:32 +00001113 Py_DECREF(it);
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001114 return maxitem;
1115
1116Fail_it_item_and_val:
1117 Py_DECREF(val);
1118Fail_it_item:
1119 Py_DECREF(item);
1120Fail_it:
1121 Py_XDECREF(maxval);
1122 Py_XDECREF(maxitem);
1123 Py_DECREF(it);
1124 return NULL;
Guido van Rossum3f5da241990-12-20 15:06:42 +00001125}
1126
Guido van Rossum79f25d91997-04-29 20:08:16 +00001127static PyObject *
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001128builtin_min(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001129{
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001130 return min_max(args, kwds, Py_LT);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001131}
1132
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001133PyDoc_STRVAR(min_doc,
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001134"min(iterable[, key=func]) -> value\n\
1135min(a, b, c, ...[, key=func]) -> value\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001136\n\
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001137With a single iterable argument, return its smallest item.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001138With two or more arguments, return the smallest argument.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001139
1140
Guido van Rossum79f25d91997-04-29 20:08:16 +00001141static PyObject *
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001142builtin_max(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001143{
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001144 return min_max(args, kwds, Py_GT);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001145}
1146
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001147PyDoc_STRVAR(max_doc,
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001148"max(iterable[, key=func]) -> value\n\
1149max(a, b, c, ...[, key=func]) -> value\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001150\n\
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001151With a single iterable argument, return its largest item.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001152With two or more arguments, return the largest argument.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001153
1154
Guido van Rossum79f25d91997-04-29 20:08:16 +00001155static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001156builtin_oct(PyObject *self, PyObject *v)
Guido van Rossum006bcd41991-10-24 14:54:44 +00001157{
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001158 return PyNumber_ToBase(v, 8);
Guido van Rossum006bcd41991-10-24 14:54:44 +00001159}
1160
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001161PyDoc_STRVAR(oct_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001162"oct(number) -> string\n\
1163\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001164Return the octal representation of an integer or long integer.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001165
1166
Guido van Rossum79f25d91997-04-29 20:08:16 +00001167static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001168builtin_ord(PyObject *self, PyObject* obj)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001169{
Guido van Rossum09095f32000-03-10 23:00:52 +00001170 long ord;
Martin v. Löwisd96ee902006-02-16 14:37:16 +00001171 Py_ssize_t size;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001172
Jeremy Hylton394b54d2000-04-12 21:19:47 +00001173 if (PyString_Check(obj)) {
1174 size = PyString_GET_SIZE(obj);
Andrew M. Kuchling34c20cf2000-12-20 14:36:56 +00001175 if (size == 1) {
Jeremy Hylton394b54d2000-04-12 21:19:47 +00001176 ord = (long)((unsigned char)*PyString_AS_STRING(obj));
Andrew M. Kuchling34c20cf2000-12-20 14:36:56 +00001177 return PyInt_FromLong(ord);
1178 }
Guido van Rossum98f97462007-04-13 03:31:13 +00001179 }
1180 else if (PyUnicode_Check(obj)) {
Jeremy Hylton394b54d2000-04-12 21:19:47 +00001181 size = PyUnicode_GET_SIZE(obj);
Andrew M. Kuchling34c20cf2000-12-20 14:36:56 +00001182 if (size == 1) {
Jeremy Hylton394b54d2000-04-12 21:19:47 +00001183 ord = (long)*PyUnicode_AS_UNICODE(obj);
Andrew M. Kuchling34c20cf2000-12-20 14:36:56 +00001184 return PyInt_FromLong(ord);
1185 }
Guido van Rossum8ac004e2007-07-15 13:00:05 +00001186#ifndef Py_UNICODE_WIDE
1187 if (size == 2) {
1188 /* Decode a valid surrogate pair */
1189 int c0 = PyUnicode_AS_UNICODE(obj)[0];
1190 int c1 = PyUnicode_AS_UNICODE(obj)[1];
1191 if (0xD800 <= c0 && c0 <= 0xDBFF &&
1192 0xDC00 <= c1 && c1 <= 0xDFFF) {
1193 ord = ((((c0 & 0x03FF) << 10) | (c1 & 0x03FF)) +
1194 0x00010000);
1195 return PyInt_FromLong(ord);
1196 }
1197 }
1198#endif
Guido van Rossum6f376c42007-05-24 14:31:33 +00001199 }
Guido van Rossum98f97462007-04-13 03:31:13 +00001200 else if (PyBytes_Check(obj)) {
1201 /* XXX Hopefully this is temporary */
1202 size = PyBytes_GET_SIZE(obj);
1203 if (size == 1) {
Guido van Rossumf9e91c92007-05-08 21:05:48 +00001204 ord = (long)((unsigned char)*PyBytes_AS_STRING(obj));
Guido van Rossum98f97462007-04-13 03:31:13 +00001205 return PyInt_FromLong(ord);
1206 }
1207 }
1208 else {
Jeremy Hylton394b54d2000-04-12 21:19:47 +00001209 PyErr_Format(PyExc_TypeError,
Andrew M. Kuchlingf07aad12000-12-23 14:11:28 +00001210 "ord() expected string of length 1, but " \
Jeremy Hylton394b54d2000-04-12 21:19:47 +00001211 "%.200s found", obj->ob_type->tp_name);
Guido van Rossum09095f32000-03-10 23:00:52 +00001212 return NULL;
1213 }
1214
Guido van Rossumad991772001-01-12 16:03:05 +00001215 PyErr_Format(PyExc_TypeError,
Andrew M. Kuchlingf07aad12000-12-23 14:11:28 +00001216 "ord() expected a character, "
Martin v. Löwisd96ee902006-02-16 14:37:16 +00001217 "but string of length %zd found",
Jeremy Hylton394b54d2000-04-12 21:19:47 +00001218 size);
1219 return NULL;
Guido van Rossum3f5da241990-12-20 15:06:42 +00001220}
1221
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001222PyDoc_STRVAR(ord_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001223"ord(c) -> integer\n\
1224\n\
Guido van Rossum8ac004e2007-07-15 13:00:05 +00001225Return the integer ordinal of a one-character string."
1226#ifndef Py_UNICODE_WIDE
1227"\nA valid surrogate pair is also accepted."
1228#endif
1229);
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001230
1231
Guido van Rossum79f25d91997-04-29 20:08:16 +00001232static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001233builtin_pow(PyObject *self, PyObject *args)
Guido van Rossum6a00cd81995-01-07 12:39:01 +00001234{
Guido van Rossum09df08a1998-05-22 00:51:39 +00001235 PyObject *v, *w, *z = Py_None;
Guido van Rossum6a00cd81995-01-07 12:39:01 +00001236
Raymond Hettingerea3fdf42002-12-29 16:33:45 +00001237 if (!PyArg_UnpackTuple(args, "pow", 2, 3, &v, &w, &z))
Guido van Rossum6a00cd81995-01-07 12:39:01 +00001238 return NULL;
Guido van Rossum09df08a1998-05-22 00:51:39 +00001239 return PyNumber_Power(v, w, z);
Guido van Rossumd4905451991-05-05 20:00:36 +00001240}
1241
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001242PyDoc_STRVAR(pow_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001243"pow(x, y[, z]) -> number\n\
1244\n\
1245With two arguments, equivalent to x**y. With three arguments,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001246equivalent to (x**y) % z, but may be more efficient (e.g. for longs).");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001247
1248
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001249
Guido van Rossum34343512006-11-30 22:13:52 +00001250static PyObject *
1251builtin_print(PyObject *self, PyObject *args, PyObject *kwds)
1252{
1253 static char *kwlist[] = {"sep", "end", "file", 0};
Georg Brandl257d3d92007-02-26 10:35:10 +00001254 static PyObject *dummy_args;
Guido van Rossum34343512006-11-30 22:13:52 +00001255 PyObject *sep = NULL, *end = NULL, *file = NULL;
1256 int i, err;
1257
Georg Brandl257d3d92007-02-26 10:35:10 +00001258 if (dummy_args == NULL) {
1259 if (!(dummy_args = PyTuple_New(0)))
1260 return NULL;
1261 }
Georg Brandl88fc6642007-02-09 21:28:07 +00001262 if (!PyArg_ParseTupleAndKeywords(dummy_args, kwds, "|OOO:print",
Guido van Rossum34343512006-11-30 22:13:52 +00001263 kwlist, &sep, &end, &file))
1264 return NULL;
1265 if (file == NULL || file == Py_None)
1266 file = PySys_GetObject("stdout");
1267
Georg Brandl16f3e032006-11-30 22:46:03 +00001268 if (sep && sep != Py_None && !PyString_Check(sep) &&
1269 !PyUnicode_Check(sep)) {
1270 PyErr_Format(PyExc_TypeError,
1271 "sep must be None, str or unicode, not %.200s",
1272 sep->ob_type->tp_name);
1273 return NULL;
1274 }
1275 if (end && end != Py_None && !PyString_Check(end) &&
1276 !PyUnicode_Check(end)) {
1277 PyErr_Format(PyExc_TypeError,
1278 "end must be None, str or unicode, not %.200s",
1279 end->ob_type->tp_name);
1280 return NULL;
1281 }
Guido van Rossum34343512006-11-30 22:13:52 +00001282
1283 for (i = 0; i < PyTuple_Size(args); i++) {
1284 if (i > 0) {
1285 if (sep == NULL || sep == Py_None)
1286 err = PyFile_WriteString(" ", file);
1287 else
1288 err = PyFile_WriteObject(sep, file,
1289 Py_PRINT_RAW);
1290 if (err)
1291 return NULL;
1292 }
1293 err = PyFile_WriteObject(PyTuple_GetItem(args, i), file,
1294 Py_PRINT_RAW);
1295 if (err)
1296 return NULL;
1297 }
1298
1299 if (end == NULL || end == Py_None)
1300 err = PyFile_WriteString("\n", file);
1301 else
1302 err = PyFile_WriteObject(end, file, Py_PRINT_RAW);
1303 if (err)
1304 return NULL;
1305
1306 Py_RETURN_NONE;
1307}
1308
1309PyDoc_STRVAR(print_doc,
Guido van Rossum452bf512007-02-09 05:32:43 +00001310"print(value, ..., file=None, sep=' ', end='\\n')\n\
Guido van Rossum34343512006-11-30 22:13:52 +00001311\n\
1312Prints the values to a stream, or to sys.stdout by default.\n\
1313Optional keyword arguments:\n\
1314file: a file-like object (stream); defaults to the current sys.stdout.\n\
1315sep: string inserted between values, default a space.\n\
1316end: string appended after the last value, default a newline.");
1317
1318
Guido van Rossuma88a0332007-02-26 16:59:55 +00001319static PyObject *
1320builtin_input(PyObject *self, PyObject *args)
1321{
Guido van Rossumeba76962007-05-27 09:13:28 +00001322 PyObject *promptarg = NULL;
Guido van Rossuma88a0332007-02-26 16:59:55 +00001323 PyObject *fin = PySys_GetObject("stdin");
1324 PyObject *fout = PySys_GetObject("stdout");
Guido van Rossumeba76962007-05-27 09:13:28 +00001325 PyObject *ferr = PySys_GetObject("stderr");
1326 PyObject *tmp;
1327 long fd;
1328 int tty;
Guido van Rossuma88a0332007-02-26 16:59:55 +00001329
Guido van Rossumeba76962007-05-27 09:13:28 +00001330 /* Parse arguments */
1331 if (!PyArg_UnpackTuple(args, "input", 0, 1, &promptarg))
Guido van Rossuma88a0332007-02-26 16:59:55 +00001332 return NULL;
1333
Guido van Rossumeba76962007-05-27 09:13:28 +00001334 /* Check that stdin/out/err are intact */
Guido van Rossuma88a0332007-02-26 16:59:55 +00001335 if (fin == NULL) {
Guido van Rossumeba76962007-05-27 09:13:28 +00001336 PyErr_SetString(PyExc_RuntimeError,
1337 "input(): lost sys.stdin");
Guido van Rossuma88a0332007-02-26 16:59:55 +00001338 return NULL;
1339 }
1340 if (fout == NULL) {
Guido van Rossumeba76962007-05-27 09:13:28 +00001341 PyErr_SetString(PyExc_RuntimeError,
1342 "input(): lost sys.stdout");
Guido van Rossuma88a0332007-02-26 16:59:55 +00001343 return NULL;
1344 }
Guido van Rossumeba76962007-05-27 09:13:28 +00001345 if (ferr == NULL) {
1346 PyErr_SetString(PyExc_RuntimeError,
1347 "input(): lost sys.stderr");
1348 return NULL;
1349 }
1350
1351 /* First of all, flush stderr */
1352 tmp = PyObject_CallMethod(ferr, "flush", "");
1353 if (tmp == NULL)
Guido van Rossumc1f779c2007-07-03 08:25:58 +00001354 PyErr_Clear();
1355 else
1356 Py_DECREF(tmp);
Guido van Rossumeba76962007-05-27 09:13:28 +00001357
1358 /* We should only use (GNU) readline if Python's sys.stdin and
1359 sys.stdout are the same as C's stdin and stdout, because we
1360 need to pass it those. */
1361 tmp = PyObject_CallMethod(fin, "fileno", "");
Guido van Rossumc1f779c2007-07-03 08:25:58 +00001362 if (tmp == NULL) {
1363 PyErr_Clear();
1364 tty = 0;
1365 }
1366 else {
Guido van Rossumeba76962007-05-27 09:13:28 +00001367 fd = PyInt_AsLong(tmp);
1368 Py_DECREF(tmp);
1369 if (fd < 0 && PyErr_Occurred())
1370 return NULL;
Guido van Rossumc1f779c2007-07-03 08:25:58 +00001371 tty = fd == fileno(stdin) && isatty(fd);
1372 }
1373 if (tty) {
1374 tmp = PyObject_CallMethod(fout, "fileno", "");
1375 if (tmp == NULL)
1376 PyErr_Clear();
1377 else {
1378 fd = PyInt_AsLong(tmp);
1379 Py_DECREF(tmp);
1380 if (fd < 0 && PyErr_Occurred())
1381 return NULL;
1382 tty = fd == fileno(stdout) && isatty(fd);
1383 }
Guido van Rossumeba76962007-05-27 09:13:28 +00001384 }
1385
1386 /* If we're interactive, use (GNU) readline */
1387 if (tty) {
Guido van Rossuma88a0332007-02-26 16:59:55 +00001388 PyObject *po;
1389 char *prompt;
1390 char *s;
1391 PyObject *result;
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 Rossumeba76962007-05-27 09:13:28 +00001397 if (promptarg != NULL) {
1398 po = PyObject_Str(promptarg);
Guido van Rossuma88a0332007-02-26 16:59:55 +00001399 if (po == NULL)
1400 return NULL;
1401 prompt = PyString_AsString(po);
Guido van Rossumeba76962007-05-27 09:13:28 +00001402 if (prompt == NULL) {
1403 Py_DECREF(po);
Guido van Rossuma88a0332007-02-26 16:59:55 +00001404 return NULL;
Guido van Rossumeba76962007-05-27 09:13:28 +00001405 }
Guido van Rossuma88a0332007-02-26 16:59:55 +00001406 }
1407 else {
1408 po = NULL;
1409 prompt = "";
1410 }
Guido van Rossumeba76962007-05-27 09:13:28 +00001411 s = PyOS_Readline(stdin, stdout, prompt);
Guido van Rossuma88a0332007-02-26 16:59:55 +00001412 Py_XDECREF(po);
1413 if (s == NULL) {
1414 if (!PyErr_Occurred())
1415 PyErr_SetNone(PyExc_KeyboardInterrupt);
1416 return NULL;
1417 }
1418 if (*s == '\0') {
1419 PyErr_SetNone(PyExc_EOFError);
1420 result = NULL;
1421 }
1422 else { /* strip trailing '\n' */
1423 size_t len = strlen(s);
1424 if (len > PY_SSIZE_T_MAX) {
1425 PyErr_SetString(PyExc_OverflowError,
1426 "input: input too long");
1427 result = NULL;
1428 }
1429 else {
1430 result = PyString_FromStringAndSize(s, len-1);
1431 }
1432 }
1433 PyMem_FREE(s);
1434 return result;
1435 }
Guido van Rossumeba76962007-05-27 09:13:28 +00001436
1437 /* Fallback if we're not interactive */
1438 if (promptarg != NULL) {
1439 if (PyFile_WriteObject(promptarg, fout, Py_PRINT_RAW) != 0)
Guido van Rossuma88a0332007-02-26 16:59:55 +00001440 return NULL;
1441 }
Guido van Rossumeba76962007-05-27 09:13:28 +00001442 tmp = PyObject_CallMethod(fout, "flush", "");
1443 if (tmp == NULL)
Guido van Rossumc1f779c2007-07-03 08:25:58 +00001444 PyErr_Clear();
1445 else
1446 Py_DECREF(tmp);
Guido van Rossuma88a0332007-02-26 16:59:55 +00001447 return PyFile_GetLine(fin, -1);
1448}
1449
1450PyDoc_STRVAR(input_doc,
1451"input([prompt]) -> string\n\
1452\n\
1453Read a string from standard input. The trailing newline is stripped.\n\
1454If the user hits EOF (Unix: Ctl-D, Windows: Ctl-Z+Return), raise EOFError.\n\
1455On Unix, GNU readline is used if enabled. The prompt string, if given,\n\
1456is printed without a trailing newline before reading.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001457
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001458
Guido van Rossum79f25d91997-04-29 20:08:16 +00001459static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001460builtin_repr(PyObject *self, PyObject *v)
Guido van Rossumc89705d1992-11-26 08:54:07 +00001461{
Guido van Rossum79f25d91997-04-29 20:08:16 +00001462 return PyObject_Repr(v);
Guido van Rossumc89705d1992-11-26 08:54:07 +00001463}
1464
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001465PyDoc_STRVAR(repr_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001466"repr(object) -> string\n\
1467\n\
1468Return the canonical string representation of the object.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001469For most object types, eval(repr(object)) == object.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001470
1471
Guido van Rossum79f25d91997-04-29 20:08:16 +00001472static PyObject *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001473builtin_round(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum9e51f9b1993-02-12 16:29:05 +00001474{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001475 double number;
Guido van Rossum9e51f9b1993-02-12 16:29:05 +00001476 double f;
1477 int ndigits = 0;
Guido van Rossum9e51f9b1993-02-12 16:29:05 +00001478 int i;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001479 static char *kwlist[] = {"number", "ndigits", 0};
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001480
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001481 if (!PyArg_ParseTupleAndKeywords(args, kwds, "d|i:round",
1482 kwlist, &number, &ndigits))
1483 return NULL;
Guido van Rossum9e51f9b1993-02-12 16:29:05 +00001484 f = 1.0;
Guido van Rossum1e162d31998-05-09 14:42:25 +00001485 i = abs(ndigits);
1486 while (--i >= 0)
Guido van Rossum9e51f9b1993-02-12 16:29:05 +00001487 f = f*10.0;
Guido van Rossum1e162d31998-05-09 14:42:25 +00001488 if (ndigits < 0)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001489 number /= f;
Guido van Rossum9e51f9b1993-02-12 16:29:05 +00001490 else
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001491 number *= f;
1492 if (number >= 0.0)
1493 number = floor(number + 0.5);
Guido van Rossum1e162d31998-05-09 14:42:25 +00001494 else
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001495 number = ceil(number - 0.5);
Guido van Rossum1e162d31998-05-09 14:42:25 +00001496 if (ndigits < 0)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001497 number *= f;
Guido van Rossum1e162d31998-05-09 14:42:25 +00001498 else
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001499 number /= f;
1500 return PyFloat_FromDouble(number);
Guido van Rossum9e51f9b1993-02-12 16:29:05 +00001501}
1502
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001503PyDoc_STRVAR(round_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001504"round(number[, ndigits]) -> floating point number\n\
1505\n\
1506Round a number to a given precision in decimal digits (default 0 digits).\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001507This always returns a floating point number. Precision may be negative.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001508
Raymond Hettinger64958a12003-12-17 20:43:33 +00001509static PyObject *
1510builtin_sorted(PyObject *self, PyObject *args, PyObject *kwds)
1511{
1512 PyObject *newlist, *v, *seq, *compare=NULL, *keyfunc=NULL, *newargs;
1513 PyObject *callable;
Martin v. Löwis15e62742006-02-27 16:46:16 +00001514 static char *kwlist[] = {"iterable", "cmp", "key", "reverse", 0};
Neal Norwitz6f0d4792005-12-15 06:40:36 +00001515 int reverse;
Raymond Hettinger64958a12003-12-17 20:43:33 +00001516
Neal Norwitz6f0d4792005-12-15 06:40:36 +00001517 /* args 1-4 should match listsort in Objects/listobject.c */
Armin Rigo71d7e702005-09-20 18:13:03 +00001518 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|OOi:sorted",
1519 kwlist, &seq, &compare, &keyfunc, &reverse))
1520 return NULL;
Raymond Hettinger64958a12003-12-17 20:43:33 +00001521
1522 newlist = PySequence_List(seq);
1523 if (newlist == NULL)
1524 return NULL;
1525
1526 callable = PyObject_GetAttrString(newlist, "sort");
1527 if (callable == NULL) {
1528 Py_DECREF(newlist);
1529 return NULL;
1530 }
Georg Brandl99d7e4e2005-08-31 22:21:15 +00001531
Raymond Hettinger64958a12003-12-17 20:43:33 +00001532 newargs = PyTuple_GetSlice(args, 1, 4);
1533 if (newargs == NULL) {
1534 Py_DECREF(newlist);
1535 Py_DECREF(callable);
1536 return NULL;
1537 }
1538
1539 v = PyObject_Call(callable, newargs, kwds);
1540 Py_DECREF(newargs);
1541 Py_DECREF(callable);
1542 if (v == NULL) {
1543 Py_DECREF(newlist);
1544 return NULL;
1545 }
1546 Py_DECREF(v);
1547 return newlist;
1548}
1549
1550PyDoc_STRVAR(sorted_doc,
1551"sorted(iterable, cmp=None, key=None, reverse=False) --> new sorted list");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001552
Guido van Rossum79f25d91997-04-29 20:08:16 +00001553static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001554builtin_vars(PyObject *self, PyObject *args)
Guido van Rossum2d951851994-08-29 12:52:16 +00001555{
Guido van Rossum79f25d91997-04-29 20:08:16 +00001556 PyObject *v = NULL;
1557 PyObject *d;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001558
Raymond Hettingerea3fdf42002-12-29 16:33:45 +00001559 if (!PyArg_UnpackTuple(args, "vars", 0, 1, &v))
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001560 return NULL;
Guido van Rossum2d951851994-08-29 12:52:16 +00001561 if (v == NULL) {
Guido van Rossum79f25d91997-04-29 20:08:16 +00001562 d = PyEval_GetLocals();
Guido van Rossum53bb7ff1995-07-26 16:26:31 +00001563 if (d == NULL) {
Guido van Rossum79f25d91997-04-29 20:08:16 +00001564 if (!PyErr_Occurred())
1565 PyErr_SetString(PyExc_SystemError,
Alex Martellia9b9c9f2003-04-23 13:34:35 +00001566 "vars(): no locals!?");
Guido van Rossum53bb7ff1995-07-26 16:26:31 +00001567 }
1568 else
Guido van Rossum79f25d91997-04-29 20:08:16 +00001569 Py_INCREF(d);
Guido van Rossum2d951851994-08-29 12:52:16 +00001570 }
1571 else {
Guido van Rossum79f25d91997-04-29 20:08:16 +00001572 d = PyObject_GetAttrString(v, "__dict__");
Guido van Rossum2d951851994-08-29 12:52:16 +00001573 if (d == NULL) {
Guido van Rossum79f25d91997-04-29 20:08:16 +00001574 PyErr_SetString(PyExc_TypeError,
Guido van Rossum2d951851994-08-29 12:52:16 +00001575 "vars() argument must have __dict__ attribute");
1576 return NULL;
1577 }
1578 }
1579 return d;
1580}
1581
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001582PyDoc_STRVAR(vars_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001583"vars([object]) -> dictionary\n\
1584\n\
1585Without arguments, equivalent to locals().\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001586With an argument, equivalent to object.__dict__.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001587
Alex Martellia70b1912003-04-22 08:12:33 +00001588
1589static PyObject*
1590builtin_sum(PyObject *self, PyObject *args)
1591{
1592 PyObject *seq;
1593 PyObject *result = NULL;
1594 PyObject *temp, *item, *iter;
1595
Raymond Hettinger5cf63942003-10-25 06:41:37 +00001596 if (!PyArg_UnpackTuple(args, "sum", 1, 2, &seq, &result))
Alex Martellia70b1912003-04-22 08:12:33 +00001597 return NULL;
1598
1599 iter = PyObject_GetIter(seq);
1600 if (iter == NULL)
1601 return NULL;
1602
1603 if (result == NULL) {
1604 result = PyInt_FromLong(0);
1605 if (result == NULL) {
1606 Py_DECREF(iter);
1607 return NULL;
1608 }
1609 } else {
1610 /* reject string values for 'start' parameter */
1611 if (PyObject_TypeCheck(result, &PyBaseString_Type)) {
1612 PyErr_SetString(PyExc_TypeError,
Alex Martellia9b9c9f2003-04-23 13:34:35 +00001613 "sum() can't sum strings [use ''.join(seq) instead]");
Alex Martellia70b1912003-04-22 08:12:33 +00001614 Py_DECREF(iter);
1615 return NULL;
1616 }
Alex Martelli41c9f882003-04-22 09:24:48 +00001617 Py_INCREF(result);
Alex Martellia70b1912003-04-22 08:12:33 +00001618 }
1619
1620 for(;;) {
1621 item = PyIter_Next(iter);
1622 if (item == NULL) {
1623 /* error, or end-of-sequence */
1624 if (PyErr_Occurred()) {
1625 Py_DECREF(result);
1626 result = NULL;
1627 }
1628 break;
1629 }
Alex Martellia253e182003-10-25 23:24:14 +00001630 temp = PyNumber_Add(result, item);
Alex Martellia70b1912003-04-22 08:12:33 +00001631 Py_DECREF(result);
1632 Py_DECREF(item);
1633 result = temp;
1634 if (result == NULL)
1635 break;
1636 }
1637 Py_DECREF(iter);
1638 return result;
1639}
1640
1641PyDoc_STRVAR(sum_doc,
Thomas Wouters89f507f2006-12-13 04:49:30 +00001642"sum(sequence[, start]) -> value\n\
Alex Martellia70b1912003-04-22 08:12:33 +00001643\n\
1644Returns the sum of a sequence of numbers (NOT strings) plus the value\n\
Thomas Wouters89f507f2006-12-13 04:49:30 +00001645of parameter 'start' (which defaults to 0). When the sequence is\n\
1646empty, returns start.");
Alex Martellia70b1912003-04-22 08:12:33 +00001647
1648
Barry Warsawcde8b1b1997-08-22 21:14:38 +00001649static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001650builtin_isinstance(PyObject *self, PyObject *args)
Barry Warsawcde8b1b1997-08-22 21:14:38 +00001651{
1652 PyObject *inst;
1653 PyObject *cls;
Guido van Rossum823649d2001-03-21 18:40:58 +00001654 int retval;
Barry Warsawcde8b1b1997-08-22 21:14:38 +00001655
Raymond Hettingerea3fdf42002-12-29 16:33:45 +00001656 if (!PyArg_UnpackTuple(args, "isinstance", 2, 2, &inst, &cls))
Barry Warsawcde8b1b1997-08-22 21:14:38 +00001657 return NULL;
Guido van Rossumf5dd9141997-12-02 19:11:45 +00001658
Guido van Rossum823649d2001-03-21 18:40:58 +00001659 retval = PyObject_IsInstance(inst, cls);
1660 if (retval < 0)
Guido van Rossumad991772001-01-12 16:03:05 +00001661 return NULL;
Guido van Rossum77f6a652002-04-03 22:41:51 +00001662 return PyBool_FromLong(retval);
Barry Warsawcde8b1b1997-08-22 21:14:38 +00001663}
1664
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001665PyDoc_STRVAR(isinstance_doc,
Guido van Rossum77f6a652002-04-03 22:41:51 +00001666"isinstance(object, class-or-type-or-tuple) -> bool\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001667\n\
1668Return whether an object is an instance of a class or of a subclass thereof.\n\
Guido van Rossum03290ec2001-10-07 20:54:12 +00001669With a type as second argument, return whether that is the object's type.\n\
1670The form using a tuple, isinstance(x, (A, B, ...)), is a shortcut for\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001671isinstance(x, A) or isinstance(x, B) or ... (etc.).");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001672
Barry Warsawcde8b1b1997-08-22 21:14:38 +00001673
1674static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001675builtin_issubclass(PyObject *self, PyObject *args)
Barry Warsawcde8b1b1997-08-22 21:14:38 +00001676{
1677 PyObject *derived;
1678 PyObject *cls;
1679 int retval;
1680
Raymond Hettingerea3fdf42002-12-29 16:33:45 +00001681 if (!PyArg_UnpackTuple(args, "issubclass", 2, 2, &derived, &cls))
Barry Warsawcde8b1b1997-08-22 21:14:38 +00001682 return NULL;
Guido van Rossum668213d1999-06-16 17:28:37 +00001683
Guido van Rossum823649d2001-03-21 18:40:58 +00001684 retval = PyObject_IsSubclass(derived, cls);
1685 if (retval < 0)
1686 return NULL;
Guido van Rossum77f6a652002-04-03 22:41:51 +00001687 return PyBool_FromLong(retval);
Barry Warsawcde8b1b1997-08-22 21:14:38 +00001688}
1689
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001690PyDoc_STRVAR(issubclass_doc,
Guido van Rossum77f6a652002-04-03 22:41:51 +00001691"issubclass(C, B) -> bool\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001692\n\
Walter Dörwaldd9a6ad32002-12-12 16:41:44 +00001693Return whether class C is a subclass (i.e., a derived class) of class B.\n\
1694When using a tuple as the second argument issubclass(X, (A, B, ...)),\n\
1695is a shortcut for issubclass(X, A) or issubclass(X, B) or ... (etc.).");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001696
Barry Warsawcde8b1b1997-08-22 21:14:38 +00001697
Barry Warsawbd599b52000-08-03 15:45:29 +00001698static PyObject*
1699builtin_zip(PyObject *self, PyObject *args)
1700{
Guido van Rossumb65fb332006-08-25 23:26:40 +00001701 /* args must be a tuple */
1702 assert(PyTuple_Check(args));
Barry Warsawbd599b52000-08-03 15:45:29 +00001703
Guido van Rossumb65fb332006-08-25 23:26:40 +00001704 return _PyZip_CreateIter(args);
Barry Warsawbd599b52000-08-03 15:45:29 +00001705}
1706
1707
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001708PyDoc_STRVAR(zip_doc,
Guido van Rossum801f0d72006-08-24 19:48:10 +00001709"zip(it1 [, it2 [...]]) -> iter([(it1[0], it2[0] ...), ...])\n\
Barry Warsawbd599b52000-08-03 15:45:29 +00001710\n\
Guido van Rossum801f0d72006-08-24 19:48:10 +00001711Return an iterator yielding tuples, where each tuple contains the\n\
1712corresponding element from each of the argument iterables.\n\
1713The returned iterator ends when the shortest argument iterable is exhausted.\n\
Guido van Rossumc1f779c2007-07-03 08:25:58 +00001714(This is identical to itertools.izip().)");
Barry Warsawbd599b52000-08-03 15:45:29 +00001715
1716
Guido van Rossum79f25d91997-04-29 20:08:16 +00001717static PyMethodDef builtin_methods[] = {
Guido van Rossum52cc1d82007-03-18 15:41:51 +00001718 {"__build_class__", (PyCFunction)builtin___build_class__,
1719 METH_VARARGS | METH_KEYWORDS, build_class_doc},
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001720 {"__import__", (PyCFunction)builtin___import__, METH_VARARGS | METH_KEYWORDS, import_doc},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001721 {"abs", builtin_abs, METH_O, abs_doc},
Raymond Hettinger96229b12005-03-11 06:49:40 +00001722 {"all", builtin_all, METH_O, all_doc},
1723 {"any", builtin_any, METH_O, any_doc},
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001724 {"bin", builtin_bin, METH_O, bin_doc},
Walter Dörwalde7efd592007-06-05 20:07:21 +00001725 {"chr", builtin_chr, METH_VARARGS, chr_doc},
1726 {"chr8", builtin_chr8, METH_VARARGS, chr8_doc},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001727 {"cmp", builtin_cmp, METH_VARARGS, cmp_doc},
Guido van Rossumd8faa362007-04-27 19:54:29 +00001728 {"compile", (PyCFunction)builtin_compile, METH_VARARGS | METH_KEYWORDS, compile_doc},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001729 {"delattr", builtin_delattr, METH_VARARGS, delattr_doc},
1730 {"dir", builtin_dir, METH_VARARGS, dir_doc},
1731 {"divmod", builtin_divmod, METH_VARARGS, divmod_doc},
1732 {"eval", builtin_eval, METH_VARARGS, eval_doc},
Georg Brandl7cae87c2006-09-06 06:51:57 +00001733 {"exec", builtin_exec, METH_VARARGS, exec_doc},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001734 {"execfile", builtin_execfile, METH_VARARGS, execfile_doc},
1735 {"filter", builtin_filter, METH_VARARGS, filter_doc},
1736 {"getattr", builtin_getattr, METH_VARARGS, getattr_doc},
1737 {"globals", (PyCFunction)builtin_globals, METH_NOARGS, globals_doc},
1738 {"hasattr", builtin_hasattr, METH_VARARGS, hasattr_doc},
1739 {"hash", builtin_hash, METH_O, hash_doc},
1740 {"hex", builtin_hex, METH_O, hex_doc},
1741 {"id", builtin_id, METH_O, id_doc},
Guido van Rossuma88a0332007-02-26 16:59:55 +00001742 {"input", builtin_input, METH_VARARGS, input_doc},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001743 {"isinstance", builtin_isinstance, METH_VARARGS, isinstance_doc},
1744 {"issubclass", builtin_issubclass, METH_VARARGS, issubclass_doc},
1745 {"iter", builtin_iter, METH_VARARGS, iter_doc},
1746 {"len", builtin_len, METH_O, len_doc},
1747 {"locals", (PyCFunction)builtin_locals, METH_NOARGS, locals_doc},
1748 {"map", builtin_map, METH_VARARGS, map_doc},
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001749 {"max", (PyCFunction)builtin_max, METH_VARARGS | METH_KEYWORDS, max_doc},
1750 {"min", (PyCFunction)builtin_min, METH_VARARGS | METH_KEYWORDS, min_doc},
Georg Brandla18af4e2007-04-21 15:47:16 +00001751 {"next", (PyCFunction)builtin_next, METH_VARARGS, next_doc},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001752 {"oct", builtin_oct, METH_O, oct_doc},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001753 {"ord", builtin_ord, METH_O, ord_doc},
1754 {"pow", builtin_pow, METH_VARARGS, pow_doc},
Guido van Rossum452bf512007-02-09 05:32:43 +00001755 {"print", (PyCFunction)builtin_print, METH_VARARGS | METH_KEYWORDS, print_doc},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001756 {"repr", builtin_repr, METH_O, repr_doc},
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001757 {"round", (PyCFunction)builtin_round, METH_VARARGS | METH_KEYWORDS, round_doc},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001758 {"setattr", builtin_setattr, METH_VARARGS, setattr_doc},
Raymond Hettinger64958a12003-12-17 20:43:33 +00001759 {"sorted", (PyCFunction)builtin_sorted, METH_VARARGS | METH_KEYWORDS, sorted_doc},
Alex Martellia70b1912003-04-22 08:12:33 +00001760 {"sum", builtin_sum, METH_VARARGS, sum_doc},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001761 {"vars", builtin_vars, METH_VARARGS, vars_doc},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001762 {"zip", builtin_zip, METH_VARARGS, zip_doc},
Guido van Rossumc02e15c1991-12-16 13:03:00 +00001763 {NULL, NULL},
Guido van Rossum3f5da241990-12-20 15:06:42 +00001764};
1765
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001766PyDoc_STRVAR(builtin_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001767"Built-in functions, exceptions, and other objects.\n\
1768\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001769Noteworthy: None is the `nil' object; Ellipsis represents `...' in slices.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001770
Guido van Rossum25ce5661997-08-02 03:10:38 +00001771PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001772_PyBuiltin_Init(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +00001773{
Fred Drake5550de32000-06-20 04:54:19 +00001774 PyObject *mod, *dict, *debug;
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001775 mod = Py_InitModule4("__builtin__", builtin_methods,
1776 builtin_doc, (PyObject *)NULL,
1777 PYTHON_API_VERSION);
Guido van Rossum25ce5661997-08-02 03:10:38 +00001778 if (mod == NULL)
1779 return NULL;
1780 dict = PyModule_GetDict(mod);
Tim Peters4b7625e2001-09-13 21:37:17 +00001781
Tim Peters7571a0f2003-03-23 17:52:28 +00001782#ifdef Py_TRACE_REFS
1783 /* __builtin__ exposes a number of statically allocated objects
1784 * that, before this code was added in 2.3, never showed up in
1785 * the list of "all objects" maintained by Py_TRACE_REFS. As a
1786 * result, programs leaking references to None and False (etc)
1787 * couldn't be diagnosed by examining sys.getobjects(0).
1788 */
1789#define ADD_TO_ALL(OBJECT) _Py_AddToAllObjects((PyObject *)(OBJECT), 0)
1790#else
1791#define ADD_TO_ALL(OBJECT) (void)0
1792#endif
1793
Tim Peters4b7625e2001-09-13 21:37:17 +00001794#define SETBUILTIN(NAME, OBJECT) \
Tim Peters7571a0f2003-03-23 17:52:28 +00001795 if (PyDict_SetItemString(dict, NAME, (PyObject *)OBJECT) < 0) \
1796 return NULL; \
1797 ADD_TO_ALL(OBJECT)
Tim Peters4b7625e2001-09-13 21:37:17 +00001798
1799 SETBUILTIN("None", Py_None);
1800 SETBUILTIN("Ellipsis", Py_Ellipsis);
1801 SETBUILTIN("NotImplemented", Py_NotImplemented);
Guido van Rossum77f6a652002-04-03 22:41:51 +00001802 SETBUILTIN("False", Py_False);
1803 SETBUILTIN("True", Py_True);
Neal Norwitz32a7e7f2002-05-31 19:58:02 +00001804 SETBUILTIN("basestring", &PyBaseString_Type);
Guido van Rossum77f6a652002-04-03 22:41:51 +00001805 SETBUILTIN("bool", &PyBool_Type);
Guido van Rossumbea18cc2002-06-14 20:41:17 +00001806 SETBUILTIN("buffer", &PyBuffer_Type);
Guido van Rossum4dfe8a12006-04-22 23:28:04 +00001807 SETBUILTIN("bytes", &PyBytes_Type);
Tim Peters4b7625e2001-09-13 21:37:17 +00001808 SETBUILTIN("classmethod", &PyClassMethod_Type);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001809#ifndef WITHOUT_COMPLEX
Tim Peters4b7625e2001-09-13 21:37:17 +00001810 SETBUILTIN("complex", &PyComplex_Type);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001811#endif
Tim Petersa427a2b2001-10-29 22:25:45 +00001812 SETBUILTIN("dict", &PyDict_Type);
Tim Peters67d687a2002-04-29 21:27:32 +00001813 SETBUILTIN("enumerate", &PyEnum_Type);
Tim Peters4b7625e2001-09-13 21:37:17 +00001814 SETBUILTIN("float", &PyFloat_Type);
Raymond Hettingera690a992003-11-16 16:17:49 +00001815 SETBUILTIN("frozenset", &PyFrozenSet_Type);
Tim Peters4b7625e2001-09-13 21:37:17 +00001816 SETBUILTIN("property", &PyProperty_Type);
Guido van Rossumddefaf32007-01-14 03:31:43 +00001817 SETBUILTIN("int", &PyLong_Type);
Tim Peters4b7625e2001-09-13 21:37:17 +00001818 SETBUILTIN("list", &PyList_Type);
Tim Peters4b7625e2001-09-13 21:37:17 +00001819 SETBUILTIN("object", &PyBaseObject_Type);
Guido van Rossum805365e2007-05-07 22:24:25 +00001820 SETBUILTIN("range", &PyRange_Type);
Raymond Hettinger85c20a42003-11-06 14:06:48 +00001821 SETBUILTIN("reversed", &PyReversed_Type);
Raymond Hettingera690a992003-11-16 16:17:49 +00001822 SETBUILTIN("set", &PySet_Type);
Guido van Rossumbea18cc2002-06-14 20:41:17 +00001823 SETBUILTIN("slice", &PySlice_Type);
Tim Peters4b7625e2001-09-13 21:37:17 +00001824 SETBUILTIN("staticmethod", &PyStaticMethod_Type);
Guido van Rossum572dbf82007-04-27 23:53:51 +00001825 SETBUILTIN("str", &PyUnicode_Type);
Guido van Rossum84fc66d2007-05-03 17:18:26 +00001826 SETBUILTIN("str8", &PyString_Type);
Tim Peters4b7625e2001-09-13 21:37:17 +00001827 SETBUILTIN("super", &PySuper_Type);
1828 SETBUILTIN("tuple", &PyTuple_Type);
1829 SETBUILTIN("type", &PyType_Type);
Guido van Rossum77f6a652002-04-03 22:41:51 +00001830 debug = PyBool_FromLong(Py_OptimizeFlag == 0);
Fred Drake5550de32000-06-20 04:54:19 +00001831 if (PyDict_SetItemString(dict, "__debug__", debug) < 0) {
1832 Py_XDECREF(debug);
Guido van Rossum25ce5661997-08-02 03:10:38 +00001833 return NULL;
Fred Drake5550de32000-06-20 04:54:19 +00001834 }
1835 Py_XDECREF(debug);
Barry Warsaw757af0e1997-08-29 22:13:51 +00001836
Guido van Rossum25ce5661997-08-02 03:10:38 +00001837 return mod;
Tim Peters7571a0f2003-03-23 17:52:28 +00001838#undef ADD_TO_ALL
Tim Peters4b7625e2001-09-13 21:37:17 +00001839#undef SETBUILTIN
Guido van Rossum3f5da241990-12-20 15:06:42 +00001840}