blob: 94d4bc387f337cbcf85a7368a2c9acd5a019ce13 [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 Hammond26cffde2001-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 Hammond26cffde2001-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 Hammond26cffde2001-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 Rossum12d12c51993-10-26 17:58:25 +000026/* Forward */
Tim Petersdbd9ba62000-07-09 03:09:57 +000027static PyObject *filterstring(PyObject *, PyObject *);
Martin v. Löwis8afd7572003-01-25 22:46:11 +000028#ifdef Py_USING_UNICODE
29static PyObject *filterunicode(PyObject *, PyObject *);
30#endif
Tim Petersdbd9ba62000-07-09 03:09:57 +000031static PyObject *filtertuple (PyObject *, PyObject *);
Guido van Rossum12d12c51993-10-26 17:58:25 +000032
Guido van Rossum79f25d91997-04-29 20:08:16 +000033static PyObject *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000034builtin___import__(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum3f5da241990-12-20 15:06:42 +000035{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000036 static char *kwlist[] = {"name", "globals", "locals", "fromlist",
37 "level", 0};
Guido van Rossum1ae940a1995-01-02 19:04:15 +000038 char *name;
Guido van Rossum79f25d91997-04-29 20:08:16 +000039 PyObject *globals = NULL;
40 PyObject *locals = NULL;
41 PyObject *fromlist = NULL;
Thomas Woutersf7f438b2006-02-28 16:09:29 +000042 int level = -1;
Guido van Rossum1ae940a1995-01-02 19:04:15 +000043
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000044 if (!PyArg_ParseTupleAndKeywords(args, kwds, "s|OOOi:__import__",
45 kwlist, &name, &globals, &locals, &fromlist, &level))
Guido van Rossum1ae940a1995-01-02 19:04:15 +000046 return NULL;
Thomas Woutersf7f438b2006-02-28 16:09:29 +000047 return PyImport_ImportModuleLevel(name, globals, locals,
48 fromlist, level);
Guido van Rossum1ae940a1995-01-02 19:04:15 +000049}
50
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000051PyDoc_STRVAR(import_doc,
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000052"__import__(name, globals={}, locals={}, fromlist=[], level=-1) -> module\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +000053\n\
54Import a module. The globals are only used to determine the context;\n\
55they are not modified. The locals are currently unused. The fromlist\n\
56should be a list of names to emulate ``from name import ...'', or an\n\
57empty list to emulate ``import name''.\n\
58When importing a module from a package, note that __import__('A.B', ...)\n\
59returns package A when fromlist is empty, but its submodule B when\n\
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000060fromlist is not empty. Level is used to determine whether to perform \n\
61absolute or relative imports. -1 is the original strategy of attempting\n\
62both absolute and relative imports, 0 is absolute, a positive number\n\
63is the number of parent directories to search relative to the current module.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +000064
Guido van Rossum1ae940a1995-01-02 19:04:15 +000065
Guido van Rossum79f25d91997-04-29 20:08:16 +000066static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000067builtin_abs(PyObject *self, PyObject *v)
Guido van Rossum1ae940a1995-01-02 19:04:15 +000068{
Guido van Rossum09df08a1998-05-22 00:51:39 +000069 return PyNumber_Absolute(v);
Guido van Rossum3f5da241990-12-20 15:06:42 +000070}
71
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000072PyDoc_STRVAR(abs_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +000073"abs(number) -> number\n\
74\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000075Return the absolute value of the argument.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +000076
Raymond Hettinger96229b12005-03-11 06:49:40 +000077static PyObject *
78builtin_all(PyObject *self, PyObject *v)
79{
80 PyObject *it, *item;
81
82 it = PyObject_GetIter(v);
83 if (it == NULL)
84 return NULL;
85
86 while ((item = PyIter_Next(it)) != NULL) {
87 int cmp = PyObject_IsTrue(item);
88 Py_DECREF(item);
89 if (cmp < 0) {
90 Py_DECREF(it);
91 return NULL;
92 }
93 if (cmp == 0) {
94 Py_DECREF(it);
95 Py_RETURN_FALSE;
96 }
97 }
98 Py_DECREF(it);
99 if (PyErr_Occurred())
100 return NULL;
101 Py_RETURN_TRUE;
102}
103
104PyDoc_STRVAR(all_doc,
105"all(iterable) -> bool\n\
106\n\
107Return True if bool(x) is True for all values x in the iterable.");
108
109static PyObject *
110builtin_any(PyObject *self, PyObject *v)
111{
112 PyObject *it, *item;
113
114 it = PyObject_GetIter(v);
115 if (it == NULL)
116 return NULL;
117
118 while ((item = PyIter_Next(it)) != NULL) {
119 int cmp = PyObject_IsTrue(item);
120 Py_DECREF(item);
121 if (cmp < 0) {
122 Py_DECREF(it);
123 return NULL;
124 }
125 if (cmp == 1) {
126 Py_DECREF(it);
127 Py_RETURN_TRUE;
128 }
129 }
130 Py_DECREF(it);
131 if (PyErr_Occurred())
132 return NULL;
133 Py_RETURN_FALSE;
134}
135
136PyDoc_STRVAR(any_doc,
137"any(iterable) -> bool\n\
138\n\
139Return True if bool(x) is True for any x in the iterable.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000140
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000141
Guido van Rossum79f25d91997-04-29 20:08:16 +0000142static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000143builtin_callable(PyObject *self, PyObject *v)
Guido van Rossum2d951851994-08-29 12:52:16 +0000144{
Guido van Rossum77f6a652002-04-03 22:41:51 +0000145 return PyBool_FromLong((long)PyCallable_Check(v));
Guido van Rossum2d951851994-08-29 12:52:16 +0000146}
147
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000148PyDoc_STRVAR(callable_doc,
Guido van Rossum77f6a652002-04-03 22:41:51 +0000149"callable(object) -> bool\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000150\n\
151Return whether the object is callable (i.e., some kind of function).\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000152Note that classes are callable, as are instances with a __call__() method.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000153
154
Guido van Rossum79f25d91997-04-29 20:08:16 +0000155static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000156builtin_filter(PyObject *self, PyObject *args)
Guido van Rossum12d12c51993-10-26 17:58:25 +0000157{
Guido van Rossumc7903a12002-08-16 07:04:56 +0000158 PyObject *func, *seq, *result, *it, *arg;
Martin v. Löwisd96ee902006-02-16 14:37:16 +0000159 Py_ssize_t len; /* guess for result list size */
160 register Py_ssize_t j;
Guido van Rossum12d12c51993-10-26 17:58:25 +0000161
Raymond Hettingerea3fdf42002-12-29 16:33:45 +0000162 if (!PyArg_UnpackTuple(args, "filter", 2, 2, &func, &seq))
Guido van Rossum12d12c51993-10-26 17:58:25 +0000163 return NULL;
Guido van Rossum12d12c51993-10-26 17:58:25 +0000164
Tim Peters0e57abf2001-05-02 07:39:38 +0000165 /* Strings and tuples return a result of the same type. */
166 if (PyString_Check(seq))
167 return filterstring(func, seq);
Martin v. Löwis8afd7572003-01-25 22:46:11 +0000168#ifdef Py_USING_UNICODE
169 if (PyUnicode_Check(seq))
170 return filterunicode(func, seq);
171#endif
Tim Peters0e57abf2001-05-02 07:39:38 +0000172 if (PyTuple_Check(seq))
173 return filtertuple(func, seq);
174
Georg Brandle35b6572005-07-19 22:20:20 +0000175 /* Pre-allocate argument list tuple. */
176 arg = PyTuple_New(1);
177 if (arg == NULL)
178 return NULL;
179
Tim Peters0e57abf2001-05-02 07:39:38 +0000180 /* Get iterator. */
181 it = PyObject_GetIter(seq);
182 if (it == NULL)
Georg Brandle35b6572005-07-19 22:20:20 +0000183 goto Fail_arg;
Tim Peters0e57abf2001-05-02 07:39:38 +0000184
185 /* Guess a result list size. */
Armin Rigof5b3e362006-02-11 21:32:43 +0000186 len = _PyObject_LengthHint(seq);
Raymond Hettingerb86269d2004-01-04 11:00:08 +0000187 if (len < 0) {
Raymond Hettingera710b332005-08-21 11:03:59 +0000188 if (!PyErr_ExceptionMatches(PyExc_TypeError) &&
189 !PyErr_ExceptionMatches(PyExc_AttributeError)) {
190 goto Fail_it;
191 }
Raymond Hettingerb86269d2004-01-04 11:00:08 +0000192 PyErr_Clear();
193 len = 8; /* arbitrary */
Guido van Rossum12d12c51993-10-26 17:58:25 +0000194 }
195
Tim Peters0e57abf2001-05-02 07:39:38 +0000196 /* Get a result list. */
Guido van Rossum79f25d91997-04-29 20:08:16 +0000197 if (PyList_Check(seq) && seq->ob_refcnt == 1) {
Tim Peters0e57abf2001-05-02 07:39:38 +0000198 /* Eww - can modify the list in-place. */
Guido van Rossum79f25d91997-04-29 20:08:16 +0000199 Py_INCREF(seq);
Guido van Rossum12d12c51993-10-26 17:58:25 +0000200 result = seq;
201 }
Guido van Rossumdc4b93d1993-10-27 14:56:44 +0000202 else {
Tim Peters0e57abf2001-05-02 07:39:38 +0000203 result = PyList_New(len);
204 if (result == NULL)
205 goto Fail_it;
Guido van Rossumdc4b93d1993-10-27 14:56:44 +0000206 }
Guido van Rossum12d12c51993-10-26 17:58:25 +0000207
Tim Peters0e57abf2001-05-02 07:39:38 +0000208 /* Build the result list. */
Tim Petersf4848da2001-05-05 00:14:56 +0000209 j = 0;
210 for (;;) {
Guido van Rossumc7903a12002-08-16 07:04:56 +0000211 PyObject *item;
Guido van Rossumdc4b93d1993-10-27 14:56:44 +0000212 int ok;
Guido van Rossum12d12c51993-10-26 17:58:25 +0000213
Tim Peters0e57abf2001-05-02 07:39:38 +0000214 item = PyIter_Next(it);
215 if (item == NULL) {
Tim Petersf4848da2001-05-05 00:14:56 +0000216 if (PyErr_Occurred())
217 goto Fail_result_it;
Tim Peters0e57abf2001-05-02 07:39:38 +0000218 break;
Guido van Rossum2d951851994-08-29 12:52:16 +0000219 }
Guido van Rossumdc4b93d1993-10-27 14:56:44 +0000220
Neil Schemenauer68973552003-08-14 20:37:34 +0000221 if (func == (PyObject *)&PyBool_Type || func == Py_None) {
Guido van Rossumc7903a12002-08-16 07:04:56 +0000222 ok = PyObject_IsTrue(item);
Guido van Rossumdc4b93d1993-10-27 14:56:44 +0000223 }
224 else {
Guido van Rossumc7903a12002-08-16 07:04:56 +0000225 PyObject *good;
226 PyTuple_SET_ITEM(arg, 0, item);
227 good = PyObject_Call(func, arg, NULL);
228 PyTuple_SET_ITEM(arg, 0, NULL);
Guido van Rossum58b68731995-01-10 17:40:55 +0000229 if (good == NULL) {
Guido van Rossum79f25d91997-04-29 20:08:16 +0000230 Py_DECREF(item);
Tim Peters0e57abf2001-05-02 07:39:38 +0000231 goto Fail_result_it;
Guido van Rossum58b68731995-01-10 17:40:55 +0000232 }
Guido van Rossumc7903a12002-08-16 07:04:56 +0000233 ok = PyObject_IsTrue(good);
234 Py_DECREF(good);
Guido van Rossum12d12c51993-10-26 17:58:25 +0000235 }
Guido van Rossumdc4b93d1993-10-27 14:56:44 +0000236 if (ok) {
Tim Peters0e57abf2001-05-02 07:39:38 +0000237 if (j < len)
238 PyList_SET_ITEM(result, j, item);
Guido van Rossum2d951851994-08-29 12:52:16 +0000239 else {
Barry Warsawfa77e091999-01-28 18:49:12 +0000240 int status = PyList_Append(result, item);
Barry Warsawfa77e091999-01-28 18:49:12 +0000241 Py_DECREF(item);
242 if (status < 0)
Tim Peters0e57abf2001-05-02 07:39:38 +0000243 goto Fail_result_it;
Guido van Rossum2d951851994-08-29 12:52:16 +0000244 }
Tim Peters0e57abf2001-05-02 07:39:38 +0000245 ++j;
Guido van Rossum12d12c51993-10-26 17:58:25 +0000246 }
Tim Peters0e57abf2001-05-02 07:39:38 +0000247 else
248 Py_DECREF(item);
Guido van Rossum12d12c51993-10-26 17:58:25 +0000249 }
250
Guido van Rossum12d12c51993-10-26 17:58:25 +0000251
Tim Peters0e57abf2001-05-02 07:39:38 +0000252 /* Cut back result list if len is too big. */
Guido van Rossum79f25d91997-04-29 20:08:16 +0000253 if (j < len && PyList_SetSlice(result, j, len, NULL) < 0)
Tim Peters0e57abf2001-05-02 07:39:38 +0000254 goto Fail_result_it;
Guido van Rossum12d12c51993-10-26 17:58:25 +0000255
Tim Peters3c6b1482001-05-21 08:07:05 +0000256 Py_DECREF(it);
Guido van Rossumc7903a12002-08-16 07:04:56 +0000257 Py_DECREF(arg);
Guido van Rossum12d12c51993-10-26 17:58:25 +0000258 return result;
259
Tim Peters0e57abf2001-05-02 07:39:38 +0000260Fail_result_it:
Guido van Rossum79f25d91997-04-29 20:08:16 +0000261 Py_DECREF(result);
Tim Peters0e57abf2001-05-02 07:39:38 +0000262Fail_it:
263 Py_DECREF(it);
Guido van Rossumc7903a12002-08-16 07:04:56 +0000264Fail_arg:
265 Py_DECREF(arg);
Guido van Rossum12d12c51993-10-26 17:58:25 +0000266 return NULL;
267}
268
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000269PyDoc_STRVAR(filter_doc,
Tim Petersd50e5442002-03-09 00:06:26 +0000270"filter(function or None, sequence) -> list, tuple, or string\n"
271"\n"
272"Return those items of sequence for which function(item) is true. If\n"
273"function is None, return the items that are true. If sequence is a tuple\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000274"or string, return the same type, else return a list.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000275
Guido van Rossum79f25d91997-04-29 20:08:16 +0000276static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000277builtin_chr(PyObject *self, PyObject *args)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000278{
279 long x;
280 char s[1];
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000281
Guido van Rossum79f25d91997-04-29 20:08:16 +0000282 if (!PyArg_ParseTuple(args, "l:chr", &x))
Guido van Rossum3f5da241990-12-20 15:06:42 +0000283 return NULL;
Guido van Rossum3f5da241990-12-20 15:06:42 +0000284 if (x < 0 || x >= 256) {
Guido van Rossum79f25d91997-04-29 20:08:16 +0000285 PyErr_SetString(PyExc_ValueError,
286 "chr() arg not in range(256)");
Guido van Rossum3f5da241990-12-20 15:06:42 +0000287 return NULL;
288 }
Guido van Rossum6bf62da1997-04-11 20:37:35 +0000289 s[0] = (char)x;
Guido van Rossum79f25d91997-04-29 20:08:16 +0000290 return PyString_FromStringAndSize(s, 1);
Guido van Rossum3f5da241990-12-20 15:06:42 +0000291}
292
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000293PyDoc_STRVAR(chr_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000294"chr(i) -> character\n\
295\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000296Return a string of one character with ordinal i; 0 <= i < 256.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000297
298
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000299#ifdef Py_USING_UNICODE
Guido van Rossum79f25d91997-04-29 20:08:16 +0000300static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000301builtin_unichr(PyObject *self, PyObject *args)
Guido van Rossum09095f32000-03-10 23:00:52 +0000302{
303 long x;
Guido van Rossum09095f32000-03-10 23:00:52 +0000304
305 if (!PyArg_ParseTuple(args, "l:unichr", &x))
306 return NULL;
Fredrik Lundh0dcf67e2001-06-26 20:01:56 +0000307
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +0000308 return PyUnicode_FromOrdinal(x);
Guido van Rossum09095f32000-03-10 23:00:52 +0000309}
310
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000311PyDoc_STRVAR(unichr_doc,
Fred Drake078b24f2000-04-13 02:42:50 +0000312"unichr(i) -> Unicode character\n\
Guido van Rossum09095f32000-03-10 23:00:52 +0000313\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000314Return a Unicode string of one character with ordinal i; 0 <= i <= 0x10ffff.");
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000315#endif
Guido van Rossum09095f32000-03-10 23:00:52 +0000316
317
318static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000319builtin_cmp(PyObject *self, PyObject *args)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +0000320{
Guido van Rossum79f25d91997-04-29 20:08:16 +0000321 PyObject *a, *b;
Guido van Rossum09df08a1998-05-22 00:51:39 +0000322 int c;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000323
Raymond Hettingerea3fdf42002-12-29 16:33:45 +0000324 if (!PyArg_UnpackTuple(args, "cmp", 2, 2, &a, &b))
Guido van Rossuma9e7dc11992-10-18 18:53:57 +0000325 return NULL;
Guido van Rossum09df08a1998-05-22 00:51:39 +0000326 if (PyObject_Cmp(a, b, &c) < 0)
Guido van Rossumc8b6df91997-05-23 00:06:51 +0000327 return NULL;
Guido van Rossum09df08a1998-05-22 00:51:39 +0000328 return PyInt_FromLong((long)c);
Guido van Rossuma9e7dc11992-10-18 18:53:57 +0000329}
330
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000331PyDoc_STRVAR(cmp_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000332"cmp(x, y) -> integer\n\
333\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000334Return negative if x<y, zero if x==y, positive if x>y.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000335
Guido van Rossum79f25d91997-04-29 20:08:16 +0000336static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000337builtin_compile(PyObject *self, PyObject *args)
Guido van Rossum5b722181993-03-30 17:46:03 +0000338{
339 char *str;
340 char *filename;
341 char *startstr;
342 int start;
Tim Peters6cd6a822001-08-17 22:11:27 +0000343 int dont_inherit = 0;
344 int supplied_flags = 0;
Tim Peters5ba58662001-07-16 02:29:45 +0000345 PyCompilerFlags cf;
Neal Norwitz3a9a3e72005-11-27 20:38:31 +0000346 PyObject *result = NULL, *cmd, *tmp = NULL;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000347 Py_ssize_t length;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000348
Just van Rossum3aaf42c2003-02-10 08:21:10 +0000349 if (!PyArg_ParseTuple(args, "Oss|ii:compile", &cmd, &filename,
Tim Peters6cd6a822001-08-17 22:11:27 +0000350 &startstr, &supplied_flags, &dont_inherit))
Guido van Rossum5b722181993-03-30 17:46:03 +0000351 return NULL;
Tim Peters6cd6a822001-08-17 22:11:27 +0000352
Just van Rossum3aaf42c2003-02-10 08:21:10 +0000353 cf.cf_flags = supplied_flags;
354
355#ifdef Py_USING_UNICODE
356 if (PyUnicode_Check(cmd)) {
357 tmp = PyUnicode_AsUTF8String(cmd);
358 if (tmp == NULL)
359 return NULL;
360 cmd = tmp;
361 cf.cf_flags |= PyCF_SOURCE_IS_UTF8;
362 }
363#endif
Just van Rossumb9b8e9c2003-02-10 09:22:01 +0000364 if (PyObject_AsReadBuffer(cmd, (const void **)&str, &length))
365 return NULL;
Tim Peters2c646c92003-02-10 14:48:29 +0000366 if ((size_t)length != strlen(str)) {
Just van Rossum3aaf42c2003-02-10 08:21:10 +0000367 PyErr_SetString(PyExc_TypeError,
Alex Martellia9b9c9f2003-04-23 13:34:35 +0000368 "compile() expected string without null bytes");
Neal Norwitz3a9a3e72005-11-27 20:38:31 +0000369 goto cleanup;
Just van Rossum3aaf42c2003-02-10 08:21:10 +0000370 }
371
Guido van Rossum5b722181993-03-30 17:46:03 +0000372 if (strcmp(startstr, "exec") == 0)
Guido van Rossumb05a5c71997-05-07 17:46:13 +0000373 start = Py_file_input;
Guido van Rossum5b722181993-03-30 17:46:03 +0000374 else if (strcmp(startstr, "eval") == 0)
Guido van Rossumb05a5c71997-05-07 17:46:13 +0000375 start = Py_eval_input;
Guido van Rossum872537c1995-07-07 22:43:42 +0000376 else if (strcmp(startstr, "single") == 0)
Guido van Rossumb05a5c71997-05-07 17:46:13 +0000377 start = Py_single_input;
Guido van Rossum5b722181993-03-30 17:46:03 +0000378 else {
Guido van Rossum79f25d91997-04-29 20:08:16 +0000379 PyErr_SetString(PyExc_ValueError,
Fred Drake661ea262000-10-24 19:57:45 +0000380 "compile() arg 3 must be 'exec' or 'eval' or 'single'");
Neal Norwitz3a9a3e72005-11-27 20:38:31 +0000381 goto cleanup;
Guido van Rossum5b722181993-03-30 17:46:03 +0000382 }
Tim Peters6cd6a822001-08-17 22:11:27 +0000383
Guido van Rossum4b499dd32003-02-13 22:07:59 +0000384 if (supplied_flags &
Martin v. Löwisbd260da2006-02-26 19:42:26 +0000385 ~(PyCF_MASK | PyCF_MASK_OBSOLETE | PyCF_DONT_IMPLY_DEDENT | PyCF_ONLY_AST))
Guido van Rossum4b499dd32003-02-13 22:07:59 +0000386 {
Tim Peters6cd6a822001-08-17 22:11:27 +0000387 PyErr_SetString(PyExc_ValueError,
388 "compile(): unrecognised flags");
Neal Norwitz3a9a3e72005-11-27 20:38:31 +0000389 goto cleanup;
Tim Peters6cd6a822001-08-17 22:11:27 +0000390 }
391 /* XXX Warn if (supplied_flags & PyCF_MASK_OBSOLETE) != 0? */
392
Tim Peters6cd6a822001-08-17 22:11:27 +0000393 if (!dont_inherit) {
394 PyEval_MergeCompilerFlags(&cf);
395 }
Just van Rossum3aaf42c2003-02-10 08:21:10 +0000396 result = Py_CompileStringFlags(str, filename, start, &cf);
Neal Norwitz3a9a3e72005-11-27 20:38:31 +0000397cleanup:
Just van Rossum3aaf42c2003-02-10 08:21:10 +0000398 Py_XDECREF(tmp);
399 return result;
Guido van Rossum5b722181993-03-30 17:46:03 +0000400}
401
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000402PyDoc_STRVAR(compile_doc,
Tim Peters6cd6a822001-08-17 22:11:27 +0000403"compile(source, filename, mode[, flags[, dont_inherit]]) -> code object\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000404\n\
405Compile the source string (a Python module, statement or expression)\n\
Georg Brandl7cae87c2006-09-06 06:51:57 +0000406into a code object that can be executed by exec() or eval().\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000407The filename will be used for run-time error messages.\n\
408The mode must be 'exec' to compile a module, 'single' to compile a\n\
Tim Peters6cd6a822001-08-17 22:11:27 +0000409single (interactive) statement, or 'eval' to compile an expression.\n\
410The flags argument, if present, controls which future statements influence\n\
411the compilation of the code.\n\
412The dont_inherit argument, if non-zero, stops the compilation inheriting\n\
413the effects of any future statements in effect in the code calling\n\
414compile; if absent or zero these statements do influence the compilation,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000415in addition to any features explicitly specified.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000416
Guido van Rossum79f25d91997-04-29 20:08:16 +0000417static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000418builtin_dir(PyObject *self, PyObject *args)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000419{
Tim Peters5d2b77c2001-09-03 05:47:38 +0000420 PyObject *arg = NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000421
Raymond Hettingerea3fdf42002-12-29 16:33:45 +0000422 if (!PyArg_UnpackTuple(args, "dir", 0, 1, &arg))
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000423 return NULL;
Tim Peters7eea37e2001-09-04 22:08:56 +0000424 return PyObject_Dir(arg);
Guido van Rossum3f5da241990-12-20 15:06:42 +0000425}
426
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000427PyDoc_STRVAR(dir_doc,
Tim Peters5d2b77c2001-09-03 05:47:38 +0000428"dir([object]) -> list of strings\n"
429"\n"
430"Return an alphabetized list of names comprising (some of) the attributes\n"
431"of the given object, and of attributes reachable from it:\n"
432"\n"
433"No argument: the names in the current scope.\n"
434"Module object: the module attributes.\n"
Tim Peters37a309d2001-09-04 01:20:04 +0000435"Type or class object: its attributes, and recursively the attributes of\n"
436" its bases.\n"
Tim Peters5d2b77c2001-09-03 05:47:38 +0000437"Otherwise: its attributes, its class's attributes, and recursively the\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000438" attributes of its class's base classes.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000439
Guido van Rossum79f25d91997-04-29 20:08:16 +0000440static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000441builtin_divmod(PyObject *self, PyObject *args)
Guido van Rossum6a00cd81995-01-07 12:39:01 +0000442{
Guido van Rossum79f25d91997-04-29 20:08:16 +0000443 PyObject *v, *w;
Guido van Rossum6a00cd81995-01-07 12:39:01 +0000444
Raymond Hettingerea3fdf42002-12-29 16:33:45 +0000445 if (!PyArg_UnpackTuple(args, "divmod", 2, 2, &v, &w))
Guido van Rossum6a00cd81995-01-07 12:39:01 +0000446 return NULL;
Guido van Rossum09df08a1998-05-22 00:51:39 +0000447 return PyNumber_Divmod(v, w);
Guido van Rossum3f5da241990-12-20 15:06:42 +0000448}
449
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000450PyDoc_STRVAR(divmod_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000451"divmod(x, y) -> (div, mod)\n\
452\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000453Return the tuple ((x-x%y)/y, x%y). Invariant: div*y + mod == x.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000454
455
Guido van Rossum79f25d91997-04-29 20:08:16 +0000456static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000457builtin_eval(PyObject *self, PyObject *args)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000458{
Just van Rossum3aaf42c2003-02-10 08:21:10 +0000459 PyObject *cmd, *result, *tmp = NULL;
Guido van Rossum79f25d91997-04-29 20:08:16 +0000460 PyObject *globals = Py_None, *locals = Py_None;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000461 char *str;
Tim Peters9fa96be2001-08-17 23:04:59 +0000462 PyCompilerFlags cf;
Guido van Rossum590baa41993-11-30 13:40:46 +0000463
Raymond Hettinger214b1c32004-07-02 06:41:07 +0000464 if (!PyArg_UnpackTuple(args, "eval", 1, 3, &cmd, &globals, &locals))
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000465 return NULL;
Raymond Hettinger214b1c32004-07-02 06:41:07 +0000466 if (locals != Py_None && !PyMapping_Check(locals)) {
467 PyErr_SetString(PyExc_TypeError, "locals must be a mapping");
Raymond Hettinger513ffe82004-07-06 13:44:41 +0000468 return NULL;
Raymond Hettinger214b1c32004-07-02 06:41:07 +0000469 }
470 if (globals != Py_None && !PyDict_Check(globals)) {
Georg Brandl99d7e4e2005-08-31 22:21:15 +0000471 PyErr_SetString(PyExc_TypeError, PyMapping_Check(globals) ?
Raymond Hettinger214b1c32004-07-02 06:41:07 +0000472 "globals must be a real dict; try eval(expr, {}, mapping)"
473 : "globals must be a dict");
Raymond Hettinger513ffe82004-07-06 13:44:41 +0000474 return NULL;
Raymond Hettinger214b1c32004-07-02 06:41:07 +0000475 }
Guido van Rossum79f25d91997-04-29 20:08:16 +0000476 if (globals == Py_None) {
477 globals = PyEval_GetGlobals();
478 if (locals == Py_None)
479 locals = PyEval_GetLocals();
Guido van Rossum6135a871995-01-09 17:53:26 +0000480 }
Guido van Rossum79f25d91997-04-29 20:08:16 +0000481 else if (locals == Py_None)
Guido van Rossum6135a871995-01-09 17:53:26 +0000482 locals = globals;
Tim Peters9fa96be2001-08-17 23:04:59 +0000483
Georg Brandl77c85e62005-09-15 10:46:13 +0000484 if (globals == NULL || locals == NULL) {
485 PyErr_SetString(PyExc_TypeError,
486 "eval must be given globals and locals "
487 "when called without a frame");
488 return NULL;
489 }
490
Guido van Rossum79f25d91997-04-29 20:08:16 +0000491 if (PyDict_GetItemString(globals, "__builtins__") == NULL) {
492 if (PyDict_SetItemString(globals, "__builtins__",
493 PyEval_GetBuiltins()) != 0)
Guido van Rossum6135a871995-01-09 17:53:26 +0000494 return NULL;
495 }
Tim Peters9fa96be2001-08-17 23:04:59 +0000496
Jeremy Hylton15c1c4f2001-07-30 21:50:55 +0000497 if (PyCode_Check(cmd)) {
Jeremy Hylton733c8932001-12-13 19:51:56 +0000498 if (PyCode_GetNumFree((PyCodeObject *)cmd) > 0) {
Jeremy Hylton15c1c4f2001-07-30 21:50:55 +0000499 PyErr_SetString(PyExc_TypeError,
500 "code object passed to eval() may not contain free variables");
501 return NULL;
502 }
Guido van Rossum79f25d91997-04-29 20:08:16 +0000503 return PyEval_EvalCode((PyCodeObject *) cmd, globals, locals);
Jeremy Hylton15c1c4f2001-07-30 21:50:55 +0000504 }
Tim Peters9fa96be2001-08-17 23:04:59 +0000505
Marc-André Lemburgd1ba4432000-09-19 21:04:18 +0000506 if (!PyString_Check(cmd) &&
507 !PyUnicode_Check(cmd)) {
Guido van Rossum79f25d91997-04-29 20:08:16 +0000508 PyErr_SetString(PyExc_TypeError,
Fred Drake661ea262000-10-24 19:57:45 +0000509 "eval() arg 1 must be a string or code object");
Guido van Rossum94390a41992-08-14 15:14:30 +0000510 return NULL;
511 }
Just van Rossum3aaf42c2003-02-10 08:21:10 +0000512 cf.cf_flags = 0;
513
514#ifdef Py_USING_UNICODE
515 if (PyUnicode_Check(cmd)) {
516 tmp = PyUnicode_AsUTF8String(cmd);
517 if (tmp == NULL)
518 return NULL;
519 cmd = tmp;
520 cf.cf_flags |= PyCF_SOURCE_IS_UTF8;
521 }
522#endif
Neal Norwitz3a9a3e72005-11-27 20:38:31 +0000523 if (PyString_AsStringAndSize(cmd, &str, NULL)) {
524 Py_XDECREF(tmp);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000525 return NULL;
Neal Norwitz3a9a3e72005-11-27 20:38:31 +0000526 }
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000527 while (*str == ' ' || *str == '\t')
528 str++;
Tim Peters9fa96be2001-08-17 23:04:59 +0000529
Tim Peters9fa96be2001-08-17 23:04:59 +0000530 (void)PyEval_MergeCompilerFlags(&cf);
Just van Rossum3aaf42c2003-02-10 08:21:10 +0000531 result = PyRun_StringFlags(str, Py_eval_input, globals, locals, &cf);
532 Py_XDECREF(tmp);
533 return result;
Guido van Rossum3f5da241990-12-20 15:06:42 +0000534}
535
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000536PyDoc_STRVAR(eval_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000537"eval(source[, globals[, locals]]) -> value\n\
538\n\
539Evaluate the source in the context of globals and locals.\n\
540The source may be a string representing a Python expression\n\
541or a code object as returned by compile().\n\
Raymond Hettinger214b1c32004-07-02 06:41:07 +0000542The globals must be a dictionary and locals can be any mappping,\n\
543defaulting to the current globals and locals.\n\
544If only globals is given, locals defaults to it.\n");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000545
Georg Brandl7cae87c2006-09-06 06:51:57 +0000546static PyObject *
547builtin_exec(PyObject *self, PyObject *args)
548{
549 PyObject *v;
550 PyObject *prog, *globals = Py_None, *locals = Py_None;
551 int plain = 0;
552
553 if (!PyArg_ParseTuple(args, "O|OO:exec", &prog, &globals, &locals))
554 return NULL;
555
556 if (globals == Py_None) {
557 globals = PyEval_GetGlobals();
558 if (locals == Py_None) {
559 locals = PyEval_GetLocals();
560 plain = 1;
561 }
562 if (!globals || !locals) {
563 PyErr_SetString(PyExc_SystemError,
564 "globals and locals cannot be NULL");
565 return NULL;
566 }
567 }
568 else if (locals == Py_None)
569 locals = globals;
570 if (!PyString_Check(prog) &&
571 !PyUnicode_Check(prog) &&
572 !PyCode_Check(prog) &&
573 !PyFile_Check(prog)) {
574 PyErr_Format(PyExc_TypeError,
575 "exec() arg 1 must be a string, file, or code "
576 "object, not %.100s", prog->ob_type->tp_name);
577 return NULL;
578 }
579 if (!PyDict_Check(globals)) {
580 PyErr_Format(PyExc_TypeError, "exec() arg 2 must be a dict, not %.100s",
581 globals->ob_type->tp_name);
582 return NULL;
583 }
584 if (!PyMapping_Check(locals)) {
585 PyErr_Format(PyExc_TypeError,
586 "arg 3 must be a mapping or None, not %.100s",
587 locals->ob_type->tp_name);
588 return NULL;
589 }
590 if (PyDict_GetItemString(globals, "__builtins__") == NULL) {
591 if (PyDict_SetItemString(globals, "__builtins__",
592 PyEval_GetBuiltins()) != 0)
593 return NULL;
594 }
595
596 if (PyCode_Check(prog)) {
597 if (PyCode_GetNumFree((PyCodeObject *)prog) > 0) {
598 PyErr_SetString(PyExc_TypeError,
599 "code object passed to exec() may not "
600 "contain free variables");
601 return NULL;
602 }
603 v = PyEval_EvalCode((PyCodeObject *) prog, globals, locals);
604 }
605 else if (PyFile_Check(prog)) {
606 FILE *fp = PyFile_AsFile(prog);
607 char *name = PyString_AsString(PyFile_Name(prog));
608 PyCompilerFlags cf;
609 cf.cf_flags = 0;
610 if (PyEval_MergeCompilerFlags(&cf))
611 v = PyRun_FileFlags(fp, name, Py_file_input, globals,
612 locals, &cf);
613 else
614 v = PyRun_File(fp, name, Py_file_input, globals,
615 locals);
616 }
617 else {
618 PyObject *tmp = NULL;
619 char *str;
620 PyCompilerFlags cf;
621 cf.cf_flags = 0;
622#ifdef Py_USING_UNICODE
623 if (PyUnicode_Check(prog)) {
624 tmp = PyUnicode_AsUTF8String(prog);
625 if (tmp == NULL)
626 return NULL;
627 prog = tmp;
628 cf.cf_flags |= PyCF_SOURCE_IS_UTF8;
629 }
630#endif
631 if (PyString_AsStringAndSize(prog, &str, NULL))
632 return NULL;
633 if (PyEval_MergeCompilerFlags(&cf))
634 v = PyRun_StringFlags(str, Py_file_input, globals,
635 locals, &cf);
636 else
637 v = PyRun_String(str, Py_file_input, globals, locals);
638 Py_XDECREF(tmp);
639 }
640 if (v == NULL)
641 return NULL;
642 Py_DECREF(v);
643 Py_RETURN_NONE;
644}
645
646PyDoc_STRVAR(exec_doc,
647"exec(object[, globals[, locals]])\n\
648\n\
649Read and execute code from a object, which can be a string, a code\n\
650object or a file object.\n\
651The globals and locals are dictionaries, defaulting to the current\n\
652globals and locals. If only globals is given, locals defaults to it.");
653
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000654
Guido van Rossum79f25d91997-04-29 20:08:16 +0000655static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000656builtin_execfile(PyObject *self, PyObject *args)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000657{
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000658 char *filename;
Guido van Rossum79f25d91997-04-29 20:08:16 +0000659 PyObject *globals = Py_None, *locals = Py_None;
660 PyObject *res;
Guido van Rossumb3a639e2001-09-05 13:37:47 +0000661 FILE* fp = NULL;
Tim Peters5ba58662001-07-16 02:29:45 +0000662 PyCompilerFlags cf;
Martin v. Löwis6b3a2c42001-08-08 05:30:36 +0000663 int exists;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000664
Raymond Hettinger66bd2332004-08-02 08:30:07 +0000665 if (!PyArg_ParseTuple(args, "s|O!O:execfile",
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000666 &filename,
Guido van Rossum79f25d91997-04-29 20:08:16 +0000667 &PyDict_Type, &globals,
Raymond Hettinger66bd2332004-08-02 08:30:07 +0000668 &locals))
Guido van Rossum0f61f8a1992-02-25 18:55:05 +0000669 return NULL;
Raymond Hettinger66bd2332004-08-02 08:30:07 +0000670 if (locals != Py_None && !PyMapping_Check(locals)) {
671 PyErr_SetString(PyExc_TypeError, "locals must be a mapping");
672 return NULL;
673 }
Guido van Rossum79f25d91997-04-29 20:08:16 +0000674 if (globals == Py_None) {
675 globals = PyEval_GetGlobals();
676 if (locals == Py_None)
677 locals = PyEval_GetLocals();
Guido van Rossum6135a871995-01-09 17:53:26 +0000678 }
Guido van Rossum79f25d91997-04-29 20:08:16 +0000679 else if (locals == Py_None)
Guido van Rossum6135a871995-01-09 17:53:26 +0000680 locals = globals;
Guido van Rossum79f25d91997-04-29 20:08:16 +0000681 if (PyDict_GetItemString(globals, "__builtins__") == NULL) {
682 if (PyDict_SetItemString(globals, "__builtins__",
683 PyEval_GetBuiltins()) != 0)
Guido van Rossum6135a871995-01-09 17:53:26 +0000684 return NULL;
685 }
Martin v. Löwis6b3a2c42001-08-08 05:30:36 +0000686
687 exists = 0;
688 /* Test for existence or directory. */
Martin v. Löwis3484a182002-03-09 12:07:51 +0000689#if defined(PLAN9)
690 {
691 Dir *d;
692
693 if ((d = dirstat(filename))!=nil) {
694 if(d->mode & DMDIR)
695 werrstr("is a directory");
696 else
697 exists = 1;
698 free(d);
699 }
Martin v. Löwis6b3a2c42001-08-08 05:30:36 +0000700 }
Martin v. Löwis3484a182002-03-09 12:07:51 +0000701#elif defined(RISCOS)
Guido van Rossume2ae77b2001-10-24 20:42:55 +0000702 if (object_exists(filename)) {
703 if (isdir(filename))
704 errno = EISDIR;
705 else
706 exists = 1;
707 }
Martin v. Löwis3484a182002-03-09 12:07:51 +0000708#else /* standard Posix */
709 {
710 struct stat s;
711 if (stat(filename, &s) == 0) {
712 if (S_ISDIR(s.st_mode))
Andrew MacIntyreda4d6cb2004-03-29 11:53:38 +0000713# if defined(PYOS_OS2) && defined(PYCC_VACPP)
Martin v. Löwis3484a182002-03-09 12:07:51 +0000714 errno = EOS2ERR;
715# else
716 errno = EISDIR;
717# endif
718 else
719 exists = 1;
720 }
721 }
722#endif
Martin v. Löwis6b3a2c42001-08-08 05:30:36 +0000723
724 if (exists) {
725 Py_BEGIN_ALLOW_THREADS
Jack Jansen7b8c7542002-04-14 20:12:41 +0000726 fp = fopen(filename, "r" PY_STDIOTEXTMODE);
Martin v. Löwis6b3a2c42001-08-08 05:30:36 +0000727 Py_END_ALLOW_THREADS
728
729 if (fp == NULL) {
730 exists = 0;
731 }
732 }
733
734 if (!exists) {
Peter Schneider-Kamp4c013422002-08-27 16:58:00 +0000735 PyErr_SetFromErrnoWithFilename(PyExc_IOError, filename);
Guido van Rossum0f61f8a1992-02-25 18:55:05 +0000736 return NULL;
737 }
Tim Peters5ba58662001-07-16 02:29:45 +0000738 cf.cf_flags = 0;
739 if (PyEval_MergeCompilerFlags(&cf))
Tim Peters748b8bb2001-04-28 08:20:22 +0000740 res = PyRun_FileExFlags(fp, filename, Py_file_input, globals,
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000741 locals, 1, &cf);
Tim Peters5ba58662001-07-16 02:29:45 +0000742 else
Tim Peters748b8bb2001-04-28 08:20:22 +0000743 res = PyRun_FileEx(fp, filename, Py_file_input, globals,
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000744 locals, 1);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000745 return res;
Guido van Rossum0f61f8a1992-02-25 18:55:05 +0000746}
747
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000748PyDoc_STRVAR(execfile_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000749"execfile(filename[, globals[, locals]])\n\
750\n\
751Read and execute a Python script from a file.\n\
752The globals and locals are dictionaries, defaulting to the current\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000753globals and locals. If only globals is given, locals defaults to it.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000754
755
Guido van Rossum79f25d91997-04-29 20:08:16 +0000756static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000757builtin_getattr(PyObject *self, PyObject *args)
Guido van Rossum33894be1992-01-27 16:53:09 +0000758{
Guido van Rossum950ff291998-06-29 13:38:57 +0000759 PyObject *v, *result, *dflt = NULL;
Guido van Rossum79f25d91997-04-29 20:08:16 +0000760 PyObject *name;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000761
Raymond Hettingerea3fdf42002-12-29 16:33:45 +0000762 if (!PyArg_UnpackTuple(args, "getattr", 2, 3, &v, &name, &dflt))
Guido van Rossum33894be1992-01-27 16:53:09 +0000763 return NULL;
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000764#ifdef Py_USING_UNICODE
Jeremy Hylton0eb11152001-07-30 22:39:31 +0000765 if (PyUnicode_Check(name)) {
766 name = _PyUnicode_AsDefaultEncodedString(name, NULL);
767 if (name == NULL)
768 return NULL;
769 }
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000770#endif
Jeremy Hylton0eb11152001-07-30 22:39:31 +0000771
772 if (!PyString_Check(name)) {
773 PyErr_SetString(PyExc_TypeError,
Alex Martellia9b9c9f2003-04-23 13:34:35 +0000774 "getattr(): attribute name must be string");
Jeremy Hylton0eb11152001-07-30 22:39:31 +0000775 return NULL;
776 }
Guido van Rossum950ff291998-06-29 13:38:57 +0000777 result = PyObject_GetAttr(v, name);
Guido van Rossumd8923572001-10-16 21:31:32 +0000778 if (result == NULL && dflt != NULL &&
779 PyErr_ExceptionMatches(PyExc_AttributeError))
780 {
Guido van Rossum950ff291998-06-29 13:38:57 +0000781 PyErr_Clear();
782 Py_INCREF(dflt);
783 result = dflt;
784 }
785 return result;
Guido van Rossum9bfef441993-03-29 10:43:31 +0000786}
787
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000788PyDoc_STRVAR(getattr_doc,
Guido van Rossum950ff291998-06-29 13:38:57 +0000789"getattr(object, name[, default]) -> value\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000790\n\
Guido van Rossum950ff291998-06-29 13:38:57 +0000791Get a named attribute from an object; getattr(x, 'y') is equivalent to x.y.\n\
792When a default argument is given, it is returned when the attribute doesn't\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000793exist; without it, an exception is raised in that case.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000794
795
Guido van Rossum79f25d91997-04-29 20:08:16 +0000796static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000797builtin_globals(PyObject *self)
Guido van Rossum872537c1995-07-07 22:43:42 +0000798{
Guido van Rossum79f25d91997-04-29 20:08:16 +0000799 PyObject *d;
Guido van Rossum872537c1995-07-07 22:43:42 +0000800
Guido van Rossum79f25d91997-04-29 20:08:16 +0000801 d = PyEval_GetGlobals();
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000802 Py_XINCREF(d);
Guido van Rossum872537c1995-07-07 22:43:42 +0000803 return d;
804}
805
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000806PyDoc_STRVAR(globals_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000807"globals() -> dictionary\n\
808\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000809Return the dictionary containing the current scope's global variables.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000810
811
Guido van Rossum79f25d91997-04-29 20:08:16 +0000812static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000813builtin_hasattr(PyObject *self, PyObject *args)
Guido van Rossum9bfef441993-03-29 10:43:31 +0000814{
Guido van Rossum79f25d91997-04-29 20:08:16 +0000815 PyObject *v;
816 PyObject *name;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000817
Raymond Hettingerea3fdf42002-12-29 16:33:45 +0000818 if (!PyArg_UnpackTuple(args, "hasattr", 2, 2, &v, &name))
Guido van Rossum9bfef441993-03-29 10:43:31 +0000819 return NULL;
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000820#ifdef Py_USING_UNICODE
Jeremy Hylton302b54a2001-07-30 22:45:19 +0000821 if (PyUnicode_Check(name)) {
822 name = _PyUnicode_AsDefaultEncodedString(name, NULL);
823 if (name == NULL)
824 return NULL;
825 }
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000826#endif
Jeremy Hylton302b54a2001-07-30 22:45:19 +0000827
828 if (!PyString_Check(name)) {
829 PyErr_SetString(PyExc_TypeError,
Alex Martellia9b9c9f2003-04-23 13:34:35 +0000830 "hasattr(): attribute name must be string");
Jeremy Hylton302b54a2001-07-30 22:45:19 +0000831 return NULL;
832 }
Guido van Rossum79f25d91997-04-29 20:08:16 +0000833 v = PyObject_GetAttr(v, name);
Guido van Rossum9bfef441993-03-29 10:43:31 +0000834 if (v == NULL) {
Guido van Rossum79f25d91997-04-29 20:08:16 +0000835 PyErr_Clear();
Guido van Rossum09df08a1998-05-22 00:51:39 +0000836 Py_INCREF(Py_False);
837 return Py_False;
Guido van Rossum9bfef441993-03-29 10:43:31 +0000838 }
Guido van Rossum79f25d91997-04-29 20:08:16 +0000839 Py_DECREF(v);
Guido van Rossum09df08a1998-05-22 00:51:39 +0000840 Py_INCREF(Py_True);
841 return Py_True;
Guido van Rossum33894be1992-01-27 16:53:09 +0000842}
843
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000844PyDoc_STRVAR(hasattr_doc,
Guido van Rossum77f6a652002-04-03 22:41:51 +0000845"hasattr(object, name) -> bool\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000846\n\
847Return whether the object has an attribute with the given name.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000848(This is done by calling getattr(object, name) and catching exceptions.)");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000849
850
Guido van Rossum79f25d91997-04-29 20:08:16 +0000851static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000852builtin_id(PyObject *self, PyObject *v)
Guido van Rossum5b722181993-03-30 17:46:03 +0000853{
Guido van Rossum106f2da2000-06-28 21:12:25 +0000854 return PyLong_FromVoidPtr(v);
Guido van Rossum5b722181993-03-30 17:46:03 +0000855}
856
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000857PyDoc_STRVAR(id_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000858"id(object) -> integer\n\
859\n\
860Return the identity of an object. This is guaranteed to be unique among\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000861simultaneously existing objects. (Hint: it's the object's memory address.)");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +0000862
863
Guido van Rossum79f25d91997-04-29 20:08:16 +0000864static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000865builtin_map(PyObject *self, PyObject *args)
Guido van Rossum12d12c51993-10-26 17:58:25 +0000866{
867 typedef struct {
Tim Peters4e9afdc2001-05-03 23:54:49 +0000868 PyObject *it; /* the iterator object */
869 int saw_StopIteration; /* bool: did the iterator end? */
Guido van Rossum12d12c51993-10-26 17:58:25 +0000870 } sequence;
871
Guido van Rossum79f25d91997-04-29 20:08:16 +0000872 PyObject *func, *result;
Guido van Rossum12d12c51993-10-26 17:58:25 +0000873 sequence *seqs = NULL, *sqp;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000874 Py_ssize_t n, len;
Guido van Rossum12d12c51993-10-26 17:58:25 +0000875 register int i, j;
876
Guido van Rossum79f25d91997-04-29 20:08:16 +0000877 n = PyTuple_Size(args);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000878 if (n < 2) {
Guido van Rossum79f25d91997-04-29 20:08:16 +0000879 PyErr_SetString(PyExc_TypeError,
880 "map() requires at least two args");
Guido van Rossum12d12c51993-10-26 17:58:25 +0000881 return NULL;
882 }
883
Guido van Rossum79f25d91997-04-29 20:08:16 +0000884 func = PyTuple_GetItem(args, 0);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000885 n--;
Guido van Rossum12d12c51993-10-26 17:58:25 +0000886
Guido van Rossumfa4ac711998-07-10 17:37:30 +0000887 if (func == Py_None && n == 1) {
888 /* map(None, S) is the same as list(S). */
889 return PySequence_List(PyTuple_GetItem(args, 1));
890 }
891
Tim Peters4e9afdc2001-05-03 23:54:49 +0000892 /* Get space for sequence descriptors. Must NULL out the iterator
893 * pointers so that jumping to Fail_2 later doesn't see trash.
894 */
Guido van Rossum79f25d91997-04-29 20:08:16 +0000895 if ((seqs = PyMem_NEW(sequence, n)) == NULL) {
896 PyErr_NoMemory();
Tim Peters4e9afdc2001-05-03 23:54:49 +0000897 return NULL;
898 }
899 for (i = 0; i < n; ++i) {
900 seqs[i].it = (PyObject*)NULL;
901 seqs[i].saw_StopIteration = 0;
Guido van Rossumdc4b93d1993-10-27 14:56:44 +0000902 }
Guido van Rossum12d12c51993-10-26 17:58:25 +0000903
Tim Peters4e9afdc2001-05-03 23:54:49 +0000904 /* Do a first pass to obtain iterators for the arguments, and set len
905 * to the largest of their lengths.
Tim Peters748b8bb2001-04-28 08:20:22 +0000906 */
Tim Peters4e9afdc2001-05-03 23:54:49 +0000907 len = 0;
908 for (i = 0, sqp = seqs; i < n; ++i, ++sqp) {
909 PyObject *curseq;
Martin v. Löwisd96ee902006-02-16 14:37:16 +0000910 Py_ssize_t curlen;
Guido van Rossumad991772001-01-12 16:03:05 +0000911
Tim Peters4e9afdc2001-05-03 23:54:49 +0000912 /* Get iterator. */
913 curseq = PyTuple_GetItem(args, i+1);
914 sqp->it = PyObject_GetIter(curseq);
915 if (sqp->it == NULL) {
Guido van Rossum12d12c51993-10-26 17:58:25 +0000916 static char errmsg[] =
Tim Peters4e9afdc2001-05-03 23:54:49 +0000917 "argument %d to map() must support iteration";
Guido van Rossum15e33a41997-04-30 19:00:27 +0000918 char errbuf[sizeof(errmsg) + 25];
Jeremy Hylton518ab1c2001-11-28 20:42:20 +0000919 PyOS_snprintf(errbuf, sizeof(errbuf), errmsg, i+2);
Guido van Rossum79f25d91997-04-29 20:08:16 +0000920 PyErr_SetString(PyExc_TypeError, errbuf);
Guido van Rossum12d12c51993-10-26 17:58:25 +0000921 goto Fail_2;
922 }
923
Tim Peters4e9afdc2001-05-03 23:54:49 +0000924 /* Update len. */
Armin Rigof5b3e362006-02-11 21:32:43 +0000925 curlen = _PyObject_LengthHint(curseq);
Raymond Hettinger77f3c872004-01-04 08:54:44 +0000926 if (curlen < 0) {
Raymond Hettingera710b332005-08-21 11:03:59 +0000927 if (!PyErr_ExceptionMatches(PyExc_TypeError) &&
928 !PyErr_ExceptionMatches(PyExc_AttributeError)) {
929 goto Fail_2;
930 }
Raymond Hettinger77f3c872004-01-04 08:54:44 +0000931 PyErr_Clear();
Tim Peters4e9afdc2001-05-03 23:54:49 +0000932 curlen = 8; /* arbitrary */
Raymond Hettinger77f3c872004-01-04 08:54:44 +0000933 }
934 if (curlen > len)
935 len = curlen;
Guido van Rossum12d12c51993-10-26 17:58:25 +0000936 }
937
Tim Peters4e9afdc2001-05-03 23:54:49 +0000938 /* Get space for the result list. */
Guido van Rossum79f25d91997-04-29 20:08:16 +0000939 if ((result = (PyObject *) PyList_New(len)) == NULL)
Guido van Rossum12d12c51993-10-26 17:58:25 +0000940 goto Fail_2;
941
Tim Peters4e9afdc2001-05-03 23:54:49 +0000942 /* Iterate over the sequences until all have stopped. */
Guido van Rossum2d951851994-08-29 12:52:16 +0000943 for (i = 0; ; ++i) {
Guido van Rossum79f25d91997-04-29 20:08:16 +0000944 PyObject *alist, *item=NULL, *value;
Tim Peters4e9afdc2001-05-03 23:54:49 +0000945 int numactive = 0;
Guido van Rossum12d12c51993-10-26 17:58:25 +0000946
Guido van Rossum79f25d91997-04-29 20:08:16 +0000947 if (func == Py_None && n == 1)
Guido van Rossum32120311995-07-10 13:52:21 +0000948 alist = NULL;
Tim Peters4e9afdc2001-05-03 23:54:49 +0000949 else if ((alist = PyTuple_New(n)) == NULL)
950 goto Fail_1;
Guido van Rossum12d12c51993-10-26 17:58:25 +0000951
952 for (j = 0, sqp = seqs; j < n; ++j, ++sqp) {
Tim Peters4e9afdc2001-05-03 23:54:49 +0000953 if (sqp->saw_StopIteration) {
Guido van Rossum79f25d91997-04-29 20:08:16 +0000954 Py_INCREF(Py_None);
955 item = Py_None;
Guido van Rossum12d12c51993-10-26 17:58:25 +0000956 }
Guido van Rossum12d12c51993-10-26 17:58:25 +0000957 else {
Tim Peters4e9afdc2001-05-03 23:54:49 +0000958 item = PyIter_Next(sqp->it);
959 if (item)
960 ++numactive;
961 else {
Tim Peters4e9afdc2001-05-03 23:54:49 +0000962 if (PyErr_Occurred()) {
Tim Petersf4848da2001-05-05 00:14:56 +0000963 Py_XDECREF(alist);
964 goto Fail_1;
Guido van Rossum2d951851994-08-29 12:52:16 +0000965 }
Tim Peters4e9afdc2001-05-03 23:54:49 +0000966 Py_INCREF(Py_None);
967 item = Py_None;
968 sqp->saw_StopIteration = 1;
Guido van Rossum2d951851994-08-29 12:52:16 +0000969 }
Guido van Rossum12d12c51993-10-26 17:58:25 +0000970 }
Tim Peters4e9afdc2001-05-03 23:54:49 +0000971 if (alist)
972 PyTuple_SET_ITEM(alist, j, item);
973 else
Guido van Rossum2d951851994-08-29 12:52:16 +0000974 break;
Guido van Rossum12d12c51993-10-26 17:58:25 +0000975 }
976
Guido van Rossum32120311995-07-10 13:52:21 +0000977 if (!alist)
978 alist = item;
Guido van Rossum2d951851994-08-29 12:52:16 +0000979
Tim Peters4e9afdc2001-05-03 23:54:49 +0000980 if (numactive == 0) {
Guido van Rossum79f25d91997-04-29 20:08:16 +0000981 Py_DECREF(alist);
Guido van Rossum2d951851994-08-29 12:52:16 +0000982 break;
Guido van Rossum12d12c51993-10-26 17:58:25 +0000983 }
Guido van Rossum2d951851994-08-29 12:52:16 +0000984
Guido van Rossum79f25d91997-04-29 20:08:16 +0000985 if (func == Py_None)
Guido van Rossum32120311995-07-10 13:52:21 +0000986 value = alist;
Guido van Rossum12d12c51993-10-26 17:58:25 +0000987 else {
Guido van Rossum79f25d91997-04-29 20:08:16 +0000988 value = PyEval_CallObject(func, alist);
989 Py_DECREF(alist);
Guido van Rossumdc4b93d1993-10-27 14:56:44 +0000990 if (value == NULL)
991 goto Fail_1;
Guido van Rossum2d951851994-08-29 12:52:16 +0000992 }
993 if (i >= len) {
Barry Warsawfa77e091999-01-28 18:49:12 +0000994 int status = PyList_Append(result, value);
Barry Warsaw21332871999-01-28 04:21:35 +0000995 Py_DECREF(value);
Barry Warsawfa77e091999-01-28 18:49:12 +0000996 if (status < 0)
997 goto Fail_1;
Guido van Rossum2d951851994-08-29 12:52:16 +0000998 }
Tim Peters4e9afdc2001-05-03 23:54:49 +0000999 else if (PyList_SetItem(result, i, value) < 0)
1000 goto Fail_1;
Guido van Rossum12d12c51993-10-26 17:58:25 +00001001 }
1002
Guido van Rossumfa4ac711998-07-10 17:37:30 +00001003 if (i < len && PyList_SetSlice(result, i, len, NULL) < 0)
1004 goto Fail_1;
1005
Tim Peters4e9afdc2001-05-03 23:54:49 +00001006 goto Succeed;
Guido van Rossum12d12c51993-10-26 17:58:25 +00001007
Guido van Rossum12d12c51993-10-26 17:58:25 +00001008Fail_1:
Guido van Rossum79f25d91997-04-29 20:08:16 +00001009 Py_DECREF(result);
Guido van Rossum12d12c51993-10-26 17:58:25 +00001010Fail_2:
Tim Peters4e9afdc2001-05-03 23:54:49 +00001011 result = NULL;
1012Succeed:
1013 assert(seqs);
1014 for (i = 0; i < n; ++i)
1015 Py_XDECREF(seqs[i].it);
1016 PyMem_DEL(seqs);
1017 return result;
Guido van Rossum12d12c51993-10-26 17:58:25 +00001018}
1019
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001020PyDoc_STRVAR(map_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001021"map(function, sequence[, sequence, ...]) -> list\n\
1022\n\
1023Return a list of the results of applying the function to the items of\n\
1024the argument sequence(s). If more than one sequence is given, the\n\
1025function is called with an argument list consisting of the corresponding\n\
1026item of each sequence, substituting None for missing values when not all\n\
1027sequences have the same length. If the function is None, return a list of\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001028the items of the sequence (or a list of tuples if more than one sequence).");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001029
1030
Guido van Rossum79f25d91997-04-29 20:08:16 +00001031static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001032builtin_setattr(PyObject *self, PyObject *args)
Guido van Rossum33894be1992-01-27 16:53:09 +00001033{
Guido van Rossum79f25d91997-04-29 20:08:16 +00001034 PyObject *v;
1035 PyObject *name;
1036 PyObject *value;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001037
Raymond Hettingerea3fdf42002-12-29 16:33:45 +00001038 if (!PyArg_UnpackTuple(args, "setattr", 3, 3, &v, &name, &value))
Guido van Rossum33894be1992-01-27 16:53:09 +00001039 return NULL;
Guido van Rossum79f25d91997-04-29 20:08:16 +00001040 if (PyObject_SetAttr(v, name, value) != 0)
Guido van Rossum33894be1992-01-27 16:53:09 +00001041 return NULL;
Guido van Rossum79f25d91997-04-29 20:08:16 +00001042 Py_INCREF(Py_None);
1043 return Py_None;
Guido van Rossum33894be1992-01-27 16:53:09 +00001044}
1045
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001046PyDoc_STRVAR(setattr_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001047"setattr(object, name, value)\n\
1048\n\
1049Set a named attribute on an object; setattr(x, 'y', v) is equivalent to\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001050``x.y = v''.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001051
1052
Guido van Rossum79f25d91997-04-29 20:08:16 +00001053static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001054builtin_delattr(PyObject *self, PyObject *args)
Guido van Rossum14144fc1994-08-29 12:53:40 +00001055{
Guido van Rossum79f25d91997-04-29 20:08:16 +00001056 PyObject *v;
1057 PyObject *name;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001058
Raymond Hettingerea3fdf42002-12-29 16:33:45 +00001059 if (!PyArg_UnpackTuple(args, "delattr", 2, 2, &v, &name))
Guido van Rossum14144fc1994-08-29 12:53:40 +00001060 return NULL;
Guido van Rossum79f25d91997-04-29 20:08:16 +00001061 if (PyObject_SetAttr(v, name, (PyObject *)NULL) != 0)
Guido van Rossum14144fc1994-08-29 12:53:40 +00001062 return NULL;
Guido van Rossum79f25d91997-04-29 20:08:16 +00001063 Py_INCREF(Py_None);
1064 return Py_None;
Guido van Rossum14144fc1994-08-29 12:53:40 +00001065}
1066
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001067PyDoc_STRVAR(delattr_doc,
Guido van Rossumdf12a591998-11-23 22:13:04 +00001068"delattr(object, name)\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001069\n\
1070Delete a named attribute on an object; delattr(x, 'y') is equivalent to\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001071``del x.y''.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001072
1073
Guido van Rossum79f25d91997-04-29 20:08:16 +00001074static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001075builtin_hash(PyObject *self, PyObject *v)
Guido van Rossum9bfef441993-03-29 10:43:31 +00001076{
Guido van Rossum9bfef441993-03-29 10:43:31 +00001077 long x;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001078
Guido van Rossum79f25d91997-04-29 20:08:16 +00001079 x = PyObject_Hash(v);
Guido van Rossum9bfef441993-03-29 10:43:31 +00001080 if (x == -1)
1081 return NULL;
Guido van Rossum79f25d91997-04-29 20:08:16 +00001082 return PyInt_FromLong(x);
Guido van Rossum9bfef441993-03-29 10:43:31 +00001083}
1084
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001085PyDoc_STRVAR(hash_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001086"hash(object) -> integer\n\
1087\n\
1088Return a hash value for the object. Two objects with the same value have\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001089the same hash value. The reverse is not necessarily true, but likely.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001090
1091
Guido van Rossum79f25d91997-04-29 20:08:16 +00001092static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001093builtin_hex(PyObject *self, PyObject *v)
Guido van Rossum006bcd41991-10-24 14:54:44 +00001094{
Guido van Rossum79f25d91997-04-29 20:08:16 +00001095 PyNumberMethods *nb;
Neil Schemenauer3a313e32004-07-19 16:29:17 +00001096 PyObject *res;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001097
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001098 if ((nb = v->ob_type->tp_as_number) == NULL ||
Guido van Rossum1899c2e1992-09-12 11:09:23 +00001099 nb->nb_hex == NULL) {
Guido van Rossum79f25d91997-04-29 20:08:16 +00001100 PyErr_SetString(PyExc_TypeError,
Guido van Rossum1899c2e1992-09-12 11:09:23 +00001101 "hex() argument can't be converted to hex");
1102 return NULL;
Guido van Rossum006bcd41991-10-24 14:54:44 +00001103 }
Neil Schemenauer3a313e32004-07-19 16:29:17 +00001104 res = (*nb->nb_hex)(v);
1105 if (res && !PyString_Check(res)) {
1106 PyErr_Format(PyExc_TypeError,
1107 "__hex__ returned non-string (type %.200s)",
1108 res->ob_type->tp_name);
1109 Py_DECREF(res);
1110 return NULL;
1111 }
1112 return res;
Guido van Rossum006bcd41991-10-24 14:54:44 +00001113}
1114
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001115PyDoc_STRVAR(hex_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001116"hex(number) -> string\n\
1117\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001118Return the hexadecimal representation of an integer or long integer.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001119
1120
Guido van Rossum79f25d91997-04-29 20:08:16 +00001121static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001122builtin_intern(PyObject *self, PyObject *args)
Guido van Rossume8811f81997-02-14 15:48:05 +00001123{
1124 PyObject *s;
Guido van Rossum43713e52000-02-29 13:59:29 +00001125 if (!PyArg_ParseTuple(args, "S:intern", &s))
Guido van Rossume8811f81997-02-14 15:48:05 +00001126 return NULL;
Jeremy Hylton4c989dd2004-08-07 19:20:05 +00001127 if (!PyString_CheckExact(s)) {
1128 PyErr_SetString(PyExc_TypeError,
1129 "can't intern subclass of string");
1130 return NULL;
1131 }
Guido van Rossume8811f81997-02-14 15:48:05 +00001132 Py_INCREF(s);
1133 PyString_InternInPlace(&s);
1134 return s;
1135}
1136
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001137PyDoc_STRVAR(intern_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001138"intern(string) -> string\n\
1139\n\
1140``Intern'' the given string. This enters the string in the (global)\n\
1141table of interned strings whose purpose is to speed up dictionary lookups.\n\
1142Return the string itself or the previously interned string object with the\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001143same value.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001144
1145
Guido van Rossum79f25d91997-04-29 20:08:16 +00001146static PyObject *
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001147builtin_iter(PyObject *self, PyObject *args)
1148{
1149 PyObject *v, *w = NULL;
1150
Raymond Hettingerea3fdf42002-12-29 16:33:45 +00001151 if (!PyArg_UnpackTuple(args, "iter", 1, 2, &v, &w))
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001152 return NULL;
1153 if (w == NULL)
1154 return PyObject_GetIter(v);
1155 if (!PyCallable_Check(v)) {
1156 PyErr_SetString(PyExc_TypeError,
1157 "iter(v, w): v must be callable");
1158 return NULL;
1159 }
1160 return PyCallIter_New(v, w);
1161}
1162
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001163PyDoc_STRVAR(iter_doc,
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001164"iter(collection) -> iterator\n\
1165iter(callable, sentinel) -> iterator\n\
1166\n\
1167Get an iterator from an object. In the first form, the argument must\n\
1168supply its own iterator, or be a sequence.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001169In the second form, the callable is called until it returns the sentinel.");
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001170
1171
1172static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001173builtin_len(PyObject *self, PyObject *v)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001174{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001175 Py_ssize_t res;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001176
Jeremy Hylton03657cf2000-07-12 13:05:33 +00001177 res = PyObject_Size(v);
Guido van Rossum8ea9f4d1998-06-29 22:26:50 +00001178 if (res < 0 && PyErr_Occurred())
1179 return NULL;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001180 return PyInt_FromSsize_t(res);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001181}
1182
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001183PyDoc_STRVAR(len_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001184"len(object) -> integer\n\
1185\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001186Return the number of items of a sequence or mapping.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001187
1188
Guido van Rossum79f25d91997-04-29 20:08:16 +00001189static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001190builtin_locals(PyObject *self)
Guido van Rossum872537c1995-07-07 22:43:42 +00001191{
Guido van Rossum79f25d91997-04-29 20:08:16 +00001192 PyObject *d;
Guido van Rossum872537c1995-07-07 22:43:42 +00001193
Guido van Rossum79f25d91997-04-29 20:08:16 +00001194 d = PyEval_GetLocals();
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00001195 Py_XINCREF(d);
Guido van Rossum872537c1995-07-07 22:43:42 +00001196 return d;
1197}
1198
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001199PyDoc_STRVAR(locals_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001200"locals() -> dictionary\n\
1201\n\
Raymond Hettinger69bf8f32003-01-04 02:16:22 +00001202Update and return a dictionary containing the current scope's local variables.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001203
1204
Guido van Rossum79f25d91997-04-29 20:08:16 +00001205static PyObject *
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001206min_max(PyObject *args, PyObject *kwds, int op)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001207{
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001208 PyObject *v, *it, *item, *val, *maxitem, *maxval, *keyfunc=NULL;
Martin v. Löwisfd39ad42004-08-12 14:42:37 +00001209 const char *name = op == Py_LT ? "min" : "max";
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001210
Guido van Rossum79f25d91997-04-29 20:08:16 +00001211 if (PyTuple_Size(args) > 1)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001212 v = args;
Martin v. Löwisfd39ad42004-08-12 14:42:37 +00001213 else if (!PyArg_UnpackTuple(args, (char *)name, 1, 1, &v))
Guido van Rossum3f5da241990-12-20 15:06:42 +00001214 return NULL;
Tim Peters67d687a2002-04-29 21:27:32 +00001215
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001216 if (kwds != NULL && PyDict_Check(kwds) && PyDict_Size(kwds)) {
1217 keyfunc = PyDict_GetItemString(kwds, "key");
1218 if (PyDict_Size(kwds)!=1 || keyfunc == NULL) {
Georg Brandl99d7e4e2005-08-31 22:21:15 +00001219 PyErr_Format(PyExc_TypeError,
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001220 "%s() got an unexpected keyword argument", name);
1221 return NULL;
1222 }
Georg Brandl99d7e4e2005-08-31 22:21:15 +00001223 }
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001224
Tim Petersc3074532001-05-03 07:00:32 +00001225 it = PyObject_GetIter(v);
1226 if (it == NULL)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001227 return NULL;
Tim Petersc3074532001-05-03 07:00:32 +00001228
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001229 maxitem = NULL; /* the result */
1230 maxval = NULL; /* the value associated with the result */
Brett Cannon9e635cf2004-12-07 00:25:35 +00001231 while (( item = PyIter_Next(it) )) {
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001232 /* get the value from the key function */
1233 if (keyfunc != NULL) {
1234 val = PyObject_CallFunctionObjArgs(keyfunc, item, NULL);
1235 if (val == NULL)
1236 goto Fail_it_item;
1237 }
1238 /* no key function; the value is the item */
1239 else {
1240 val = item;
1241 Py_INCREF(val);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001242 }
Tim Petersc3074532001-05-03 07:00:32 +00001243
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001244 /* maximum value and item are unset; set them */
1245 if (maxval == NULL) {
1246 maxitem = item;
1247 maxval = val;
1248 }
1249 /* maximum value and item are set; update them as necessary */
Guido van Rossum2d951851994-08-29 12:52:16 +00001250 else {
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001251 int cmp = PyObject_RichCompareBool(val, maxval, op);
1252 if (cmp < 0)
1253 goto Fail_it_item_and_val;
1254 else if (cmp > 0) {
1255 Py_DECREF(maxval);
1256 Py_DECREF(maxitem);
1257 maxval = val;
1258 maxitem = item;
Guido van Rossum53451b32001-01-17 15:47:24 +00001259 }
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001260 else {
1261 Py_DECREF(item);
1262 Py_DECREF(val);
Guido van Rossumc8b6df91997-05-23 00:06:51 +00001263 }
Guido van Rossum2d951851994-08-29 12:52:16 +00001264 }
Guido van Rossum3f5da241990-12-20 15:06:42 +00001265 }
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001266 if (PyErr_Occurred())
1267 goto Fail_it;
1268 if (maxval == NULL) {
Martin v. Löwisfd39ad42004-08-12 14:42:37 +00001269 PyErr_Format(PyExc_ValueError,
1270 "%s() arg is an empty sequence", name);
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001271 assert(maxitem == NULL);
1272 }
1273 else
1274 Py_DECREF(maxval);
Tim Petersc3074532001-05-03 07:00:32 +00001275 Py_DECREF(it);
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001276 return maxitem;
1277
1278Fail_it_item_and_val:
1279 Py_DECREF(val);
1280Fail_it_item:
1281 Py_DECREF(item);
1282Fail_it:
1283 Py_XDECREF(maxval);
1284 Py_XDECREF(maxitem);
1285 Py_DECREF(it);
1286 return NULL;
Guido van Rossum3f5da241990-12-20 15:06:42 +00001287}
1288
Guido van Rossum79f25d91997-04-29 20:08:16 +00001289static PyObject *
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001290builtin_min(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001291{
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001292 return min_max(args, kwds, Py_LT);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001293}
1294
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001295PyDoc_STRVAR(min_doc,
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001296"min(iterable[, key=func]) -> value\n\
1297min(a, b, c, ...[, key=func]) -> value\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001298\n\
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001299With a single iterable argument, return its smallest item.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001300With two or more arguments, return the smallest argument.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001301
1302
Guido van Rossum79f25d91997-04-29 20:08:16 +00001303static PyObject *
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001304builtin_max(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001305{
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001306 return min_max(args, kwds, Py_GT);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001307}
1308
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001309PyDoc_STRVAR(max_doc,
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001310"max(iterable[, key=func]) -> value\n\
1311max(a, b, c, ...[, key=func]) -> value\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001312\n\
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00001313With a single iterable argument, return its largest item.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001314With two or more arguments, return the largest argument.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001315
1316
Guido van Rossum79f25d91997-04-29 20:08:16 +00001317static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001318builtin_oct(PyObject *self, PyObject *v)
Guido van Rossum006bcd41991-10-24 14:54:44 +00001319{
Guido van Rossum79f25d91997-04-29 20:08:16 +00001320 PyNumberMethods *nb;
Neil Schemenauer3a313e32004-07-19 16:29:17 +00001321 PyObject *res;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001322
Guido van Rossum1899c2e1992-09-12 11:09:23 +00001323 if (v == NULL || (nb = v->ob_type->tp_as_number) == NULL ||
1324 nb->nb_oct == NULL) {
Guido van Rossum79f25d91997-04-29 20:08:16 +00001325 PyErr_SetString(PyExc_TypeError,
Guido van Rossum1899c2e1992-09-12 11:09:23 +00001326 "oct() argument can't be converted to oct");
1327 return NULL;
Guido van Rossum006bcd41991-10-24 14:54:44 +00001328 }
Neil Schemenauer3a313e32004-07-19 16:29:17 +00001329 res = (*nb->nb_oct)(v);
1330 if (res && !PyString_Check(res)) {
1331 PyErr_Format(PyExc_TypeError,
1332 "__oct__ returned non-string (type %.200s)",
1333 res->ob_type->tp_name);
1334 Py_DECREF(res);
1335 return NULL;
1336 }
1337 return res;
Guido van Rossum006bcd41991-10-24 14:54:44 +00001338}
1339
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001340PyDoc_STRVAR(oct_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001341"oct(number) -> string\n\
1342\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001343Return the octal representation of an integer or long integer.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001344
1345
Guido van Rossum79f25d91997-04-29 20:08:16 +00001346static PyObject *
Thomas Wouters477c8d52006-05-27 19:21:47 +00001347builtin_open(PyObject *self, PyObject *args, PyObject *kwds)
1348{
1349 return PyObject_Call((PyObject*)&PyFile_Type, args, kwds);
1350}
1351
1352PyDoc_STRVAR(open_doc,
1353"open(name[, mode[, buffering]]) -> file object\n\
1354\n\
1355Open a file using the file() type, returns a file object.");
1356
1357
1358static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001359builtin_ord(PyObject *self, PyObject* obj)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001360{
Guido van Rossum09095f32000-03-10 23:00:52 +00001361 long ord;
Martin v. Löwisd96ee902006-02-16 14:37:16 +00001362 Py_ssize_t size;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001363
Jeremy Hylton394b54d2000-04-12 21:19:47 +00001364 if (PyString_Check(obj)) {
1365 size = PyString_GET_SIZE(obj);
Andrew M. Kuchling34c20cf2000-12-20 14:36:56 +00001366 if (size == 1) {
Jeremy Hylton394b54d2000-04-12 21:19:47 +00001367 ord = (long)((unsigned char)*PyString_AS_STRING(obj));
Andrew M. Kuchling34c20cf2000-12-20 14:36:56 +00001368 return PyInt_FromLong(ord);
1369 }
Martin v. Löwis339d0f72001-08-17 18:39:25 +00001370#ifdef Py_USING_UNICODE
Jeremy Hylton394b54d2000-04-12 21:19:47 +00001371 } else if (PyUnicode_Check(obj)) {
1372 size = PyUnicode_GET_SIZE(obj);
Andrew M. Kuchling34c20cf2000-12-20 14:36:56 +00001373 if (size == 1) {
Jeremy Hylton394b54d2000-04-12 21:19:47 +00001374 ord = (long)*PyUnicode_AS_UNICODE(obj);
Andrew M. Kuchling34c20cf2000-12-20 14:36:56 +00001375 return PyInt_FromLong(ord);
1376 }
Martin v. Löwis339d0f72001-08-17 18:39:25 +00001377#endif
Jeremy Hylton394b54d2000-04-12 21:19:47 +00001378 } else {
1379 PyErr_Format(PyExc_TypeError,
Andrew M. Kuchlingf07aad12000-12-23 14:11:28 +00001380 "ord() expected string of length 1, but " \
Jeremy Hylton394b54d2000-04-12 21:19:47 +00001381 "%.200s found", obj->ob_type->tp_name);
Guido van Rossum09095f32000-03-10 23:00:52 +00001382 return NULL;
1383 }
1384
Guido van Rossumad991772001-01-12 16:03:05 +00001385 PyErr_Format(PyExc_TypeError,
Andrew M. Kuchlingf07aad12000-12-23 14:11:28 +00001386 "ord() expected a character, "
Martin v. Löwisd96ee902006-02-16 14:37:16 +00001387 "but string of length %zd found",
Jeremy Hylton394b54d2000-04-12 21:19:47 +00001388 size);
1389 return NULL;
Guido van Rossum3f5da241990-12-20 15:06:42 +00001390}
1391
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001392PyDoc_STRVAR(ord_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001393"ord(c) -> integer\n\
1394\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001395Return the integer ordinal of a one-character string.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001396
1397
Guido van Rossum79f25d91997-04-29 20:08:16 +00001398static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001399builtin_pow(PyObject *self, PyObject *args)
Guido van Rossum6a00cd81995-01-07 12:39:01 +00001400{
Guido van Rossum09df08a1998-05-22 00:51:39 +00001401 PyObject *v, *w, *z = Py_None;
Guido van Rossum6a00cd81995-01-07 12:39:01 +00001402
Raymond Hettingerea3fdf42002-12-29 16:33:45 +00001403 if (!PyArg_UnpackTuple(args, "pow", 2, 3, &v, &w, &z))
Guido van Rossum6a00cd81995-01-07 12:39:01 +00001404 return NULL;
Guido van Rossum09df08a1998-05-22 00:51:39 +00001405 return PyNumber_Power(v, w, z);
Guido van Rossumd4905451991-05-05 20:00:36 +00001406}
1407
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001408PyDoc_STRVAR(pow_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001409"pow(x, y[, z]) -> number\n\
1410\n\
1411With two arguments, equivalent to x**y. With three arguments,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001412equivalent to (x**y) % z, but may be more efficient (e.g. for longs).");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001413
1414
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001415
1416/* Return number of items in range (lo, hi, step), when arguments are
1417 * PyInt or PyLong objects. step > 0 required. Return a value < 0 if
1418 * & only if the true value is too large to fit in a signed long.
1419 * Arguments MUST return 1 with either PyInt_Check() or
1420 * PyLong_Check(). Return -1 when there is an error.
1421 */
1422static long
1423get_len_of_range_longs(PyObject *lo, PyObject *hi, PyObject *step)
1424{
1425 /* -------------------------------------------------------------
1426 Algorithm is equal to that of get_len_of_range(), but it operates
1427 on PyObjects (which are assumed to be PyLong or PyInt objects).
1428 ---------------------------------------------------------------*/
1429 long n;
1430 PyObject *diff = NULL;
1431 PyObject *one = NULL;
1432 PyObject *tmp1 = NULL, *tmp2 = NULL, *tmp3 = NULL;
1433 /* holds sub-expression evaluations */
1434
Guido van Rossum47b9ff62006-08-24 00:41:19 +00001435 /* If (lo >= hi), return length of 0 (or error). */
1436 n = PyObject_RichCompareBool(lo, hi, Py_LT);
1437 if (n <= 0)
1438 return n;
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001439
1440 if ((one = PyLong_FromLong(1L)) == NULL)
1441 goto Fail;
1442
1443 if ((tmp1 = PyNumber_Subtract(hi, lo)) == NULL)
1444 goto Fail;
1445
1446 if ((diff = PyNumber_Subtract(tmp1, one)) == NULL)
1447 goto Fail;
1448
1449 if ((tmp2 = PyNumber_FloorDivide(diff, step)) == NULL)
1450 goto Fail;
1451
1452 if ((tmp3 = PyNumber_Add(tmp2, one)) == NULL)
1453 goto Fail;
1454
1455 n = PyLong_AsLong(tmp3);
1456 if (PyErr_Occurred()) { /* Check for Overflow */
1457 PyErr_Clear();
1458 goto Fail;
1459 }
1460
1461 Py_DECREF(tmp3);
1462 Py_DECREF(tmp2);
1463 Py_DECREF(diff);
1464 Py_DECREF(tmp1);
1465 Py_DECREF(one);
1466 return n;
1467
1468 Fail:
1469 Py_XDECREF(tmp3);
1470 Py_XDECREF(tmp2);
1471 Py_XDECREF(diff);
1472 Py_XDECREF(tmp1);
1473 Py_XDECREF(one);
1474 return -1;
1475}
1476
1477/* An extension of builtin_range() that handles the case when PyLong
1478 * arguments are given. */
1479static PyObject *
1480handle_range_longs(PyObject *self, PyObject *args)
1481{
1482 PyObject *ilow;
Tim Peters874e1f72003-04-13 22:13:08 +00001483 PyObject *ihigh = NULL;
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001484 PyObject *istep = NULL;
Tim Peters874e1f72003-04-13 22:13:08 +00001485
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001486 PyObject *curnum = NULL;
1487 PyObject *v = NULL;
1488 long bign;
1489 int i, n;
Guido van Rossum47b9ff62006-08-24 00:41:19 +00001490 int step_pos;
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001491
Tim Peters874e1f72003-04-13 22:13:08 +00001492 PyObject *zero = PyLong_FromLong(0);
1493
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001494 if (zero == NULL)
1495 return NULL;
1496
Tim Peters874e1f72003-04-13 22:13:08 +00001497 if (!PyArg_UnpackTuple(args, "range", 1, 3, &ilow, &ihigh, &istep)) {
1498 Py_DECREF(zero);
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001499 return NULL;
1500 }
1501
Tim Peters874e1f72003-04-13 22:13:08 +00001502 /* Figure out which way we were called, supply defaults, and be
1503 * sure to incref everything so that the decrefs at the end
1504 * are correct.
1505 */
1506 assert(ilow != NULL);
1507 if (ihigh == NULL) {
1508 /* only 1 arg -- it's the upper limit */
1509 ihigh = ilow;
1510 ilow = NULL;
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001511 }
Tim Peters874e1f72003-04-13 22:13:08 +00001512 assert(ihigh != NULL);
1513 Py_INCREF(ihigh);
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001514
Tim Peters874e1f72003-04-13 22:13:08 +00001515 /* ihigh correct now; do ilow */
1516 if (ilow == NULL)
1517 ilow = zero;
1518 Py_INCREF(ilow);
1519
1520 /* ilow and ihigh correct now; do istep */
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001521 if (istep == NULL) {
1522 istep = PyLong_FromLong(1L);
1523 if (istep == NULL)
1524 goto Fail;
1525 }
1526 else {
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001527 Py_INCREF(istep);
1528 }
1529
Tim Peters874e1f72003-04-13 22:13:08 +00001530 if (!PyInt_Check(ilow) && !PyLong_Check(ilow)) {
Guido van Rossum28e83e32003-04-15 12:43:26 +00001531 PyErr_Format(PyExc_TypeError,
Alex Martellif471d472003-04-23 13:00:44 +00001532 "range() integer start argument expected, got %s.",
Guido van Rossum817d6c92003-04-14 18:25:04 +00001533 ilow->ob_type->tp_name);
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001534 goto Fail;
1535 }
1536
Tim Peters874e1f72003-04-13 22:13:08 +00001537 if (!PyInt_Check(ihigh) && !PyLong_Check(ihigh)) {
Guido van Rossum28e83e32003-04-15 12:43:26 +00001538 PyErr_Format(PyExc_TypeError,
Alex Martellif471d472003-04-23 13:00:44 +00001539 "range() integer end argument expected, got %s.",
Guido van Rossum817d6c92003-04-14 18:25:04 +00001540 ihigh->ob_type->tp_name);
Tim Peters874e1f72003-04-13 22:13:08 +00001541 goto Fail;
1542 }
1543
1544 if (!PyInt_Check(istep) && !PyLong_Check(istep)) {
Guido van Rossum28e83e32003-04-15 12:43:26 +00001545 PyErr_Format(PyExc_TypeError,
Alex Martellif471d472003-04-23 13:00:44 +00001546 "range() integer step argument expected, got %s.",
Guido van Rossum817d6c92003-04-14 18:25:04 +00001547 istep->ob_type->tp_name);
Tim Peters874e1f72003-04-13 22:13:08 +00001548 goto Fail;
1549 }
1550
Guido van Rossum47b9ff62006-08-24 00:41:19 +00001551 step_pos = PyObject_RichCompareBool(istep, zero, Py_GT);
1552 if (step_pos < 0)
Tim Peters874e1f72003-04-13 22:13:08 +00001553 goto Fail;
Guido van Rossum47b9ff62006-08-24 00:41:19 +00001554 if (step_pos)
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001555 bign = get_len_of_range_longs(ilow, ihigh, istep);
1556 else {
Guido van Rossum47b9ff62006-08-24 00:41:19 +00001557 int step_zero = PyObject_RichCompareBool(istep, zero, Py_EQ);
Guido van Rossum93a66922006-08-24 02:10:21 +00001558 PyObject *neg_istep;
Guido van Rossum47b9ff62006-08-24 00:41:19 +00001559 if (step_zero < 0)
1560 goto Fail;
1561 if (step_zero) {
1562 PyErr_SetString(PyExc_ValueError,
1563 "range() step argument must not be zero");
1564 goto Fail;
1565 }
Guido van Rossum93a66922006-08-24 02:10:21 +00001566 neg_istep = PyNumber_Negative(istep);
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001567 if (neg_istep == NULL)
1568 goto Fail;
1569 bign = get_len_of_range_longs(ihigh, ilow, neg_istep);
1570 Py_DECREF(neg_istep);
1571 }
1572
1573 n = (int)bign;
1574 if (bign < 0 || (long)n != bign) {
1575 PyErr_SetString(PyExc_OverflowError,
1576 "range() result has too many items");
1577 goto Fail;
1578 }
1579
1580 v = PyList_New(n);
1581 if (v == NULL)
1582 goto Fail;
1583
1584 curnum = ilow;
1585 Py_INCREF(curnum);
1586
1587 for (i = 0; i < n; i++) {
1588 PyObject *w = PyNumber_Long(curnum);
1589 PyObject *tmp_num;
1590 if (w == NULL)
1591 goto Fail;
1592
1593 PyList_SET_ITEM(v, i, w);
1594
1595 tmp_num = PyNumber_Add(curnum, istep);
1596 if (tmp_num == NULL)
1597 goto Fail;
1598
1599 Py_DECREF(curnum);
1600 curnum = tmp_num;
1601 }
Tim Peters874e1f72003-04-13 22:13:08 +00001602 Py_DECREF(ilow);
1603 Py_DECREF(ihigh);
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001604 Py_DECREF(istep);
1605 Py_DECREF(zero);
Tim Peters874e1f72003-04-13 22:13:08 +00001606 Py_DECREF(curnum);
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001607 return v;
1608
1609 Fail:
Tim Peters874e1f72003-04-13 22:13:08 +00001610 Py_DECREF(ilow);
1611 Py_DECREF(ihigh);
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001612 Py_XDECREF(istep);
Tim Peters874e1f72003-04-13 22:13:08 +00001613 Py_DECREF(zero);
1614 Py_XDECREF(curnum);
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001615 Py_XDECREF(v);
1616 return NULL;
1617}
1618
Guido van Rossum124eff01999-02-23 16:11:01 +00001619/* Return number of items in range/xrange (lo, hi, step). step > 0
1620 * required. Return a value < 0 if & only if the true value is too
1621 * large to fit in a signed long.
1622 */
1623static long
Thomas Wouterse28c2962000-07-23 22:21:32 +00001624get_len_of_range(long lo, long hi, long step)
Guido van Rossum124eff01999-02-23 16:11:01 +00001625{
1626 /* -------------------------------------------------------------
1627 If lo >= hi, the range is empty.
1628 Else if n values are in the range, the last one is
1629 lo + (n-1)*step, which must be <= hi-1. Rearranging,
1630 n <= (hi - lo - 1)/step + 1, so taking the floor of the RHS gives
1631 the proper value. Since lo < hi in this case, hi-lo-1 >= 0, so
1632 the RHS is non-negative and so truncation is the same as the
1633 floor. Letting M be the largest positive long, the worst case
1634 for the RHS numerator is hi=M, lo=-M-1, and then
1635 hi-lo-1 = M-(-M-1)-1 = 2*M. Therefore unsigned long has enough
1636 precision to compute the RHS exactly.
1637 ---------------------------------------------------------------*/
1638 long n = 0;
1639 if (lo < hi) {
1640 unsigned long uhi = (unsigned long)hi;
1641 unsigned long ulo = (unsigned long)lo;
1642 unsigned long diff = uhi - ulo - 1;
1643 n = (long)(diff / (unsigned long)step + 1);
1644 }
1645 return n;
1646}
1647
Guido van Rossum79f25d91997-04-29 20:08:16 +00001648static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001649builtin_range(PyObject *self, PyObject *args)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001650{
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001651 long ilow = 0, ihigh = 0, istep = 1;
Guido van Rossum124eff01999-02-23 16:11:01 +00001652 long bign;
Guido van Rossum3f5da241990-12-20 15:06:42 +00001653 int i, n;
Guido van Rossum124eff01999-02-23 16:11:01 +00001654
Guido van Rossum79f25d91997-04-29 20:08:16 +00001655 PyObject *v;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001656
Guido van Rossum79f25d91997-04-29 20:08:16 +00001657 if (PyTuple_Size(args) <= 1) {
1658 if (!PyArg_ParseTuple(args,
Guido van Rossum0865dd91995-01-17 16:30:22 +00001659 "l;range() requires 1-3 int arguments",
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001660 &ihigh)) {
1661 PyErr_Clear();
1662 return handle_range_longs(self, args);
1663 }
Guido van Rossum3f5da241990-12-20 15:06:42 +00001664 }
1665 else {
Guido van Rossum79f25d91997-04-29 20:08:16 +00001666 if (!PyArg_ParseTuple(args,
Guido van Rossum0865dd91995-01-17 16:30:22 +00001667 "ll|l;range() requires 1-3 int arguments",
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001668 &ilow, &ihigh, &istep)) {
1669 PyErr_Clear();
1670 return handle_range_longs(self, args);
1671 }
Guido van Rossum3f5da241990-12-20 15:06:42 +00001672 }
1673 if (istep == 0) {
Guido van Rossumefbbb1c2003-04-11 18:43:06 +00001674 PyErr_SetString(PyExc_ValueError,
Alex Martellif471d472003-04-23 13:00:44 +00001675 "range() step argument must not be zero");
Guido van Rossum3f5da241990-12-20 15:06:42 +00001676 return NULL;
1677 }
Guido van Rossum124eff01999-02-23 16:11:01 +00001678 if (istep > 0)
1679 bign = get_len_of_range(ilow, ihigh, istep);
1680 else
1681 bign = get_len_of_range(ihigh, ilow, -istep);
1682 n = (int)bign;
1683 if (bign < 0 || (long)n != bign) {
Guido van Rossume23cde21999-01-12 05:07:47 +00001684 PyErr_SetString(PyExc_OverflowError,
Fred Drake661ea262000-10-24 19:57:45 +00001685 "range() result has too many items");
Guido van Rossume23cde21999-01-12 05:07:47 +00001686 return NULL;
1687 }
Guido van Rossum79f25d91997-04-29 20:08:16 +00001688 v = PyList_New(n);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001689 if (v == NULL)
1690 return NULL;
1691 for (i = 0; i < n; i++) {
Guido van Rossum79f25d91997-04-29 20:08:16 +00001692 PyObject *w = PyInt_FromLong(ilow);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001693 if (w == NULL) {
Guido van Rossum79f25d91997-04-29 20:08:16 +00001694 Py_DECREF(v);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001695 return NULL;
1696 }
Guido van Rossuma937d141998-04-24 18:22:02 +00001697 PyList_SET_ITEM(v, i, w);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001698 ilow += istep;
1699 }
1700 return v;
1701}
1702
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001703PyDoc_STRVAR(range_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001704"range([start,] stop[, step]) -> list of integers\n\
1705\n\
1706Return a list containing an arithmetic progression of integers.\n\
1707range(i, j) returns [i, i+1, i+2, ..., j-1]; start (!) defaults to 0.\n\
1708When step is given, it specifies the increment (or decrement).\n\
1709For example, range(4) returns [0, 1, 2, 3]. The end point is omitted!\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001710These are exactly the valid indices for a list of 4 elements.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001711
1712
Guido van Rossum79f25d91997-04-29 20:08:16 +00001713static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001714builtin_reload(PyObject *self, PyObject *v)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001715{
Guido van Rossum79f25d91997-04-29 20:08:16 +00001716 return PyImport_ReloadModule(v);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001717}
1718
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001719PyDoc_STRVAR(reload_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001720"reload(module) -> module\n\
1721\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001722Reload the module. The module must have been successfully imported before.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001723
1724
Guido van Rossum79f25d91997-04-29 20:08:16 +00001725static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001726builtin_repr(PyObject *self, PyObject *v)
Guido van Rossumc89705d1992-11-26 08:54:07 +00001727{
Guido van Rossum79f25d91997-04-29 20:08:16 +00001728 return PyObject_Repr(v);
Guido van Rossumc89705d1992-11-26 08:54:07 +00001729}
1730
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001731PyDoc_STRVAR(repr_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001732"repr(object) -> string\n\
1733\n\
1734Return the canonical string representation of the object.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001735For most object types, eval(repr(object)) == object.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001736
1737
Guido van Rossum79f25d91997-04-29 20:08:16 +00001738static PyObject *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001739builtin_round(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum9e51f9b1993-02-12 16:29:05 +00001740{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001741 double number;
Guido van Rossum9e51f9b1993-02-12 16:29:05 +00001742 double f;
1743 int ndigits = 0;
Guido van Rossum9e51f9b1993-02-12 16:29:05 +00001744 int i;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001745 static char *kwlist[] = {"number", "ndigits", 0};
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001746
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001747 if (!PyArg_ParseTupleAndKeywords(args, kwds, "d|i:round",
1748 kwlist, &number, &ndigits))
1749 return NULL;
Guido van Rossum9e51f9b1993-02-12 16:29:05 +00001750 f = 1.0;
Guido van Rossum1e162d31998-05-09 14:42:25 +00001751 i = abs(ndigits);
1752 while (--i >= 0)
Guido van Rossum9e51f9b1993-02-12 16:29:05 +00001753 f = f*10.0;
Guido van Rossum1e162d31998-05-09 14:42:25 +00001754 if (ndigits < 0)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001755 number /= f;
Guido van Rossum9e51f9b1993-02-12 16:29:05 +00001756 else
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001757 number *= f;
1758 if (number >= 0.0)
1759 number = floor(number + 0.5);
Guido van Rossum1e162d31998-05-09 14:42:25 +00001760 else
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001761 number = ceil(number - 0.5);
Guido van Rossum1e162d31998-05-09 14:42:25 +00001762 if (ndigits < 0)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001763 number *= f;
Guido van Rossum1e162d31998-05-09 14:42:25 +00001764 else
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001765 number /= f;
1766 return PyFloat_FromDouble(number);
Guido van Rossum9e51f9b1993-02-12 16:29:05 +00001767}
1768
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001769PyDoc_STRVAR(round_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001770"round(number[, ndigits]) -> floating point number\n\
1771\n\
1772Round a number to a given precision in decimal digits (default 0 digits).\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001773This always returns a floating point number. Precision may be negative.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001774
Raymond Hettinger64958a12003-12-17 20:43:33 +00001775static PyObject *
1776builtin_sorted(PyObject *self, PyObject *args, PyObject *kwds)
1777{
1778 PyObject *newlist, *v, *seq, *compare=NULL, *keyfunc=NULL, *newargs;
1779 PyObject *callable;
Martin v. Löwis15e62742006-02-27 16:46:16 +00001780 static char *kwlist[] = {"iterable", "cmp", "key", "reverse", 0};
Neal Norwitz6f0d4792005-12-15 06:40:36 +00001781 int reverse;
Raymond Hettinger64958a12003-12-17 20:43:33 +00001782
Neal Norwitz6f0d4792005-12-15 06:40:36 +00001783 /* args 1-4 should match listsort in Objects/listobject.c */
Armin Rigo71d7e702005-09-20 18:13:03 +00001784 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|OOi:sorted",
1785 kwlist, &seq, &compare, &keyfunc, &reverse))
1786 return NULL;
Raymond Hettinger64958a12003-12-17 20:43:33 +00001787
1788 newlist = PySequence_List(seq);
1789 if (newlist == NULL)
1790 return NULL;
1791
1792 callable = PyObject_GetAttrString(newlist, "sort");
1793 if (callable == NULL) {
1794 Py_DECREF(newlist);
1795 return NULL;
1796 }
Georg Brandl99d7e4e2005-08-31 22:21:15 +00001797
Raymond Hettinger64958a12003-12-17 20:43:33 +00001798 newargs = PyTuple_GetSlice(args, 1, 4);
1799 if (newargs == NULL) {
1800 Py_DECREF(newlist);
1801 Py_DECREF(callable);
1802 return NULL;
1803 }
1804
1805 v = PyObject_Call(callable, newargs, kwds);
1806 Py_DECREF(newargs);
1807 Py_DECREF(callable);
1808 if (v == NULL) {
1809 Py_DECREF(newlist);
1810 return NULL;
1811 }
1812 Py_DECREF(v);
1813 return newlist;
1814}
1815
1816PyDoc_STRVAR(sorted_doc,
1817"sorted(iterable, cmp=None, key=None, reverse=False) --> new sorted list");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001818
Guido van Rossum79f25d91997-04-29 20:08:16 +00001819static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001820builtin_vars(PyObject *self, PyObject *args)
Guido van Rossum2d951851994-08-29 12:52:16 +00001821{
Guido van Rossum79f25d91997-04-29 20:08:16 +00001822 PyObject *v = NULL;
1823 PyObject *d;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001824
Raymond Hettingerea3fdf42002-12-29 16:33:45 +00001825 if (!PyArg_UnpackTuple(args, "vars", 0, 1, &v))
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001826 return NULL;
Guido van Rossum2d951851994-08-29 12:52:16 +00001827 if (v == NULL) {
Guido van Rossum79f25d91997-04-29 20:08:16 +00001828 d = PyEval_GetLocals();
Guido van Rossum53bb7ff1995-07-26 16:26:31 +00001829 if (d == NULL) {
Guido van Rossum79f25d91997-04-29 20:08:16 +00001830 if (!PyErr_Occurred())
1831 PyErr_SetString(PyExc_SystemError,
Alex Martellia9b9c9f2003-04-23 13:34:35 +00001832 "vars(): no locals!?");
Guido van Rossum53bb7ff1995-07-26 16:26:31 +00001833 }
1834 else
Guido van Rossum79f25d91997-04-29 20:08:16 +00001835 Py_INCREF(d);
Guido van Rossum2d951851994-08-29 12:52:16 +00001836 }
1837 else {
Guido van Rossum79f25d91997-04-29 20:08:16 +00001838 d = PyObject_GetAttrString(v, "__dict__");
Guido van Rossum2d951851994-08-29 12:52:16 +00001839 if (d == NULL) {
Guido van Rossum79f25d91997-04-29 20:08:16 +00001840 PyErr_SetString(PyExc_TypeError,
Guido van Rossum2d951851994-08-29 12:52:16 +00001841 "vars() argument must have __dict__ attribute");
1842 return NULL;
1843 }
1844 }
1845 return d;
1846}
1847
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001848PyDoc_STRVAR(vars_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001849"vars([object]) -> dictionary\n\
1850\n\
1851Without arguments, equivalent to locals().\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001852With an argument, equivalent to object.__dict__.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001853
Alex Martellia70b1912003-04-22 08:12:33 +00001854
1855static PyObject*
1856builtin_sum(PyObject *self, PyObject *args)
1857{
1858 PyObject *seq;
1859 PyObject *result = NULL;
1860 PyObject *temp, *item, *iter;
1861
Raymond Hettinger5cf63942003-10-25 06:41:37 +00001862 if (!PyArg_UnpackTuple(args, "sum", 1, 2, &seq, &result))
Alex Martellia70b1912003-04-22 08:12:33 +00001863 return NULL;
1864
1865 iter = PyObject_GetIter(seq);
1866 if (iter == NULL)
1867 return NULL;
1868
1869 if (result == NULL) {
1870 result = PyInt_FromLong(0);
1871 if (result == NULL) {
1872 Py_DECREF(iter);
1873 return NULL;
1874 }
1875 } else {
1876 /* reject string values for 'start' parameter */
1877 if (PyObject_TypeCheck(result, &PyBaseString_Type)) {
1878 PyErr_SetString(PyExc_TypeError,
Alex Martellia9b9c9f2003-04-23 13:34:35 +00001879 "sum() can't sum strings [use ''.join(seq) instead]");
Alex Martellia70b1912003-04-22 08:12:33 +00001880 Py_DECREF(iter);
1881 return NULL;
1882 }
Alex Martelli41c9f882003-04-22 09:24:48 +00001883 Py_INCREF(result);
Alex Martellia70b1912003-04-22 08:12:33 +00001884 }
1885
1886 for(;;) {
1887 item = PyIter_Next(iter);
1888 if (item == NULL) {
1889 /* error, or end-of-sequence */
1890 if (PyErr_Occurred()) {
1891 Py_DECREF(result);
1892 result = NULL;
1893 }
1894 break;
1895 }
Alex Martellia253e182003-10-25 23:24:14 +00001896 temp = PyNumber_Add(result, item);
Alex Martellia70b1912003-04-22 08:12:33 +00001897 Py_DECREF(result);
1898 Py_DECREF(item);
1899 result = temp;
1900 if (result == NULL)
1901 break;
1902 }
1903 Py_DECREF(iter);
1904 return result;
1905}
1906
1907PyDoc_STRVAR(sum_doc,
1908"sum(sequence, start=0) -> value\n\
1909\n\
1910Returns the sum of a sequence of numbers (NOT strings) plus the value\n\
1911of parameter 'start'. When the sequence is empty, returns start.");
1912
1913
Barry Warsawcde8b1b1997-08-22 21:14:38 +00001914static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001915builtin_isinstance(PyObject *self, PyObject *args)
Barry Warsawcde8b1b1997-08-22 21:14:38 +00001916{
1917 PyObject *inst;
1918 PyObject *cls;
Guido van Rossum823649d2001-03-21 18:40:58 +00001919 int retval;
Barry Warsawcde8b1b1997-08-22 21:14:38 +00001920
Raymond Hettingerea3fdf42002-12-29 16:33:45 +00001921 if (!PyArg_UnpackTuple(args, "isinstance", 2, 2, &inst, &cls))
Barry Warsawcde8b1b1997-08-22 21:14:38 +00001922 return NULL;
Guido van Rossumf5dd9141997-12-02 19:11:45 +00001923
Guido van Rossum823649d2001-03-21 18:40:58 +00001924 retval = PyObject_IsInstance(inst, cls);
1925 if (retval < 0)
Guido van Rossumad991772001-01-12 16:03:05 +00001926 return NULL;
Guido van Rossum77f6a652002-04-03 22:41:51 +00001927 return PyBool_FromLong(retval);
Barry Warsawcde8b1b1997-08-22 21:14:38 +00001928}
1929
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001930PyDoc_STRVAR(isinstance_doc,
Guido van Rossum77f6a652002-04-03 22:41:51 +00001931"isinstance(object, class-or-type-or-tuple) -> bool\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001932\n\
1933Return whether an object is an instance of a class or of a subclass thereof.\n\
Guido van Rossum03290ec2001-10-07 20:54:12 +00001934With a type as second argument, return whether that is the object's type.\n\
1935The form using a tuple, isinstance(x, (A, B, ...)), is a shortcut for\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001936isinstance(x, A) or isinstance(x, B) or ... (etc.).");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001937
Barry Warsawcde8b1b1997-08-22 21:14:38 +00001938
1939static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001940builtin_issubclass(PyObject *self, PyObject *args)
Barry Warsawcde8b1b1997-08-22 21:14:38 +00001941{
1942 PyObject *derived;
1943 PyObject *cls;
1944 int retval;
1945
Raymond Hettingerea3fdf42002-12-29 16:33:45 +00001946 if (!PyArg_UnpackTuple(args, "issubclass", 2, 2, &derived, &cls))
Barry Warsawcde8b1b1997-08-22 21:14:38 +00001947 return NULL;
Guido van Rossum668213d1999-06-16 17:28:37 +00001948
Guido van Rossum823649d2001-03-21 18:40:58 +00001949 retval = PyObject_IsSubclass(derived, cls);
1950 if (retval < 0)
1951 return NULL;
Guido van Rossum77f6a652002-04-03 22:41:51 +00001952 return PyBool_FromLong(retval);
Barry Warsawcde8b1b1997-08-22 21:14:38 +00001953}
1954
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001955PyDoc_STRVAR(issubclass_doc,
Guido van Rossum77f6a652002-04-03 22:41:51 +00001956"issubclass(C, B) -> bool\n\
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001957\n\
Walter Dörwaldd9a6ad32002-12-12 16:41:44 +00001958Return whether class C is a subclass (i.e., a derived class) of class B.\n\
1959When using a tuple as the second argument issubclass(X, (A, B, ...)),\n\
1960is a shortcut for issubclass(X, A) or issubclass(X, B) or ... (etc.).");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00001961
Barry Warsawcde8b1b1997-08-22 21:14:38 +00001962
Barry Warsawbd599b52000-08-03 15:45:29 +00001963static PyObject*
1964builtin_zip(PyObject *self, PyObject *args)
1965{
Guido van Rossumb65fb332006-08-25 23:26:40 +00001966 /* args must be a tuple */
1967 assert(PyTuple_Check(args));
Barry Warsawbd599b52000-08-03 15:45:29 +00001968
Guido van Rossumb65fb332006-08-25 23:26:40 +00001969 return _PyZip_CreateIter(args);
Barry Warsawbd599b52000-08-03 15:45:29 +00001970}
1971
1972
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001973PyDoc_STRVAR(zip_doc,
Guido van Rossum801f0d72006-08-24 19:48:10 +00001974"zip(it1 [, it2 [...]]) -> iter([(it1[0], it2[0] ...), ...])\n\
Barry Warsawbd599b52000-08-03 15:45:29 +00001975\n\
Guido van Rossum801f0d72006-08-24 19:48:10 +00001976Return an iterator yielding tuples, where each tuple contains the\n\
1977corresponding element from each of the argument iterables.\n\
1978The returned iterator ends when the shortest argument iterable is exhausted.\n\
1979NOTE: This is implemented using itertools.izip().");
Barry Warsawbd599b52000-08-03 15:45:29 +00001980
1981
Guido van Rossum79f25d91997-04-29 20:08:16 +00001982static PyMethodDef builtin_methods[] = {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001983 {"__import__", (PyCFunction)builtin___import__, METH_VARARGS | METH_KEYWORDS, import_doc},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001984 {"abs", builtin_abs, METH_O, abs_doc},
Raymond Hettinger96229b12005-03-11 06:49:40 +00001985 {"all", builtin_all, METH_O, all_doc},
1986 {"any", builtin_any, METH_O, any_doc},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001987 {"callable", builtin_callable, METH_O, callable_doc},
1988 {"chr", builtin_chr, METH_VARARGS, chr_doc},
1989 {"cmp", builtin_cmp, METH_VARARGS, cmp_doc},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001990 {"compile", builtin_compile, METH_VARARGS, compile_doc},
1991 {"delattr", builtin_delattr, METH_VARARGS, delattr_doc},
1992 {"dir", builtin_dir, METH_VARARGS, dir_doc},
1993 {"divmod", builtin_divmod, METH_VARARGS, divmod_doc},
1994 {"eval", builtin_eval, METH_VARARGS, eval_doc},
Georg Brandl7cae87c2006-09-06 06:51:57 +00001995 {"exec", builtin_exec, METH_VARARGS, exec_doc},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001996 {"execfile", builtin_execfile, METH_VARARGS, execfile_doc},
1997 {"filter", builtin_filter, METH_VARARGS, filter_doc},
1998 {"getattr", builtin_getattr, METH_VARARGS, getattr_doc},
1999 {"globals", (PyCFunction)builtin_globals, METH_NOARGS, globals_doc},
2000 {"hasattr", builtin_hasattr, METH_VARARGS, hasattr_doc},
2001 {"hash", builtin_hash, METH_O, hash_doc},
2002 {"hex", builtin_hex, METH_O, hex_doc},
2003 {"id", builtin_id, METH_O, id_doc},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002004 {"intern", builtin_intern, METH_VARARGS, intern_doc},
2005 {"isinstance", builtin_isinstance, METH_VARARGS, isinstance_doc},
2006 {"issubclass", builtin_issubclass, METH_VARARGS, issubclass_doc},
2007 {"iter", builtin_iter, METH_VARARGS, iter_doc},
2008 {"len", builtin_len, METH_O, len_doc},
2009 {"locals", (PyCFunction)builtin_locals, METH_NOARGS, locals_doc},
2010 {"map", builtin_map, METH_VARARGS, map_doc},
Raymond Hettinger3b0c7c22004-12-03 08:30:39 +00002011 {"max", (PyCFunction)builtin_max, METH_VARARGS | METH_KEYWORDS, max_doc},
2012 {"min", (PyCFunction)builtin_min, METH_VARARGS | METH_KEYWORDS, min_doc},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002013 {"oct", builtin_oct, METH_O, oct_doc},
Thomas Wouters477c8d52006-05-27 19:21:47 +00002014 {"open", (PyCFunction)builtin_open, METH_VARARGS | METH_KEYWORDS, open_doc},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002015 {"ord", builtin_ord, METH_O, ord_doc},
2016 {"pow", builtin_pow, METH_VARARGS, pow_doc},
2017 {"range", builtin_range, METH_VARARGS, range_doc},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002018 {"reload", builtin_reload, METH_O, reload_doc},
2019 {"repr", builtin_repr, METH_O, repr_doc},
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002020 {"round", (PyCFunction)builtin_round, METH_VARARGS | METH_KEYWORDS, round_doc},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002021 {"setattr", builtin_setattr, METH_VARARGS, setattr_doc},
Raymond Hettinger64958a12003-12-17 20:43:33 +00002022 {"sorted", (PyCFunction)builtin_sorted, METH_VARARGS | METH_KEYWORDS, sorted_doc},
Alex Martellia70b1912003-04-22 08:12:33 +00002023 {"sum", builtin_sum, METH_VARARGS, sum_doc},
Martin v. Löwis339d0f72001-08-17 18:39:25 +00002024#ifdef Py_USING_UNICODE
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002025 {"unichr", builtin_unichr, METH_VARARGS, unichr_doc},
Martin v. Löwis339d0f72001-08-17 18:39:25 +00002026#endif
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002027 {"vars", builtin_vars, METH_VARARGS, vars_doc},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002028 {"zip", builtin_zip, METH_VARARGS, zip_doc},
Guido van Rossumc02e15c1991-12-16 13:03:00 +00002029 {NULL, NULL},
Guido van Rossum3f5da241990-12-20 15:06:42 +00002030};
2031
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002032PyDoc_STRVAR(builtin_doc,
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002033"Built-in functions, exceptions, and other objects.\n\
2034\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002035Noteworthy: None is the `nil' object; Ellipsis represents `...' in slices.");
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002036
Guido van Rossum25ce5661997-08-02 03:10:38 +00002037PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002038_PyBuiltin_Init(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +00002039{
Fred Drake5550de32000-06-20 04:54:19 +00002040 PyObject *mod, *dict, *debug;
Guido van Rossumf9d9c6c1998-06-26 21:23:49 +00002041 mod = Py_InitModule4("__builtin__", builtin_methods,
2042 builtin_doc, (PyObject *)NULL,
2043 PYTHON_API_VERSION);
Guido van Rossum25ce5661997-08-02 03:10:38 +00002044 if (mod == NULL)
2045 return NULL;
2046 dict = PyModule_GetDict(mod);
Tim Peters4b7625e2001-09-13 21:37:17 +00002047
Tim Peters7571a0f2003-03-23 17:52:28 +00002048#ifdef Py_TRACE_REFS
2049 /* __builtin__ exposes a number of statically allocated objects
2050 * that, before this code was added in 2.3, never showed up in
2051 * the list of "all objects" maintained by Py_TRACE_REFS. As a
2052 * result, programs leaking references to None and False (etc)
2053 * couldn't be diagnosed by examining sys.getobjects(0).
2054 */
2055#define ADD_TO_ALL(OBJECT) _Py_AddToAllObjects((PyObject *)(OBJECT), 0)
2056#else
2057#define ADD_TO_ALL(OBJECT) (void)0
2058#endif
2059
Tim Peters4b7625e2001-09-13 21:37:17 +00002060#define SETBUILTIN(NAME, OBJECT) \
Tim Peters7571a0f2003-03-23 17:52:28 +00002061 if (PyDict_SetItemString(dict, NAME, (PyObject *)OBJECT) < 0) \
2062 return NULL; \
2063 ADD_TO_ALL(OBJECT)
Tim Peters4b7625e2001-09-13 21:37:17 +00002064
2065 SETBUILTIN("None", Py_None);
2066 SETBUILTIN("Ellipsis", Py_Ellipsis);
2067 SETBUILTIN("NotImplemented", Py_NotImplemented);
Guido van Rossum77f6a652002-04-03 22:41:51 +00002068 SETBUILTIN("False", Py_False);
2069 SETBUILTIN("True", Py_True);
Neal Norwitz32a7e7f2002-05-31 19:58:02 +00002070 SETBUILTIN("basestring", &PyBaseString_Type);
Guido van Rossum77f6a652002-04-03 22:41:51 +00002071 SETBUILTIN("bool", &PyBool_Type);
Guido van Rossumbea18cc2002-06-14 20:41:17 +00002072 SETBUILTIN("buffer", &PyBuffer_Type);
Guido van Rossum4dfe8a12006-04-22 23:28:04 +00002073 SETBUILTIN("bytes", &PyBytes_Type);
Tim Peters4b7625e2001-09-13 21:37:17 +00002074 SETBUILTIN("classmethod", &PyClassMethod_Type);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002075#ifndef WITHOUT_COMPLEX
Tim Peters4b7625e2001-09-13 21:37:17 +00002076 SETBUILTIN("complex", &PyComplex_Type);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002077#endif
Tim Petersa427a2b2001-10-29 22:25:45 +00002078 SETBUILTIN("dict", &PyDict_Type);
Tim Peters67d687a2002-04-29 21:27:32 +00002079 SETBUILTIN("enumerate", &PyEnum_Type);
Thomas Wouters477c8d52006-05-27 19:21:47 +00002080 SETBUILTIN("file", &PyFile_Type);
Tim Peters4b7625e2001-09-13 21:37:17 +00002081 SETBUILTIN("float", &PyFloat_Type);
Raymond Hettingera690a992003-11-16 16:17:49 +00002082 SETBUILTIN("frozenset", &PyFrozenSet_Type);
Tim Peters4b7625e2001-09-13 21:37:17 +00002083 SETBUILTIN("property", &PyProperty_Type);
2084 SETBUILTIN("int", &PyInt_Type);
2085 SETBUILTIN("list", &PyList_Type);
2086 SETBUILTIN("long", &PyLong_Type);
2087 SETBUILTIN("object", &PyBaseObject_Type);
Raymond Hettinger85c20a42003-11-06 14:06:48 +00002088 SETBUILTIN("reversed", &PyReversed_Type);
Raymond Hettingera690a992003-11-16 16:17:49 +00002089 SETBUILTIN("set", &PySet_Type);
Guido van Rossumbea18cc2002-06-14 20:41:17 +00002090 SETBUILTIN("slice", &PySlice_Type);
Tim Peters4b7625e2001-09-13 21:37:17 +00002091 SETBUILTIN("staticmethod", &PyStaticMethod_Type);
2092 SETBUILTIN("str", &PyString_Type);
2093 SETBUILTIN("super", &PySuper_Type);
2094 SETBUILTIN("tuple", &PyTuple_Type);
2095 SETBUILTIN("type", &PyType_Type);
Raymond Hettingerc4c453f2002-06-05 23:12:45 +00002096 SETBUILTIN("xrange", &PyRange_Type);
Martin v. Löwis339d0f72001-08-17 18:39:25 +00002097#ifdef Py_USING_UNICODE
Tim Peters4b7625e2001-09-13 21:37:17 +00002098 SETBUILTIN("unicode", &PyUnicode_Type);
Martin v. Löwis339d0f72001-08-17 18:39:25 +00002099#endif
Guido van Rossum77f6a652002-04-03 22:41:51 +00002100 debug = PyBool_FromLong(Py_OptimizeFlag == 0);
Fred Drake5550de32000-06-20 04:54:19 +00002101 if (PyDict_SetItemString(dict, "__debug__", debug) < 0) {
2102 Py_XDECREF(debug);
Guido van Rossum25ce5661997-08-02 03:10:38 +00002103 return NULL;
Fred Drake5550de32000-06-20 04:54:19 +00002104 }
2105 Py_XDECREF(debug);
Barry Warsaw757af0e1997-08-29 22:13:51 +00002106
Guido van Rossum25ce5661997-08-02 03:10:38 +00002107 return mod;
Tim Peters7571a0f2003-03-23 17:52:28 +00002108#undef ADD_TO_ALL
Tim Peters4b7625e2001-09-13 21:37:17 +00002109#undef SETBUILTIN
Guido van Rossum3f5da241990-12-20 15:06:42 +00002110}
2111
Guido van Rossume77a7571993-11-03 15:01:26 +00002112/* Helper for filter(): filter a tuple through a function */
Guido van Rossum12d12c51993-10-26 17:58:25 +00002113
Guido van Rossum79f25d91997-04-29 20:08:16 +00002114static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002115filtertuple(PyObject *func, PyObject *tuple)
Guido van Rossum12d12c51993-10-26 17:58:25 +00002116{
Guido van Rossum79f25d91997-04-29 20:08:16 +00002117 PyObject *result;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002118 Py_ssize_t i, j;
2119 Py_ssize_t len = PyTuple_Size(tuple);
Guido van Rossum12d12c51993-10-26 17:58:25 +00002120
Guido van Rossumb7b45621995-08-04 04:07:45 +00002121 if (len == 0) {
Walter Dörwaldc3da83f2003-02-04 20:24:45 +00002122 if (PyTuple_CheckExact(tuple))
2123 Py_INCREF(tuple);
2124 else
2125 tuple = PyTuple_New(0);
Guido van Rossumb7b45621995-08-04 04:07:45 +00002126 return tuple;
2127 }
2128
Guido van Rossum79f25d91997-04-29 20:08:16 +00002129 if ((result = PyTuple_New(len)) == NULL)
Guido van Rossum2586bf01993-11-01 16:21:44 +00002130 return NULL;
Guido van Rossum12d12c51993-10-26 17:58:25 +00002131
Guido van Rossum12d12c51993-10-26 17:58:25 +00002132 for (i = j = 0; i < len; ++i) {
Guido van Rossum79f25d91997-04-29 20:08:16 +00002133 PyObject *item, *good;
Guido van Rossumdc4b93d1993-10-27 14:56:44 +00002134 int ok;
Guido van Rossum12d12c51993-10-26 17:58:25 +00002135
Walter Dörwald8dd19322003-02-10 17:36:40 +00002136 if (tuple->ob_type->tp_as_sequence &&
2137 tuple->ob_type->tp_as_sequence->sq_item) {
2138 item = tuple->ob_type->tp_as_sequence->sq_item(tuple, i);
Walter Dörwaldc58a3a12003-08-18 18:28:45 +00002139 if (item == NULL)
2140 goto Fail_1;
Walter Dörwald8dd19322003-02-10 17:36:40 +00002141 } else {
Alex Martellia9b9c9f2003-04-23 13:34:35 +00002142 PyErr_SetString(PyExc_TypeError, "filter(): unsubscriptable tuple");
Guido van Rossumdc4b93d1993-10-27 14:56:44 +00002143 goto Fail_1;
Walter Dörwald8dd19322003-02-10 17:36:40 +00002144 }
Guido van Rossum79f25d91997-04-29 20:08:16 +00002145 if (func == Py_None) {
2146 Py_INCREF(item);
Guido van Rossumdc4b93d1993-10-27 14:56:44 +00002147 good = item;
2148 }
2149 else {
Raymond Hettinger8ae46892003-10-12 19:09:37 +00002150 PyObject *arg = PyTuple_Pack(1, item);
Walter Dörwaldc58a3a12003-08-18 18:28:45 +00002151 if (arg == NULL) {
2152 Py_DECREF(item);
Guido van Rossumdc4b93d1993-10-27 14:56:44 +00002153 goto Fail_1;
Walter Dörwaldc58a3a12003-08-18 18:28:45 +00002154 }
Guido van Rossum79f25d91997-04-29 20:08:16 +00002155 good = PyEval_CallObject(func, arg);
2156 Py_DECREF(arg);
Walter Dörwaldc58a3a12003-08-18 18:28:45 +00002157 if (good == NULL) {
2158 Py_DECREF(item);
Guido van Rossum12d12c51993-10-26 17:58:25 +00002159 goto Fail_1;
Walter Dörwaldc58a3a12003-08-18 18:28:45 +00002160 }
Guido van Rossum12d12c51993-10-26 17:58:25 +00002161 }
Guido van Rossum79f25d91997-04-29 20:08:16 +00002162 ok = PyObject_IsTrue(good);
2163 Py_DECREF(good);
Guido van Rossumdc4b93d1993-10-27 14:56:44 +00002164 if (ok) {
Guido van Rossum79f25d91997-04-29 20:08:16 +00002165 if (PyTuple_SetItem(result, j++, item) < 0)
Guido van Rossumdc4b93d1993-10-27 14:56:44 +00002166 goto Fail_1;
Guido van Rossum12d12c51993-10-26 17:58:25 +00002167 }
Walter Dörwaldc58a3a12003-08-18 18:28:45 +00002168 else
2169 Py_DECREF(item);
Guido van Rossum12d12c51993-10-26 17:58:25 +00002170 }
2171
Tim Peters4324aa32001-05-28 22:30:08 +00002172 if (_PyTuple_Resize(&result, j) < 0)
Guido van Rossum12d12c51993-10-26 17:58:25 +00002173 return NULL;
2174
Guido van Rossum12d12c51993-10-26 17:58:25 +00002175 return result;
2176
Guido van Rossum12d12c51993-10-26 17:58:25 +00002177Fail_1:
Guido van Rossum79f25d91997-04-29 20:08:16 +00002178 Py_DECREF(result);
Guido van Rossum12d12c51993-10-26 17:58:25 +00002179 return NULL;
2180}
2181
2182
Guido van Rossume77a7571993-11-03 15:01:26 +00002183/* Helper for filter(): filter a string through a function */
Guido van Rossum12d12c51993-10-26 17:58:25 +00002184
Guido van Rossum79f25d91997-04-29 20:08:16 +00002185static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002186filterstring(PyObject *func, PyObject *strobj)
Guido van Rossum12d12c51993-10-26 17:58:25 +00002187{
Guido van Rossum79f25d91997-04-29 20:08:16 +00002188 PyObject *result;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002189 Py_ssize_t i, j;
2190 Py_ssize_t len = PyString_Size(strobj);
2191 Py_ssize_t outlen = len;
Guido van Rossum12d12c51993-10-26 17:58:25 +00002192
Guido van Rossum79f25d91997-04-29 20:08:16 +00002193 if (func == Py_None) {
Walter Dörwald1918f772003-02-10 13:19:13 +00002194 /* If it's a real string we can return the original,
2195 * as no character is ever false and __getitem__
2196 * does return this character. If it's a subclass
2197 * we must go through the __getitem__ loop */
2198 if (PyString_CheckExact(strobj)) {
Walter Dörwaldc3da83f2003-02-04 20:24:45 +00002199 Py_INCREF(strobj);
Walter Dörwald1918f772003-02-10 13:19:13 +00002200 return strobj;
2201 }
Guido van Rossum12d12c51993-10-26 17:58:25 +00002202 }
Guido van Rossum79f25d91997-04-29 20:08:16 +00002203 if ((result = PyString_FromStringAndSize(NULL, len)) == NULL)
Guido van Rossum2586bf01993-11-01 16:21:44 +00002204 return NULL;
Guido van Rossum12d12c51993-10-26 17:58:25 +00002205
Guido van Rossum12d12c51993-10-26 17:58:25 +00002206 for (i = j = 0; i < len; ++i) {
Walter Dörwald1918f772003-02-10 13:19:13 +00002207 PyObject *item;
Guido van Rossumdc4b93d1993-10-27 14:56:44 +00002208 int ok;
Guido van Rossum12d12c51993-10-26 17:58:25 +00002209
Guido van Rossumdc4b93d1993-10-27 14:56:44 +00002210 item = (*strobj->ob_type->tp_as_sequence->sq_item)(strobj, i);
2211 if (item == NULL)
2212 goto Fail_1;
Walter Dörwald1918f772003-02-10 13:19:13 +00002213 if (func==Py_None) {
2214 ok = 1;
2215 } else {
2216 PyObject *arg, *good;
Raymond Hettinger8ae46892003-10-12 19:09:37 +00002217 arg = PyTuple_Pack(1, item);
Walter Dörwald1918f772003-02-10 13:19:13 +00002218 if (arg == NULL) {
2219 Py_DECREF(item);
2220 goto Fail_1;
2221 }
2222 good = PyEval_CallObject(func, arg);
2223 Py_DECREF(arg);
2224 if (good == NULL) {
2225 Py_DECREF(item);
2226 goto Fail_1;
2227 }
2228 ok = PyObject_IsTrue(good);
2229 Py_DECREF(good);
Tim Peters388ed082001-04-07 20:34:48 +00002230 }
Walter Dörwald903f1e02003-02-04 16:28:00 +00002231 if (ok) {
Martin v. Löwisd96ee902006-02-16 14:37:16 +00002232 Py_ssize_t reslen;
Walter Dörwald903f1e02003-02-04 16:28:00 +00002233 if (!PyString_Check(item)) {
2234 PyErr_SetString(PyExc_TypeError, "can't filter str to str:"
2235 " __getitem__ returned different type");
2236 Py_DECREF(item);
2237 goto Fail_1;
2238 }
2239 reslen = PyString_GET_SIZE(item);
2240 if (reslen == 1) {
2241 PyString_AS_STRING(result)[j++] =
2242 PyString_AS_STRING(item)[0];
2243 } else {
2244 /* do we need more space? */
Martin v. Löwisd96ee902006-02-16 14:37:16 +00002245 Py_ssize_t need = j + reslen + len-i-1;
Walter Dörwald903f1e02003-02-04 16:28:00 +00002246 if (need > outlen) {
2247 /* overallocate, to avoid reallocations */
2248 if (need<2*outlen)
2249 need = 2*outlen;
2250 if (_PyString_Resize(&result, need)) {
2251 Py_DECREF(item);
2252 return NULL;
2253 }
2254 outlen = need;
2255 }
2256 memcpy(
2257 PyString_AS_STRING(result) + j,
2258 PyString_AS_STRING(item),
2259 reslen
2260 );
2261 j += reslen;
2262 }
2263 }
Tim Peters388ed082001-04-07 20:34:48 +00002264 Py_DECREF(item);
Guido van Rossum12d12c51993-10-26 17:58:25 +00002265 }
2266
Walter Dörwald903f1e02003-02-04 16:28:00 +00002267 if (j < outlen)
Tim Peters5de98422002-04-27 18:44:32 +00002268 _PyString_Resize(&result, j);
Guido van Rossum12d12c51993-10-26 17:58:25 +00002269
Guido van Rossum12d12c51993-10-26 17:58:25 +00002270 return result;
2271
Guido van Rossum12d12c51993-10-26 17:58:25 +00002272Fail_1:
Guido van Rossum79f25d91997-04-29 20:08:16 +00002273 Py_DECREF(result);
Guido van Rossum12d12c51993-10-26 17:58:25 +00002274 return NULL;
2275}
Martin v. Löwis8afd7572003-01-25 22:46:11 +00002276
2277#ifdef Py_USING_UNICODE
2278/* Helper for filter(): filter a Unicode object through a function */
2279
2280static PyObject *
2281filterunicode(PyObject *func, PyObject *strobj)
2282{
2283 PyObject *result;
Martin v. Löwis725507b2006-03-07 12:08:51 +00002284 register Py_ssize_t i, j;
Martin v. Löwisd96ee902006-02-16 14:37:16 +00002285 Py_ssize_t len = PyUnicode_GetSize(strobj);
2286 Py_ssize_t outlen = len;
Martin v. Löwis8afd7572003-01-25 22:46:11 +00002287
2288 if (func == Py_None) {
Walter Dörwald1918f772003-02-10 13:19:13 +00002289 /* If it's a real string we can return the original,
2290 * as no character is ever false and __getitem__
2291 * does return this character. If it's a subclass
2292 * we must go through the __getitem__ loop */
2293 if (PyUnicode_CheckExact(strobj)) {
Walter Dörwaldc3da83f2003-02-04 20:24:45 +00002294 Py_INCREF(strobj);
Walter Dörwald1918f772003-02-10 13:19:13 +00002295 return strobj;
2296 }
Martin v. Löwis8afd7572003-01-25 22:46:11 +00002297 }
2298 if ((result = PyUnicode_FromUnicode(NULL, len)) == NULL)
2299 return NULL;
2300
2301 for (i = j = 0; i < len; ++i) {
2302 PyObject *item, *arg, *good;
2303 int ok;
2304
2305 item = (*strobj->ob_type->tp_as_sequence->sq_item)(strobj, i);
2306 if (item == NULL)
2307 goto Fail_1;
Walter Dörwald1918f772003-02-10 13:19:13 +00002308 if (func == Py_None) {
2309 ok = 1;
2310 } else {
Raymond Hettinger8ae46892003-10-12 19:09:37 +00002311 arg = PyTuple_Pack(1, item);
Walter Dörwald1918f772003-02-10 13:19:13 +00002312 if (arg == NULL) {
2313 Py_DECREF(item);
2314 goto Fail_1;
2315 }
2316 good = PyEval_CallObject(func, arg);
2317 Py_DECREF(arg);
2318 if (good == NULL) {
2319 Py_DECREF(item);
2320 goto Fail_1;
2321 }
2322 ok = PyObject_IsTrue(good);
2323 Py_DECREF(good);
Martin v. Löwis8afd7572003-01-25 22:46:11 +00002324 }
Walter Dörwald903f1e02003-02-04 16:28:00 +00002325 if (ok) {
Martin v. Löwisd96ee902006-02-16 14:37:16 +00002326 Py_ssize_t reslen;
Walter Dörwald903f1e02003-02-04 16:28:00 +00002327 if (!PyUnicode_Check(item)) {
Georg Brandl99d7e4e2005-08-31 22:21:15 +00002328 PyErr_SetString(PyExc_TypeError,
Jeremy Hylton1aad9c72003-09-16 03:10:59 +00002329 "can't filter unicode to unicode:"
2330 " __getitem__ returned different type");
Walter Dörwald903f1e02003-02-04 16:28:00 +00002331 Py_DECREF(item);
2332 goto Fail_1;
2333 }
2334 reslen = PyUnicode_GET_SIZE(item);
Georg Brandl99d7e4e2005-08-31 22:21:15 +00002335 if (reslen == 1)
Walter Dörwald903f1e02003-02-04 16:28:00 +00002336 PyUnicode_AS_UNICODE(result)[j++] =
2337 PyUnicode_AS_UNICODE(item)[0];
Jeremy Hylton1aad9c72003-09-16 03:10:59 +00002338 else {
Walter Dörwald903f1e02003-02-04 16:28:00 +00002339 /* do we need more space? */
Martin v. Löwisd96ee902006-02-16 14:37:16 +00002340 Py_ssize_t need = j + reslen + len - i - 1;
Walter Dörwald903f1e02003-02-04 16:28:00 +00002341 if (need > outlen) {
Georg Brandl99d7e4e2005-08-31 22:21:15 +00002342 /* overallocate,
Jeremy Hylton1aad9c72003-09-16 03:10:59 +00002343 to avoid reallocations */
2344 if (need < 2 * outlen)
2345 need = 2 * outlen;
Jeremy Hylton364f6be2003-09-16 03:17:16 +00002346 if (PyUnicode_Resize(
2347 &result, need) < 0) {
Walter Dörwald903f1e02003-02-04 16:28:00 +00002348 Py_DECREF(item);
Walter Dörwald531e0002003-02-04 16:57:49 +00002349 goto Fail_1;
Walter Dörwald903f1e02003-02-04 16:28:00 +00002350 }
2351 outlen = need;
2352 }
Jeremy Hylton1aad9c72003-09-16 03:10:59 +00002353 memcpy(PyUnicode_AS_UNICODE(result) + j,
2354 PyUnicode_AS_UNICODE(item),
2355 reslen*sizeof(Py_UNICODE));
Walter Dörwald903f1e02003-02-04 16:28:00 +00002356 j += reslen;
2357 }
2358 }
Martin v. Löwis8afd7572003-01-25 22:46:11 +00002359 Py_DECREF(item);
2360 }
2361
Walter Dörwald903f1e02003-02-04 16:28:00 +00002362 if (j < outlen)
Martin v. Löwis8afd7572003-01-25 22:46:11 +00002363 PyUnicode_Resize(&result, j);
2364
2365 return result;
2366
2367Fail_1:
2368 Py_DECREF(result);
2369 return NULL;
2370}
2371#endif